Why is the output always the same? - python

My task is to check whether or not a number's (maximum eight digits) individual digits cubed will equal the number inputted (has to remain as a string). For example, 215 would return 2 x 2 x 2 + 1 x 1 x 1 + 5 x 5 x 5 = 134 (not true).
371 = 3 x 3 x 3 + 7 x 7 x 7 + 1 x 1 x 1 = 371 (true)
The program is to continue forever until an input of 0 is made. I understand that I have to make a function before the main program. But my program never breaks even if I enter 0...
def sum_of_cubes(num):
num_string = str(num)
sum = 0
for i in num_string:
digit = int(i)
cube = digit * digit * digit
sum = sum + cube
return sum
def main():
while True:
number = input("Enter a number (max 8 digits): ")
result = sum_of_cubes(number)
print(result)
number_result= str(result)
if result == number:
print("Yes")
if result!= number:
print("No")
if number=='0':
break
main()

You should add the cubed numbers to the sum inside the for loop.
you currently have it outside, so it will add only the last digit's cubed number.
try this:
.
.
.
sum = 0
for i in num_string:
digit = int(i)
cube = digit * digit * digit
sum = sum + cube
return sum

Related

Collatz Conjecture in Python for N inputs

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:
...

Reading in a positive int and transform every digit of that number in an even-odd way

So what I need to do is read in a number and transform every digit.
add 2 to an odd digit
subtract 3 from an even digit (watch out for negative numbers!)
zero stays 0
input
14502
wanted output
31701
Current output
14504
Below is what I have for now, I can read every digit in a for loop but I don't know how to transorm them one by one.
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
ALSO NO IMPORTS
num = input("Enter a number:")
new_num = []
single_number = ''
for digit in num:
digit = int(digit)
if digit == 0:
new_num.append(digit)
elif (digit % 2)!=0:
digit = digit+2
new_num.append(digit)
elif (digit % 2)==0:
digit = digit-3
if digit>=0:
new_num.append(digit)
else:
digit = digit*(-1)
new_num.append(digit)
print(new_num)
# for single int instead of array
for digit in new_num:
digit = str(digit)
single_number = single_number+digit
print(single_number)
new_number is array of digits single_number is the final number you want.
is your code missing the indent after the for loop? I know that may not solve the question but is that another issue with your code or just a formatting issue here on stack?
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num + 2)
else:
print(num - 3)
num = int(input("Enter a number:"))
print(len(str(num)))
finaloutput = []
for i in range(len(str(num))):
digit = num%10
if digit%2==0:
if digit - 3 < 0:
digit = 0
else:
digit = digit - 3
else:
digit = digit + 2
finaloutput.append(digit)
num = num //10
print(finaloutput)
string=""
for i in range(len(finaloutput)):
string = string + str(finaloutput[i])
print(string[::-1])
Might be a big scuffed but gets the job done. Substract 3 from even, add 2 to odds, and watch for zeros.
output:
Enter a number:14502
5
[0, 0, 7, 1, 3]
31700
I put it so if an even number sub 3 is less than zero it jus stays zero, bc thats how I understood it. You can easily modify the code to suit your need and in accordance with your task or whatever
Try:
num = 9876543210
l = [int(c) for c in str(s)]
l = [min(c, 7) + 2 if c % 2 else max(c, 4) - 3 if c != 0 else c for c in l]
out = int(''.join(str(c) for c in l))
Output:
>>> out
9593715130
Details:
9 -> 9 (else 12)
8 -> 5 (-3)
7 -> 9 (else 10)
6 -> 3 (-3)
5 -> 7 (+2)
4 -> 1 (-3)
3 -> 5 (+2)
2 -> 1 (else -1)
1 -> 3 (+2)
0 -> 0 (do nothing)
A simple implementation based on your solution. It can only handle integers though. And there is one case which you have not specified which is
what to do when the digit is 9? As 9 + 2 = 11 and 11 is not a digit but could well be what you want in your algorithm?
In this implementation 9 is turned to 1.
def calc_on_digits(num: str):
result: str = ""
for digit in num:
digit = int(digit)
if digit == 0:
result += "0"
continue
if digit % 2 == 0:
# in case it get negative take the absolute value
digit = abs(digit - 3)
else:
digit += 2
# in case its 9 the result would be 11 -> make it one
digit = digit % 10
result += str(digit)
return result
# string in this implementation can only contain valid integer values
print(calc_on_digits("14502"))
You cannot calculate modulo from string. Also you have to perform the comparison per digit, not for the whole number.
num = input("Enter a number:") # no need to cast to int just to transform back to str below
new_number = ""
for digit in num:
digit = int(digit)
print(digit)
if (digit % 2) = 0:
tmp = digit + 2
if tmp >= 10:
tmp = 0
else:
tmp = digit - 3
if tmp < 0:
tmp = 0
new_number += str(tmp)

