How to improve this python code? [closed] - python

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am doing a problem in which i have to code about this problem-
>>> getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
>>> getNumbers(9)
[81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
I am getting answers with my code but i am not satisfied with my code,please suggest some options to improve this code.
def getNumbers(num):
myList=[]
mylist=[]
if num%2==0:
for numbers in range(num,-2,-2):
myList.append(numbers**2)
for numbers in range(2,num+2,2):
mylist.append(numbers**2)
print myList+mylist
elif num%3==0:
for numbers in range(num,-1,-2):
myList.append(numbers**2)
for numbers in range(1,num+2,2):
mylist.append(numbers**2)
print myList+mylist
else:
print(mylist)
4 for loops!!! this is what teasing me here!!!

Like this?
def getNumbers(n):
return [i * i for i in range(-n, n + 1, 2)]

Related

python dictionary list, getting an item inside a bracket [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 2 years ago.
Improve this question
items = {
'flour': [20, 10, 15, 8, 32, 15],
'beef': [3,4,2,8,2,4],
'bread': [2, 3, 3],
'cc': [0.3, 0.5, 0.8, 0.3, 1]
}
I ned to get the third element on each of the ingredients' bracket,
the answer will be (15, 2, 3, 0.8)
Please, thanks for your help!
You can do :
op = [v[2] for v in items.values()]
print(op)
Note: It won't maintain the same order in prior versions of python3.7

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]

What is a clearer way to generate this sequence of numbers? [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 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.

Get numerical values from string input in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to make a function that takes a string as input and outputs a list of all numerical values.
Some examples:
"22-28, 31-35, 37" should output: [22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 34, 35, 37]
"22, 24" should output: [22, 24]
"23" should output: [23]
How can I do this?
Try regular expressions.
import re
r = re.findall('[0-9]+-[0-9]+|[0-9]+',string)
ans = []
for i in r:
if '-' in i:
t = i.split('-')
ans.extend(range(int(t[0]),int(t[1])))
else:
ans.append(int(i))
print ans
Without regular expressions:
def text_range(s):
res = []
for pc in s.split(','):
if '-' in pc: # this assumes no negative numbers in the list!
a,b = [int(i) for i in pc.split('-')]
res.extend(range(a, b+1))
else:
res.append(int(pc))
return res
then
text_range("22-28, 31-35, 37") # -> [22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 34, 35, 37]

Categories

Resources