What is a clearer way to generate this sequence of numbers? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to generate a list like this:
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
and this is my current code
g = lambda x: x + g(x - 2) if x > 0 else 0
print([g(2 * i) for i in range(10)])
Is there a clearer and more direct way to generate the sequence?

These appear to be the first few pronic numbers. That is, a number which is the product of two consecutive integers, n * (n + 1).
I've found this by searching in the OEIS. It's simple to generate them with a list comprehension:
>>> [x*(x + 1) for x in range(10)]
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]

Your algorithm is, as #wim has already pointed out, for "pronic numbers", and can be summarised to:
The n-th pronic number is the sum of the first n even integers
You can therefore write it as:
def pronic(n):
"""Create a list of the first n pronic numbers."""
return [sum(range(0, 2*i+1, 2)) for i in range(n)]
However, while this is a clear implementation of the approach you've taken, the other definition can make it even neater, as #wim's answer shows.
You could also consider implementation as a generator:
def pronic():
"""Generate the pronic numbers."""
i = 0
while True:
yield i * (i + 1)
i += 1

list1 = [x+(x ** 2) for x in range(10)]
print list1
Output : [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
This will give you the series that you have asked for.

Related

How can you write a code that prints out the last lowest number in a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
How to find last lowest number in a list.
Lowest number can be defined as: The first number from the last which is continuously decreasing until the next element is greater than or equal to previous element.
E.g. for num_list = [88, 2, 22, 35, 76, 4, 50, 19, 12 , 56, 82]
last lowest would be 12
my code:
my_list = [88, 2, 22, 35, 76, 4, 50, 19, 12 , 56, 82]
last_number = my_list[-1]
for number in my_list:
if number < last_number:
last_number = number
print(last_number)
output getting: 2
expected output: 12
You can iterate through a list backwards by reversing the list and doing normal for item in my_list, or you can do a range with negative step. Either way, as soon as you identify that the current value is more than the previous (which by definition of the problem must be the lowest from the back), you break the loop.
my_list = [88, 2, 22, 35, 76, 4, 50, 19, 12 , 56, 82]
lowest = my_list[-1]
# starts at len(my_list)-2 to skip my_list[-1].
# will return the same result even if it starts at len(my_list)-1
for idx in range(len(my_list)-2, 0, -1):
if my_list[idx] <= lowest:
lowest = my_list[idx]
else:
break
print(lowest)

First number in list a variable isn't larger than [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Is there a quick way that doesn't involve a bunch of if-statements to get the first element in a list that my variable isn't bigger than? For example, if
x = 50
compare = [1, 4, 9, 16, 25, 36, 49, 64, 81]
I want this to return 64. My list will also be written in increasing order, so not every element in the list will need to be compared.
There's a short way of doing this that doesn't involve any for loop:
>>> x = 50
>>> compare = [1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> next(item for item in compare if item >=x)
64
This creates an iterator of values that are >= x, and then selects the first one.
Use a loop. Test each element, and break out of the loop when you find what you're looking for.
result = None
for el in compare:
if x < el:
result = el
break
if result is not None:
print('Found', result)
else:
print('Not found')
Here is a solution with numpy:
import numpy as np
x = 50
compare = np.array([1, 4, 9, 16, 25, 36, 49, 64, 81] )
compare[compare>=x][0]
I would use a while loop:
count = 0
while x < compare[count]:
count += 1
print(compare[count])

python: how can i create a list of integers,to a number? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I receive an input int that I don't previously know. How can I create a new list of integer from 0 to that int? An easy way please. Thank you in advance.
I mean that:
k = n
...
list = [0, ... , k]
numbers = list(range(k+1)) # For Python 2, it is just range(k+1).
Given an integer k, which you can get with input.
The range creates an iterator (in Python 3) with those numbers (k+1 because it is not inclusive, but you need it to be), then we make it into a list.
Demo:
>>> k = int(input())
16
>>> numbers = list(range(k+1))
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
A simple function would look like this, assuming you've got your input number n:
For python2.x:
def get_range(n):
return range(n + 1)
For python3.x:
def get_range(n):
return list(range(n + 1))
In either case:
int_list = get_range(10)
>>> print(int_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Adding more than one list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to try the many ways the function of python
So, I want to not use zip use other python function ,how can i do to?
this is use zip and adding more than one list:
but i want to other way not use zip:
x = [12, 22, 32, 42, 52, 62, 72, 82, 29]
y = [10, 11, 12, 13, 14, 15, 16, 17, 18]
def add_list(i, j):
l = []
for n, m in zip(x, y):
l.append(n + m)
return l
i know this way,
without using zip, you can use map:
from operator import add
x = [12, 22, 32, 42, 52, 62, 72, 82, 29]
y = [10, 11, 12, 13, 14, 15, 16, 17, 18]
res = map(add, x, y)
# [22, 33, 44, 55, 66, 77, 88, 99, 47]
Note that if the iterables are of different lengths, than the shortest will be padded with None which will cause a TypeError in the add instead of zip which will truncate to the shortest list.
On an aside there's absolutely nothing wrong with using zip - I'd probably re-write it as a list-comp though, eg:
[sum(items) for items in zip(x, y)]
This then scales easily to doing zip(x, y, z, another_list) etc...
oh, there are plenty of possibilities, here are a few:
# most simple way
res = []
for i in range(len(x)):
res.append(x[i]+y[i])
# this is the same as
res = [x[i]+y[i] for i in range(len(x))]
# more pythonic
from operator import add
res = map(add, x, y)
# less pytonic
res = map(int.__add__, x, y)
# using numpy
import numpy as np
res = list(np.array(x) + np.array(y))
# alternatively
res = list(np.add(x, y))
# also
res = list(np.sum([x,y], axis=0))

Expand a string describing a set of numbers noted as a list of numbers and/or ranges [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to parse a string which describes a set of numbers. The numbers are listed in order, but a range of consecutive numbers can be abbreviated with a "range" using a hyphen/dash.
Example: "001,008-011,020"
I want to interpret this string this as an ordered list: [ 1, 8, 9, 10, 11, 20 ]
There could be a arbitrary number of ranges and elements.
You could do something like the following..
>>> def findval(str):
... val = []
... for x in str.split(','):
... if '-' in x:
... lnum, rnum = x.split('-')
... lnum, rnum = int(lnum), int(rnum)
... val.extend(range(lnum, rnum + 1))
... else:
... lnum = int(x)
... val.append(lnum)
... return val
>>> findval('001,008-011,020')
[1, 8, 9, 10, 11, 20]
See Working demo
If you know that the string will always be in that format...
x = "001,008-011,020"
x = x.split(',') # Split at the commas
y = []
# Iterate over the list
for i in x:
try:
# Will append the integer to your output list
y.append(int(i))
except ValueError:
# If you get a ValueError (from trying to int('008-011') for example)
# then split the string at the hyphen and individually append
# the integers in between.
j = i.split('-')
for k in range(int(j[0]), int(j[1])+1):
y.append(k)
I think that should work, though you may want to check that no other ValueErrors will be inadvertantly caught in the try/except loop.
How about:
def expand(s):
parts = (map(int, x.split('-')) for x in s.split(','))
return (n for p in parts for n in range(p[0], p[-1]+1))
after which
>>> expand("001")
<generator object <genexpr> at 0x901b784>
>>> list(expand("001"))
[1]
>>> list(expand("001,008-011,020"))
[1, 8, 9, 10, 11, 20]
Implement something like so, capturing the range and iterating based on the integer value:
str = "001,008-011,020"
spl = str.split(",")
output = []
for s in spl:
if '-' in s:
rng = s.split(r"-")
for r in range(int(rng[0]), int(rng[1])+1):
output.append(r)
else:
output.append(int(s))
print output
prints:
[1, 8, 9, 10, 11, 20]

Categories

Resources