Need to match exact decimal output Python

The German mathematician Gottfried Leibniz developed the following method to approximate the value of π:
π/4 = 1 - 1/3 + 1/5 - 1/7 + . . .
Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting value.
An example of the program input and output is shown below:
Enter the number of iterations: 5
The approximation of pi is 3.3396825396825403
iteration = int(input("Enter the number of iteration: "))
list01 = []
list02 = []
y = 1
for x in range(1, iteration+1):
number = (1.0/y)
list01.append(number)
y += 2.0
#print(number)
for i in range(1, iteration, 2):
neg = list01[i]*-1.0
list02.append(neg)
#print(neg)
comb = (sum(list01)) + (sum(list02)) + (sum(list02))
pi = comb*4.0
print("The approximation of pi is", pi)
With this code for:
1 iteration, output is 4.0 which matches the required output of 4
5 iteration, output is 3.339682539682539 which doesn't match the required output of 3.3396825396825403
10 iteration, output is 3.0418396189294015 which doesn't match the required output of 3.0418396189294032
999 iteration, output is 3.1425936543400352 which doesn't match the required output of 3.142593654340044
"""pure step by step Leibniz idea
'sign'-- sign switcher. If you need the sum of even divisors
summ +1/1 (n=0), +1/5 (n=2), +1/9 (n=4), sign is True.
With each odd divisible, 'sign' changes to False, changing the
sign of the next term, summ -1/3 (n=1), -1/7 (n=3), -1/11 (n=5), etc..
"""
iteration = int(input("n: "))
presumm = 0
div = 1
sign = True
for i in range(iteration):
presumm = presumm + 1 / div if sign else presumm - 1 / div
div += 2
sign = not sign
pi = presumm * 4
print(pi)
# n==5, output: 3.3396825396825403
# n==10, output: 3.0418396189294032
# n==999, output: 3.142593654340044
iterations = int(input("Enter the number of iterations: "))
answer = 0
d = 1
pos = True
for f in range(iterations):
if pos:
answer += 1 / d
pos = False
else:
answer -= 1 / d
pos = True
d += 2
final = 4 * answer
print("The approximation of pi is " + str(final))
For an alternating sum, the "floating point error" should be small as can be starting from the small end:
# π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
def leibniz(n_terms):
""" Return pi as per alternating sum of n_terms odd stem fractions. """
if n_terms <= 0:
return 0
sum = .0
for stem in range(n_terms * 2 - 1, 0, -2):
# print(sum, float(1-(stem&2))/stem)
sum += float(1-(stem&2))/stem
return 4 * sum

Weird output when looking for sum of factorial of digits in smallest number == the given number

