How to define a range and using an input, use that range to print - range

i would like to write code that will print out a selected message if the input falls within a pre-defined range from 1 to 10. im very new to this so my code may not even be right to begin with.
here is the code.
a = range (1, 3)
b = range (4, 6)
c = range (7, 9)
d = 10
scale = int(input())
if scale == a:
print ("I'm sure things will get better!")
if scale == b:
print ("Thats not too bad!")
if scale == c:
print ("Keep up the good work!")

if scale in range(1, 3):
print ("I'm sure things will get better!")
if scale in range(4, 6):
print ("Thats not too bad!")
if scale in range(7, 9):
print ("Keep up the good work!")
maybe like this, not sure if you need the range in a variable, but this way you dont have to declare the variable.

Related

Logic behind Two Number Sum Algorithm

Could someone explain to me the logic behind this hashMap algorithm? I'm getting confused about how the algorithm receives the total sum. I'm starting to learn about algorithms, so it's a little confusing for me. I made comments in my code to pinpoint each line code, but I'm not sure I'm grasping logic correctly. I'm just looking for an easier way to understand how the algorithm works to avoid confusing myself.
//**calculate Two Number Sum
func twoNumberSum(_ array: [Int], _ targetSum: Int) -> [Int] {
//1) initilize our Array to hold Integer Value: Boolean value to store value into hashTable
var numbersHashMap = [Int:Bool]()
//2) create placeHolder called number that iterates through our Array.
for number in array {
//3) variable = y - x
let match = targetSum - number
//4) ??
if let exists = numbersHashMap[match], exists {
//5) match = y / number = x
return [match, number] //
} else {
//6) Store number in HashTable and repeats
numbersHashMap[number] = true
}
}
return []
}
twoNumberSum([3,5,-4, 8, 11, 1, -1, -6], 10)
// x = Number
// y = Unknown *Solve for Y*
Sure, I can walk you through it. So we have a list of numbers, are we are trying to find two numbers that add together to make the specified target. To do this, for each number x, we check if (target - x) is in the list. If it is not, then we add x to the list. If it is, then we return x and (target - x).
Step 4 in your code is the part where we check if (target - x) is in the list. To see why this makes sense, let's walk through an example.
Say we have [2, 3, -1] and our target is 1. In this case, we first consider x = 2 and check our hashmap for (target - x) = (1 - 2) = -1. Since -1 is not in the hashmap, we add 2 to the hashmap. We then consider x = 3 and check for (1 - 3) = -2. Again, -2 is not in the hashmap, so we add it. Now we check x - -1. In this case, when we check (target - x) = (1 - (-1)) = 2, 2 is in the hashmap. Intuitively, we have already "seen" 2, and know that 2 and -1 can be added to get our value.
This is what provides the speed optimization over checking every two numbers in the list.

Why networkx list(g.edges) does not return int?

