How to create a list from a for-loop - python

I am trying to create a list of numbers from a function and a for-loop. Here is a copy of my code:
Rh = 1096776000000
print "What is your value for 'n'?"
n = float(raw_input(">"))
m = range(int(n+1), int(n+21))
def wavelength(a,b):
list = [((1 / (Rh * ((1 / (a**2)) - (1 / (float(x)**2))))) * 10 ** 14)
for x in b]
return list
for elements in wavelength(n,m):
print "%.3f" % elements, 'nm'
This will print out what I want, but I need to take all of the data points and put them into a list. Any ideas?

I guess you're in need of something like this:
l = [] # An empty list
for elements in wavelength(n,m):
l.append("%.3f" % elements, 'nm') # Adding rounded values to the list
print l # Print the full list

results = ["%.3f nm" % elements for elements in wavelength(n,m)]

Related

Why can't I sum these lists? It only returns the first answer, but if I print I can get it to print all answers instead? Thanks :)

This is the code that I have so far. I don't understand why it would work with print but not as a return function?
# Setup
import numpy as np
data_string = input("Enter elements of a list separated by space")
data = data_string.split()
# Function
def sumrescubed(data):
for i in range(len(data)):
data[i] = float(data[i])
data_sum = sum(data)
mean = sum(data) / len(data)
for i in range(1, len(data)):
answer_sum = sum([(data[i] - mean) ** 3])
return answer_sum
sumrescubed(data)
What you probably want to do is make answer_sum a list, and append each cube to it so that you can return the list of individual items (which are what you're seeing when you print(answer_sum) within the loop in your current code):
answer_sum = []
for i in data:
answer_sum.append((i - mean)**3)
return answer_sum
I'd suggest simplifying the whole thing by using comprehensions instead of iterating over the lists by index:
def sumrescubed(data):
nums = [float(i) for i in data]
mean = sum(nums) / len(nums)
return [(i - mean)**3 for i in nums]

Python: How do you add a math forumla for all elements in two lists?

I have converted three columns from an Excel document to three lists in Python.
I now wish to make a function, where I loop through all three lists and insert items from each list into a formula.
Example:
list1[1] + list2[1] / list3[1]
There are over 3000 items in all 3 lists, so having to write down a formula for every single item would take forever, so when I want the function, I want the program to automatically go from
list1[1] + list2[1] / list3[1]
to
list1[2] + list2[2] / list3[2],
then to
list1[3] + list2[3] / list3[3]
and so on.
How can I accomplish this?
Here is the (unfinished) code that I wrote so far.
df = pd.read_excel(r'C:\Users\KOM\Downloads\PO case study 1 - volume factor check NEW.xlsx')
wb = load_workbook(r'C:\Users\KOM\Downloads\PO case study 1 - volume factor check NEW.xlsx') # Work Book
ws1 = wb.get_sheet_by_name("DPPIV & SGLT2") # Work Sheet
pack_size = ws1['F'] # Column F
quantity = ws1['H'] # Column H
conversion = ws1['K'] # Column K
column_list_1 = [pack_size[x].value for x in range(len(pack_size))]
column_list_2 = [quantity[x].value for x in range(len(quantity))]
column_list_3 = [conversion[x].value for x in range(len(conversion))]
for (x, y, z) in zip(column_list_1[7:3030], column_list_2[7:3030], column_list_3[7:3030]):
NumPy implements well optimized broadcasting operations, so that's what I would use.
import numpy as np
...
column_list_1 = np.array(x.value for x in pack_size)
column_list_2 = np.array(x.value for x in quantity)
column_list_3 = np.array(x.value for x in conversion)
result = column_list_1[7:3030] + column_list_2[7:3030] / column_list_3[7:3030]
I also took the liberty to make your comprehensions more Pythonic by iterating directly over the elements. You rarely actually need to use list indices in Python.
You can use the x,y,z values you loop through and just append the answer to a new list:
answer = []
for (x, y, z) in zip(column_list_1[7:3030], column_list_2[7:3030], column_list_3[7:3030]):
answer.append(x + y / z)

Python output method

A = [[1,2,3,4,5],
[2,3,1,0,2],
[2,31,2,5,2],
[12,3,2,2,3]]
flattenA = list(chain(*A))
def partition(lst, n):
division = len(lst) / float(n)
return [lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n)]
for x in xrange(0,10):
random.shuffle(flattenA)
for i in xrange(3,18):
print"CLUSTER {}: ".format(partition(flattenA,i))
Cal = [sum(e) for e in partition(flattenA, i)]
result.append(Cal)
min_total = min(result)
print min_total
#now print
just number ex) 12
#i want print
min 6 list [1,2,3]
When I run it with my current coding, only the constant is output. What I've done so far is to split the list, compute the values inside, and print the smallest value. But what I want to ask is that when the smallest value is printed with applicable list. What should I do? if you let me know, i'm so appreciate
I suppose you are trying to output the min and the list at the same time.
try
print 'min{0} list{1}'.format(min_total,result)

