def sumOfStudentDigits():
studentdigit = (studentdigit1 + studentdigit2 + studentdigit3 + studentdigit4 + studentdigit5 + studentdigit6 + studentdigit7)
studentdigit1=3 studentdigit2=6 studentdigit3=9 studentdigit4=3
studentdigit5=1 studentdigit6=0 studentdigit7=0
I need to assign seven digits to seven variables and add them together.
If your confusion is how to get the studentdigits into your function, you can pass them into the function like this:
def sumOfStudentDigits(studentdigit1, studentdigit2, studentdigit3,
studentdigit4, studentdigit5, studentdigit6,
studentdigit7):
studentdigit = (studentdigit1
+ studentdigit2
+ studentdigit3
+ studentdigit4
+ studentdigit5
+ studentdigit6
+ studentdigit7)
My advice would be to have all those digits stored in a list, and then pass merely that list to the function, then iterate over the list:
listofdigits = [studentdigit1,
studentdigit2,
studentdigit3,
studentdigit4,
studentdigit5,
studentdigit6,
studentdigit7]
def sumOfStudentDigits(studentdigitlist):
sum = 0
for digit in studentdigitlist:
sum += digit
return sum
print(sumOfStudentDigits(listofdigits))
We have to set sum = 0 before we can use sum because python wants to know what sum is before it uses it, so we assign it 0 so that we can count up from there.
Notice how studentdigitlist and listofdigits are different?
You can pass a list of any name to the function, all that matters is that you use the variable (ie a list in this case) name that you have used in def myfunction(yourvariable): throughout the function definition. Python with substitute whatever you pass into the function for where you have that placeholder name within the function. Then when you run the function:
eg
def myfunction(yourvariable):
# do stuff with yourvariable
myvariable = myvariable + 7
somenumber = 2
myfunction(somenumber)
# now somenumber will equal 9
You could also pass in the entire student number and break it down inside of your function.
def sum_student_digits(student_id):
running_total = 0
for i in str(student_id):
running_total += int(i)
return running_total
print(sum_student_digits(12345))
Keeping things basic. You need to assign the seven digit student number, one to each variable.
def sumOfStudentDigits():
digit1 = 3
digit2 = 6
digit3 = 9
digit4 = 3
digit5 = 1
digit6 = 0
digit7 = 0
And then add them together:
print(digit1 + digit2 + digit3 + digit4 + digit5 + digit6 + digit7)
Note that the variable assignments can't be on the same line, and need to come before the sum.
Related
Goal is to find the maximum amount of times you can subtract t from s.
t = ab, s = aabb. In the first step, we check if t is contained within s. Here, t is contained in the middle i.e. a(ab)b. So, we will remove it and the resultant will be ab and increment the count value by 1. We again check if t is contained within s. Now, t is equal to s i.e. (ab). So, we remove that from s and increment the count. So, since t is no more contained in s, we stop and print the count value, which is 2 in this case.
Problem occurs when you have something as s = 'abbabbaa' t = 'abba'.
Now it matters if you take it from the end or beggining, since you will get more steps from the end.
def MaxNum(s,t):
if not t in s:
return 0
elif s.count(t) == 1:
front = s.find(t)
sfront = s[:front] + s[front + len(t):]
return 1 + MaxNum(sfront,t)
else:
back = s.rfind(t)
front = s.find(t)
sback = s[:back] + s[back +len(t):]
sfront = s[:front] + s[front + len(t):]
print (sfront,sback)
return max(1 + MaxNum(sfront,t),1 + MaxNum(sback,t))
def foo(t,s):
return max([0] + [
1 + foo(t,s[:i]+s[i+len(t):]) for i in range(len(s)) if s[i:].startswith(t)])
Should I ask why you care?
Hey guys i have a trouble when i want to add two binaries numbers in Python, i mean i can enter a chain of character in a form of a string but i don't know how to select a specific value in the chain. Here is my code:
chaina = input('Enter your first binary number')
chainb = input('Enter your second binary number')
liste = str()
r = 0
for i in range [-1,chaina]:
t = 0
t = chaina() + chainb() + r
if t == 2 :
r = 1
liste = str(t) + liste
elif t == 0 or t == 1:
r = 0
liste = str(t) + liste
To add two binary numbers chaina and chainb:
bin(eval('0b{} + 0b{}'.format(chaina, chainb)))
Or, if you want the binary number without the leading '0b':
format(eval('0b{} + 0b{}'.format(chaina, chainb)), 'b')
Explanation
Assume for illustration that chaina = '1010' and chainb = '1111'. Then:
>>> '0b{} + 0b{}'.format(chaina, chainb)
'0b1010 + 0b1111'
By applying eval() on this string, we get the same result as if we typed the expression 0b1010 + 0b1111 directly into Python console.
>>> 0b1010 + 0b1111
25
>>> eval('0b1010 + 0b1111')
25
Finally, bin() produces a binary representation of the number passed to it as an argument:
>>> bin(25)
'0b11001'
The same thing is accomplished by calling format() with a 'b' argument:
>>> format(25, 'b')
'11001'
All put together, we are getting the expressions shown above.
Why don't you simply convert them into decimal and add them as you would do with decimals:
y = '0b101010'
z = '0b101010'
print(int(y,2) + int(z,2))
print(bin((int(y,2) + int(z,2))))
Assuming that you want to do a binary sum by hand, you must:
process both numbers starting from the end (reversed will help here)
consistently add bits processing carry until the lengther of both numbers is exhausted
reorder the result bits (here again reversed)
Code could be (assuming that you can be sure that chaina and chainb only consist in 0 and 1 characters, no test for it here):
def binsum(chaina, chainb):
def next0(it):
"""Retrieve next digit from a binary representation, 0 when exhausted"""
try:
return int(next(it))
except StopIteration:
return 0
a = reversed(chaina) # reverse chains to start with lowest order bit
b = reversed(chainb)
r = 0
result = [] # future result
for i in range(n):
t = next0(a) + next0(b) + r # add with carry
if t > 1:
t -= 2
r = 1
else:
r = 0
result.append('1' if t else '0')
if r != 0: # do not forget last carry
result.append('1')
return ''.join(result)
A couple of suggestions
normalize the lengths of the bit strings
l0, l1 = map(len, (str0, str1))
if l0 < l1:
str0 = "0"*(l1-l0) + str0
elif l1 < l0:
str1 = "0"*(l0-l1) + str1
do a loop on the reversed strings elements and construct the binary string bottom up
remainder = 0
result = ""
for bit_0, bit1 in zip(reversed(str0), reversed(str1)):
bit_0, bit_1 = map(int, (bit_0, bit_1))
new_bit, remainder = f(bit_0, bit_1, remainder)
result = str(new_bit) + result
if remainder != 0
...
writing f(bit_0, bit_1, remainder) and treating what to do if remainder is not null at the end of the loop is left as an exercise.
I'm trying to make my program return the exact same string but with ** between each character. Here's my code.
def separate(st):
total = " "
n = len(st + st[-1])
for i in range(n):
total = str(total) + str(i) + str("**")
return total
x = separate("12abc3")
print(x)
This should return:
1**2**a**b**c**3**
However, I'm getting 0**1**2**3**4**5**6**.
You can join the characters in the string together with "**" as the separator (this works because strings are basically lists in Python). To get the additional "**" at the end, just concatenate.
Here's an example:
def separate(st):
return "**".join(st) + "**"
Sample:
x = separate("12abc3")
print(x) # "1**2**a**b**c**3**"
A note on your posted code:
The reason you get the output you do is because you loop using for i in range(n): so the iteration variable i will be each index in st. Then when you call str(total) + str(i) + str("**"), you cast i to a string, and i was just each index (from 0 to n-1) in st.
To fix that you could iterate over the characters in st directly, like this:
for c in st:
or use the index i to get the character at each position in st, like this:
for i in range(len(st)):
total = total + st[i] + "**"
welcome to StackOverflow!
I will explain part of your code line by line.
for i in range(n) since you are only providing 1 parameter (which is for the stopping point), this will loop starting from n = 0, 1, 2, ... , n-1
total = str(total) + str(i) + str("**") this add i (which is the current number of iteration - 1) and ** to the current total string. Hence, which it is adding those numbers sequentially to the result.
What you should do instead is total = str(total) + st[i] + str("**") so that it will add each character of st one by one
In addition, you could initialize n as n = len(st)
I have this section of code:
if storagetypecheck1 == "Virtual":
def storagecheck():
d = 1
dforid = str(1-d)
while d <= int(numcount):
storageidprefix = "specimen" + "[" + dforid + "]"
driver.find_element_by_id(storageidprefix + ".storageContainerForSpecimen").click()
pag.press('a')
pag.press('enter')
time.sleep(1)
d = d + 1
storagecheck()
storagecheck()
When the storage type of a webform is set to virtual, it will run and change the type to auto in the textboxes.
The problem is that it has to do so with multiple textboxes which follow the format specimen[x].storageContainerForSpecimen.
However, when I run this code, it just loops over and over without changing the value of d to 2, 3, etc.
I tried having d = 1 above the if statement, but then it says for line dforid = str(1-d) that d is not defined.
Where should I put the d = 1 expression so that it is able to be recognized by the storagecheck() loop while also being able to increase by 1 every loop?
storagecheck() calls itself recursively. Each time it calls itself, the line d = 1 is being executed, so the value of d is being reset. You need to place d outside of the function definition for d to continue incrementing, like so:
if storagetypecheck1 == "Virtual":
d = 1
def storagecheck():
global d
dforid = str(1-d)
while d <= int(numcount):
storageidprefix = "specimen" + "[" + dforid + "]"
driver.find_element_by_id(storageidprefix + ".storageContainerForSpecimen").click()
pag.press('a')
pag.press('enter')
time.sleep(1)
d = d + 1
storagecheck()
storagecheck()
We use the keyword global to introduce the variable d into the namespace of the function.
What is wrong in the method end in the code?
The method end returns always 1 although it should return 0 with the current data.
# return 1 if the sum of four consecutive elements equal the sum over other sum of the other three sums
# else return 0
# Eg the current sums "35 34 34 34" should return 0
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
print equality
for i in range(0,4):
summat = []
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)
I can't really tell what you're trying to do here, but I can certainly say why end() returns 1 instead of 0. In your last for loop, you reset summat to [] at the start of the loop, so at the end, summat only contains a single value (the one you most recently appended on). So when you ask for summat[2:5] on a list of a single item, Python returns an empty list (as there are no values in that range) - in which case there are no chances for equality to be set to zero because the loop in end never runs.
I think you may have an off-by-one error. Remember that array indexes in Python start at 0, not 1. So where you do this:
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
you are not looking at summat[0] at all. Try perhaps:
for i in summat[1:4]:
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
You should also study this piece of code
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = map(int,data.split("|"))
summat = [sum(arra[i:i+4]) for i in range(0,len(arra),4)]
print summat
print len(set(summat))==1
First off, end doesn't return 1. It returns None. It prints 1. Kind of deceptive if you're running it from the command line.
Second, when you call end, summat is equal to [34]. So this:
for i in summat[2:5]:
never even executes. It won't do anything unless summat contains at least 3 elements.
You have two problems. Initialising summat to [] inside the loop, also the off by one error Greg mentioned
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[1:]: # 1 <=== IS THE SECOND ELEMENT
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
print equality
summat = [] # <=== DO THIS BEFORE THE LOOP
for i in range(0,4):
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)