pair = list(g.edges()) print(pair)
Why is the result of the second node is not an 'int'?
result
I used firstnode = pair[a][0], secondnode = int(pair[a][1] for converting the number of the second node from a float to an int.
But I am still confused why it is float?
So I am not entirely sure how your code looks like, but since you have for all of the edges in your graph a float as the second number and you want to type it as an integer, I would suggest you to do this:
My code example:
import networkx as nx
# Create dummy graph
g = nx.Graph()
g.add_edge(1,2.0)
g.add_edge(5,4.3)
g.add_edge(8,3.9)
# Get list of all edges
pair = list(g.edges())
print(pair)
# Iterate through all edges
for a in range(len(g.edges())):
# Get first node of edge
firstnode = pair[a][0]
# Get second node of edge and type cast it to int
secondnode = int(pair[a][1])
# Print nodes / or execute something else here
print(firstnode,secondnode)
print()
And this is the output:
[(1, 2.0), (5, 4.3), (8, 3.9)]
1 2
5 4
8 3
I hope that helps!
I had the same question - to descibe my case - if I print my edges of nodes:
for edge in G.edges():
print(edge)
Gives:
('1', '11')
('1', '6')
('2', '2')
...etc
Meaning the nodes IDs were STRINGS not INT. SO for example, you would need:
print("Node {} has degree {}".format(node_id, G.degree[node_id]))
print("Node {} has degree {}".format('1', G.degree['i']))

Selecting min or max value of a list using ortools for python

I've been researching and learning about optimization in general, and ortools in particular, and I need help with understanding what it is I'm doing wrong with this simple problem using ortools.
The problem itself is simple (so simple that ortools should be overkill), but keep in mind this is just for learning the basics:
How to select the smallest (and largest) integer from a list of integers?
Here's the code I have.
# 1. A simple problem:
# Select the smallest number from a list of integers
from __future__ import print_function
from ortools.sat.python import cp_model
# Define data
cost_data = [
5, 4, 3, 6, 9, 12, 5, 9, 12, 14
]
num_hours = len(cost_data)
hours = range(num_hours)
# Create model
model = cp_model.CpModel()
# Create variables
cost_vars = [] # Keep variables for costs
pick_vars = [] # Keep variables for picked items (later we add a constraint for only selecting one pick)
for i in hours:
cost_vars.append(model.NewIntVar(0, 20, ''))
pick_vars.append(model.NewBoolVar(''))
# Create constraints
# Only one pick
model.Add(sum(pick_vars) == 1)
for i in hours:
model.Add(cost_vars[i] == cost_data[i]).OnlyEnforceIf(pick_vars[i])
# Set objective function
model.Minimize(sum(cost_vars)) # This works (returns 3)
# model.Maximize(sum(cost_vars)) # This doesnt work (returns 194 as objective value)
# Solve problem
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.INFEASIBLE:
print("INFEASIBLE")
elif status == cp_model.FEASIBLE:
print("FEASIBLE")
elif status == cp_model.OPTIMAL:
print("OPTIMAL")
print("ObjectiveValue()")
print(solver.ObjectiveValue())
This example works when I use the Minimize function, but if I replace Minimize with Maximize, it somehow returns 194 as the objective value.
What am I doing wrong?
What is happening right now is:
9*20+14 = 194
Because you are telling the solver that cost_var is only equal to your cost if it is picked, else it can be any integer between 0 and 20.
Edit:
the logic that you want is:
model.Add(cost_vars[i] == cost_data[i]).OnlyEnforceIf(pick_vars[i])
model.Add(cost_vars[i] == 0).OnlyEnforceIf(pick_vars[i].Not())
You should also take a look at AddMaxEquality and AddMinEquality

Testing a tensorflow network: in_top_k() replacement for multilabel classification

I've created a neural network in tensorflow. This network is multilabel. Ergo: it tries to predict multiple output labels for one input set, in this case three. Currently I use this code to test how accurate my network is at predicting the three labels:
_, indices_1 = tf.nn.top_k(prediction, 3)
_, indices_2 = tf.nn.top_k(item_data, 3)
correct = tf.equal(indices_1, indices_2)
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
percentage = accuracy.eval({champion_data:input_data, item_data:output_data})
That code works fine. The problem is now that I'm trying to create code that tests if the top 3 items it finds in indices_1 are amongst the top 5 images in indices_2. I know tensorflow has an in_top_k() method, but as far as I know that doesn't accept multilabel. Currently I've been trying to compare them using a for loop:
_, indices_1 = tf.nn.top_k(prediction, 5)
_, indices_2 = tf.nn.top_k(item_data, 3)
indices_1 = tf.unpack(tf.transpose(indices_1, (1, 0)))
indices_2 = tf.unpack(tf.transpose(indices_2, (1, 0)))
correct = []
for element in indices_1:
for element_2 in indices_2:
if element == element_2:
correct.append(True)
else:
correct.append(False)
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
percentage = accuracy.eval({champion_data:input_data, item_data:output_data})
However, that doesn't work. The code runs but my accuracy is always 0.0.
So I have one of two questions:
1) Is there an easy replacement for in_top_k() that accepts multilabel classification that I can use instead of custom writing code?
2) If not 1: what am I doing wrong that results in me getting an accuracy of 0.0?
When you do
correct = tf.equal(indices_1, indices_2)
you are checking not just whether those two indices contain the same elements but whether they contain the same elements in the same positions. This doesn't sound like what you want.
The setdiff1d op will tell you which indices are in indices_1 but not in indices_2, which you can then use to count errors.
I think being too strict with the correctness check might be what is causing you to get a wrong result.

find the two highest factors of a single number that are closest to each other

36-> 6*6 (not 9*4)
40-> 5*8 (not 10*4)
35-> 7*5
etc
I'm guessing something like:
candidate = input.square_root.round_to_nearest_int;
while (true){
test = input/candidate;
if (test.is_integer) return;
else
candidate.decrement;
}
Your approach does work.
If n = ab then a <= sqrt(n) <= b, hence if a,b are chosen so that b-a is minimized, it follows that a is the largest divisor of n which is less than or equal to the square root. The only tweak I would make to your pseudocode is to check the remainder and see if it is zero, rather than checking if the quotient is an integer. Something like (in Python):
import math
def closestDivisors(n):
a = round(math.sqrt(n))
while n%a > 0: a -= 1
return a,n//a
For example,
>>> closestDivisors(36)
(6, 6)
>>> closestDivisors(40)
(5, 8)
>>> closestDivisors(1000003)
(1, 1000003)
(since the last input is prime).