Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion 12_09_practice.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,111 @@
#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5].

def make_big(lst):
return ["big" if el > 0 else el for el in lst ]

print(make_big([-1, 3, 5, -5]))

#Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number).

def add_number_positives(lst):
lst[len(lst)-1] = len([i for i in lst if i>0])
return lst

print(add_number_positives([-1,1,1,1]))

#SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10

def sum_total(lst):
return sum(lst)

print(sum_total([1,2,3,4]))

#Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5

def get_avg(lst):
return sum(lst)/len(lst)

print(get_avg([1,2,3,4]))

#Length - Create a function that takes a list as an argument and returns the length of the list. For example length([1,2,3,4]) should return 4

def get_length(lst):
return len(lst)

print(get_length([1,2,3,4]))

#Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3.

def get_minimum(lst):
return False if len(lst) == 0 else min(lst)


print(get_minimum([1,2,3,4]), get_minimum([-1,-2,-3]))
#
#Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. If the passed list is empty, have the function return false. #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1.

def get_maximum(lst):
return False if len(lst) == 0 else max(lst)

print(get_maximum([1,2,3,4]), get_maximum([-1,-2,-3]))

#Ultimateaalyze - Create a function that takes a list as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list.

def ultimateanalyze(lst):
dct = {}
dct['sumTotal'] = sum(lst)
dct['average'] = sum(lst)/len(lst)
dct['minimum'] = min(lst)
dct['maximum'] = max(lst)
dct['length'] = len(lst)
return dct

print(ultimateanalyze([1,2,3,4]))

#ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews.

def reverselist(lst):
return lst[::-1]

print(reverselist([1,2,3]))
#Ispalindrome- Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome.

def ispalindrome(lst):
return lst == lst[::-1]

print(ispalindrome('abba'))
#Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions:
#If the number is a multiple of 3, print “Fizz” instead of the number.
#If the number is a multiple of 5, print “Buzz” instead of the number.
#If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number.

#Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions:
#If the number is a multiple of 3, print “Fizz” instead of the number.
#If the number is a multiple of 5, print “Buzz” instead of the number.
#If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number.

def fizzbuzz():
p = lambda x: print(x)

[p('FizzBuzz') if (i%3==0 and i%5==0)
else (p('Fizz') if i%3==0
else ( p('Buzz') if i%5==0 else p(i)))
for i in range(1,101)]

fizzbuzz()

#Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is,
#F(0) = 0, F(1) = 1
#F(n) = F(n - 1) + F(n - 2), for n > 1.
#Create a function that accepts any number and will create a sequence based on the fibonacci sequence.
#Create a function that accepts any number and will create a sequence based on the fibonacci sequence.

def fibonacci(n):
if n == 0: return 0
dct_fibo = {}
dct_fibo[0] = 0
dct_fibo[1] = 1
for i in range(2,n+1):
dct_fibo[i] = dct_fibo[i-1] + dct_fibo[i-2]
return [values for _, values in dct_fibo.items()]

print(fibonacci(10))
62 changes: 62 additions & 0 deletions modify_xml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 15 20:24:04 2022

@author: SAE
"""

import xml.etree.ElementTree as ET
import re

# import xml
tree = ET.parse('movies.xml')
root = tree.getroot()

# -Add a new genre called Anime to the root
new_genre = ET.SubElement(root, 'genre')
new_genre.attrib["category"] = 'Anime'
print(ET.tostring(new_genre))

# -Add a new decade to the new anime genre. First check the decade for the Batman movies:

for title in root.findall("./genre/decade/movie/[@title]"):
match = re.match('Batman', title.attrib['title'])
if match:
print(title.attrib['title'])

# returns two movies:
# Batman Returns
# Batman: The Movie

# Find which year these movies belong to:

for movie in root.iter('movie'):
for y in movie.iter('year'):
match = re.match('Batman', movie.attrib['title'])
if match:
print(movie.attrib['title'], y.text)

# returns two movies with dates:
# Batman Returns 1992
# Batman: The Movie 1966

# Create anime decade 1990s
anime = root.find("./genre[@category='Anime']")
new_decade = ET.SubElement(anime, 'decade')
new_decade.attrib["years"] = '1990s'
print(new_decade.attrib)

# Add Batman returns
batman = root.find("./genre/decade/movie[@title='Batman Returns']")
decade1990s = root.find("./genre[@category='Anime']/decade[@years='1990s']")
decade1990s.append(batman)
print(ET.tostring(root, encoding='utf8').decode('utf8'))


# Delete Batman from the old genre:
dec1990s = root.find("./genre[@category='Action']/decade[@years='1990s']")
dec1990s.remove(batman)
print(ET.tostring(root, encoding='utf8').decode('utf8'))

# Write updated tree to xml file
tree.write("movies.xml")
120 changes: 120 additions & 0 deletions movies.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<collection>
<genre category="Action">
<decade years="1980s">
<movie favorite="True" title="Indiana Jones: The raiders of the lost Ark">
<format multiple="No">DVD</format>
<year>1981</year>
<rating>PG</rating>
<description>
'Archaeologist and adventurer Indiana Jones
is hired by the U.S. government to find the Ark of the
Covenant before the Nazis.'
</description>
</movie>
<movie favorite="True" title="The Karate Kid">
<format multiple="Yes">DVD,Online</format>
<year>1984</year>
<rating>PG</rating>
<description>None provided.</description>
</movie>
<movie favorite="False" title="Back to the Future">
<format multiple="No">Blu-ray</format>
<year>1985</year>
<rating>PG</rating>
<description>Marty McFly</description>
</movie>
</decade>
<decade years="1990s">
<movie favorite="False" title="Reservoir Dogs">
<format multiple="No">Online</format>
<year>1992</year>
<rating>R</rating>
<description>WhAtEvER I Want!!!?!</description>
</movie>
</decade>
<decade years="2000s"><movie favorite="False" title="X-Men">
<format multiple="Yes">dvd, digital</format>
<year>2000</year>
<rating>PG-13</rating>
<description>Two mutants come to a private academy for their kind whose resident superhero team must
oppose a terrorist organization with similar powers.</description>
</movie>
</decade></genre>

<genre category="Thriller">
<decade years="1970s">
<movie favorite="False" title="ALIEN">
<format multiple="No">DVD</format>
<year>1979</year>
<rating>R</rating>
<description>"""""""""</description>
</movie>
</decade>
<decade years="1980s">
<movie favorite="True" title="Ferris Bueller's Day Off">
<format multiple="No">DVD</format>
<year>1986</year>
<rating>PG13</rating>
<description>Funny movie about a funny guy</description>
</movie>
<movie favorite="FALSE" title="American Psycho">
<format multiple="No">blue-ray</format>
<year>2000</year>
<rating>Unrated</rating>
<description>psychopathic Bateman</description>
</movie>
</decade>
</genre>

