I wrote a script in python to tell which numbers in new were in the first 10 numbers in new. I know it looks more complicated than it has too and that has to do with what I'm trying to do with the script later. For now though I'm trying to figure out why it's printing 'each' for EVERY number in the list 'new' and not just the ones before the tenth.
Here's my code:
i = 10
new = ['A lot of numbers']
for each in re.findall(r'[0-9]+', new):
if any(each for x in (re.findall(r'[0-9]+', new)[0:i])):
print each
else:
pass
You need to refer to x somehow in your generator expression, or else you're just checking any([each, each, each, ....]), which will always evaluate to true if each evaluates to true (which it always will for your regular expression). I suspect you want something like this, which tests if any of the first i items is equal to each:
if any(x==each for x in (re.findall(r'[0-9]+', new)[0:i])):
If you're looking for the first 10 letters in new, did you mean
if any(each for x in (re.findall(r'[0-9]+', new[0:i]))):
rather than:
if any(each for x in (re.findall(r'[0-9]+', new)[0:i])):
Also, did you mean for new to be a list? A list can't be passed to findall.
Finally, note that you never need an else: pass statement, an if works fine on its own.
If new is a list of strings, some of which are numbers like "123", and you want the first 10 of these numbers:
allnumbers = [x for x in new if re.match("[0-9]+", x)]
first10numbers = allnumbers[:10]
(For Python 2.x)
If new is a string, you'd have
allnumbers = [x for x in re.findall("[0-9]+", x)]
I'm not exactly sure what you're doing with this later, but if you're just trying to print the later numbers only if they show up in the first 10 numbers, you might just go like:
for number in [x for x in allnumbers if x in first10numbers]:
print number
Related
This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 6 months ago.
I am still relatively new to coding. I've been doing this for less than a year and most of the basics I completely understand now. However, every now and then I come across a type of for loop that I can't get my head around.
It usually goes like this:
x for x in list if x in otherList
I completley understand for loops and if statements. But that particular line of code always confuses me. Would anyone be able to provide a detailed explanation of what actually is happening there, please?
It's called a list comprehension if it's in brackets []:
This:
new_list = [x for x in my_list if x in other_list]
Is equivalent to this:
new_list = []
for x in my_list:
if x in other_list:
new_list.append(x)
If it's in parentheses () it's called a generator:
This:
new_list = (x for x in my_list if x in other_list)
Is sort of equivalent to this:
def foo():
for x in my_list:
if x in other_list:
yield x
new_list = foo()
You might want to read this question and answer to understand more about generators and yielding functions.
This is used within a list comprehension and the if statement acts as a filter.
You may begin with a list of all numbers from 0-9:
mynums = range(10)
But then you might want only the even numbers in a new list:
myevennums=[]
for i in mynums:
if mynums%2 ==0:
myevennums.append(i)
That works but so many keystrokes š
So python allows list comprehensions:
myevennums = [i for i in mynums if i%2==0]
The condition could be anything, including membership in another list:
evens_to_20 = list(range(0,21,2))
Then you could create a list with the elements of your list that are also in the other list:
myevennums = [i for i in mynums if i in evens_to_20]
In general, when you see a statement like that you can always expand it as:
Y_comprehension = [i for i in X if condition(i)]
# the same as
Y_loop=[]
for i in X:
if condition(i):
Y_loop.append(i)
assert Y_comprehension == Y_loop
If the condition really is very simple, the list-comprehension is usually the better choice. If it starts to get complicated, you probably want the loop or an intermediate function def condition(item): ...
Given a list of numbers and a numberĀ k, return whether any two numbers from the list add up toĀ k.
For example, givenĀ [10, 15, 3, 7]Ā andĀ kĀ ofĀ 17, return true sinceĀ 10 + 7Ā isĀ 17.
Bonus: Can you do this in one pass?
I wrote my code like this and i got right answer for the above input
x=[10,15,3,7]
y=17
for i in x:
if (y-i) in x:
print(True)
break
And checked others code too to know that i was right or wrong and many used sets in their code as
def sum_exists(l,k):
s = set()
for x in l:
if k-x in s:
return True
s.add(x)
return False
I still don't understand the difference between their code and mine.Am i wrong?
What is the use of sets differ from my code?
Your code iterates the list once and checks the list with in - in total you do lots of runs through the list.
You can do it in one pass with the additional space of a set:
x = [10,15,3,7]
y = 17
s = set()
for i in x: # go throug the list once
if y-i in s:
return True
s.add(i)
return False
Checking if something is in a set is O(1) (constant time) checking in in list is O(n) (linear time). If you have a list of 1 million uniqe numbers that do not add up to y your code iterates the list of 1 million times 1000001 times - once to go through and 1000000 times to check. Total time is O(1000001*1000000)
If you use a set it is O(1000000)+1000000*O(1) which is "better" but it takes some additional space/memory.
x={}
continueQ=input("would you like to continue?"))
if (continueQ=="yes"):
#if there is less than 4
if x<4:
variable=float(input("Input a float to append to the array:")
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array .
Also how to append to an array from an input.
Create a list with x = [], Use len(x) to get the length of list, use while loop with condition if x<4
x=[]
continueQ=input("would you like to continue?")
if (continueQ=="yes"):
#if there is less than 4
while len(x)<4:
variable=float(input("Input a float to append to the array:"))
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
The first thing you'll want to do is change that x={} to an x=[]. What you've done is create a dictionary rather than an array, and consequently will run into an assortment of issues as you're dealing with the wrong data structure.
Once you've done that, we can move on to how to check if there are less than 4 values inside an array. In Python, arrays carry a length attribute, which can be accessed by writing len(arrayName), or in your case, len(x). For example, if your array x contained the following values: [1,2,3], then len(x) would return 3, seems simple enough.
Now to check that the length is less than 4, you need to replace your if x<4: with if len(x)<4:.
You already have the correct code to append to your array, it likely wasn't working before because you created a dictionary instead of an array.
There are several errors in your code. Here's a working version:
x = []
continueQ = input('Would you like to continue?')
if continueQ.lower() == 'yes':
while len(x) < 4:
variable=float(input('Input a float to append to the array:'))
x.append(variable)
print(x)
print("Goodbye!")
Explanation
[] represents an empty list, while {} is use for an empty set.
Make sure your bracketing is consistent; all open brackets must be closed.
Use len(x) to find the number of entries in a list x.
Use a while loop to repeat logic until a criterion is satisfied.
So I've recently picked up John Guttag's Introduction to Computation and Programming Using Python,the revised and expanded edition, after having worked through most of LPTHW. I am using the book in conjunction with MIT OCW 006. Now, I was trying to complete one of the Finger Exercises listed in the book, specifically the one of page 85, chapter 7, where the author asks you to implement a function using a try-except block:
def sumDigits(s):
"""Assumes s is a string
Returns the sum of the decimal digits in s
For example, if is is'a2b3c' it returns 5"""
This is my code:
def sumDigits(s):
try:
total = 0
list1 = [s]
new_list = [x for x in list1 if x.isdigit()]
for e in new_list:
total += new_list[e]
return total
except TypeError:
print "What you entered is not a string."
When I run this program in the IDLE using a test input, the total is always computed to be zero, indicating that none of the elements of new_list are being passed to the accumulator. Could someone suggest why that is? Thanks.
It seems like the errors have been pointed out already by Rafael but it is still important to note that the more pythonic way to approach this would be:
return sum([int(x) for x in s if x.isdigit()])
There are actually several errors with your code.
Let's break them down in detail
The main problem is located in these lines:
list1 = [s]
new_list = [x for x in list1 if x.isdigit()]
You should loop directly over the string first
new_list = [x for x in s if x.isdigit()] #s is the input string
When you create a new list as you did, the variable x in x for x in list1 will take place as elements of the list. So, in your case, the list will have only one element, which happen to be whole string (because you defined the list as [s]. As the whole string is not a digit, new_list will be an empty list.
That is why you are getting 0 as a return.
However, if you loop through the string directly, x will take place as each letter in the string, and then it will be possible to check whether x is digit or not.
It is also important to highlight that new_list[e] will raise IndexError. You should correct that for e only. The sintax of for e in new_list makes the local variable e assume each value inside the list, so you do not have to get the value via indexes: you can use e directly.
Finally, in order to sum the values in your new_list, the values should be integers (int) and not string (str), so you have to cast the values to int before summing (or, you can cast each element to int during the list comprehension, by using int(x) for x in s if x.isdigit() instead of x for x in s if x.isdigit()). Also, in order to check if the input is a string or not, you better use isinstance(s, basestring) if you're in python2, or isinstance(s, str) if you're using python3.
So the whole code would look like this :
def sumDigits(s):
if isinstance(s, basestring):
total = 0
new_list = [x for x in s if x.isdigit()]
for e in new_list:
total += int(e)
return total
else:
print "What you entered is not a string."
I'm working through the same book and the MITx: 6.00.1x course on edX; here's my solution:
def sumDigits(s):
'''
Assumes s is a string
Returns the sum of the decimal digits in s
For example, if s is 'a2b3c' it returns 5
'''
result = 0
try:
for i in range(len(s)):
if s[i].isdigit():
result += int(s[i])
return result
except:
print('Your input is not a string.')
Since we are to assume that s is a string, the except block should handle those cases where s is not a string. So simple, but it was not obvious to me at first.
You can use reduce method
reduce( (lambda x, y: x + y), [int(x) for x in new if x.isdigit()] )
I'm working through the same book too. I think we should use the try-except block on determining whether characters of string convertible to an integer. So here is my solution.
def sumDigits(s):
"""Assumes s is a string
Returns the sum of the decimal digits in s
For example, if s is 'a2b3c' it returns 5"""
sum = 0
for i in s:
try:
sum += int(i)
except ValueError:
None
return sum
So I made this little code at school, and i know that input() can understand lists as is. I tried it again at home but it doesnt work. My school computer has python 2. something while my laptop has 3.4.
The code looks like this
a = input()
list = []
count = 0
for y in range(1, len(a)):
min = a[count]
for x in range(count +1, len(a)):
if min > a[x]:
min = a[x]
print(min)
a[count] = min #str object does not support item assignment
count=count+1
print (a)
I want to input a list such as [1,2,3,4,5] but what happens is, it reads the whole thing as a string, along with the commas, when i want to see it as a list of integers.
Python 3's input returns a string (same as Python 2's raw_input), whilst Python 2's input evaluates the text. To get similar behaviour, if you've got a valid Python list that can be evaluated, then you can use ast.literal_eval, eg:
import ast
a = ast.literal_eval(input())
# do other stuff with `a` here...
So you'd enter something like [1, 2, 3, 4, 5] as your input, and you'll end up with a being a Python list.
I assume your input would be something like: "1 2 3 4 5" -- judging by the code which comes later. This oufcourse is a string. If you want to work with the numbrs in the string as integers you need to:
a = input()
a = map(int, a.split())