Beginner in Python; For Loops & Zips - python

So I'm a freshman comp sci major. I'm taking a class that teaches Python. This is my assignment:
Create a function that takes a string and a list as parameters. The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. Zip the string and list into a list of tuples that pair each letter and number. The function should then print the number and corresponding letter respectively on separate lines. Hint: Use the zip function and a loop!
This is what I have so far:
def alpha(letter, number):
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
return zip(letter, number)
print alpha(letter, number)
The problem I have is an error on line 5 that says 'letter' is not defined. I feel like there should be a for loop but, I don't know how to incorporate it. Please help me.

zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. It looks like you want a for loop to print the pairs however.
Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible:
def alpha(letter, number):
for pair in zip(letter, number):
print pair[0], pair[1]
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)

The error you are having is due to the scope of the variables. You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined.
For printing the result you could iterate the result of zip, as in the following example:
def alpha(letters, numbers):
for c,n in zip(letters,numbers):
print c,n
letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)
Output:
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10

Related

how to print the sum of all the inputs?

I wanted to take two numbers as an input 5 times and then print out all their sum. it would look like
enter two numbers:3 4
enter two numbers:3 5
enter two numbers:7 8
enter two numbers:7 1
enter two numbers:7 4
and an out put
7
8
15
8
11
Here is what i tried.
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
My code prints out the sum for the last two inputs only.
The issue is that you are reassigning a and b during each iteration of the loop. Since you aren't storing the sum of a and b anywhere and when you move to the next iteration these values are updated to the latest inputs, there's no way to print them out. One easy fix is to append the sums to a list as you go and then print out the sums:
sums = []
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
sums.append(a+b)
for sum in sums:
print(sum)
Had you put the print(a+b) statement within the loop, this would simply print the sums after each pair of inputs is entered and before the next inputs can be entered. In case you're wondering, the reason the final sum is actually printed is that Python continues to store the values of a and b even after the loop is over. This is not necessarily expected behavior, but it allows you to print a and b even when the loop has finished as Python still remembers the last values that were assigned to them.
Put the print statement inside of the scope of the for loop like so:
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
for i in range(5):
a,b = input("enter two numbers:").split()
print(int(a)+int(b))
I think that code can help you what you need.split method converts a and b to string.So you need to convert them to integer value when you sum them.

Remove numbers from list which contains some particular numbers in python

Given List:
l = [1,32,523,336,13525]
I am having a number 23 as an output of some particular function.
Now,
I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.
Output should be:[1]
I want to write some cool one liner code.
Please help!
My approach was :
1.) Convert list of int into list of string.
2.) then use for loop to check for either character 2 or character 3 like this:
A=[x for x in l if "2" not in x] (not sure for how to include 3 also in this line)
3.) Convert A list into integer list using :
B= [int(numeric_string) for numeric_string in A]
This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.
You could convert the numbers to sets of characters:
>>> values = [1, 32, 523, 336, 13525]
>>> number = 23
>>> [value for value in values
... if set(str(number)).isdisjoint(set(str(value)))]
[1]
You're looking for the filter function. Say you have a list of ints and you want the odd ones only:
def is_odd(val):
return val % 2 == 1
filter(is_odd, range(100))
or a list comprehension
[x for x in range(100) if x % 2 == 1]
The list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.

How to create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer?

Doing some basic python coding. Here is the problem I was presented.
Create a function that takes 3 inputs:
Two lists of integers
one integer n
Prints the pairs of integers, one from the first input list and the other form the second list, that adds up to n. Each pair should be printed.
Final Result (Example):
pair([2,3,4], [5,7,9,12], 9)
2 7
4 5
I'm still awfully new to Python, studying for a test and for some reason this one keeps giving me some trouble. This is an intro course so basic coding is preferred. I probably won't understand most advanced coding.
The simplest naieve approach would be to just test all possible combinations to see if they add up.
def pair(list1, list2, x):
for a in list1:
for b in list2:
if a + b == x:
print a, b
There are more efficient ways to do it (eg. ignore duplicates, ignore numbers greater than x, etc.)
If you wanted to do it in a single loop, python has some convenience functions for that
from itertools import product
for a, b in product(list1, list2):
if a + b == x:
print a, b

