Get numerical values from string input in Python [closed] - python

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]

Related

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])

Creating two lists and compare the matching [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 two list of numbers but I need a evaluate and see if any numbers match then out put the # of matching numbers.
import random
matches = random.sample (range(1, 20), 5),random.sample (range(1, 20), 5)
You might be able to use a set intersection.
from random import sample
set_a = set(sample(range(0, 50), 10))
set_b = set(sample(range(0, 50), 10))
print set_a.intersection(set_b) # [3, 4]
print set_a & set_b # sugar for the same thing
list comprehension one liner:
[x for x in list_a if x in list_b]
you get the list of items contained in both lists.
to demonstrate all items are found:
>>> a = range(10,50)
>>> b = range(10,50)
>>> [x for x in a if x in b]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
From what I understood from your code I came up with following code. Let me know if this helped you
m = [1,2,3]
n = [3,4,1]
for i in m:
for j in n:
if i == j:
print "matched elements are list1 and list2 are (%s) and (%s)" %(i,j)
else:
print "list1 and list2 have unique elements"

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))

Python string to list conversion [duplicate]

This question already has answers here:
Converting a string that represents a list, into an actual list object [duplicate]
(5 answers)
Closed 8 years ago.
i have a string like this
sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"
how do i convert that to list? I am expecting the output to be list, like this
output=[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]
I am aware of split() function but in this case if i use
sample.split(',')
it will take in the [ and ] symbols. Is there any easy way to do it?
EDIT Sorry for the duplicate post..I didn't see this post until now
Converting a string that represents a list, into an actual list object
If you're going to be dealing with Python-esque types (such as tuples for instance), you can use ast.literal_eval:
from ast import literal_eval
sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"
sample_list = literal_eval(sample)
print type(sample_list), type(sample_list[0]), sample_list
# <type 'list'> <type 'int'> [2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]
you can use standard string methods with python:
output = sample.lstrip('[').rstrip(']').split(', ')
if you use .split(',') instead of .split(',') you will get the spaces along with the values!
you can convert all values to int using:
output = map(lambda x: int(x), output)
or load your string as json:
import json
output = json.loads(sample)
as a happy coincidence, json lists have the same notation as python lists! :-)

How to improve this python code? [closed]

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)]

Categories

Resources