Confused about a program about finding factors - python-3.6

I was searching the web about finding factors and saw the one below
I was confused about it and wanted some help
I don't know what it means
This is for a project that we are making which is to make a game to find factors in which users have to input a number and the program will show the factors
I've tried putting
if ValueError:
print("Sorry, I didn't understand that.")
but it doesn't work, I wanted the program to say "Sorry, I didn't understand that." if the user typed a letter or special character
how do I loop it too if the user typed a letter or special character
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("Enter a number: "))
print_factors(num)
the program works but I can't seem to add loops and the value error thing on the top

You can use try catch block, and catch the valueError exception. Like below
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
try:
num = int(input("Enter a number: "))
print_factors(num)
except ValueError:
print("Sorry, I didn't understand that.");

Related

Unexpected behaviour adding two if(){}else{} constructs

Consider the following R input:
if(TRUE){1}else{0} + if(TRUE){1}else{0}
The result is 1, but I was expecting 2. If I enclose each if-else statement in parentheses,
(if(TRUE){1}else{0}) + (if(TRUE){1}else{0})
then the result is 2.
Can someone explain this behaviour?
The else clause doesn't end till R can identify the end of the expression. In R the {} aren't part of the syntax for if/else statements. The {} can be used anywhere you want to possibly put multiple statements. You can also do
if(TRUE) 1 else 0 + if(TRUE) 1 else 0
The {} aren't really meaningful. And since
0 + if(TRUE) 1 else 0
is a valid expression, R just assumes you wanted all of that for your else clause. Normally R will end the else clause when it encounters a newline after a completed expression. This means that
if(TRUE){1}else{0} +
if(TRUE){1}else{0}
will also return the same value because the + at the end of the first line indicates that there's more to come because a valid expression can't end in +.
Note you can see how the expression is turned into the abstract syntax tree with the help of the lobstr package if you are really curious.
#lobstr::ast(if(TRUE){1}else{0} + if(TRUE){1}else{0})
o-`if`
+-TRUE
+-o-`{`
| \-1
\-o-`+`
+-o-`{`
| \-0
\-o-`if`
+-TRUE
+-o-`{`
| \-1
\-o-`{`
\-0
Here we see that everything is nested in the first if. The + is not the main operator.
As you've done, you can use () or {} to end the expression blocks explicitly
{if(TRUE){1}else{0}} + {if(TRUE){1}else{0}}
Consider also the case of
x <- 5
if(FALSE) x+1 else x+2
# [1] 7
if(FALSE) x+1 else {x}+{2}
# [1] 7
Note how the x+2 is taken all together for the else expression. It doesn't end at the first symbol x.
Is has something to to with operator affinity which determines the order of evaluation. Like math, parenthesis have a higher priority than multiplications with have a higher priority than plus and minus. The second part of the expression will never get evaluated and thus ignored resulting in 1 e.g. if(TRUE){1}else{0} + message("I'll never get printed"). Including the parenthesis will force to first evaluate both parts seperatley and then do the plus resulting in 2.

Is there a consistent way to force errors on incorrect list or vector indexing

My expectation from other programming languages is that (1:4)[3:5] and list(asdf = 4, qwerty = 5)$asdg should both raise exceptions. Instead, the first silently returns c(3, 4, NA), and the second silently returns NULL (as does or list(asdf = 4, qwerty = 5)[[asdg]]).
While this sort of behavior can occasionally be useful, far more often (in my experience), it turns a minor typo, off-by-one error, or failure to rename a variable everywhere that it's used from a trigger for an immediate and easy-to-debug error, into a trigger for a truly baffling error about 20 (or 200) steps down the line, when the silently propagating NULLs or NAs finally get fed into a function or operation that is loud about them. (Of course, that's still better than the times that it doesn't produce an error at all, just garbage results.)
data.frame()[,'wrong'] gives an error, but data.frame()['wrong',] just returns NA.
What I'm looking for is a way to do vector/array/list/data.frame/etc. subscripting/member access that will reliably cause an error immediately if I use an index that is invalid. For lists, get('wrong', list()) does what I'm looking for, but that can be quite ugly at times (especially if using the result as for subscripting something else). It's usable, but something better would be nice. For vectors (and data.frame rows), even that doesn't work.
Is there a good way to do this?
I am not sure if you can change this behaviour globally but you can handle them on individual basis as needed based on type of the data.
For example, for vectors -
subset_values <- function(x, ind) {
if(min(ind) > 0 && max(ind) <= length(x)) x[ind]
else stop('Incorrect length')
}
subset_values(1:4, 3:5)
#Error in subset_values(1:4, 3:5) : Incorrect length
subset_values(1:4, -1:3)
#Error in subset_values(1:4, -1:3) : Incorrect length
subset_values(1:4, 1:3)
#[1] 1 2 3

