This is my first time using Stack Overflow. I will try my best to be as clear as I can be. I need to write a code that returns my initial number, the number of even values, the number of odd values and the biggest value for each N I input. My issue with this is: I have at least two entries: N, number of values my program will receive, and X, the number itself (for N = 1, for example). When I finished my code, I noticed that for N > 1 the number of even and odd numbers are stacking, but the biggest number for each sequence is correct.
For N = 2, X = 9 and X = 15, the output is:
Initial value: 9
Even numbers: 13
Odd numbers: 7
Biggest number: 52
Initial value: 15
Even numbers: 25
Odd numbers: 13
Biggest number: 160
Any idea of why this is happening? Here is my code:
N = int(input())
EVEN = 0
ODD = 0
for i in range(N):
X = int(input())
print("Initial value: ", X)
MAX = X
while = True
if X % 2 == 0:
EVEN = EVEN + 1
X = X / 2
elif X == 1:
ODD = ODD + 1
break
elif X % 2 == 1:
ODD = ODD + 1
X = (3 * X) + 1
if X > MAX
MAX = X
print("Even numbers: ", EVEN)
print("Odd numbers: ", ODD)
print("Biggest number: ", MAX)
As mentioned in the comments, you forgot to reset the even/odd counters at every step of the for loop. It should work like this:
...
for i in range(N):
EVEN = 0
ODD = 0
X = int(input())
print("Initial value: ", X)
MAX = X
while True:
...
Related
def myfunc():
number = int(input('Enter a number : '))
x = 3
d = [2]
g = []
while 0<=number<=1:
return 'There is no prime number'
while 0>number:
return 'There is no prime number'
while number == 2:
return 'Prime number : 2 '
while x<=number:
for y in range(3,x,2):
if x%y == 0:
x += 2
break
else:
d.append(x)
x += 2
for c in d:
if number%c == 0:
g.append(c)
else:
pass
return max(g)
myfunc()
Input:
600851475143
I typed that and my function didn't respond to me.
This is the code that I am running. No problem is coming up, but it doesn't give me an answer either. I can't find the problem.
You have too many loops and it runs very, very long.
If you want to get only max value which divides number then you can find min value which divides number - ie. x - and number // x gives you max value which divide number.
Also you don't have check all values but only to math.sqrt(number)
which you can also write as number**0.5
def myfunc():
number = int(input('Enter a number : '))
if number <= 1:
return 'There is no prime number'
if number == 2:
return 'Prime number : 2 '
if number % 2 == 0:
return number // 2
for x in range(3, int(number**0.5), 2):
if number % x == 0:
return number // x
return number # prime
myfunc()
And now 600851475143 gives result 8462696833 in few milliseconds.
because
8462696833 = 600851475143 / 71
so it has to check only ~36 numbers: 2 and 3, 5, 7, 9, ... ,71
I'm having trouble trying to
compute x * y using only addition, printing the intermediate result for each loop iteration, and
printing the final number. This is my
teacher's example of what the output should look like
I could really use some help figuring it out,, I don't really understand how to yet.
Edit: I am a first time coder so I'm not very skilled, I do know the basics though (Also very new to this website) Here's what my code looks like so far:
x = int(input("Input positive x: "))
y = int(input("Input positive y: "))
z = 0
w = 0
if x < 0:
exit("Please input a positive number for x")
if y < 0:
exit("Please input a positive number for y")
def multiplier(number, iterations):
for i in range(1, iterations):
number = number + 3
print(number) # 12
multiplier(number=3, iterations=4)
My answer. Little shorter than the others.
Ok, try thinking of multiplication as adding a number with itself by x times. Hence, 3*4 = 3+3+3+3 = 12, which is adding 3 by itself 4 times
Replicating this with a for loop:
#inputs
x = 3
y = 4
#output
iteration = 1
result = 0
for num in range(4):
result += x
print(f'Sum after iteration {iteration}: {result}')
iteration += 1 #iteration counter
The resulting output will be:
Sum after iteration 1: 3 Sum after iteration 2: 6 Sum after iteration
3: 9 Sum after iteration 4: 12
The code is simple and straightforward,Check which number is bigger and iterate according to that number.
x = 3
y = 4
out = 0
if x > y:
for v in range(0,x):
out += y
print("after iteration",v+1, ":", out)
if y > x:
for v in range(0,y):
out += x
print("after iteration",v+1, ":", out)
print(x,"*", y, "=", out)
Use print to print inside the loop to show each number after adding and the number of iteration occurs.
Here is a start. This assume both arguments are integers 0 or more:
def m(n1, n1a):
n1b = 0
while n1a > 0:
n1b += n1
n1a -= 1
return n1b
n = m(9, 8)
print(n == 72)
I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9
I have some code where I must find the multiples of number 3 and then summarize them
I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found.
I have tried so many times and tried to find the solution on google, but could not find
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them
It's easier than you think:
sum(range(0, 1000, 3))
Explanation:
range is defined as such: range([start], end[, step]) so range(0, 1000, 3) means go from 0 to 1000 in steps of 3
The sum function will sum over any iterable (which includes range)
You need a variable to hold the sum (If you are in learning stage):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit:
To answer your comment use condition or condition:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result variable to which you can keep adding:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter and sum:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)
I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
It freezes up without showing an error message, and I have no clue why this happens.
1) You are invoking range() incorrectly.
Your code: for n in range(max - min): produces the range of numbers starting at 0 and ending at the value max-min. Rather, you want the range of numbers starting at min and ending at max.
Try this:
for n in range(min, max):
2) You are performing floating-point division, but this program should use only integer division. Try this:
num = num // 2
3) You are updating the count variable in the wrong loop context. Try indenting it one stop.
4) Your final line could be:
print('Number: '+str(n)+' Steps needed: '+str(count))
Program:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
Result:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5
It looks like it's getting stuck in the while not num == 1 loop. Remember that range() starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.
EDIT: I earlier said that count = 0 needed to be moved. Actually, looking more carefully it seems like the line count = count + 1 line just needs to be moved under the while loop.