How to compare words in two lists according to same order in python?(I have def a function)

Recently, I def a function which can compare two words in each wordlist. However, I also found some problems here.
def printcorrectletters():
x=0
for letters in correctanswer:
for letters2 in userinput:
if letters == letters2:
x = x+1
break
return x
In this function, if the correctanswer='HUNTING', and I input 'GHUNTIN', it will show 6 letters are correct. However, I want it compare words' letters 1 by 1. So, it should march 0. For example, 'H' will match first letter of userinput.. and so on.
I also think another function which can solve it by using 'zip'. However, our TA ask me to finish it without things like 'zip'.
If the strings are different lengths, you want to compare each letter of the shorter string:
shortest_length = min(len(correctanswer), len(userinput))
min just gives you the minimum of two or more values. You could code it yourself as:
def min(a, b):
return a if a < b else b
You can index a character in a string, using [index]:
>>> 'Guanfong'[3]
n
So you can loop over all the letter indices:
correct = 0
for index in range(shortest_length):
if correctanswer[index] == userinput[index]:
correct += 1
If you did use zip and sum:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
if correct_char == user_char)
Python provides great facilities for simplifying ideas and for communicating with the computer and programmers (including yourself, tomorrow).
Without zip you can use enumerate() to loop over elements of correctanswer , and get index and element at the same time. Example -
def printcorrectletters():
x=0
for i, letter in enumerate(correctanswer):
if i < len(userinput) and letter == userinput[i]:
x = x+1
return x
Or if even enumerate() is not allowed, simply use range() loop till len(correctanswer) and get elements from each index.

Printing out letter sequences given letters - python

In a practice exam question, we are given the following:
ALPHABET = "ABCD" # letters to use in sequences
seq = 3 * [ "" ]
letterSeqs = [ ] # list of all the letter sequences
for seq[0] in ALPHABET:
for seq[1] in ALPHABET:
for seq[2] in ALPHABET:
letterSeqs.append("".join(seq))
We are supposed to estimate the total number of entries in the list letterSeqs as well as the first and last entries. Can anyone explain how the code works?
Thanks!
This is odd code, but legal…
First:
seq = 3 * [ "" ]
… creates an empty string, and a list consisting of three references to that empty string.
Later, you do this:
for seq[0] in ALPHABET:
That's the tricky bit. It loops over ALPHABET, assigning each of the 4 letters in turn to seq[0]. Normally, you use a variable as the loop variable, not a complex target like this. In fact, I'm guessing the teacher did this specifically to throw you off. However, it does turn out to be useful, sort of.
And then, for each of those 4 iterations, you do this:
for seq[1] in ALPHABET:
That again loops 4 times, per outer loop, so that's a total of 16 middle loops. And then, for each of those 16, you do this:
for seq[2] in ALPHABET:
That again loops 4 times, per middle loop, for a total of 64 inner loops.
And then, for each one, you do this:
letterSeqs.append("".join(seq))
At this point, seq will always be a list of 3 single-character strings. That's the payoff for using seq[0] as your loop variable. That being said, there are much better ways to do the same thing. Just use for i, for j, and for k and this could be i+j+k instead. (And if you want to generalize to something other than 3 strings, the static nested loop structure is the hard part, not the separate variables…)
So, it will join into a single 3-character string. Which you then append to the empty list.
So, at the end, you've got a list of 64 3-character strings.
for _ in container:
will run len(container) times. As you're nested three deep, it runs
len(container) ** 3 == 4 ** 3 == 64
times. Each time you append one str object, "".join(seq), so the length at the end will be 64.
When the first item is appended, all positions in seq have the first value in ALPHABET, so the item is "AAA". At the end, they all have the last value from ALPHABET, so the last item will be "DDD".

Categories