Showing posts with label lists. Show all posts
Showing posts with label lists. Show all posts

Wednesday, May 28, 2014

Exercise 15: A Password Generator

Exercise

Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.
Extra:
  • Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list.

Discussion

There are no new topics this week, but you will need to use Python's random module, described in this post.

Happy coding!

Explore away!
Forgot how to submit exercises?

SOLUTION Exercise 14: Reverse Word Order

Exercise

Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.

Sample solution

Here is the quick, one-liner solution to the problem:

But most likely you didn't come up with that solution right away. You most likely went through a number of iterations like this:

But you also could have taken a hybrid approach:

Thursday, May 22, 2014

Exercise 14: Reverse Word Order

Exercise

Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.

Discussion

Concepts for this week:
  • More string things

More string things

Python has a lot of interesting things you can do with strings. I will show a few here, but you can see many more methods that may or may not be useful at the official Python documentation about the string format.

Remember that strings are lists.

Splitting strings

You can "split" or tear apart strings based on a given set of characters. For example:
teststring = "this is a test"
result = teststring.split("t")
And at the end, result will contain the list:
['', 'his is a ', 'es', '']
Instead of "t", you can write any character you want. If you do not include any character, it means "split on all whitespace":
teststring = "  this      has a lot    of   spaces and    tabs"
result = testring.split()
Then result contains:
['this', 'has', 'a', 'lot', 'of', 'spaces', 'and', 'tabs']

Joining strings

You can also relatively easily "join" or "smush" strings together:
listofstrings = "['a', 'b', 'c']"
result = "**".join(listofstrings)
Then result will contain the string:
a**b**c
Take a look at the official Python documentation for more information.

Happy coding!

Explore away!
Forgot how to submit exercises?

SOLUTION Exercise 13: List Duplicates

Exercise

Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.
Extras:
  • Write two different functions to do this - one using a loop and constructing a list, and another using sets.
  • Go back and do Exercise 5 using sets, and write the solution for that in a different function.

Sample solution

This solution has two different functions doing the solution in two ways - one does it with a loop, and one with sets!

Thursday, May 15, 2014

Exercise 13: List Duplicates

Exercise

Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.

Extras:
  • Write two different functions to do this - one using a loop and constructing a list, and another using sets.
  • Go back and do Exercise 5 using sets, and write the solution for that in a different function.

Discussion

Concepts for this week:
  • Sets

Sets

In mathematics, a set is a collection of elements where no element is repeated. This becomes useful because if you know your data is stored in a set, you are guaranteed to have unique elements.

Features of sets

  • Sets are not ordered. This means that there is no "first element" or "last element." There are just "elements". You cannot ask a set for it's "next element".
  • There are no repeat elements in sets.
  • You can convert between sets and lists very easily.

In Python

In Python, you make and use a set with the set() keyword. For example:
names = set()
names.add("Michele")
names.add("Robin")
names.add("Michele")
print(names)
And the output will be;
set(['Michele', 'Robin'])
You can do to a set almost anything you can do to a list (except ask for things like "the third element"). See the Python documentation about sets to get a full list of things you can do to sets.
You can convert from a list to a set and a set to a list pretty easily:
names = ["Michele", "Robin", "Sara", "Michele"]
names = set(names)
names = list(names)
print(names)
And the result of this will be:
['Michele', 'Robin', 'Sara']
Explore away!

Happy coding!

Forgot how to submit exercises?

SOLUTION Exercise 12: List Ends

Exercise

Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.

Sample solution

Friday, April 25, 2014

Exercise 12: List Ends

Exercise

Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.

Concepts to practice

  • Lists and properties of lists
  • List comprehensions (maybe)
  • Functions

Happy coding!

Forgot how to submit exercises?

Wednesday, April 16, 2014

SOLUTION Exercise 10: List overlap comprehensions

Exercise

This week's exercise was an old exercise (see Exercise 5), requiring the solution in a different way.
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python.

