Loop problems Even Count - python-2.7

I have a beginner question. Loops are extremely hard for me to understand, so it's come to me asking for help.
I am trying to create a function to count the amount of even numbers in a user input list, with a negative at the end to show the end of the list. I know I need to use a while loop, but I am having trouble figuring out how to walk through the indexes of the input list. This is what I have so far, can anyone give me a hand?
def find_even_count(numlist):
count = 0
numlist.split()
while numlist > 0:
if numlist % 2 == 0:
count += 1
return count
numlist = raw_input("Please enter a list of numbers, with a negative at the end: ")
print find_even_count(numlist)
I used the split to separate out the indexes of the list, but I know I am doing something wrong. Can anyone point out what I am doing wrong, or point me to a good step by step explanation of what to do here?
Thank you guys so much, I know you probably have something more on your skill level to do, but appreciate the help!

You were pretty close, just a couple of corrections:
def find_even_count(numlist):
count = 0
lst = numlist.split()
for num in lst:
if int(num) % 2 == 0:
count += 1
return count
numlist = raw_input("Please enter a list of numbers, with a negative at the end: ")
print find_even_count(numlist)
I have used a for loop rather than a while loop, stored the outcome of numlist.split() to a variable (lst) and then just iterated over this.

You have a couple of problems:
You split numlist, but don't assign the resulting list to anything.
You then try to operate on numlist, which is still the string of all numbers.
You never try to convert anything to a number.
Instead, try:
def find_even_count(numlist):
count = 0
for numstr in numlist.split(): # iterate over the list
num = int(numstr) # convert each item to an integer
if num < 0:
break # stop when we hit a negative
elif num % 2 == 0:
count += 1 # increment count for even numbers
return count # return the total
Or, doing the whole thing in one line:
def find_even_count(numlist):
return sum(num % 2 for num in map(int, numlist.split()) if num > 0)
(Note: the one-liner will fail in cases where the user tries to trick you by putting more numbers after the "final" negative number, e.g. with numlist = "1 2 -1 3 4")
If you must use a while loop (which isn't really the best tool for the job), it would look like:
def find_even_count(numlist):
index = count = 0
numlist = list(map(int, numlist.split()))
while numlist[index] > 0:
if numlist[index] % 2 == 0:
count += 1
index += 1
return count

Related

Efficient way for the following code

I saw this problem on hackerrank.com, the problem is to find a 4 letter palindrome from a given string which can be a long string also.
Constraint is as follows:
where, |s| is the length of the string and a,b,c,d are the positions of the corresponding letters in the palindrome.
I found out the solution for this, but it isn't efficient enough, as in during the processing time it gives 'time out' error. The code is as follows:
s='kkkkkkz'
n=0
c_i,c_j,c_k,c_l=0,0,0,0
for i in range(len(s)):
j=0;c_i+=1
while j>=0 and j<len(s):
c_j+=1
if j>i:
k=0
while k>=0 and k<len(s):
c_k+=1
if k>j:
l=0
while l>=0 and l<len(s):
c_l+=1
if l>k:
a=s[i]+s[j]+s[k]+s[l]
if a[0]==a[3] and a[1]==a[2]: n+=1
l+=1
k+=1
j+=1
print n
I thought of noticing the number of times each loop runs, which right now is 7,49,147 and 245.
It is still better than the techniques I followed before, but I am not able to to do better than this.
Suggestions please ?
One way is to use the following, but this will still not be efficient enough. Scores 12/40 ..
import itertools
s=WHATEVERSTRING
n=0
for a in itertools.combinations(s, 4):
n += (a[0] == a[3])*(a[1]==a[2])
print(n)
A working solution is to go down the following route: create a set of unique characters in the string, and map substring pairs to a dictionary. Then count all the occurrences of pairwise pairs.
from collections import defaultdict as di
data = [x for x in s.strip()]
chars = set(data)
sum_a = 0
for c in chars:
a = 0
b = di(int)
double_pairs = 0
for d in data:
if d == c:
sum_a += double_pairs
double_pairs += b[c]
b[c]+=a
a += 1
else:
double_pairs += b[d]
b[d] += a
print(sum_a%(10**9+7))

python 2.7 iterate on list printing subsets of a list

I have this list: l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] and I would like to iterate on it, printing something like
0: [1,2,3,4]
1: [2,3,4,5]
2: [3,4,5,6]
...
n: [17,18,19,20]
So far I made this code to print 5 elements at a time, but the last iteration prints 3:
for index, item in enumerate(l):
if index == 0 or index == 1 or index == 2:
continue
print index, l[index - 3:index + 2]
How can I solve this?
You're on the right track with your list slices. Here's a tweak to make it easier:
sub_len = 4
for i in range(len(mylist) - sub_len + 1):
print l[i:i + sub_len]
Where sub_len is the desired length of the slices you print.
demo

How many times a number in list 1 appears in list 2 without using count()

trying to write this code to see how many times the numbers in list 1 appear in the list two, can use a nested for or while loop but I came up with this it doesn't work. I don't want to use count.
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
def compare(list1, list2):
freq = ([i for i in list1 if i == num])
return
print('The number 4 occurs in list2', freq, 'times')
print('The number 7 occurs in list2', freq, 'times')
print('The number 2 occurs in list2', freq, 'times')
I'm not completely sure that I understand the question,
but this code seems to work, though if it may be slow if you need it for an interactive program.
Hope this helps!
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences
try this:
list1 = [4,7,2]
list2 = [2,3,4,2,5,6,3,2,6,7,3,4]
occurrences = [0,0,0]
for i in range(len(list1)):
for j in list2:
if list1[i] == j:
occurrences[i]+=1
print occurrences

I before E program not working

Just wrote a python program to determine how useful the mnemonic "I before E except after C" is.
With the input:
'I before e except when conducting an efficient heist on eight foreign neighbors. I believe my friend has left the receipt for the diet books hidden in the ceiling'
It would display:
Number of times the rule helped: 5
Number of times the rule was broken: 5
Changed a few things and thought I changed them back but the code is now broken, any advice will be helpful
while True:
line = input("Line: ")
count = 0
h = 0
nh = 0
words = line.split()
for x in range(0, len(words)):
word = words[count]
if "ie" in word:
if "cie" in word:
nh += 1
else:
h +=1
if "ei" in word:
if "cei" in word:
h += 1
else:
nh += 1
else:
h += 0
count += 1
print("Number of times the rule helped:",h)
print("Number of times the rule was broken:",nh)
print()
Good god I'm an idiot. I've probably spent a total of 3 hours or so trying to fix this thing.
for x in range(0, len(words)):
word = words[count]
if "ie" in word:
if "cie" in word:
nh += 1
else:
h +=1
if "ei" in word:
if "cei" in word:
h += 1
else:
nh += 1
count += 1
Can anyone spot the difference between this and the corresponding part of the old code? That 'count+=1' at the end is just indented an additional time. All those hours wasted... sorry if I wasted anyone else's time here :|
You'd be well-served to better articulate your test cases. I don't exactly understand what you're trying to do.
It seems like all you need is to see how many times 'cie' or 'cei' occurred in the text.
In which case:
for i in range(0, len(line)):
print("scanning {0}".format(line[i:i+3]))
if line[i:i+3].lower() == "cie":
nh += 1
if line[i:i+3].lower() == "cei":
h += 1

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s