Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tp #5

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

tp #5

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
1 change: 0 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"files.autoSave": "afterDelay",
"screencastMode.onlyKeyboardShortcuts": true,
"terminal.integrated.fontSize": 18,
"workbench.activityBar.visible": true,
"workbench.colorTheme": "Visual Studio Dark",
"workbench.fontAliasing": "antialiased",
"workbench.statusBar.visible": true
Expand Down
29 changes: 29 additions & 0 deletions src/01 Find Prime Factors/my_factor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
def get_primes(num):
primes = []
isPrime = False
for numToTest in range(2, num + 1):
if (num % numToTest == 0):
if (not primes):
primes.append(numToTest)
for prime in primes:
if (numToTest not in primes and prime != 1 and numToTest % prime == 0):
isPrime = False
if (isPrime == True):
primes.append(numToTest)
else:
isPrime = True
return primes;

def get_prime_factors(num):
primes = []
numTmp = num
for i in get_primes(num):
numTmp = num
while(numTmp % i == 0):
primes.append(i)
numTmp = numTmp / i
return primes


print(get_prime_factors(630)) # [2, 3, 3, 5, 7]
print(get_prime_factors(13)) # [13]
11 changes: 11 additions & 0 deletions src/02 Identify a Palindrome/my_palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def is_palindrome(str):
str = str.upper().replace(" ", "").replace("'", "").replace(",", "")
for i in range((len(str) // 2) + 1):
print(i)
if (str[i] != str[len(str) - 1 -i]):
print(str[len(str) - 1 -i])
print(str[i])
return False
return True

print(is_palindrome("Go hang a salami, I'm a lasagna hog")) # true
4 changes: 4 additions & 0 deletions src/03 Sort a String/my_sort_words.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def sort_string(str):
return' '.join(sorted(str.split(" "), key=lambda s: s.lower()))

print(sort_string('banana ORANGE apple'))
27 changes: 27 additions & 0 deletions src/04 Find All List Items/my_index_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def index_all(array, search):
print("array " , array)
tab = []
for i, value in enumerate(array):
if (type(value) == list and value != search):
tabList = []
a = index_all(value, search)
if (a):
for n in a:
if (type(n) == list):
n.append(i)
tabList.append(n)
else:
tabList.append([i,n])
for tabListItem in tabList:
tab.append(tabListItem)
print("ddd tab " , tab, "array " , array, "value" , value, " a = " , a)
else:
if (value == search):
tab.append(i)
print("array " , array, "tab " , tab, "value" , value)
return tab

# example = [[[1, 2, 3], 2, [1, 3]], [1, 2, 3]]
example = [[[1, 2, 3], 2, [1, 3]], [1, 2, 3]]
print(index_all(example, 2)) # [[0, 0, 1], [0, 1], [1, 1]]
print(index_all(example, [1, 2, 3])) # [[0, 0], [1]]
25 changes: 25 additions & 0 deletions src/05 Play the Waiting Game/my_waiting_game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import time

def waiting_game():
print("Your target time is 4 seconds")
x = input("---Press Enter to Begin--")
end = 0
print("x = " , x)
if (x != None):
start = time.time()
y = input("---Press Enter to Begin--")
print("start ", start)
print("x = " , x)
if (y != None):
end = time.time()
print("end ", end)
print("Elapsed time: " , abs(round((end - start) *1000) /1000)," seconds")
if ((end - start) >4):
s ="seconds too slow"
else:
s = "seconds too fast"
print("(",
abs(4 - round((end - start) *1000) /1000),
s," )" )

waiting_game()
13 changes: 13 additions & 0 deletions src/06 Save a Dictionary/my_dictionary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import json
def save_dict( dict,filePath):
with open(filePath, "w") as outfile:
json.dump(dict, outfile)
outfile.close()
def load_dict(filePath):
with open(filePath, "r") as outfile:
jsonString = outfile.read()
return json.loads(jsonString)
test_dict = {1: 'a', 2: 'b', 3: 'c'}
save_dict(test_dict, 'test_dict.pickle')
recovered = load_dict('test_dict.pickle')
print(recovered)
16 changes: 16 additions & 0 deletions src/07 Schedule a Function/my_schedule_function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import sched
import time
from datetime import datetime


def schedule_function(event_time, function, *args):
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enterabs( event_time.timestamp(), 1, function, args)
scheduler.run()



def hello():
print("ggggggggggggggg")

schedule_function(datetime(2024, 9, 8, 0, 28), hello, None)
20 changes: 20 additions & 0 deletions src/08 Send an Email/my_send_email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
def send_mail(receiverAdress, subject, content):
msg = EmailMessage()
msg.set_content(content)
sender = "[email protected]"
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiverAdress
with smtplib.SMTP_SSL('smtp.orange.fr', 465) as smtp_server:
smtp_server.login(sender, "")
smtp_server.sendmail(sender,receiverAdress, msg.as_string())



send_mail('[email protected]', 'Notification', 'Everything is awesome!')
35 changes: 35 additions & 0 deletions src/09 Simulate Dice/my_roll_dice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import random

def roll_dice(*args):
nbTirage = 1000000
resultDice = []
sumResultDice = []


for i in range(len(args)):
a = []
for l in range(nbTirage):
a.append(random.randrange(1, args[i] + 1))
resultDice.append(a)
for i in range(nbTirage):
sum = 0
for r in range(len(args)):
sum = sum + resultDice[r][i]
sumResultDice.append(sum)
sumNumberSide = 0
for r in range(len(args)):
sumNumberSide = sumNumberSide + args[r]
dict ={}
for outcome in range(len(args), sumNumberSide + 1):
for i in sumResultDice:
if (outcome is i):
if (outcome not in dict.keys()):
dict[outcome] = 1
else:
dict[outcome] = dict[outcome] + 1
print(dict)
for k,j in dict.items():
print(k, " ", round( (j/ nbTirage) * 10000) / 100)

roll_dice(4, 6, 6)
roll_dice(4, 6, 6, 20)
29 changes: 29 additions & 0 deletions src/10 Count Unique Words/my_count_words.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import re
def count_words(filePath):
with open(filePath, "r") as infile:
s = infile.read()
tokens =[token.upper() for token in re.findall(r'[0-9a-zA-Z-]+', s)]
setWord = list(set(tokens))
dict = {}

for i in tokens:
if i in dict.keys():
dict[i] = dict[i] + 1
else:
dict[i] = 1
def myFunc(e):
if e in dict.keys():
return dict[e]
else:
return 0

print("Total words: ", len(tokens))
print("Top 20 words:")
# print(setWord.sort(reverse=True, key=myFunc))

#
setWord.sort(reverse=True, key=myFunc)
print(setWord[0:20])
for i in setWord[0:20]:
print(i, " ", dict[i])
count_words('shakespeare.txt')
29 changes: 29 additions & 0 deletions src/11 Generate a Password/my_diceware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import secrets


def splitLines(line):
lineSplited = line.split()
if len(lineSplited) > 1:
return (lineSplited[0], lineSplited[1])
else:
return ("line","")


def generate_passphrase(num_words, wordlist_path='diceware.wordlist.asc'):
with open(wordlist_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
dict = {splitLines(line)[0]: splitLines(line)[1] for line in lines[2:]}
resultArray = []
for i in range(0, num_words):
resultArrayOfALine = []
for j in range(0, 5):
resultArrayOfALine.append(str(secrets.choice(range(1, 7))))
resultArray.append(resultArrayOfALine)
wordList = [dict["".join(tutu)] for tutu in resultArray]
return " ".join(wordList)




print(generate_passphrase(7))
print(generate_passphrase(7))
7 changes: 7 additions & 0 deletions src/12 Merge CSV Files/all_students.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Lab,Midterm,Name,Final
,61,Tony,51
,98,Nick,91
,85,Keith,73
79,52,Alice,87
77,84,Steve,53
91,82,Ralph,83
30 changes: 30 additions & 0 deletions src/12 Merge CSV Files/my_merge_csv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import csv


def merge_csv(arrayOfCsvFileNameInput, csvFileNameOutput):
inputEntries = {}
for fileName in arrayOfCsvFileNameInput:
with open(fileName, "r") as f:
inputEntries[fileName] = list(csv.DictReader(f))
fieldNameSet = set({})
for j in inputEntries.values():
fieldNameSet = fieldNameSet.union(set(j[1].keys()))

resLine = {}
resultsOutput = []
for inputFileValue in inputEntries.values():
for lineOfResults in inputFileValue:
for fieldOfTheSet in fieldNameSet:
if fieldOfTheSet in inputFileValue[1].keys():
resLine[fieldOfTheSet] = lineOfResults[fieldOfTheSet]
else:
resLine[fieldOfTheSet] = None
resultsOutput.append(resLine)
resLine = {}
with open(csvFileNameOutput, "w") as f:
writer = csv.writer(f)
writer.writerow(list(fieldNameSet))
for row in resultsOutput:
writer.writerow(row.values())

merge_csv(['class1.csv', 'class2.csv'], 'all_students.csv')
Loading