I want to represent a user entered number in expanded form.
For eg: user_input = 12345
Output = 1 * 10000 + 2 * 1000 + 3 * 100 + 4 * 10 + 5 * 1
iterate through the string form of the number backwards, use the place of the number to get the power of 10, add to result, then join reversed result using pluses
user_input = 12345
result = []
for i, num in enumerate(str(user_input)[::-1]):
result.append(f'{num} * {10 ** i}')
print(' + '.join(result[::-1]))
Related
Ok, so I am trying to make a program that implements the main() function to make a random addition equation when it is called, using numbers up to 3 digits. This is what I have so far:
def main():
import random
# Generating random 3 digit number
num1 = random.randint(1,1000)
num2 = random.randint(1,1000)
#Displying the three digit numbers
print(" ",num1)
print("+",num2)
answer = num1 + num2
user_answer = int(input("Enter sum of numbers: "))
if user_answer == answer:
print("Correct answer - Good Work!")
else:
print("Incorrect... The Correct answer is:", + answer)
main()
The thing I am having issues with is the formatting for the generated numbers. Since they are random, you could generate something like 375 + 67, which would make the output like this:
375
+ 67
Enter sum of numbers:
The immediate issue here is that it isn't aligned with the right place, so it is difficult to do addition. I want it to be aligned in the correct place like this:
375
+ 67
Enter sum of numbers:
Is there an argument in the format function that lets me align it correctly using a blank space like ' '?
If you want the overall width of the equation to be dynamic based on the "widest" number:
a, b = random.sample(range(1, 1001), k=2)
ans = a + b
a, b = map(str, (a, b))
w = max(map(len, (a, b)))
print("{}\n+ {}".format(a.rjust(w + 2), b.rjust(w)))
In the above snippet, the w + 2 accounts for the extra space produced by the plus sign and a single whitespace to its right which will always be present on the bottom row: '+ '.
Some sample outputs:
196
+ 301
7
+ 9
1000
+ 598
1000
+ 1000
487
+ 76
7
+ 676
If instead you want a fixed width so that all equations are the same width no matter how many digits are in the "widest" number:
a, b = random.sample(range(1, 1001), k=2)
ans = a + b
a, b = map(str, (a, b))
w = 4 # 4 digits in 1000, the max
print("{}\n+ {}".format(a.rjust(w + 2), b.rjust(w)))
Output:
196
+ 301
4
+ 8
1000
+ 598
1000
+ 1000
478
+ 76
7
+ 682
Try right-aligning the outputs using string formatting. The general syntax would be f"{yourValue:>width}".
print(f"{num1:>2}")
print(f"+ {num2:>2}")
The question is as follows:
Users needs to input 3 numbers within the lists and according to the numbers entered, you need to put them in the equation and get the result (with using functions for equation). In the last part ı wanted to show full equation and result together
equation right here q = ((2 * n1 * n2) / (n3) ** 1 / 2)
I did this
def sum (myList=[]):
for x in myList:
q = float(((2 * myList[0] * myList[1]) / myList[3]) ** 1 / 2)
round(q)
print("q=(2*" + str(myList[0]) + "" + str(myList[1]) + ")/" + str(myList[3]) + "*1/2" +"= "+
str(q))
mylist=[]
item = int(input("Enter your Item to the List n1,n2,n3: "))
mylist.append(item)
sum(mylist)
and ım getting this error:
ValueError: invalid literal for int() with base 10: '100,75,80'
input() returns a string and you can't parse the string to int when there is ','. You can use this to split numbers:
def sum (myList=[]):
for x in myList:
q = float(((2 * myList[0] * myList[1]) / myList[3]) ** 1 / 2)
round(q)
print("q=(2*" + str(myList[0]) + "" + str(myList[1]) + ")/" + str(myList[3]) + "*1/2" +"= "+
str(q))
mylist=[]
item = list(map(int,input("Enter your Item to the List n1,n2,n3: ").split(','))
mylist.extend(item)
sum(mylist)
There is an error in handling the input.
input() reads an entire line as a string. If you want to pass three comma separated numbers, you could do something like:
mylist = [*map(int, input().split(','))]
your code would look something like:
def sum (myList):
q = float(((2 * myList[0] * myList[1]) / myList[2]) ** 1 / 2)
round(q)
print("q=(2*" + str(myList[0]) + "" + str(myList[1]) + ")/" + str(myList[2]) + "**1/2" +"= "+ str(q))
mylist = [*map(int, input("Enter your Item to the List n1,n2,n3: ").split(','))]
sum(mylist)
I'm trying to hone my Python 3 (specifically, nested loops) with the good old triangle exercises (which only takes an odd input for now). However, I have come across a problem I can't warp my head around with.
user_input = 7
x = 1
temp = user_input
spaces = " "
stars = ""
y = temp - 2
t = 0
while x < temp:
while y > t:
stars = "*" * x
spaces = spaces * y
print(spaces + stars)
spaces= " "
y -= 1
x += 2
I have a user_input (which is 7 for now so I don't have to give an input each time I run).
A variable x and t used for the while loop
Another temporary variable that holds my user_input (in case I decrement it as not to 'damage' the original variable).
A variable spaces and another variable stars (which should be self explanatory as I'm trying to draw a triangle based on asterisks).
I have a variable y which is equal to temp - 2
Expected output of 7 should be like this:
*
***
*****
*******
The reason I have made y equal to temp - 2 is because the first row has spaces equal to user_input - 2.
So let's say our input was 7, first row's amount of spaces is 5.
If our input is 9, first row's amount of spaces is 7
The first while loop will loop from 1 to 7 (1, 3 , 5, 7) which is why I made x equal to 1.
The second while loop should loop from input - 2 until 0.
Weird thing is, that if my user_input is equal to 5, it outputs just how I expected it to be.
*
***
*****
But once I enter something like 7, it builds a triangle from 1 to 9 (1, 3, 5, 7, 9)
*
***
*****
*******
*********
But I expect it to end right before the last row, it should output as many asterisks as my input.
Is my thought process wrong? If so, where did I end up wrong?
I hope I have clarified everything as much as possible.
Thanks a bunch.
Seems overly complicated. Why not just:
input = 7
i = 1
while i <= input:
spaces = ' ' * ((input-i) // 2)
stars = '*' * i
print(spaces + stars)
i += 2
*
***
*****
*******
Or even simpler, using str.center:
while i <= input:
print(('*' * i).center(input))
i += 2
Let's clarify a bit your code a bit :
t is useless since it holds only 0 and never changes, use 0 instead
user_input is never used except to make temp = user_input, use user_input instead of temp. As for decrementing it, it doesn't happen, and anyway you never return it to the user so it would be ok.
that's kind of a typo so it's ok, but avoid letting your debugging prints like print(x,y) when you show some code on Stack Overflow, it's harder for us to understand the whole code.
If you change back spaces = " " at the end of the while, just use spaces = " " * y.
You do nothing between the two while so you can "merge" them with an and on conditions.
So now we have :
user_input = 9
x = 1
y = user_input - 2
while x < user_input and y > 0:
stars = "*" * x
spaces = " " * y
print(spaces + stars)
y -= 1
x += 2
As you can see, you have two stopping conditions on your while when only one would be clearer. The reason behind your code works with 7 and not more is because 7 is the limit between when one condition stops loop and when the other does.
I would suggest to change your code to :
user_input = 3
x = 0
while x < user_input//2:
stars = "*" * (x * 2 + 1)
spaces = " " * (user_input//2 - x)
print(spaces + stars)
x += 1
There is a bug in your code. Here is the rectified code.
user_input = 7
x = 1
temp = user_input
spaces = " "
stars = ""
y = temp - 2
t = 0
while x <= temp:
stars = "*" * x
spaces = spaces * y
print(spaces + stars)
spaces= " "
y -= 1
x += 2
It is not necessary to check y>0 since your first while loop is enough to meet the requirement. Because of that extra while loop you are getting ambiguous values of (x,y).
The lazy solution using the builtin center() and the format mini language:
user_input = [5,7,9]
def getStars(num):
return ('*' * i for i in range(1,num+1,2))
def sol1(num):
for s in getStars(num):
print(s.center(num))
def sol2(num):
stars = getStars(num)
for s in stars:
print( ("{:^"+str(num)+"}").format(s))
for s in user_input:
sol1(s)
sol2(s)
Output:
*
***
*****
*
***
*****
*
***
*****
*******
*
***
*****
*******
*
***
*****
*******
*********
*
***
*****
*******
*********
Hi I have been experimenting for some time to try and total 7 variables at once. I am trying to calculate the 8th number for GTIN 8 codes. I have tried many things and so far I am using float. I Don't know what it does but people say use it. I need to times the 1,3,5,7 number by 3 and 2,4,6 number by 1. Then find the total of all of them added together. I have looked everywhere and I cant find anything. Anything will help. Thanks Ben
code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
Quick solution:
x = "1234567"
checksum_value = sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
# (1*3) + 2 + (3*3) + 4 + (5*3) + 6 + (7*3)
# ==
# 3 + 2 + 9 + 4 + 15 + 6 + 21
# ==
# sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
Explanation:
# Sum the contained items
sum(
# multiply by three if the index is 0,2,4 or 6
int(v) * 3 if i in (0,2,4,6) else int(v)
# grab our index `i` and value `v` from `enumerate()`
for (i, v) in
# Provide a list of (index, value) from the iterable
enumerate(
# use the first 7 elements
x[:7]
)
)
`enter code here`code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
GS1 codes come in different lengths, ranging from GTIN-8 (8 digits) to SSCC (2 digit application ID + 18 digits). Here's a simple, general Python formula that works for any length GS1 identifier:
cd = lambda x: -sum(int(v) * [3,1][i%2] for i, v in enumerate(str(x)[::-1])) % 10
Explanation:
Convert input to string, so input can be numeric or string - just a convenience factor.
Reverse the string - simple way to align the 3x/1x pattern with variable-length input.
The weighting factor is selected based on odd and even input character position by calculating i mod 2. The last character in the input string (i=0 after the string has been reversed) gets 3x.
Calculate the negative weighted sum mod 10. Equivalent to the (10 - (sum mod 10)) mod 10 approach you'd get if you follow the GS1 manual calculation outline exactly, but that's ugly.
Test Cases
## GTIN-8
>>> cd(1234567)
0
>>> cd(9505000)
3
## GTIN-12
>>> cd(71941050001)
6
>>> cd('05042833241')
2
## GTIN-13
>>> cd(900223631103)
6
>>> cd(501234567890)
0
## GTIN-14
>>> cd(1038447886180)
4
>>> cd(1001234512345)
7
## SSCC (20 digits incl. application identifier)
>>> cd('0000718908562723189')
6
>>> cd('0037612345000001009')
1
This question already has answers here:
accepting multiple user inputs separated by a space in python and append them to a list
(4 answers)
Closed 7 years ago.
I am trying to create a function that calculates the sum of an artithmetic sequence. I know how to set up the mathematical calculations but I don't know how to take input from the user to actually perform them.
How can I take user input (like below) such that the three ints on each line are read as A, B, N, with A being the first value
of the sequence, B being the step size and N the number of steps.
8 1 60
19 16 69
17 4 48
What should come next?
def arithmetic_progression():
a = raw_input('enter the numbers: ')
with raw_input you generally get a string
>> a = raw_input('enter the numbers')
you enter the numbers 8 1 60, so a will be a string '8 1 60'. Then you can split the string into the 3 substrings
>> b = a.split()
This will return you a list ['8', '1', '60']. Out of this you can get your numbers
>> A = int(b[0])
>> B = int(b[1])
>> N = int(b[2])
To read multiple lines you could add a function similar to this
def readlines():
out = raw_input('enter the numbers\n')
a = 'dummy'
while(len(a)>0):
a = raw_input()
out += '\n' + a
return out
This function would read any input and write it to the out string until you have one empty line. To get the numbers out of the string just do again the same as for a single line.
Sum to n terms of AP is: Sn = (n/2) [ 2a + (n-1)d ]
def arithmetic_progression():
inp = raw_input('enter the numbers: ').split(' ')
if not len(inp) == 3: # in case of invalid input
return arithmetic_progression() # prompt user to enter numbers again
a = float(inp[0])
d = float(inp[1])
n = float(inp[2])
s = ( (2 * a) + ((n - 1) * d) ) * (n / 2)
print('Sum to n terms of given AP is: ' + str(s))
arithmetic_progression()