What is the consistency steps of a recursive function?

I am finding inconsistency in recursive function examples, so I need help clarifying its workings.
This recursive function has the argument x value be returned along with function fracrec. This fracrec gets multiplied by the original value of x. The value of it is whatever the parenthesis gives x-1 . It repeats until it exits at x == 0. Meaning that the x portion and '*' of return is the "formula" and what is used for every round.
facrec <- function(x){
if(x==0){
return(1)
} else {
return(x*facrec(x-1))
}
}
Now take this next one and there isn't anything like x and ''. So I then look at it differently since myfibrec(5) gives '5'. Taking the absolute value of the first pass would be 4+3 and already surpassing 5 with more passes still to go. There isn't any formula to go off of, so I am having difficulty understanding how the 5 came about. In the above I used the formula to be 'x' and '', which I'll admit its odd and probably incorrect.
myfibrec <- function(n) {
if(n==1||n==2){
return(1)
}else{
return(myfibrec(n-1)+myfibrec(n-2))
}
}
In yet another one, below it treats the value in the argument as the formula. This gives 2,3,4,5,6,7,8,9,10.
function Count (integer N)
if (N <= 0) return "Must be a positive integer";
if (N >9 ) return "counting completed";
else return Count (N+1);
end function
Where are all the formulas or math calculations coming from in these recursive functions?
for 'facrec' google "factorial"
for 'myfibrec' google "Fibonacci"
last one seems to be java code, not R

Total Beginner: Python 3.4 spot the syntax error

When running the following code, I get an error as follows:
for (x in List[0] and y in range(0,11)):
^
SyntaxError: invalid syntax
I am very new to Python programming. When I try to run the iteration at the top I get the above error-message.
Could someone please kindly explain which part of the syntax is invalid?
The tiny arrow underneath seems to point to the colon.
Many thanks.
Syntax Error: The brackets are not necessary; use the following:
for x in List[0] and y in range(0, 11): ...
More Problems Although as in my comment, this won't necessarily work.
Merging the Arrays:
If you are trying to go through all values in List[0] and then in range(0, 11), do the following:
for x in (List[0] + range(0, 11)): ...
No Duplicates:
Or, if you want no duplicates, and ordering does not matter, use this:
for x in list(set(List[0] + range(0, 11))): ...
Going through all pairs:
Or, if you are trying to go through all pairs consisting of a value in List[0] and a value in range(0, 11), use the following:
for x in List[0]:
for y in range(0, 11):
...

dynamic programming pseudocode for Travelling Salesman

this is a dynamic programming pseudocode for TSP (Travelling Salesman Problem). i understood its optimal substructure but i can't figure out what the code in red brackets do.
i am not asking anyone to write the actual code, i just need explanation on what is happening so i can write my own.... thanks:)
here is a link for the pseudocode, i couln't uploaded over here.
http://www.imagechicken.com/viewpic.php?p=1266328410025325200&x=jpg
Here is some less mathematical pseudo-code. I don't know if this will explain what's happening, but it may help you read it. This isn't a functional algorithm (lots of := all over), so I'm going to use Python pseudo-code.
# I have no idea where 'i' comes from. It's not defined anywhere
for k in range(2,n):
C[set(i,k), k] = d(1,k)
shortest_path = VERY_LARGE_NUMBER
# I have to assume that n is the number of nodes in the graph G
# other things that are not defined:
# d_i,j -- I will assume it's the distance from i to j in G
for subset_size in range(3,n):
for index_subset in subsets_of_size(subset_size, range(1,n)):
for k in index_subset:
C[S,k] = argmin(lambda m: C[S-k,m] + d(G,m,k), S - k)
shortest_path = argmin(lambda k: C[set(range(1,n)),k] + d(G,1,k), range(2,n))
return shortest_path
# also needed....
def d(G, i, j):
return G[i][j]
def subsets_of_size(n, s): # returns a list of sets
# complicated code goes here
pass
def argmin(f, l):
best = l[0]
bestVal = f(best)
for x in l[1:]:
newVal = f(x)
if newVal < bestVal:
best = x
bestVal = newVal
return best
Some notes:
The source algorithm is not complete. At least, its formatting is weird in the inner loop, and it rebinds k in the second argmin. So the whole thing is probably wrong; I've not tried to run this code.
arguments to range should probably all be increased by 1 since Python counts from 0, not 1. (and in general counting from 1 is a bad idea).
I assume that G is a dictionary of type { from : { to : length } }. In other words, an adjacency list representation.
I inferred that C is a dictionary of type { (set(int),int) : int }. I could be wrong.
I use a set as keys to C. In real Python, you must convert to a frozen_set first. The conversion is just busywork so I left it out.
I can't remember the set operators in Python. I seem to remember it uses | and & instead of + and -.
I didn't write subsets_of_size. It's fairly complicated.

Resources