Python Gtin 8 Code not totaling - python

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

Related

When user input the numbers it should get expand

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]))

Alternating sums of a list [duplicate]

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

Replace characters in a list by column rather than by row

Currently I have the following lists:
counter = [13]
instruments = ['3\t ---', '2\t / \\', '1\t / \\', '0\t--- \\ ---', '-1\t \\ /', '-2\t \\ /', '-3\t ---']
score = ['|*************|']
What I am trying to do is to replace the characters in the instruments list with the characters from the score list (excluding the |).
I am currently experiencing the following issues
The characters are being replaced row by row, rather than column by column.
Instrument List:
3 ---
2 / \
1 / \
0 --- \ ---
-1 \ /
-2 \ /
-3 ---
Score List:
|*************|
EXPECTED OUTPUT:
3 ***
2 * *
1 * *
0 *** *
-1 *
-2 *
-3
Current Output:
3 ***
2 * *
1 * *
0 *** * **
-1
-2
-3
This is how I am currently replacing the characters in the instruments list:
for elements in counter:
current_counter = elements
count = 0
for elements in instrument_wave:
amplitude, form = elements.split('\t')
for characters in form:
if characters in ['-', '/', '\\']:
form = form.replace(characters, '*', 1)
count += 1
if count == current_counter:
break
for characters in form:
if characters in ['-', '/', '\\']:
form = form.replace(characters, '')
if '-' not in amplitude:
amplitude = ' ' + amplitude
new_wave = amplitude + "\t" + form
waveform.append(new_wave)
Any help would be appreciated, especially with regards to how I should fix my replace character to make it go column by column rather than row by row.
To solve your first issue, you need to iterate via columns.
If you zip the lists (via itertools.zip_longest(), as they are not all the same length), you can then go through them in order and truncate the result:
import itertools
cols = list(itertools.zip_longest(*lst, fillvalue=" "))
for i in range(3, 17): # skip negative signs
cols[i] = "".join(cols[i]).replace('-', '*', 1)
cols[i] = "".join(cols[i]).replace('/', '*', 1)
cols[i] = "".join(cols[i]).replace('\\', '*', 1)
fixed = map("".join, zip(*cols[:17])) # no need to zip longest
for l in fixed:
print(l)
See a working example on repl.it, which outputs:
3 ***
2 * *
1 * *
0 *** *
-1 *
-2 *
-3
Note it does pad the lists out with spaces, so you may want to .strip() the results if it isn't just for printing. Adapting that to your score input I'll leave up to you.
Another option, which is probably clearer:
def convert_and_truncate(lst, cutoff):
result = []
for str in lst:
str = str[0] + str[1:].replace('-', '*') # skip the negative signs
str = str.replace('/', '*')
str = str.replace('\\', '*')
result.append(str[:cutoff]) # truncate
return result
Because we're truncating the rest of the list, it doesn't matter that replace is changing them all.
Without itertools, instead self padding to longest part in list:
counter = [16]
instruments = ['3\t ---', '2\t / \\', '1\t / \\', '0\t--- \\ ---', '-1\t \\ /', '-2\t \\ /', '-3\t ---']
score = ['|*************|']
# get longes part list
maxL = max ( len(p) for p in instruments)
#enlarge all to max length
instrum2 = [k + ' '* (maxL-len(k)) for k in instruments]
# mask out leading - to ~ (we reverse it later)
instrum3 = [k if k[0] != '-' else '~'+''.join(k[1:]) for k in instrum2]
# transpose and join to one lengthy sentence, #### are where we later split again
trans = '####'.join(map(''.join,zip(*instrum3)))
# replace the right amount of /-\ with * after that, replace with space instead
cnt = 0
maxCnt = score[0].count('*')
result = []
for t in trans:
if t in '/-\\':
if cnt < maxCnt:
result.append('*')
cnt+=1
else:
result.append(' ')
else:
result.append(t)
# resultlist back to string and split into columns again
result2 = ''.join(result)
trans2 = result2.split('####')
# transpose back to rows and make - correct
trans3 = [''.join(k).replace('~','-') for k in zip(*trans2 )]
for p in trans3:
print(p)
Output:
3 ***
2 * *
1 * *
0 *** *
-1 *
-2 *
-3