Extra:
  • Randomly generate two lists to test this

Sample solution

Great example of a solution including the extras!

Friday, April 11, 2014

Exercise 10: List overlap comprehensions

Exercise

This week's exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way.
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python. (Hint: Remember list comprehensions from Exercise 7).

Extra:
  • Randomly generate two lists to test this

Discussion

Concepts for this week:
  • List comprehensions
  • Random numbers, continued

List comprehensions

We already discussed list comprehensions in Exercise 7, but they can be made much more complicated.
For example:
x = [1, 2, 3]
y = [5, 10, 15]
allproducts = [a*b for a in x for b in y]
At the end of this piece of code, allproducts will contain the list [5, 10, 15, 10, 20, 30, 15, 30, 45]. So you can put multiple for loops inside the comprehension. But you can also add more complicated conditionals:
x = [1, 2, 3]
y = [5, 10, 15]
customlist = [a*b for a in x for b in y if a*b%2 != 0]
Now customlist contains [5, 15, 15, 45] because only the odd products are added to the list.
In general, the list comprehension takes the form:
[EXPRESSION FOR_LOOPS CONDITIONALS]
as shown in the examples above.


Random numbers, continued

Try to use the Python random documentation to figure out how to generate a random list. As a hint look below:
a = random.sample(range(100), 5)
This line of code will leave a containing a list of 5 random numbers from 0 to 99.


Happy coding!

Forgot how to submit exercises?

Thursday, March 27, 2014

SOLUTION Exercise 7: list comprehensions

Exercise

Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

Sample solutions

For the meat of the solution, check this out:

And for a "complete" solution, look at this:

For a solution that uses the random library to generate test lists, check this out:

Wednesday, March 19, 2014

Exercise 7: List comprehensions

Exercise

Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

Discussion

Concepts for this week:
  • List comprehensions


List comprehensions

The idea of a list comprehension is to make code more compact to accomplish tasks involving lists. Take for example this code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = []
for year in years_of_birth: 
    ages.append(2014 - year)
And at the end, the variable ages has the list [24, 23, 24, 24, 22, 23]. What this code did was translate the years of birth into ages, and it took us a for loop and an append statement to a new list to do that.

Compare to this piece of code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2014 - year for year in years_of_birth]
The second line here - the line with ages is a list comprehension.

It accomplishes the same thing as the first code sample - at the end, the ages variable has a list containing [24, 23, 24, 24, 22, 23], the ages corresponding to all the birthdates.

The idea of the list comprehension is to condense the for loop and the list appending into one simple line. Notice that the for loop just shifted to the end of the list comprehension, and the part before the for keyword is the thing to append to the end of the new list.

Try it yourself!

Forgot how to submit exercises?

Wednesday, March 12, 2014

Exercise 6: Strings as lists

Exercise

Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)

Discussion

Concepts for this week:

  • List indexing
  • Strings are lists

List indexing

In Python (and most programming in general), you start counting lists from the number 0. The first element in a list is "number 0", the second is "number 1", etc.

As a result, when you want to get single elements out of a list, you can ask a list for that number element:

>>> a = [5, 10, 15, 20, 25]
>>> a[3]
20
>>> a[0]
5

There is also a convenient way to get sublists between two indices:

>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:4]
[10, 15, 20]
>>> a[6:]
[35, 40]
>>> a[:-1]
[5, 10, 15, 20, 25, 30, 35]

The first number is the "start index" and the last number is the "end index."

You can also include a third number in the indexing, to count how often you should read from the list:

>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:5:2]
[10, 20]
>>> a[0:3:-1]
[15, 10, 5]

To read the whole list, just use the variable name (in the above examples, a), or you can also use [:] at the end of the variable name (in the above examples, a[:]).

Strings are lists

Because strings are lists, you can do to strings everything that you do to lists. You can iterate through them:

string = "example"
for c in string: 
    print "one letter: " + c

Will give the result:

one letter: e
one letter: x
one letter: a
one letter: m
one letter: p
one letter: l
one letter: e

You can take sublists:

>>> string = "example"
>>> s = string[0:5]
>>> print s
exam

Now s has the string "exam" in it.

Moral of the story: a string is a list.

Happy coding!

Forgot how to submit exercises?

Wednesday, March 5, 2014

Exercise 5: list overlap

Exercise

Take two lists, say for example these two:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

Extras:

  1. Randomly generate two lists to test this
  2. Write this in one line of Python (don't worry if you can't figure this out at this point - we'll get to it soon)

List properties

In other words, "things you can do with lists."

One of the interesting things you can do with lists in Python is figure out whether something is inside the list or not. For example:

>>> a = [5, 10, 15, 20]
>>> 10 in a
True
>>> 3 in a
False

You can of course use this in loops, conditionals, and any other programming constructs.

list_of_students = ["Michele", "Sara", "Cassie"]

name = input("Type name to check: ")
if name in list_of_students:
    print("This student is enrolled.")
Forgot how to submit exercises?

Wednesday, February 26, 2014

SOLUTION Exercise 3: lists

Exercise

Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
  1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  2. Write this in one line of Python.
  3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

Sample solution

I will note that none of the solutions that were submitted were written in one line of Python. There will be more exercises later that show you how to do this!
Here is a sample solution that solves the exercise, including extras 1 and 3.

Saturday, February 15, 2014

Exercise 3: lists

Followers and friends, I apologize for not posting this week. Sometimes life throws you lemons (or appendicitis) and you need to make lemonade (or spend a few nights in the hospital and have emergency surgery). I am now recovering, and this post will be up for a week and a half. Happy hacking!

Exercise

Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.

Extras:

  1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  2. Write this in one line of Python.
  3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

  4. Discussion

    This week's topics:
    1. Lists
    2. More conditionals (if statements)


    3. Lists


      This week's exercise hits on a topic critical for all types and styles of programming: lists. Lists are basically an ordered way of grouping things (called elements) - the cool thing about lists in Python is that you can have a list that contains objects of multiple types. Your list can mix between strings, integers, objects, other lists, what have you.
      The way to construct an empty list is just to do
      x = []
      And your variable x now holds an empty list. To add things to this list, just "append" them to the list. Like so:
      x = []
      x.append(3)
      Your list x now looks like [3].

      In Python, lists are also iterables, which means you can loop through them with a for loop in a convenient way. (If you come from other languages like C++ or Java you are most likely used to using a counter to loop through indices of a list - in Python you can actually loop through the elements.) I will let the code speak for itself:
      my_list = [1, 3, "Michele", [5, 6, 7]]
      for element in my_list:
          print element
      Will yield the result:
      1 
      3
      "Michele"
      [5, 6, 7]
      There are many other properties of lists, but for the basic exercise all you should need is this for loop property. Future weeks will address other properties of lists.
      For more information about lists in Python, check out these resources:
      • The official Python documentation on lists
      • Tutorialspoint on Python lists
      • Someone else's blog post about lists

      • More Conditionals


        The nice thing about conditionals is that they follow logical operations. They can also be used to test equality. Let's do a small example. Let's say I want to make a piece of code that converts from a numerical grade (1-100) to a letter grade (A, B, C, D, F). The code would look like this:
        grade = input("Enter your grade: ")
        if grade >= 90:
            print("A")
        elif grade >= 80:
            print("B")
        elif grade >= 70:
            print("C")
        elif grade >= 65:
            print("D")
        else:
            print("F")
        What happens if grade is 50? All the conditions are false, so "F" gets printed on the screen. But what if grade is 95? Then all the conditions are true and everything gets printed, right? Nope! What happens is the program goes line by line. The first condition (grade >= 90) is satisfied, so the program enters into the code inside the if statement, executing print("A"). Once code inside a conditional has been executed, the rest of the conditions are skipped and none of the other conditionals are checked.

        Forgot how to submit exercises?