Python - Adding all digits in string

How can i create a function that returns the sum of a string made up of 3 or more digits. For example, if the parameter/string is "13456". How can I return the result of (1*3 + 3*4 + 4*5 + 5*6). Thank you, all help is appreciated. Very new to python.
Another one-liner:
a = '13456'
print(sum([int(x)*int(y) for x, y in zip(a[1:], a[:-1])]))
You just need to go through the string, multiplying the actual value to the next value and add it to a variable to return it later.
def func(param):
ret = 0
for i in range(len(param)-1):
ret = ret + int(param[i]) * int(param[i+1])
return ret
my_string = "12345"
total = 0
for n in range(len(my_string) - 1):
total += int(my_string[n]) * int(my_string[n+1])
This function first turns your string into a list and then applies a map on it to convert all the elements to ints. Finally it uses a loop to access and multiply consecutive elements,
def str_sum(nstr):
nint = list(map(int, list(nstr)));
res = 0;
for i in range(len(nint[:-1])):
res += nint[i]*nint[i+1]
return res
Converting result of map into list using list(map(...)) is redundant in Python 2.7 but necessary in Python 3.X as map returns an object instead of a list.
Use range + sum
l = '13456'
sum([int(l[i])*int(l[i+1]) for i in range(len(l)-1)])
#Output:
#65
with range(len(l)-1), you can get the start, end indexes like below
Output:[0, 1, 2, 3]
Looping through the above list and indexing on list l,
int(l[i])*int(l[i+1]) # gives [1*3, 3*4 , ...]
Summing the output list
sum([1*3, 3*4 , ...]) # gives 65
def func(input):
return sum([int(input[i])*int(input[i+1]) for i in range(len(input)-1)])

Python list, take even elements and odd elements to their own respective new lists

