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]))
Related
I have the below code, what i have to do is add the 2 strings together to make 150 and then convert that string into a integer i have used the code below but not sure how ti add 2 strings together and then return it, help thanks
def sum_to_int("50", "100"):
numbers = "50"
numbers1 = "100"
myarr = numbers.split(" ")
myarr2 = numbers1.split(" ")
print(myarr)
print(myarr2)
myarr = [int(i) for i in myarr]
myarr2 = [int(i) for i in myarr2]
print(myarr, myarr2)
result = sum_to_int
print(sum_to_int(numbers, numbers1))
def sum_to_int(str_1 ,str_2):
#first convert string values to int
int_1 = int(str_1)
int_2 = int(str_2)
#just plus integers
total = int_1 + int_2
return total
#use -> return int(str_1)+int(str_2)
print(sum_to_int("100","50"))
Be simple :
def sum_to_int(numbers1, numbers2):
return int(numbers1) + int(numbers2)
print(sum_to_int("50","100"))
# 150
i am trying to compare an "i" counter whitch is interger with a list whitch inludes str numbers , and add it in a string variable
LPL = ["1","2","3"]
f = str()
for i in range (x):
if str(i) == LPL[i]:
f+=str(i)
i expected the f variable had the result of the comparsion: f = 123
List index starts from 0:
LPL = ["1","2","3"]
s = ""
for i in range(1,len(LPL)+1):
if i == int(LPL[i-1]):
s+=str(i)
print(s)
Note that you should use a range from a number to a number and also that python indexes starts from 0, so you need to adapt the code in a way like:
LPL = ["1","2","3"]
f = str()
for i in range (1, len(LPL)+1):
### note that your LPL[0] == 1 and not LPL[1] == 1, so you need to decreasee a number here, that's why a +1 in the range too
if str(i) == LPL[i-1]:
f+=str(i)
### OUTPUT
>>> f
'123'
Perhaps I missing something, but if you wish to combine the elements of the list, either by conjoining strings or adding integers, consider using reduce:
LPL = ["1","2","3"]
LPL2 = [1,2,3]
f = reduce(lambda a,b : a+b, LPL) # "123"
f_int = reduce(lambda a,b : a+b, LPL) # 6
This is a parser I'm trying to create, and it's going well, but somehow I can't do arithmetic expressions with more than one place value. It works for everything up to 9 but nothing like 10 or 21. The second function is just for integrating accessing text files.
For example, I can do 9 * 9 , but I cannot do 12 * 8.
# AditPradipta_Equation_Solving
def only_parsing(equation):
operators = {0: lambda x, y : int(x) + int(y),
1: lambda x, y : int(x) - int(y),
2: lambda x, y : int(x) * int(y),
3: lambda x, y : int(x) / int(y)}
operators_list = ["+", "-", "*", "/"]
equation = equation.strip()
equation = equation.strip("=")
print(equation)
operator_num = 0
for operator in operators_list:
if operator_num == 3:
zero_division_check = equation.find("0")
if not zero_division_check != True:
continue
elif not zero_division_check != False:
return "You cannot divide by 0."
operator_find = equation.find(operators_list[operator_num])
if not operator_find != True:
first_num = equation[0]
second_num = equation[-1]
return operators[operator_num](int(first_num), int(second_num))
else:
operator_num = operator_num + 1
def multi_line_parsing(filename, new_file_name):
file = open(filename, 'r')
file_lines = file.readlines()
print(file_lines)
new_file = []
for line in file_lines:
print(line)
new_file.append(str(only_parsing(line)) + str("\n"))
print(new_file)
new_file_string_data = ''.join(new_file)
print(new_file_string_data)
file.close()
write_file = open(new_file_name, 'w+')
write_file.write(new_file_string_data)
write_file.close()
return
file_name = input("Please enter a filename: ")
new_file = input("Please enter another new file name: ")
multi_line_parsing(file_name, new_file)
An example of expected input and output and actual input and output is
#Expected input
12 * 8
100 * 10
#Expected Output
96
1000
#Actual Output
None
None
Any help would be appreciated.
Comment: str.split() ... good only ... formatted with delimiting spaces.
It won't correctly tokenize "12*8"
To handle both, and other possible format, replace with re.split(...), for example:
import re
# Split by blank, require ALWAYS three parts delimited with blank
v1, v2 = re.split('[\+\-\*\/]', equation)
op = equation[len(v1)]
Output:
12*8 = 96
12* 8 = 96
100 *10 = 1000
division by zero: You cannot divide by 0
12 / 0 = None
Question: Arithmetic Expressions ... not working with more than one place value
Using str.split() you can handle Values of any length.
Simplify your approach, for example:
def only_parsing(equation):
# Use the operators as dict key
operators = {'+': lambda x, y: int(x) + int(y),
'-': lambda x, y: int(x) - int(y),
'*': lambda x, y: int(x) * int(y),
'/': lambda x, y: int(x) / int(y)}
# Split by blank, require ALWAYS three parts delimited with blank
v1, op, v2 = equation.split()
#print("{}".format((v1, op, v2)))
# Use try:...except to catch ZeroDivisionError
try:
# Call the lambda given by dict key
return operators[op](v1, v2)
except ZeroDivisionError as e:
print("{}: You cannot divide by 0".format(e,))
for exp in ['12 * 8', '100 * 10', '12 / 0']:
print("{} = {}".format(exp, only_parsing(exp)))
Qutput:
12 * 8 = 96
100 * 10 = 1000
division by zero: You cannot divide by 0
12 / 0 = None
Tested with Python:3.4.2
I have a variety of values in a text field of a CSV
Some values look something like this
AGM00BALDWIN
AGM00BOUCK
however, some have duplicates, changing the names to
AGM00BOUCK01
AGM00COBDEN01
AGM00COBDEN02
My goal is to write a specific ID to values NOT containing a numeric suffix
Here is the code so far
prov_count = 3000
prov_ID = 0
items = (name, x, y)
xy_tup = tuple(items)
if "*1" not in name and "*2" not in name:
prov_ID = prov_count + 1
else:
prov_ID = ""
It seems that the the wildcard isn't the appropriate method here but I can't seem to find an appropriate solution.
Using regular expressions seems appropriate here:
import re
pattern= re.compile(r'(\d+$)')
prov_count = 3000
prov_ID = 0
items = (name, x, y)
xy_tup = tuple(items)
if pattern.match(name)==False:
prov_ID = prov_count + 1
else:
prov_ID = ""
There are different ways to do it, one with the isdigit function:
a = ["AGM00BALDWIN", "AGM00BOUCK", "AGM00BOUCK01", "AGM00COBDEN01", "AGM00COBDEN02"]
for i in a:
if i[-1].isdigit(): # can use i[-1] and i[-2] for both numbers
print (i)
Using regex:
import re
a = ["AGM00BALDWIN", "AGM00BOUCK", "AGM00BOUCK01", "AGM00COBDEN01", "AGM00COBDEN02"]
pat = re.compile(r"^.*\d$") # can use "\d\d" instead of "\d" for 2 numbers
for i in a:
if pat.match(i): print (i)
another:
for i in a:
if name[-1:] in map(str, range(10)): print (i)
all above methods return inputs with numeric suffix:
AGM00BOUCK01
AGM00COBDEN01
AGM00COBDEN02
You can use slicing to find the last 2 characters of the element and then check if it ends with '01' or '02':
l = ["AGM00BALDWIN", "AGM00BOUCK", "AGM00BOUCK01", "AGM00COBDEN01", "AGM00COBDEN02"]
for i in l:
if i[-2:] in ('01', '02'):
print('{} is a duplicate'.format(i))
Output:
AGM00BOUCK01 is a duplicate
AGM00COBDEN01 is a duplicate
AGM00COBDEN02 is a duplicate
Or another way would be using the str.endswith method:
l = ["AGM00BALDWIN", "AGM00BOUCK", "AGM00BOUCK01", "AGM00COBDEN01", "AGM00COBDEN02"]
for i in l:
if i.endswith('01') or i.endswith('02'):
print('{} is a duplicate'.format(i))
So your code would look like this:
prov_count = 3000
prov_ID = 0
items = (name, x, y)
xy_tup = tuple(items)
if name[-2] in ('01', '02'):
prov_ID = prov_count + 1
else:
prov_ID = ""
I am a beginner programmer and I am doing a task for school. The task is to assign 4 constant variables and then use a code to work out the value. Each value has a corresponding letter and the program is asking the user to type in 5 numbers then the program will return the word. The code is the following:
array = [["L","N"], #define the 2d array, L=Letters, N=Numbers
["-","-"]] #line for space
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
array.append(["e",e])
array.append(["f",f])
array.append(["g",g])#append all the calculations
array.append(["h",h])
array.append(["i",i])
array.append(["j",j])
array.append(["k",k])
array.append(["l",l])
array.append(["m",m])
array.append(["n",n])
array.append(["o",o])
array.append(["p",p])
array.append(["q",q])
array.append(["r",r])
array.append(["s",s])
def answer():
len_row = len(array)
number_input = int(input("Enter number: "))
for i in range(len_row):
if number_input == (array[i][1]):
return array[i][0]
break
one_let = answer()
two_let = answer()
thr_let = answer()
fou_let = answer()
fiv_let = answer()
print(one_let,two_let,thr_let,fou_let,fiv_let)
The numbers that I am meant to put in are 6, 18,, 7, 8, and 3.
The word that prints is "spife" and the word that is meant to be printed is "spine". The problem is that there are two letters that have a variable of 8 and Python gets the first one only. Is there a way to print out the two seperate words but first with the first variable in a 2D array and second with the second 2D array? i.e spife then spine
Thank you for your help ahead, I am just a beginner! :)
Yes you can do it but is a bit tricky the secret is to use itertools.product on the list of letters that could have each of the five values.
First you need to use a better data structure such as a dict, (in this case a collection.defaltdict) to hold the letters that have some value. You can do this way:
import collections
import itertools
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
dat = collections.defaultdict(list)
for c in "abcdefghijklmnopqrs":
dat[eval(c)].append(c)
Now in dat you have a list of letters that match some number, for example
print(dat[6])
print(dat[18])
print(dat[7])
print(dat[8])
print(dat[3])
Outputs:
['s']
['p']
['i']
['f', 'n']
['e']
OK, then you need to change answerto return a list of letters, and collect the user input:
def answer():
number_input = int(input("Enter number: "))
return dat[number_input]
letts = [answer() for _ in range(5)] #collect five answers of the user
And the final magic is done here:
for s in map(lambda x: "".join(x),itertools.product(*letts)):
print(s)
Now if you are confused then study:
collections
collections.defaultdict
itertools
itertools.product
str.join