How to draw this bow tie pattern using Python 2.7?

I need to draw the following pattern using Python While Loops.
I have spent quite a lot of time and came up with this code which prints it perfectly but this code is so much long and I feel like it is not one of those good codes.
If anybody here can help me out shrinking this code or suggesting a better way to output?
here is the code:
#Question 10, Alternate Approach
temp = 1
pattern = ""
innerSpace = 7
starCount = 1
while temp <= 5:
st = 1
while st <= starCount:
pattern = pattern + "*"
if st != starCount:
pattern = pattern + " "
st = st + 1
sp = 0
if temp == 5:
innerSpace = 1
while sp < innerSpace:
pattern = pattern + " "
sp = sp + 1
st = 1
while st <= starCount:
if temp == 5:
st = st + 1
pattern = pattern + "*"
if st != starCount:
pattern = pattern + " "
st = st + 1
temp = temp + 1
innerSpace = innerSpace - 2
pattern = pattern + "\n"
if temp % 2 == 0:
pattern = pattern + " "
else:
starCount = starCount + 1
starCount = 2
innerSpace = 1
while temp > 5 and temp <= 9:
st = 1
while st <= starCount:
pattern = pattern + "*"
if st != starCount:
pattern = pattern + " "
st = st + 1
sp = 0
while sp < innerSpace:
pattern = pattern + " "
sp = sp + 1
st = 1
while st <= starCount:
pattern = pattern + "*"
if st != starCount:
pattern = pattern + " "
st = st + 1
temp = temp + 1
innerSpace = innerSpace + 2
pattern = pattern + "\n"
if temp % 2 == 0:
starCount = starCount - 1
pattern = pattern + " "
print pattern
Since this looks like an assignment, I'll give you a hint how I would do it.
Take advantage of the symmetry of the bow. It is symmetrical about the horizontal and vertical axis. Therefore, you really only need to solve 1 corner, then copy/mirror the results to get the rest.
This code gives one way of looking at the problem, which is just shifting a initial string (the middle of the bow) to get the desired shape:
m = '*'
size = 4
n = 5 # must be odd
pad = ' ' * n
middle = (m + pad) * size
half = int(n / 2) + 1
print middle
print middle[half*1:]
print middle[half*2:]
print middle[half*3:]
print middle[half*4:]
print middle[half*5:]
print middle[half*6:]
Which yields this:
* * * *
* * *
* * *
* *
* *
*
*
Good luck!
I would use list comprehensions and strings and would exploit the symmetry of the figure.
Not a complete solution, but could be a part of a loop body
In [2]: a = '*' + ' '*8
In [3]: a
Out[3]: '* '
In [24]: result = ''
In [25]: result += a
In [26]: result
Out[26]: '* '
In [27]: result += a[-1::-1]
In [28]: result
Out[28]: '* *'
In [29]: result += '\n'
In [30]: a = ' '+'*' + ' '*7
In [31]: a
Out[31]: ' * '
In [32]: result += a
In [33]: result += a[-1::-1]
In [34]: result += '\n'
In [36]: print result
* *
* *
IMHO you use while loop much as if they where for loops.
I don't think that's what your teacher wants.
The idea behind while is to run until a certain condition is met, not
necessarily when the number of iterations exceed a certain limit.
The condition does not need to be included in the while statement, you can check it later and use the break command to escape the loop
Try for example this:
start = '*'
while True:
print start
if start[0] == '*':
start = ' ' + start
else:
start = '*' + start
if (start == '* * *'):
break
output is just a part of your assignment, think you should be able to work it out to the final, expected result!
Hopefully by this time HW is done. Since I solved this using dynamic programming, I thought I would list solution here.
Observations:
While looking at pattern its observed that bottom half is palindrome of top half. Hence we need to calculate only the top half.
Next we see that for every row count,we have pattern like,
row 1 = 1 , n
row 2 = 2 , n -1
row 3 = 1,3, n-2, n
row 4 = 2, 4 , n-3, n-1
.. and so on.
With iteration index as row count and n as input value we can dynamically calculate remaining values very efficiently.
Source-Code
def get_list(bound, alist):
tmp_list = []
for i in xrange(1,bound + 1):
tmp_list.append(star if i in alist else dot)
return tmp_list
star = "*"
dot = " "
n = 20 #How large of BowTie do you want?
m = (n * 2) - 1
#get top half list
th = []
for idx,k in enumerate(xrange(1,n+1)): #run through 1 - n
row = idx + 1
tmplst = []
if row % 2 != 0:
tmplst.append(i for i in xrange(1,row + 1) if i % 2 != 0)
tmplst.append(i for i in xrange(m, m-row, -1) if i % 2 != 0)
else:
tmplst.append(i for i in xrange(1,row + 1) if i % 2 == 0)
tmplst.append(i for i in xrange(m, m-row, -1) if i % 2 == 0)
#append each row value to top half list.
th.append(sorted(set([j for i in tmplst for j in i])))
#create palindrome of top half which is our bottom half
th = th + th[len(th) -2::-1]
#create list of * and blanks
final = [get_list(m, i) for i in th]
#Print BowTie
for i in final:
print ' '.join(i)
Using a stars and spacing and counting variable
counting=1
star_amount=1
space_amount=6
loop_var=7
while loop_var>0:
loop_var-=1
if space_amount==0:
counting*=-1
stars=" * "*star_amount
spaces=" "*space_amount
print(stars+spaces+stars)
star_amount+=counting
space_amount-= counting*2