#Function factorial
def fact(d):
f=1
for i in range(d,0,-1):
f=f*i
print(f"factorial {f}")
return f
#Function for summation of factorial of digits
def f(n):
s=0
d=n%10
s=fact(d)+s
n=int(n/10)
print(f"summing {s}")
return s
l=[]
q=int(input("enter number of queries"))
print(q)
n=int(input("enter the number to which you want to calculate"))
m=int(input("enter range"))
for i in range(1,n+1):
l.append(i) #adding elements from 1 to n in list
print(l[i-1])
for j in range(1,m+1):
p=f(j)
if(l[i-1]==p):#element in list is equal to function (i.e sum of factorial of digits)
l[i-1]=p #then assign p to list
print(f"list {l[i-1]}")
break #then break the second loop
Like for eg:
For query 1
n= 3 and m=100
Till 1 to n
look in m for numbers whose sum of factorial of digits is equal to number in n
For eg :
5=25 ( as 2! + 5! = 2+ 120 = 122
1+2+2=5)
Then break for the next i iteration but I don't know where I'm making the mistake.
Goal: Find the smallest x such that the sum of digits of the factorials of the digits of x is n.
Sample behavior:
Find the smallest x such that:
the sum of digits of the factorials of the digits of x is n
Please provide n: 12
Please provide the maximal x to check: 10000
Trying 1:
Sum of the digits of factorials of the digits of 1 is:
digit_sum(1!)
= digit_sum(1)
= 1
...
Trying 4:
Sum of the digits of factorials of the digits of 4 is:
digit_sum(4!)
= digit_sum(24)
= 6
...
Trying 16:
Sum of the digits of factorials of the digits of 16 is:
digit_sum(1!) + digit_sum(6!)
= digit_sum(1) + digit_sum(720)
= 10
...
Trying 33:
Sum of the digits of factorials of the digits of 33 is:
digit_sum(3!) + digit_sum(3!)
= digit_sum(6) + digit_sum(6)
= 12
x is 33.
Source code:
import math
def print_sum_eq(x):
print(f" Sum of digits of the factorials of the digits of {x} is:")
msg1 = [f"digit_sum({d}!)" for d in str(x)]
print(" " + " + ".join(msg1))
msg2 = [f"digit_sum({math.factorial(int(d))})" for d in str(x)]
fact_values_str = " + ".join(msg2)
print(f" = {fact_values_str}")
def digit_sum(x):
return sum(int(d) for d in str(x))
def sum_fact_digit(x):
"""Calculate sum of factorials of the digits of x
For example, when x = 25, the digits are 2 and 5. The sum of the
factorials of the digits is 2! + 5! = 2 + 120 = 122.
Parameters
----------
x : int
Returns
-------
digit_sum : int
Sum of the factorials of the digits of x
"""
s = 0
print_sum_eq(x)
# Loop over the digits of x
for d in str(x):
digit = int(d)
digit_fact = math.factorial(digit)
s += digit_sum(digit_fact)
print(f" = {s}")
return s
def search(n, max_x=None):
"""Try to find x such that sum of factorials of the digits of x is n
Parameters
----------
n : int
max_x : int, optional
The function will search over x = 1, 2, ..., max_x
Returns
-------
result : int or None
If we find x, the result is x.
If we can't find x, the result is None.
"""
if max_x is None:
max_x = int(10 ** n)
for x in range(1, max_x + 1):
print(f"Trying {x}:")
sum = sum_fact_digit(x)
if sum == n:
return x
return None
def main():
print("Find the smallest x such that:")
print(" the sum of digits of the factorials of the digits of x is n")
n = int(input("Please provide n: "))
max_x = int(input("Please provide the maximal x to check: "))
x = search(n, max_x=max_x)
if x is None:
print("Cannot find such a x.")
else:
print(f"x is {x}.")
main()

Python function to check if credit card number is a valid number using for loops

So this is a cs assignment, and I wrote code that works for 2 out of the 9 test cases (which are unknown), but I don't know why it won't work/pass any other ones. I understand I should try to figure out how to do this on my own, and I have tried, but I am really lost and need help!
"Write a file named credit_card.py containing a single function, check. Check accepts a single input – a positive integer. It returns True if the integer represents a valid credit card number. As with all functions that return a bool value, if it does not return True it should return False.
Credit card numbers have what is called a check digit. This is a simple way of detecting common mis-typings of card numbers. The algorithm is as follows:
Form a sum of every other digit, including the right-most digit; so 5490123456789128 (5490123456789128) sums to 4 + 0 + 2 + 4 + 6 + 8 + 1 + 8 = 33.
Double each remaining digit, then sum all the digits that creates it; the remaining digits (5 9 1 3 5 7 9 2) in our example (5490123456789128) double to 10 18 2 6 10 14 18 4, which sums to 1+0 + 1+8 + 2 + 6 + 1+0 + 1+4 + 1+8 + 4 = 37
Add the two sums above (33 + 37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number."
def check(x):
num1 = 0
num2 = 0
if x < 0:
return False
for i in str(x) [1::2]:
num1 += int(i)
return num1
for i in str(x) [0::2]:
num2 += int(int(i * 2) % 10) + int(int(i * 2) / 10)
return num2
check_digit = num1 + num2
if check_digit % 10 == 0:
return True
else:
return False
def check(x):
if x[0] == '-': # x is [str], "x < 0" is wrong
return False
try:
nums = map(int, x)
except Exception:
return False
sum1 = 0
sum2 = 0
for i in nums[1::2]:
sum1 += int(i)
for i in nums[0::2]:
sum2 += ((i * 2) % 10 + (i * 2) / 10) # i is [str], "i * 2" is wrong
check_digit = sum1 + sum2
if check_digit % 10 == 0:
return True
else:
return False

Categories

Resources