I have a list with int values that I would like to add to each other and log the end value. So far I could create a working solution, but it's not so elegant and I would be happy if somebody could show me a smarter solution to achieve the same result.
numberList = (list(string_dict.values()))
numz = []
placeholder = 0
for x in numberList:
numz.append(int(x))
for y in numz:
placeholder = placeholder + y
print (placeholder)
# [1,2,3]
# result: 6
You can use the sum function:
print(sum(int(x) for x in string_dict.values()))
You can take out both loops by using the map() and sum() functions:
numberList = list(string_dict.values())
numz = []
placeholder = 0
numz = list(map(int, numberList))
placeholder = sum(numz)
print (placeholder)
You don't really need to have numberList and numz in there, though. Just do this:
placeholder = sum(map(int, string_dict.values()))
You can use reduce function also:
from functools import reduce
print reduce( (lambda x, y: x + y), string_dict.values() )
Related
Here is a problem that I am having trouble solving:
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Here is the code that I have so far:
def naturalNumbers(x):
x = input()
myList = []
for i in range (0, x):
return myList = myList + [i]
print(myList)
I'm really confused as to when to put return for functions.
you are working very hard
the function range() returns a an object castable to list, so all you need to do is
def naturalNumbers(x):
return list(range(1,x + 1)) #didnt notice we are in python 3
0 is not considered a natural number
Your are mixing both your 'main' code and the function that you are being asked to write.
let your function be only for your list generating function naturalNumbers.
and use a different main function.
you can ignore the main method and the if __name__ = '__main__'
this is just to run correctly with good form.
# this method outputs a list from 0 to x
def naturalNumbers (x):
l = list[]
for i in range(0, x+1):
list.append(i)
return l
def main():
x = input()
# should check if x is an integer (defensive programming)
print (naturalNumbers(x))
if __name__ = "__main__"
main()
also depending on the definition used natural numbers can start form 0 or 1
Return is the output from a function. Without the return the function doesn't 'give back' anything to where it was called.
def naturalNumbers(n):
return [x for x in range(0,n)]
print(naturalNumbers(5))
The above print statement uses the output of natural numbers and will print [0,1,2,3,4].
Say we remove the return and just assign it to a value.
def naturalNumbers(n):
numbers = [x for x in range(0,n)]
#assignment rather than return, we could do other operations.
print(naturalNumbers(5))
#returns None
The above print statement prints 'None' as this is the default return value in Python
def naturalNumbers(n):
n = input()
myList = []
for i in range(1, n + 1):
myList.append(i)
return myList
Or use list comprehension:
def naturalNumbers(n):
n = input()
myList = [i for i in range(1, n + 1)]
return myList
return is the end of a function, it should be outside of a loop.
Try this simple method:
def naturalNumbers(n):
myList = []
for i in range(0,n):
myList = myList+[i+1]
return myList
list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
so I have this code that gives the result of
lecture 1
lecture 2
for an input of lecture(3). Now, when I change the code to
list = []
def lecture(x):
for x in range(1,x):
y = 'lecture', x
print y
i get an output of
('lecture', 1)
('lecture', 2)
Ultimately I would like to know why this is the case as I am trying to find a way of appending the first results, the:
lecture 1
lecture 2
into a list but I can't as I get a list with the lecture number separated from its number by a comma etc.
You are getting that strange notation because 'lecture', x is a tuple. A datatype which acts like a list, but a non-flexible list. You can't change them that easily. You have to use the +-operator instead of a comma to put those two values into one variable.
And putting values in a list is done with the append function.
list = []
def lecture(x):
for x in range(1,x):
y = 'lecture' + str(x)
list.append(y);
lecture(5)
Also note:
y = 'lecture' + str(x)
the str(x) is to make sure the different datatypes (int and string) don't conflict. Because String + Int ain't possible.
5 (Int) + 5 (Int) is 10.
5 (String) + 5 (String) is 55.
But 5 (String) + 5 (Int) is an error.
Swap y = 'lecture', x with:
y = 'lecture ' + str(x)
This will append the variable x to 'lecture' and set it in variable y
With the expression y = 'lecture', x, you are creating a tuple. Create an empty list instead, and append values to it with the for loop:
def lecture(x):
lecture_list=[]
for item in range(1,x+1):
y='lecture '+str(item)
lecture_list.append(y)
return lecture_list
An alternative way:
class Lectures(object):
def __init__(self, x):
self.x = x
def __iter__(self):
for i in range(1, self.x):
yield "lecture" + i
Here an iterable class Lectures is made.
First you need to initialize it, passing x as an attribute:
lectures = Lectures(x)
Then you can use it as an iterable:
list_of_lectures = list(lectures)
or
for lecture in lectures:
do_something
I have a list of words . I wants to filter out words which do not have minimum length. I tried filter, but showing some error . My code is
def words_to_integer(x,y):
return len(x)> y
print("enter the list of words : ")
listofwords = [ str(x) for x in input().split()] #list of words
minimumlength = print("enter the length ")
z = list(filter(words_to_integer,(listofwords,minimumlength)))
print("words with length greater than ",minimumlength ,"are" ,z )
error is
z = list(filter(words_to_integer,(listofwords,minimumlength)))
TypeError: words_to_integer() missing 1 required positional argument: 'y'
You should look at functools.partial:
from functools import partial
z = filter(partial(words_to_integer, y=minimumlength), listofwords)
partial(words_to_integer, y=minimumlength) is the same function as words_to_integer, but with argument y being fixed at minimumlength.
You can't do that. You need to pass a function that already knows about minimumlength.
One easy way to do this would be to use a lambda instead of your standalone function:
filter(lambda x: len(x) > minimumlength, listofwords)
When you type this
list(filter(words_to_integer,(listofwords,minimumlength)))
python tries to do something like this:
z = []
if words_to_integer(listofwords):
z.append(listofwords)
if words_to_integer(minimumlength):
z.append(minimumlength)
which will fail, because words_to_integer accepts 2 arguments, but only one was given.
You probably want something like this:
z = []
for word in listofwords:
if words_to_integer(word):
z.append(word)
which looks like this with filter:
z = list(filter(lambda word: words_to_integer(word, minimumlength), listofwords))
or use partial like in the other answer.
I want to join the elements in this list, L, and store the result in a variable k.
such that
L=[1,1,0,1,0]
k=11010
If you are using Python (like I suspect [and a previous question of yours was on python]), this isn't very difficult.
x = [0,1,2,3,4]
xs = ""
for i in x:
xs+=str(i)
print(xs) #As string
If you want to get it as an integer, you can add
k = int(xs)
As a function, this would be:
def makeIntFromList(x):
xs = ""
for i in x:
xs+=i
return int(xs)
Or, you can use join().
def joinElementsToInt(x):
return int("".join([str(i) for i in x]))
In javascript:
var k, L=[1,1,0,1,0];
k = L.join("");
will do the job.
I have a generator that will keep giving numbers that follow a specific formula. For sake of argument let's say this is the function:
# this is not the actual generator, just an example
def Generate():
i = 0
while 1:
yield i
i+=1
I then want to get a list of numbers from that generator that are below a certain threshold. I'm trying to figure out a pythonic way of doing this. I don't want to edit the function definition. I realize you could just use a while loop with your cutoff as the condition, but I'm wondering if there is a better way. I gave this a try, but soon realized why it wouldn't work.
l = [x for x in Generate() x<10000] # will go on infinitely
So is there a correct way of doing this.
Thanks
An itertools solution to create another iterator:
from itertools import takewhile
l = takewhile(lambda x: x < 10000, generate())
Wrap it in list() if you are sure you want a list:
l = list(takewhile(lambda x: x < 10000, generate()))
Or if you want a list and like inventing wheels:
l = []
for x in generate():
if x < 10000:
l.append(x)
else:
break
Wrap your generator within another generator:
def no_more_than(limit):
def limiter(gen):
for item in gen:
if item > limit:
break
yield item
return limiter
def fib():
a,b = 1,1
while 1:
yield a
a,b = b,a+b
cutoff_at_100 = no_more_than(100)
print list(cutoff_at_100(fib()))
Prints:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
itertools.takewhile will only work until it comes across an item that does not fulfill the predicate. If you need to return all values from a possibly unordered iterable, I'd recommend using itertools.ifilter for Python 2.x as in
from itertools import ifilter
f = ifilter(lambda x: x < 400, gen())
f.next()
This filtered a generator yielding random integers between 0 and 400 as hoped.
FWIW itertools.ifilter was deprecated in Python 3.x in favour of the built-in filter() which has slightly different syntax for iterating
f = filter(lambda x: x < 400, gen())
next(f)
Wrap it on a zip generator of a range of the limit:
gen = range(100_000_000_000)
limit = 10
(z[1] for z in zip(range(limit), gen))
zip creates a tuple, that is the reason for z[1]
This may be used on for loops:
for g in (z[1] for z in zip(range(limit), gen)):
print(g)
Or you could use lambda:
wrap = lambda gen, limit: (z[1] for z in zip(range(limit), gen))
for g in wrap(gen, 10):
print(g)
Just use a counter for an infinite generator:
gen=Generate() # your generator function example
l=[gen.next() for i in range(100)]
But since it is a generator, use a generator expression:
seq=(gen.next() for i in xrange(100)) #need x in xrange in Python 2.x; 3.x use range
Edit
OK, then just use a controller:
def controler(gen,limit):
n=gen.next()
while n<limit:
yield n
n=gen.next()
seq=[i for i in controler(Generate(),100)]
replace Generate() with xrange(10000)