<genre category="Comedy">
<decade years="1960s">
<movie favorite="False" title="Batman: The Movie">
<format multiple="Yes">DVD,VHS</format>
<year>1966</year>
<rating>PG</rating>
<description>What a joke!</description>
</movie>
</decade>
<decade years="2010s">
<movie favorite="True" title="Easy A">
<format multiple="No">DVD</format>
<year>2010</year>
<rating>PG--13</rating>
<description>Emma Stone = Hester Prynne</description>
</movie>
<movie favorite="True" title="Dinner for SCHMUCKS">
<format multiple="Yes">DVD,digital,Netflix</format>
<year>2011</year>
<rating>Unrated</rating>
<description>Tim (Rudd) is a rising executive
who succeeds in finding the perfect guest,
IRS employee Barry (Carell), for his boss monthly event,
a so-called dinner for idiots, which offers certain
advantages to the exec who shows up with the biggest buffoon.
</description>
</movie>
</decade>
<decade years="1980s">
<movie favorite="False" title="Ghostbusters">
<format multiple="Yes">Online,VHS</format>
<year>1984</year>
<rating>PG</rating>
<description>Who ya gonna call?</description>
</movie>
</decade>
<decade years="1990s">
<movie favorite="True" title="Robin Hood: Prince of Thieves">
<format multiple="No">Blu_Ray</format>
<year>1991</year>
<rating>Unknown</rating>
<description>Robin Hood slaying</description>
</movie>
</decade>
</genre>
<genre category="Anime"><decade years="1990s"><movie favorite="True" title="Batman Returns">
<format multiple="No">VHS</format>
<year>1992</year>
<rating>PG13</rating>
<description>NA.</description>
</movie>
</decade></genre><genre category="Anime" /></collection>
75 changes: 75 additions & 0 deletions python_exercises2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#####################################################################
# GENERATORS:
#####################################################################
# Generator exercises: Create a generator, primes_gen that generates prime numbers starting from 2.

import math
from functools import reduce

# use the principle that if a number have any factor less than the numbers square root, then the number cannot be prime

def isprime(n):
if n == 2: return True
nroot = int(math.sqrt(n))+ 1
for i in range(2,nroot+1):
if n % i == 0:
return False
return True

def primes_gen():
n = 2
while True:
if isprime(n):
yield n
n += 1

gen = primes_gen()
print('primes')
for _ in range(10):
print(next(gen), end=' ')
#####################################################################
#Create a generator, unique_letters that generates unique letters from the input string. It should generate the letters in the same order as from the input string.

def unique_letters(str):
mem = [] # memory list to keep unique letters
for lt in str:
if lt not in mem:
yield lt
mem.append(lt)
print('\nUnique Letters:')
for letter in unique_letters('hello'):
print(letter, end=' ')

#####################################################################
# LAMBDA FUNCTIONS
#####################################################################
#Consider the list:
prog_lang = [('Python', 3.8),
('Java', 13),
('JavaScript', 2019),
('Scala', 2.13)]

#1. Sort the list by each language's version in ascending order.

print(sorted(prog_lang, key = lambda x : x[1]))

#2. Sort the list by the length of the name of each language in descending order.

print(sorted(prog_lang, key = lambda x : len(x[0]), reverse=True))

#3. Filter the list so that it only contains languages with 'a' in it.

print(list(filter(lambda x : True if 'a' in x[0] else False, prog_lang)))

#4. Filter the list so that it only contains languages whose version is in integer form.
print(list(filter(lambda x : isinstance(x[1],int) , prog_lang)))

#5 Transform the list so that it contains the tuples in the form,("language in all lower case", length of the language string)

print(list(map(lambda x: (x[0].lower(), len(x[0])), prog_lang)))

#6 Generate a tuple in the form, ("All languages separated by commas", "All versions separated by commas")


print((reduce(lambda x,y: ",".join([x,y]), [x for (x,y) in prog_lang]),(reduce(lambda x,y: ",".join([x,y]), [str(y) for (x,y) in prog_lang]))))

Loading