Return mean value without tuple? - python

Expected output: report_exam_avg(100, 95, 80) == 'Your average score: 91.7'
def report_exam_avg(a, b, c):
assert is_number(a) and is_number(b) and is_number(c)
a = float(a)
b = float(b)
c = float(c)
mean = (a + b + c) / 3.0
mean = round(mean,1)
x = 'Your average score: ', mean
return x
Actual output: ('Your average score: ', 91.7)
Note: cant unpack the tuple such as below because I need the sentence returned not printed
avg, score = report_exam_avg(100, 95, 80)
print(avg, score)

You are returning x as a tuple in this case. So this is why when you simply print x you get a tuple as output. You should either use the print statement in Function or modify function as follows:
def report_exam_avg(a, b, c):
assert is_number(a) and is_number(b) and is_number(c)
a = float(a)
b = float(b)
c = float(c)
mean = (a + b + c) / 3.0
mean = round(mean,1)
x = mean
return x
So your call to function would be:
print ("Your Avg. Score:", report_exam_avg(100, 95, 80))

I would suggest changing the use of the comma to plus. This would change where you set the variable x:
x = 'Your average score: ' + str(mean)
This will properly handle string concatenation, whereas the comma will generate a tuple.
Additionally, if you are using python 3.6, you could make use of fstrings, a very handy string interpolation tool. This would change the line to look like this:
x = f'Your average score: {mean}'
You can then return x in string form.

Python supports return multiple values in a function, just delimit them with ,. In your case, Python thinks you'are doing this, thus returns a tuple.
To return a string, simply concat string with +:
x = 'Your average score: ' + str(mean)
return x
Or, use string format
x = 'Your average score: {}'.format(mean)
return x

Related

choose variable via input (python)

i wanna choose the variable via an input
a=1
b=2
c=3
x=input("a/b/c")
The Idea is now that the calculation is 7 times 1 and therefore the solution: 7
solution=7*a
print(solution)
But python recognizes the input as string not as a variable. How do i change that?
You need to create a 'lookup table' that will map the chars to numbers.
lookup = {'a':1,'b':2,'c':3}
x=input("a/b/c: ")
value = lookup.get(x)
if value is None:
print('invalid input')
else:
print(f'Solution is {7 * value}')
You can turn a string into a variable like this.
a = 1
b = 2
c = 3
x = input("a/b/c: ")
x = locals()[x]
solution = 7 * x
print(solution)

Addition of two binaries numbers in Python

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.

Printing answer when using map. Python 3

I am trying to create code in order to take sequence A and B and multiply them together in order to get a new list.
e.g. if the two inputs were:
1,5,7
3,5,8
The new list would be:
3,25,56.
The current code I have is as follows.
print ("INPUT:")
num_sequence_A = input( "enter sequence A: " )
num_sequence_B = input( "enter sequence B: " )
#calculation in order to calculate for new list.
calc = map(lambda x,y:x*y,num_sequence_A,num_sequence_B)
I cannot however find a way to print the calculation.
I have tried :
calc = map(print, lambda x,y:x*y,num_sequence_A,num_sequence_B)
and
list(map(print, calc))
with no success.
Use map, filter or list comprehensions to create new iterables and never for side-effects like printing. To print the items in calc you can just use a for loop.
calc = map(lambda x, y: x*y, num_sequence_A, num_sequence_B)
for num in calc:
print(num)
First, you need to convert you inputs to arrays of int.
num_sequence_A = input("enter sequence A: ")
num_sequence_B = input("enter sequence B: ")
num_sequence_A = [int(i) for i in num_sequence_A.split(',')]
num_sequence_B = [int(i) for i in num_sequence_B.split(',')]
Then, calculate the result:
calc = map(lambda x, y: x * y, num_sequence_A, num_sequence_B)
Finally, print the output:
print(','.join([str(i) for i in calc]))
Additionally, you can use re:
import re
num_sequence_A = input("enter sequence A: ") # 3.4 5.6 7.8
num_sequence_B = input("enter sequence B: ") # 4.5 7 6
num_sequence_A = re.findall(r'(\d+\.\d+)|(\d+)', num_sequence_A)
num_sequence_B = re.findall(r'(\d+\.\d+)|(\d+)', num_sequence_B)
num_sequence_A = [float(i[0]) if len(i[0]) != 0 else float(i[1]) for i in num_sequence_A]
num_sequence_B = [float(i[0]) if len(i[0]) != 0 else float(i[1]) for i in num_sequence_B]
calc = map(lambda x, y: x * y, num_sequence_A, num_sequence_B)
print(','.join(['%.2f' % i for i in calc]))