Function doesn't return all results from 'for' loop [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 6 months ago.
I've made a simple function to print out a times table chart depending on the number you decide to run with. The problem I'm having due to my basic understanding of the language is why it only returns the first loop and nothing else.
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
return (str(c) + " * " + str(c) + " = " + str(b))
print(timestables(5))
I get the answer ..
1 * 1 = 1
I've tried to rectify this issue by using print instead of return but this ultimately results with a None appearing as well.
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
print (str(c) + " * " + str(c) + " = " + str(b))
print(timestables(5))
I get the answer ..
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
None
How can I return all given results from the for loop to avoid a None error?
yield them.
def timestables(number):
for a in range(1, number+1):
yield '%s + %s = %s' % (a, a, a*a )
for x in timestables(5):
print x
This turns your function into a generator function, and you need to iterate over the results, i.e. the result is not a list, but an iterable.
If you need a list, the simplest is to explicitly create one:
res = list(timestables(5))
But again, if you don't, you don't.
IMHO, this is the most pythonic way.
You're returning inside the for loop - and functions stop execution immediately once they hit a return statement.
To work around this, you can use a list to store those values, and then return that list.
def timestables(number):
lst = []
for a in range(1, number+1):
b = a*a
c = a
lst.append(str(c) + " * " + str(c) + " = " + str(b))
return lst
As a side note, you should use string formatting to build the string, like so.
lst.append('{a} * {a} = {b}'.format(a=a, b=a*a))
Now we can get rid of all those intermediate variables (b and c), and we can use a list comprehension instead.
def timestables(number):
return ['{a} * {a} = {b}'.format(a=a, b=a*a) for a in range(1, number+1)]
If you don't want the function to return a list, but a multi-line string, you can use str.join:
def timestables(number):
return '\n'.join('{a} * {a} = {b}'.format(a=a, b=a*a) for a in range(1, number+1))
Now we can test the function:
>>> print(timestables(5))
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
You can return an array:
def timestables(number):
out = []
for a in range(1, number+1):
b = a*a
c = a
out.append( str(c) + " * " + str(c) + " = " + str(b))
return out
print(timestables(5))

Categories

Resources