Here is what I want to accomplish :
a = 1235
My result r should calculate 1/2 + 2/(2*2) + 3/(2*2*2) + 5/(2*2*2*2), so
r will output 1.6875
I tried..
s = 123
l = list(map(int, str(s))) # converted into list
print(l)
y = [int(x)/(2**s.index(x)) for x in l]
print(y)
but it does not work.
Don't use index (slow and will return the first index over and over, which is wrong), just iterate on the index (plus 1) of the string using enumerate.
Then feed directly to sum.
BTW your code can be simplified to write this directly in one line:
y = sum(int(x)/(2**i) for i,x in enumerate(str(1235),1))
result:
1.6875
Related
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)])
My function looks like this:
def accum(s):
a = []
for i in s:
b = s.index(i)
a.append(i * (b+1))
x = "-".join(a)
return x.title()
with the expected input of:
'abcd'
the output should be and is:
'A-Bb-Ccc-Dddd'
but if the input has a recurring character:
'abccba'
it returns:
'A-Bb-Ccc-Ccc-Bb-A'
instead of:
'A-Bb-Ccc-Cccc-Bbbbb-Aaaaaa'
how can I fix this?
Don't use str.index(), it'll return the first match. Since c and b and a appear early in the string you get 2, 1 and 0 back regardless of the position of the current letter.
Use the enumerate() function to give you position counter instead:
for i, letter in enumerate(s, 1):
a.append(i * letter)
The second argument is the starting value; setting this to 1 means you can avoid having to + 1 later on. See What does enumerate mean? if you need more details on what enumerate() does.
You can use a list comprehension here rather than use list.append() calls:
def accum(s):
a = [i * letter for i, letter in enumerate(s, 1)]
x = "-".join(a)
return x.title()
which could, at a pinch, be turned into a one-liner:
def accum(s):
a = '-'.join([i * c for i, c in enumerate(s, 1)]).title()
This is because s.index(a) returns the first index of the character. You can use enumerate to pair elements to their indices:
Here is a Pythonic solution:
def accum(s):
return "-".join(c*(i+1) for i, c in enumerate(s)).title()
simple:
def accum(s):
a = []
for i in range(len(s)):
a.append(s[i]*(i+1))
x = "-".join(a)
return x.title()
I tried to add the comma seprated value between the : seprated then multiply the whole value
For example, consider my value is 1,2,3:4,5,6
I want to add the 1+2+3 ,and 4+5+6 then multiply the result of this value so answer is 6 * 15 = 90
For my bellow data i want the result is 7.224 but this script gives 61.658886435
I don't know what is the problem in my script'
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
x_add = 0
for i in x_data:
x_each = i.split(",")
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
Is any possible way to get the result without iterating loop? For above problem
This problem could be also solved in a functional way:
You have to multiply all values in the list - this is what functools.reduce + operator.mul for
You have to sum up all values in all inner lists - this is what sum for
Example:
In [5]: ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
In [6]: import operator
In [7]: import functools
In [8]: functools.reduce(operator.mul, (sum(float(x) for x in s.split(',')) for s in ar.split(':')))
Out[8]: 7.223521582500001
I don't necessarily recommend this complicated expression, but you can do it with list comprehensions and avoid the for loops:
import operator
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
reduce(operator.mul, [sum([float(n) for n in e]) for e in [x.split(',') for x in ar.split(":")]], 1)
Use missed the initialize value as zero (x_add = 0) in each iterating. So your script add with the previous values
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
for i in x_data:
x_each = i.split(",")
x_add = 0 # Here you not initialize it
for j in x_each:
x_add = x_add + float(j)
x_final = x_add * x_final
print x_final
!!! As from #jpmc26 and #soon comment. Avoid using eval, and conform your input string format.
Without looping use regex for to do it
Use regex for solve your problem without looping.
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
import re
ar = "("+ar #Add the ( with your data
ar = re.sub(r",","+",ar) #Substitute with + instead of ,
ar = re.sub(r"(?=\:|$)",")",ar) #look ahead for add `)` after colon
ar = re.sub(r"(?<=)\:","*(",ar) #Replace the color with *
#NOw you data look likes(0.212+1.231+0.112)*(1.001+3.212+0.002)*(0.002+0.0001+1.1)
#Finally evaluvate the string as a expression
print eval(ar)
thats what I get:
TypeError: 'float' object is unsubscriptable
Thats what I did:
import numpy as N
import itertools
#I created two lists, containing large amounts of numbers, i.e. 3.465
lx = [3.625, 4.625, ...]
ly = [41.435, 42.435, ...] #The lists are not the same size!
xy = list(itertools.product(lx,ly)) #create a nice "table" of my lists
#that iterttools gives me something like
print xy
[(3.625, 41.435), (3.625, 42.435), (... , ..), ... ]
print xy[0][0]
print xy[0][1] #that works just fine, I can access the varios values of the tuple in the list
#down here is where the error occurs
#I basically try to access certain points in "lon"/"lat" with values from xy through `b` and `v`with that iteration. lon/lat are read earlier in the script
b = -1
v = 1
for l in xy:
b += 1
idx = N.where(lon==l[b][b])[0][0]
idy = N.where(lat==l[b][v])[0][0]
lan/lot are read earlier in the script. I am working with a netCDF file and this is the latitude/longitude,read into lan/lot.
Its an array, build with numpy.
Where is the mistake?
I tried to convert b and v with int() to integers, but that did not help.
The N.where is accessing through the value from xy a certain value on a grid with which I want to proceed. If you need more code or some plots, let me know please.
Your problem is that when you loop over xy, each value of l is a single element of your xy list, one of the tuples. The value of l in the first iteration of the loop is (3.625, 41.435), the second is (3.625, 42.435), and so on.
When you do l[b], you get 3.625. When you do l[b][b], you try to get the first element of 3.625, but that is a float, so it has no indexes. That gives you an error.
To put it another way, in the first iteration of the loop, l is the same as xy[0], so l[0] is the same as xy[0][0]. In the second iteration, l is the same as xy[1], so l[0] is the same as xy[1][0]. In the third iteration, l is equivalent to xy[2], and so on. So in the first iteration, l[0][0] is the same as xy[0][0][0], but there is no such thing so you get an error.
To get the first and second values of the tuple, using the indexing approach you could just do:
x = l[0]
y = l[1]
Or, in your case:
for l in xy:
idx = N.where(lon==l[0])[0][0]
idy = N.where(lat==l[1])[0][0]
However, the simplest solution would be to use what is called "tuple unpacking":
for x, y in xy:
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
This is equivalent to:
for l in xy:
x, y = l
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
which in turn is equivalent to:
for l in xy:
x = l[0]
y = l[1]
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
Say I have a list of numbers such as:
my_list = [1, 17, 2]
And I wanted to add those together. I know I can use print(sum(my_list)). However I wanted to see if there was another way of doing so, so I tried the following:
b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
m += m
print(m)
I am sure something like this should work, but I am obviously doing it wrong. The output of this is 2. After I tried:
result = 0
b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
result = result + m
print(result)
This outputs 1.
Please explain what I am doing wrong and how I can correct it.
Since you are using range function defining range between 1 and 2. The only data generated in m is 1 hence result is 1.
In Python, you can iterate over the elements of a sequence directly:
m = [1, 17, 2]
res = 0
for i in m:
res += i
print res
First, you should put a correct range: 0..2 in your case (since your list items' indexes starts from 0 and has 2 items)
for i in range(0, b):
result = result + my_list[i];
Or if you prefer "for each" style you should itterate by list you are summing:
for m in my_list:
result = result + m;
Finally if you want to print a final sum only you should correct print indent:
for m in my_list:
result = result + m;
print(result) # <- mind indent
Wrapping up:
my_list = [1, 17, 2]
result = 0
for m in my_list:
result = result + m;
print(result)
from operator import add
my_list = [1, 17, 2]
result=reduce(add, my_list)
import functools
print(functools.reduce(lambda x,y: x+y, my_list))
try this
my_list = [1, 17, 2]
reduce(lambda x, y: x+y, my_list)
to get the values from my_list you can use this syntax:
for m in my_list:
print m
If you use range it will give you a range from 1 ( first value of your list ) to 2 (length of your list -1)
To add the values of your list you can try this code:
out = 0
for m in my_list:
out = out + m
print(out)