Print without space in python 3

I'm new to Python, and I'm wondering how to print multiple values without having the extra space added in between. I want the output ab rather than a b without having to call print twice:
print("a", end="")
print("b")
Also, I have the following code:
a = 42
b = 84
and I want to print their values as a = 42, b = 84, yet if I do
print("a = ", a, ", ", b = ", b)
extra spaces are added (it outputs a = 42 , b = 84)
Whereas the Java style,
print("a = " + a + ", b = " + b)
raises a TypeError.
You can use the sep parameter to get rid of the spaces:
>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc
I don't know what you mean by "Java style"; in Python you can't add strings to (say) integers that way, although if a and b are strings it'll work. You have several other options, of course:
>>> print("a = ", a, ", b = ", b, sep="")
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3
The last one requires Python 3.6 or later. For earlier versions, you can simulate the same effect (although I don't recommend this in general, it comes in handy sometimes and there's no point pretending otherwise):
>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
You can see it has an arg sep with default value ' '. That's why space gets inserted in between.
print("United","States") #Output: United States
print("United","States",sep="") #Output: UnitedStates
You can also use
print("%d%d" %(a,b))
to print a and b not seperated by spaces in form of a formatted string. This is similar to the one in c.
To separate the strings or values you can use sep parameter in print()
print(a,b,sep='')
print() will automatically make spaces between arguments.
>>> print("a", "b", "c")
a b c
To have more control over spacing, you could use string formatting:
>>> v0, v1, v2 = "a", "b", "c"
>>> print("%s%s%s" % (v0, v1, v2))
abc
>>> print("%s%s%s".format(v0, v1, v2)
abc
>>> print(f"{v0}{v1}{v2}")
abc
I like this guide on the subject: https://realpython.com/python-f-strings/
On this page the answer is to print your normal text and at the end to use
sep="".
So the command
print("Hole", hole, "Par", par, sep="")
will give
"Hole1Par4"
assuming that hole==1 and par==4.

Python, context sensitive string substitution

Is it possible to do something like this in Python using regular expressions?
Increment every character that is a number in a string by 1
So input "123ab5" would become "234ab6"
I know I could iterate over the string and manually increment each character if it's a number, but this seems unpythonic.
note. This is not homework. I've simplified my problem down to a level that sounds like a homework exercise.
a = "123ab5"
b = ''.join(map(lambda x: str(int(x) + 1) if x.isdigit() else x, a))
or:
b = ''.join(str(int(x) + 1) if x.isdigit() else x for x in a)
or:
import string
b = a.translate(string.maketrans('0123456789', '1234567890'))
In any of these cases:
# b == "234ab6"
EDIT - the first two map 9 to a 10, the last one wraps it to 0. To wrap the first two into zero, you will have to replace str(int(x) + 1) with str((int(x) + 1) % 10)
>>> test = '123ab5'
>>> def f(x):
try:
return str(int(x)+1)
except ValueError:
return x
>>> ''.join(map(f,test))
'234ab6'
>>> a = "123ab5"
>>> def foo(n):
... try: n = int(n)+1
... except ValueError: pass
... return str(n)
...
>>> a = ''.join(map(foo, a))
>>> a
'234ab6'
by the way with a simple if or with try-catch eumiro solution with join+map is the more pythonic solution for me too

Categories