so how was the homework? did you get the permutations one?
if not, don't feel too bad it was fairly tough.
here's the two functions
Code:
def factorial(val,n):
if n ==1:
return val
else:
n = n-1
val = val*factorial(val-1,n)
return val
def permute( variation, word, index):
if len(word) == 0:
print variation
return
if index >= len(word):
return
permute(variation,word,index+1)
permute(variation+word[index],word[:index]+word[index+1:],0)
note that the solution for permutations assume you enter in the digits in the form of a array, which though i haven't gone over yet, will do so now.
an array is a fairly simple thing, its simply a block of data, such as integers.
for example, array= 10*[0] declares an array of 10 integers, starting value of 0. in python, you have a powerful array accessing tool called slicing. for example, array = array[1:4] will give all array elements from 1 to 3. lets take a specific example.
Code:
string1 = "this is a long string of many words that does nothing."
string2 = string1[4:10]
print string2
string2 = string1[:20:2]
print string2
it will print " is a " first, then "ti saln ti". (the 2 means to skip every other character.)
though strings can be accessed they are difficult to modify. for example
string1 = "hi"
string1[0] = "b"
would result in an error.
you could however do something like this
string1 ="hi"
string1 = "b" +string[1]
note however that strings are just one possible thing you can do with an array.
for example, say you want a list of all primes up to 100.
using arrays would allow easy access for this.
Code:
index = 2
x =2
mark = [1,1] +[0]*98
while x*x<len(mark):
while index*x <len(mark):
if mark[index] == 0:
mark[index*x] =1
if mark[index] == 1:
mark[index*x] = 1
mark[index] = 2
index = index+1
x = x+1
while mark[x] != 0:
x = x+1
index = x
for i in range(0,100):
if mark[i] == 0:
print i,
the above code may look a little confusing, but basically here's what its doing. first it declares an array of size 100, then it marks all multiples of 2, then all multiples of 3, then 5, then 7. any unmarked numbers are prime. well that's it for this lesson. practice problem for you. write a program that sorts an array of integers.