I am working on a problem wherein I paste a set of numbers, and I want to put the even and odd list elements from these numbers and put them in their own list, then add them together for a 3rd list.
Here is my code:
#list of numbers
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
x = start.split()
#turn string into list elements then append to a list
step_two = []
step_two.append(x)
print step_two
# doublecheck that step_two is a list with all the numbers
step_three = step_two[1::2]
#form new list that consists of all the odd elements
print step_three
#form new list that consists of all the even elements
step_four = step_two[0::2]
print step_four
#add ascending even/odd element pairs together and append to new list
final_step = [x + y for x, y in zip(step_three, step_four)]
print final_step
This code yields these results:
"""
"Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
[['601393', '168477', '949122', '272353', '944397', '564134', '406351', '745395'
, '281988', '610822', '451328', '644000', '198510', '606886', '797923', '388924'
, '470601', '938098', '578263', '113262', '796982', '62212', '504090', '378833']
]
[]
[['601393', '168477', '949122', '272353', '944397', '564134', '406351', '745395'
, '281988', '610822', '451328', '644000', '198510', '606886', '797923', '388924'
, '470601', '938098', '578263', '113262', '796982', '62212', '504090', '378833']
]
[]
"""
Why is my list in step_three and step_four not working? I am not sure why my [::] functions aren't registering.
Thanks in advance for any advice.
You were too explicit here in step two:
x = start.split()
#turn string into list elements then append to a list
step_two = []
step_two.append(x)
x is already the list you need. step_two creates a new list and adds the previous list to it, so instead of ['601393', '168477',...], you have [['601393', '168477',...]].
To fix this, simply call the split string step_two and proceed from there:
step_two = start.split()
The reason your lists don't split the numbers into odd and even is that your code assumes that the list alternates between them - you take every other index for each list generation, but the numbers aren't arranged that way in the original string.
You'll need to do an 'evenness' test:
step_two = start.split()
step_three = []
step_four = []
for item in step_two:
if int(item) % 2: # If it divides evenly by two, it returns 0, or False
step_three.append(item)
else:
step_four.append(item)
The lists step_three and step_four will now correctly contain only odds or evens.
Here is how I would generate the odd list, hope it helps!
import sys
# Provided main(), calls mimic_dict() and mimic()
def main():
#list of numbers
start = '601393 168477 949122 272353 944397 564134 406351 745395 281988 610822 451328 644000 198510 606886 797923 388924470601 938098 578263 113262 796982 62212 504090 378833'
x = start.split()
#turn string into list elements then append to a list
step_two = []
# gives you 23 items in your list "step_two" instead of 1 item with original append on it's own
for s in x:
step_two.append(s)
#print (step_two)
# print (step_two)
# doublecheck that step_two is a list with all the numbers
i = 1
step_three_odd_list = []
while i < len(step_two):
currentodditem = step_two[i]
step_three_odd_list.append(currentodditem)
i = i + 2
#form new list that consists of all the odd elements
print (step_three_odd_list)
if __name__ == '__main__':
main()
The [::] that you have going on are extended slices, not tests for even and odd:
https://docs.python.org/release/2.3.5/whatsnew/section-slices.html
Also, since those numbers are in a string, when you split them you end up with strings, not integers that you test with math. So, you need to convert them to integers.
This post clued me in on a quick even/odd test: Check if a number is odd or even in python
This code seems to do what you want, if I understand it correctly:
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
# List comprehension to generate a list of the numbers converted to integers
step_two = [int(x) for x in start.split()]
# Sort the list
step_two.sort()
# Create new lists for even and odd
even_numbers = []
odd_numbers = []
# For each item in the list, test for even or odd and add to the right list
for number in step_two:
if (number % 2 == 0):
#even
even_numbers.append(number)
else:
#odd
odd_numbers.append(number)
print(even_numbers)
print(odd_numbers)
final_step = [x + y for x, y in zip(even_numbers, odd_numbers)]
print(final_step)
You can use list comprehensions to create two lists odd and even :
import itertools
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
lst = start.split()
even = [int(i) for i in lst if int(i) % 2 == 0]
odd = [int(i) for i in lst if int(i) % 2 != 0]
Then you can zip these 2 lists but as even and odd are not the same length, you have to use itertools.zip_longest() in Python 3 and itertools.izip_longest() in Python 2. You will then have a list of tuples:
final_step = [i for i in itertools.zip_longest(even,odd)]
[(949122, 601393),
(564134, 168477),
(281988, 272353),
(610822, 944397),
(451328, 406351),
(644000, 745395),
(198510, 797923),
(606886, 470601),
(388924, 578263),
(938098, 378833),
(113262, None),
(796982, None),
(62212, None),
(504090, None)]
You can create the third list result to sum() the values using an other list comprehension but you have to make sure not to try to sum the tuples where one value is None.
result = [sum(e) if e[1] is not None else e[0] for e in final_step]
The final output:
[1550515,
732611,
554341,
1555219,
857679,
1389395,
996433,
1077487,
967187,
1316931,
113262,
796982,
62212,
504090]

Categories

Resources