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)
Related
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]))
I didn't know how to describe it in the question properly, so I'll try again here.
I have to solve this question where my code should print different types of squares. I have all of that figured out, however, I'm stuck at the printing part.
So, I start by inputting 4 as the size, and it results in different types of squares being made. For example, these two:
first = ""
for j in range(size-1):
first += "*" * size + "\n"
first += "*" * size
two = ""
for j in range(size-1):
if j == 0:
two += "*" * size + "\n"
else:
two += "*" + ((size - 2) * " ") + "*" + "\n"
two += "*" * size
Now, I have to print them like this:
**** ****
**** * *
**** * *
**** ****
separated by a '\t'.
Since these squares are 'stored' in different strings, this is unfamiliar territory for me as the cursor is at the end of the first square. I don't know what to do, help pls.
There are many ways for that, one is here:
>>> v = '\n'.join([i+'\t' + j for i,j in list(zip([i for i in first.split('\n') if i], [ i for i in two.split('\n') if i]))])
>>> print(v)
**** ****
**** * *
**** * *
**** ****
What i did:
Splitted both strings at newline character, then took corresponding parts and joined them by tab in between, then assembled the whole string.
You can change the data structure you use. Let the square will be not a string, but list of strings, where each string is line should be printed.
Then you can for each line write line_first + '\t' + line_two and print it.
This code worked as you expect.
first = []
for j in range(size - 1):
first.append("*" * size)
first.append("*" * size)
two = []
for j in range(size - 1):
if j == 0:
two.append("*" * size)
else:
two.append("*" + ((size - 2) * " ") + "*")
two.append("*" * size)
for f, t in zip(first, two):
print(f + '\t' + t)
This question already has answers here:
Writing a function that alternates plus and minus signs between list indices
(7 answers)
Closed 2 years ago.
9.Write a program that accepts 9 integers from the user and stores them in a list. Next, compute the alternating sum of all of the elements in the list. For example, if the user enters
1 4 9 16 9 7 4 9 11
then it computes
1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2
myList = []
value = None
count = 0
while count != 9:
value = int(input("Please enter a number: "))
myList.append(value)
count = count + 1
if count == 9:
break
print(myList)
def newList(mylist):
return myList[0] - myList[1] + myList[2] - myList[3] + myList[4] - myList[5] + myList[6] - myList[7] + myList[8]
x = newList(myList)
print(x)
My code returns the correct answer, but I need it to print out the actual alternating sums as in the example. I have been stuck on this for a while. I am having a mental block on this and havent been able to find anything similar to this online.
I appreciate any help or tips.
Also, this is python 3.
Thank you.
a=[1, 4, 9, 16, 9, 7, 4, 9, 11]
start1=0
start2=1
sum1=0
first_list=[a[i] for i in range(start1,len(a),2)]
second_list=[a[i] for i in range(start2,len(a),2)]
string=''
for i,j in zip(first_list,second_list):
string+=str(i)+'-'+str(j)+'+'
string.rstrip('+')
print('{}={}'.format(string,str(sum(first_list)-sum(second_list))))
Output
1-4+9-16+9-7+4-9+=-2
Try doing this:
positives = myList[::2]
negatives = myList[1::2]
result = sum(positives) - sum(negatives)
print ("%s = %d" % (" + ".join(["%d - %d" % (p, n) for p, n in zip(positives, negatives)]), result))
I'll explain what I'm doing here. The first two lines are taking slices of your list. I take every other number in myList starting from 0 for positives and starting from 1 for negatives. From there, finding the result of the alternating sum is just a matter of taking the sum of positives and subtracting the sum of negatives from it.
The final line is somewhat busy. Here I zip positives and negatives together which produces a list of 2-tuples where of the form (positive, negative) and then I use string formatting to produce the p - n form. From there I use join to join these together with the plus sign, which produces p0 - n0 + p1 - n1 + p2 - n2.... Finally, I use string formatting again to get it in the form of p0 - n0 + p1 - n1 + p2 - n2 ... = result.
You can do as you did but place it in a print statement
print(myList[0] + " - " + myList[1] + " + " + myList[2] + " - " + myList[3] + " + " + myList[4] + " - " + myList[5] + " + " + myList[6] + " - " + myList[7] + " + " + myList[8] + " = " + x)
Its not perfectly clean, but it follows your logic, so your teacher won't know you got your solution from someone else.
Something along the lines of the following would work:
def sumList(theList):
value = 0
count = 0
steps = ""
for i in theList:
if count % 2 == 0:
value += i
steps += " + " + str(i)
else:
value -= i
steps += " - " + str(i)
count += 1
print(steps[3:])
return value
print(sumList(myList))
It alternates between + and - by keeping track of the place in the list and using the modulus operator. Then it calculates the value and appends to a string to show the steps which were taken.
You can also do something like below once your 9 or more numbers list is ready
st = ''
sum = 0
for i, v in enumerate(myList):
if i == 0:
st += str(v)
sum += v
elif i % 2 == 0:
st += "+" + str(v)
sum += v
else:
st += "-" + str(v)
sum -= v
print("%s=%d" % (st, sum))
It prints : 1-4+9-16+9-7+4-9+11=-2
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
I'm trying to print this pattern in Python:
*............*
.**........**
..***....***
...********
...********
..***....***
.**........**
*............*
And came up with this code that does the job:
for row in range(1,5):
print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
for row in range (0,4):
print("." * (3-row)+ "*" *(4 -row) + row * 4 * "." +"*" *(4 -row))
My question: is it possible to do this without using two loops? BTW, this is not for homework, I'm just playing around with some exercises from "Think Like a Programmer" by V. Anton Spraul and implementing the solutions in Python rather than C++.
Thanks in advance.
Without changing anything else, you can just do the loop over two ranges:
for row in range(1,5)+range(4,0,-1):
print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
Since you can add lists together:
In [8]: range(1,5)
Out[8]: [1, 2, 3, 4]
In [9]: range(4,0,-1)
Out[9]: [4, 3, 2, 1]
In [10]: range(1,5) + range(4,0,-1)
Out[10]: [1, 2, 3, 4, 4, 3, 2, 1]
By the way, you can get rid of the leading dots using spaces:
for row in range(1,5)+range(4,0,-1):
print " " * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
*............*
**........**
***....***
********
********
***....***
**........**
*............*
A more elegant thing to do might be to build a list of strings:
X = []
for row in range(1,5):
X.append(" " * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*")
Now, add the bottom half by just duplicating the top half in reverse:
X = X + list(reversed(X))
But when we print it we see a list:
print X
#['*............*', ' **........**', ' ***....***', ' ********', ' ********', ' ***....***', ' **........**', '*............*']
So we can join them together with newlines:
print '\n'.join(X)
*............*
**........**
***....***
********
********
***....***
**........**
*............*
here's an answer with one while loop
def star(size=14): ##size for the star in your post
asterisk=1;
space=0;
def func(x):
x+=1
return x
def decrement(x):
x-=1
return x
while (asterisk > 0):
line=''
line+=' '*space
if((size-(2*space)-(2*asterisk))<=0):
line+='*'*(size-(2*space))
else:
line+='*'*asterisk
line+=' '*(size-(2*space)-(2*asterisk))
line+='*'*asterisk
print ''.join(line)
if((size-(2*space)-(2*asterisk))<=0):
func=decrement ### switch to decreasing number of asterisks after we cross the middle of the star
print ''.join(line)
space=func(space);
asterisk=func(asterisk);
for i in range(20): ##whee
star(i)
I liked askewchan's elegant approach which noticed the symmetry between the top and bottom. There is also left-right symmetry. Here's an attempt to take advantage of that (it does have two loops though):
stars = [" "*(row-1) + "*"*row + " "*(8-row*2) for row in range(1,5)]
for line in stars + list(reversed(stars)):
print line + line[::-1]