I am trying some stuff on the 3x+1 problem and noticed when I check if this num is divisible by two comes always true even that the second iteration should be false it goes like this for 20 iterations and then start to act right. I guess it is a long number issue?
num = 3656565605161651626526625291991265161656
while num != 1:
if (num % 2 == 0):
num /= 2
print("2")
else:
num *= 3
num += 1
print("3")
num2=f'{num:.1f}'
print(num2)
Here is the start of the result:
2
1828282802580825918440824287108404346880
2
914141401290412959220412143554202173440
2
457070700645206479610206071777101086720
2
You need to use integer division, not float.
num //= 2
Here are the first 20 lines of the output, where you can see it is working:
2
1828282802580825813263312645995632580828
2
914141401290412906631656322997816290414
2
457070700645206453315828161498908145207
3
1371212101935619359947484484496724435622
2
685606050967809679973742242248362217811
3
2056818152903429039921226726745086653434
2
1028409076451714519960613363372543326717
3
3085227229355143559881840090117629980152
2
1542613614677571779940920045058814990076
2
771306807338785889970460022529407495038
Related
def fact(n):
f=1
for num in range(1,n+1):
if num==0:
return 1
else:
f=f*num
print(num,f)
n=int(input())
fact(n)
#here is my code, but the output should be
0 0
1 1
2 2
3 6
4 24
5 120
6 720
instead of
1 1
2 2
3 6
4 24
5 120
6 720
Can you tell me what is wrong and what should I add to the code?
0, 0 can't really be part of the factorial because then all following numbers would have to be multiplied by 0, making them all zero. I guess you could just print it out first.
def fact(n):
f=1
print(0, 0)
for num in range(1,n+1):
f=f*num
print(num,f)
n=int(input())
fact(n)
Taking for granted that 0! = 1 and 1! = 1, then you already have the two first numbers of your sequence. So you can multiply by num+1 to avoid multiplying by zero. Then you take your output before doing the next multiplication.
def fact(n):
f=1
for num in range(n+1):
print(num,f)
f=f*(num+1)
fact(5)
0 1
1 1
2 2
3 6
4 24
5 120
You can also create a lookup table if you want:
def fact(n):
FACT=[]
f=1
for num in range(n+1):
FACT += [f]
f=f*(num+1)
return FACT
F = fact(n)
F[0]
>>> 1
F[4]
>>> 24
range should start from 0, hence range(0, n+1) or just range(n+1) because in your code the condition is never hit
when the condition is hit you should have a print: print(0, 0)
def fact(n):
f=1
for num in range(0,n+1):
if num==0:
print(num, num) # num is just 0
else:
f=f*num
print(num,f)
Remarks:
the return is really needed? it is always 1 independently from n
0! = 1 by definition. Maybe print(0, 1)?
I am trying to create a for loop and I want the output to be this:
0 is even.
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
And all I have gotten this far:
my_range=range(0,11)
for i in my_range:
print(i)
and the output is all the numbers:
0
1
2
3
4
5
6
7
8
9
10
You just need to do is, change your print function as -
print(i," is", 'even.' if (i % 2 == 0) else 'odd.')
What you need to use here is conditional statements along with 'String Interpolation' in python.
The Below code will give you the desired output:
my_range=range(0,11)
for i in my_range:
if i%2:
print("{} is odd".format(i))
else:
print("{} is even".format(i))
I'm quite new in Python. I have searched on site but I couldn't find solution for that pease show me if I missed.
I am trying to understand loops and "and" "or" I did some experiment with these elements but I confused.
Bellow code I was expecting code pass the numbers which isn't dividable by 3 or 5 and print rest. But suprisingly It print the numbers which is dividable by 15! (other words which is dividable by 3 and 5)
for x in range(100):
if x % 3 != 0 or x % 5 != 0:
continue
print(x)
output:
0
15
30
45
60
75
90
And this one I was expecting it will pass the number which isn't dividable 3 and 5 But it prints the numbers which is dividable 3 or 5 as I wanted in my first example.
for x in range(100):
if x % 3 != 0 and x % 5 != 0:
continue
print(x)
output:
0
3
5
6
9
10
12
15
18
20
.............
I don't understand what I am missing. I'm aware that I can make it happen with if, elif and else form but I wanted to learn more about "continue" usage. I'd appereciate if you help me.
Thank you!
You may have an easier time understanding what's happening just by walking through the numbers and seeing what your logic does for each number. You have walked into a logic equivalence that can be confusing, and is expressed in De Morgan's Laws. Essentially you can say
(x % 3 != 0 or x % 5 != 0) = !(x % 3 == 0 and x % 5 == 0)
so your first logic test is checking whether a number is divisible by both 3 and 5, which are the multiples of 15. And your second test is
x % 3 != 0 and x % 5 != 0 = !(x % 3 == 0 or x % 5 == 0)
so you are testing whether a number is divisible by either 3 or 5.
The continue keyword will essentially end the current iteration of the loop, and jump directly to the start of the loop to re-evaluate the loop condition (see https://docs.python.org/3.8/tutorial/controlflow.html).
So, in your first block of code, any time x is not divisible by 3 or 5, it will not print the number, meaning the only numbers which are printed are those which are divisible by both 3 and 5.
You can clear up the or logic like this:
for x in range(100):
if x % 3 != 0: # skip 1,2,4,5,7,8,10,11,13,14,16....
continue
if x % 5 != 0: # skip 1,2,3,4,6,7,8,9,11,12,13,14,16...
continue
print(x) # only numbers that pass both checks 0,15,30,...
With this, only 0, 15, 30, ... get through
If you convert it with boolean algebra,
if x % 3 != 0 or x % 5 != 0:
is the same as
if x % 3 == 0 and x % 5 == 0:
which gives the same results (0,15,30,...)
while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
In this question I had to create a program that prompts the user for a number and then prompt again for how many rows to create. Something like:
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
This is what I came up with and I have tried many different ways to get the same result but it didn't work.
num=int(input("Enter a number between 1 and 10: "))
rows=int(input("Enter how many rows to of numbers: "))
for i in range(num):
print(i,end=" ")
for x in range(rows):
print (x)
This is the output I came up with:
Enter a number between 1 and 10: 6
Enter how many rows to of numbers: 4
0 1 2 3 4 5 0
1
2
3
You may simply do it like:
num = 5
rows = 4
for i in range(1, num+1):
print('{} '.format(i) * rows)
Output:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
Explanation: When you multiply a str with some number say n, new string is returned with original string repeated n times. Doing this you will eliminate your nested loop
Simple solution: Just use nested for loops:
num = int(input("Enter a number between 1 and 10: "))
rows = int(input("Enter how many rows to of numbers: "))
for i in range(num):
print ('\n')
for x in range(rows):
print (i + 1)
The code above will go through the range 0 to num, printing first a new line and then printing the current number rows times.
rows = 5
side = int(input("Please Enter any Side of a Square : "))
for i in range(side):
for j in range(side):
if(i == 0 or i == side - 1 or j == 0 or j == side - 1):
print(i, end = ' ')
else:
print(i, end = ' ')
print()