blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
717d5182de32647219d29dde6cb6f5298b8ac557
jemg2030/Retos-Python-CheckIO
/ELECTRONIC_STATION/AcceptablePasswordVI.py
3,022
4.15625
4
''' In this mission you need to create a password verification function. The verification conditions are: the length should be bigger than 6; should contain at least one digit, but it cannot consist of just digits; having numbers or containing just numbers does not apply to the password longer than 9; a string should not contain the word "password" in any case. Input: A string. Output: A bool. Examples: assert is_acceptable_password("short") == False assert is_acceptable_password("short54") == True assert is_acceptable_password("muchlonger") == True assert is_acceptable_password("ashort") == False How it’s used: For password verification form. Also it's good to learn how the task can be evaluated. ---------- ---------- En esta misión debe crear una función de verificación de contraseña. Las condiciones de verificación son: la longitud debe ser superior a 6 debe contener al menos un dígito, pero no puede consistir sólo en dígitos; tener números o contener sólo números no se aplica a la contraseña de longitud superior a 9; la cadena no debe contener la palabra "contraseña" en ningún caso. Entrada: Una cadena. Salida: Un bool. Ejemplos: assert es_contraseña_aceptable("corta") == False assert es_contraseña_aceptable("corta54") == True assert is_acceptable_password("muchlonger") == True assert is_acceptable_password("ashort") == False Cómo se usa: Para el formulario de verificación de contraseñas. También es bueno aprender cómo se puede evaluar la tarea. ''' # Taken from mission Acceptable Password V # Taken from mission Acceptable Password IV # Taken from mission Acceptable Password III # Taken from mission Acceptable Password II # Taken from mission Acceptable Password I def is_acceptable_password(password: str) -> bool: # your code here return (len(password) > 9 or (len(password) > 6 and any(sym.isdigit() for sym in password) and not password.isdigit())) \ and password.lower().find('password') == -1 and len(set(password)) > 2 print("Example:") print(is_acceptable_password("short")) # These "asserts" are used for self-checking assert is_acceptable_password("short") == False assert is_acceptable_password("short54") == True assert is_acceptable_password("muchlonger") == True assert is_acceptable_password("ashort") == False assert is_acceptable_password("muchlonger5") == True assert is_acceptable_password("sh5") == False assert is_acceptable_password("1234567") == False assert is_acceptable_password("12345678910") == True assert is_acceptable_password("password12345") == False assert is_acceptable_password("PASSWORD12345") == False assert is_acceptable_password("pass1234word") == True assert is_acceptable_password("aaaaaa1") == False assert is_acceptable_password("aaaaaabbbbb") == False assert is_acceptable_password("aaaaaabb1") == True assert is_acceptable_password("abc1") == False assert is_acceptable_password("abbcc12") == True assert is_acceptable_password("aaaaaaabbaaaaaaaab") == False
9105a12873ac75bf31b13250203e7194a3a2aa84
521tong/PythonChallenge
/PyBank/main.py
1,050
3.890625
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv # Define path to csv file csvpath = os.path.join('..', 'budget_data.csv') month_count = 0 net_amount = 0 # Convert path into a file with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: # Total number of months included in dataset month_count += 1 # Total net amount of "Profits/Losses" over the entire period net_amount += (int(row[1])) # Average change in "Profit/Losses" between months over the entire period # Greatest increase in profits (date and amount) over the entire period # Greatest decrease in losses (date and amount) over the entire period print("Financial Analysis") print("-----------------------------------") print("Total Months: " + (str(month_count))) print("Total: $" +(str(net_amount)))
48f3869d891491aa6b613debd803a508ac811071
saumya470/python_assignments
/.vscode/Challenges/QuizCodeSnippets.py
405
3.8125
4
# class Student: # name='Rohan' # age=16 # s1=Student() # s2=Student() # print(s1.name,end='') # print(s2.name,end='') # class change: # def __init__(self,x,y,z): # self.a=x+y+z # x=change(1,2,3) # y=getattr(x,'a') # setattr(x,'a',y+1) class A: def __init__(self): self.x=1 self.__y=1 def getY(self): return self.__y a=A() a.__y=45 print(a.getY())
2274ba88f9d95d1c8f743662c0b4469118b4f996
lachezarbozhkov/adventofcode_2019
/4_passwords.py
1,899
3.59375
4
# https://adventofcode.com/2019/day/4 # six digit password # The value is within the range given in your puzzle input. (372037-905157) # Two adjacent digits are the same (like 22 in 122345). # Going from left to right, the digits never decrease; # second round: # the two adjacent matching digits are not part of a larger group of matching digits. UPPER_BOUND = 905157 LOWER_BOUND = 372037 def two_adjacent_are_the_same(password): return password[0] == password[1] or password[1] == password[2] or password[2] == password[3] or password[3] == password[4] or password[4] == password[5] def two_adjacent_are_the_same_no_groups(password): return ((password[0] == password[1] and password[1] != password[2]) or (password[1] == password[2] and password[1] != password[0] and password[2] != password[3]) or (password[2] == password[3] and password[2] != password[1] and password[3] != password[4]) or (password[3] == password[4] and password[3] != password[2] and password[4] != password[5]) or (password[4] == password[5] and password[4] != password[3])) def never_decrease(password): return password[0] <= password[1] and password[1] <= password[2] and password[2] <= password[3] and password[3] <= password[4] and password[4] <= password[5] def check_for_consistency(password): int_password = password password = str(password) return (len(password) == 6 and int_password <= UPPER_BOUND and int_password >= LOWER_BOUND and two_adjacent_are_the_same(password) and never_decrease(password) and two_adjacent_are_the_same_no_groups(password)) # assert(check_for_consistency(444444) == True) assert(check_for_consistency(223450) == False) assert(check_for_consistency(123789) == False) print(sum(map(check_for_consistency, range(LOWER_BOUND, UPPER_BOUND))))
9d0442a588adb44726c5edc442733cec5f4c6365
dorkk0/Anigma-Project
/PlugBoard.py
1,518
3.5625
4
import sys from Translator import Translator class PlugBoard(Translator): def __init__(self, config): self.permutation = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") self.setConfig(config) def setConfig(self, config): if len(config) > 10: print("Error, number of pairs in configuration must be at most 10 paris") sys.exit(0) elif len(config) > 0 and len(config) <= 10: #checks if there are only 2 letters in each switch for pair in config: if len(pair)!=2: print("plugboard configuration isn't legal") sys.exit(0) #checks if each letter appear only once in the configuration for pair in config: for pair2 in config: if pair != pair2: if pair2.count(pair[0]) !=0 or pair2.count(pair[1]) !=0: print("illegal plugboard configuration, each pair of letters must contain different letters") sys.exit(0) for pair in config: f_letter = pair[0] s_letter = pair[1] f_index = Translator.letterToindex(f_letter) s_index = Translator.letterToindex(s_letter) self.permutation[f_index] = s_letter self.permutation[s_index] = f_letter def translation(self, letter): return self.permutation[Translator.letterToindex(letter)]
b73fc80a689005321b1e91c96044ee6006efb37f
nandadao/Python_note
/note/download_note/first_month/day05/exercise04.py
570
3.515625
4
""" 练习: 在列表中[5,6,17,78,34,5] 删除大于10的元素 温馨提示:调试/画图 """ list01 = [5, 6, 17, 78, 34, 5] # for item in list01: # if item > 10: # # 删除的是变量 # # del item # # 漏删(后面元素向前移动) # list01.remove(item) # for i in range(len(list01)): # if list01[i] > 10: # # 错误(删除元素则总数减少) # del list01[i]# # 解决:倒序删除 for i in range(len(list01) - 1, -1, -1): if list01[i] > 10: del list01[i] print(list01)
76a1fe6b96995368f430ef3228372db68bae6601
PedroVitor1995/Uri
/Iniciantes/Questao1060.py
170
3.6875
4
def main(): qtd = 0 for i in range(6): numero = input('') if numero > 0: qtd += 1 print('%d valores positivos') % qtd if __name__ == '__main__': main()
2adf65a914a48aba52c2ee305f0bf2f19585d6da
charmip09/Python_Training
/TASK2_While_loop_break.py
623
4.03125
4
''' In the previous question, insert “break” after the “Good guess!” print statement. “break” will terminate the while loop so that users do not have to continue guessing after they found the number. If the user does not guess the number at all, print “Sorry but that was not very successful”. ''' counter = 0 while counter <= 4: counter = counter +1 number = int(input("Guess the " + str(counter) + ". number ")) if number != 5: print("Try again.") else: print("Good guess!") break if counter == 5: print("Game over") else: print("Sorry but that was not very successful")
13a985e9a523a96db5430f72edf64a7bb8883a3e
82-petru/Functions
/List_Functions_19.py
2,342
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 21:00:58 2019 @author: petru """ n = [1, 3, 5, 16, 8, 9, 11] print(n) #print first element from the list print(n[1]) # multiply the second element of the n list by 5 n[1] = n[1] * 5 n.append(4) n.pop(2) #will remove index mentioned in brakets, just one item n.remove(15) #will remove 'item' from list if will find it del(n[4]) #is like .pop in that it will remove the item at the given index, but it won’t return it: print(n) #Example with 2 parameters m = 6 n = 8 def funct(x, y): return x + y print(funct(m, n)) #Example with string n = 'Hello' def string(s): return s + ' world' print(string(n)) #You pass a list to a function the same way you pass any other argument to a function. #print item from a list , remove print operator otherwise shows 'none' def list(item): print(item[0]) n = [3, 5, 8] list(n) # other posibility with return operator but have to use print, too def list(item): return item[1] n = [3, 5, 8] print(list(n)) #modifying an item into the list def list(item): n[0] = n[0] * 2 return item[0] n = [3, 5, 8] print(list(n)) #append function n = [3, 5, 8] n.append(11) def list(item): n[0] = n[0] * 2 return item[0] print(list(n)) print(n) # n = [3, 5, 7] # functie cu folosirea loop for si functia range def print_list(x): for i in range(0, len(x)): print(x[i]) print_list(n) #un exemplu cu strings n = ['danemarca', 'anglia', 'belgia'] def listos(x): for i in range(0, len(x)): print(x[i]) listos(n) def lisk(y): return y print(lisk(range(5))) for r in range(0, 61, 1):#printing all odd numbers print(r, end=', ')# ca sa afiseze in linie dupa loop de for #nice example sampleList = [3, 6, 9, 12, 15] for i in range(len(sampleList)): print( "Element Index[", i, "]", "Previous Value ", sampleList[i], "Now ", sampleList[i] * 2) for i in range(0, 19, 1): print(i, end= ',') #Iterating over a list in a function #Method 1 - for item in list: #for item in list: #print item #Method 1 is useful to loop through the list, but it’s not possible to modify the list this way. #Method 2 - iterate through indexes: #for i in range(len(list)): # print list[i] #Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed
fe24930651b1086ac4792c277f3556e4431241a8
Flame221/test1
/codewars.py
456
4.03125
4
def positive_sum(arr): sum_of_numbers = 0 for i in arr: if i >= 0: sum_of_numbers += i return sum_of_numbers def sum_array(arr): if arr is None or len(arr) < 3: return 0 else: return sum(arr) - max(arr) - min(arr) def validate_pin(pin): if pin.isdigit(): if len(pin) == 4 or len(pin) == 6: return True else: return False else: return False
a73687ba74f6d3f9ab1f14a316a2a8f1c8903412
olexxxa/CIS106-Oleksa-Ivankiv
/Session 4/1.5.py
533
3.65625
4
print("Please enter your last name") uN = input() print("Please input number of dependents") dQ = int(input()) print("Please enter your gross income") gI = int(input()) aGI = gI - dQ * 12000 if aGI > 50000: tR = 0.2 iT = aGI * tR else: if aGI >= 0: tR = 0.1 iT = aGI * tR else: iT = 100 print("Your last name entered is " + uN + ", Gross income is " + str(gI) + ", Number of dependence is " + str(dQ) + ", Adjusted gross income is " + str(aGI) + ", Income tax is " + str(iT))
eebe316148171fbb0cbbc048887f8c815538c0a4
moakes010/ThinkPython
/Chapter10/Chapter10_Exercise12.py
478
4.1875
4
''' Exercise 12 Two words are a reverse pair if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. ''' word_list = ['the', 'brown', 'dog', 'ran', 'down', 'street'] word = 'god' def rev_pair(lword, word): rev_word = word[::-1] if rev_word in lword: return True def main(): if rev_pair(word_list, word): print("Reverse pair: " + word, word[::-1]) else: print("No reverse pair") main()
95954f086bd18701a0668159f470f8e2a2784d4f
souzaMateus99/Study
/Python/loops.py
115
3.546875
4
# the else clausule is triggered when the loop condition is false i = 0 while i < 10: i += 1 else: print(i)
d38a71e49031cd73380aa81b949b4ae91e924a90
Streich676/PUI2016_cjs676
/HW3_cjs676/assignment_2.py
2,820
3.5
4
# coding: utf-8 # In[1]: from __future__ import print_function, division import pylab as pl import pandas as pd import numpy as np import os as os import zipfile as zp import csv as csv import urllib as ulr get_ipython().magic('pylab inline') get_ipython().system("curl -O 'https://s3.amazonaws.com/tripdata/201402-citibike-tripdata.zip'") zf = zp.ZipFile('201402-citibike-tripdata.zip') zf.extractall() zf.close() # In[2]: zf = zp.ZipFile('201402-citibike-tripdata.zip') zf.extractall() zf.close() # In[3]: data = pd.read_csv('2014-02 - Citi Bike trip data.csv') data # In[4]: print ('We have the data of the city bike trip of February 2014') print ('') print (' HYPOTHESIS ') print (' The average number of bike-trips of a working day in February') print (' is higher than the average numbers of bike trips in the weekend') print ('') print (' Lets define') print (' WORKING DAY = MONDAY-FRIDAY ') print (' WEEK-END = SATURDAY AND SUNDAY') print (' BIKE TRIP = A pick up of a bike') print (' AVERAGE NUMBER OF BIKE-TRIPS = Total number of bike-trips of "n" days divided by "n"') print ('') print ('') print (' NULL HYPOTHESIS') print (' The average number of bike-trips of a working day in February') print (' is equal or less than the average numbers of bike trips in the weekend ') print ('') print ('Significance level a=0.05') # In[5]: data.columns # In[6]: data['date'] = pd.to_datetime(data['starttime']) data.drop(['tripduration', 'starttime', 'stoptime', 'start station id', 'start station name', 'start station latitude', 'start station longitude', 'end station id', 'end station name', 'end station latitude', 'end station longitude', 'bikeid', 'usertype', 'birth year', 'gender'], axis=1, inplace=True) # In[7]: data # In[8]: print (' We know that the 01 February 2014 was Saturday') # In[9]: data ['weekday'] = data ['date'].apply(lambda x: x.weekday()) # In[10]: data # In[11]: norm_w = 1 ax = ((data['date'].groupby([data['date'].dt.weekday]).count()) / norm_w).plot(kind="bar", color='IndianRed', alpha=0.5) tmp = ax.xaxis.set_ticklabels(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], fontsize=20) # In[12]: data_count = data.groupby('weekday').size() working_day_trip = 0 weekend_day_trip = 0 for i in range(0 , 4): working_day_trip = data_count[i] + working_day_trip for i in (5,6): weekend_day_trip = data_count[i] + weekend_day_trip print (weekend_day_trip) print (working_day_trip) # In[13]: average_weekend_day_trip = weekend_day_trip / 8 average_working_day_trip = working_day_trip / 20 # In[14]: print (average_weekend_day_trip) print (average_working_day_trip) # In[15]: array = [average_weekend_day_trip , average_working_day_trip] array # In[ ]: # In[ ]: # In[ ]: # In[ ]:
2e1edcb9652714b663e036149dacc4b86c7cc482
steffemb/INF4331
/Assignement5/scraper.py
2,882
3.546875
4
import re import urllib.request def find_emails(text): """ function that scans a string "text" and returns a list of all "email like" expressions. """ regex = r"([a-zA-Z0-9.#$%&~’*+-/=?‘|{}]+?@[a-zA-Z0-9.#$%&~’*+-/=? ‘|{}_]+?\.[a-zA-Z][a-zA-Z.,_]*[a-zA-Z])" match = re.findall(regex,text) return match def find_hyperlinks(text): """ function that scans a string "text" in HTML format and returns a list of all "url like" expressions. """ regex = r"<a href=(['\"])(\w*://\w*?[a-zA-Z][a-zA-Z.,_]*[a-zA-Z]\.[a-zA-Z][a-zA-Z.,_]*[a-zA-Z][\w.~/-]*)\1" matches = re.findall(regex,text) #print(matches) matches = [match[1] for match in matches] # the regex captures an extra empty string return matches def all_the_emails(url,depth): """ function to recursively search for email adresses on a HTML string. The function stores all hyperlinks and email adresses and then follows the links to search for more recursively a number of times. url: start adress for search depth: number of hyperlink layeres to follow (carefull on this one) Function stores finds in the files hyperlinks.txt and emails.txt """ # initial html = str(url_to_html(url)) hyperlinks = find_hyperlinks(html) emails = find_emails(html) length = 0 i = 0 print("stealing stuff!") while i < depth: print("sneaking around") # Iknow the task specifically ask for a call to # itself, but i find this to be an easier implementation for k in range(len(hyperlinks)-length): #iterate over all new links html = str(url_to_html(hyperlinks[k])) hyperlinks += find_hyperlinks(html) emails += find_emails(html) hyperlinks = remove_duplicates(hyperlinks) emails = remove_duplicates(emails) length = len(hyperlinks) i += 1 # depth counter hyperlinks = remove_duplicates(hyperlinks) emails = remove_duplicates(emails) print("found %i hyperlinks" % len(hyperlinks)) write_list_to_file(hyperlinks, "hyperlinks.txt") print("found %i emails" % len(emails)) write_list_to_file(emails, "emails.txt") #####additional functions for tidyness##### def remove_duplicates(mylist): """ removes anny duplicate entries in a list """ newlist = [] for i in mylist: if i not in newlist: newlist.append(i) return newlist def url_to_html(url): """opens url and copies pure HTML as string""" with urllib.request.urlopen(url) as url: html = url.read() #from StackOverflow return html def write_list_to_file(list_name, file_name): f = open(file_name, 'w') for item in list_name: f.write(item + "\n") if __name__ == "__main__": url = "https://lucidtech.io/" depth = 2 all_the_emails(url,depth)
5bcf1663526b25583769be6e788195195200c75d
thanedpon/software2
/timezone2.py
406
3.609375
4
import datetime class timezone(datetime.tzinfo): def __init__(self, name="+0000"): self.name = name seconds = int(name[:-2])*3600+int(name[-2:])*60 self.offset = datetime.timedelta(seconds=seconds) def utcoffset(self, dt): return self.offset def dst(self, dt): return timedelta(0) def tzname(self, dt): return self.name
ddd8965743d0b00404917ff82f214be6d857e5fc
Sivious/github
/pySolitarie.py
3,520
3.5625
4
#!/usr/bin/env python import os #define constants pOccupied = 'O' pFree = 'F' pProhibited = 'P' mGame = [ ['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'F', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['P', 'P', 'O', 'O', 'O', 'P', 'P']] #Cleaning function class cls(object): def __repr__(self): os.system('cls' if os.name == 'nt' else 'clear') return '' #This function simply print the (in) Matrix def printBoard(mBoard = []): numRow = 0 print ' 0123456' for rows in mBoard: board = '' for item in rows: if item == 'P': board += ' ' elif item == 'O': board += 'X' elif item == 'F': board += ' ' print str(numRow) + ' ' + board numRow += 1 #this function consolidate the board with the correct move def moveIt (posFrom = [], posTo = []): posFromX = int(posFrom[0]) posFromY = int(posFrom[1]) posToX = int(posTo[0]) posToY = int(posTo[1]) mGame[posFromX][posFromY] = 'F' mGame[(posFromX+posToX)//2][(posFromY+posToY)//2] = 'F' mGame[posToX][posToY] = 'O' #this function returns if a tab can move to the position def canMove(posFrom = [], posTo = []): posFromX = int(posFrom[0]) posFromY = int(posFrom[1]) posToX = int(posTo[0]) posToY = int(posTo[1]) mMoves = [] # Create a list with the 4 possible movements # using the ternary operators (op1 if condition else op2) if mGame[(posFromX+posToX)//2][(posFromY+posToY)//2] == 'O' : mMoves.append([posFromX-2 , posFromY, mGame[posFromX - 2][posFromY]] if posFromX-2 >= 0 else 'P') mMoves.append([posFromX , posFromY-2, mGame[posFromX][posFromY - 2]] if posFromY-2 >= 0 else 'P') mMoves.append([posFromX+2 , posFromY, mGame[posFromX + 2][posFromY]] if posFromX+2 <= 5 else 'P') mMoves.append([posFromX , posFromY+2, mGame[posFromX][posFromY + 2]] if posFromY+2 <= 5 else 'P') if [posToX, posToY, pFree] in mMoves: return True else: return False def newGame (): mGame = [['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'F', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', 'O', 'O'], ['P', 'P', 'O', 'O', 'O', 'P', 'P'], ['P', 'P', 'O', 'O', 'O', 'P', 'P']] print 'Game Start' newGame() printBoard(mGame) while 1 == 1: selection = raw_input('Play>> ') token = selection.split(' ') if token[0] == 'move' and len(token) == 3 : try: porFrom = [] posFrom = token[1].split(',', 1) posTo = [] posTo = token[2].split(',', 1) if canMove(posFrom, posTo) : moveIt(posFrom, posTo) printBoard(mGame) else : print 'Movement not allowed!' except ValueError: print 'Bad Spelling!' elif token[0] == 'print' : printBoard(mGame) elif token[0] == 'quit' : print 'Bye' break elif token[0] == 'printBoard' : print mGame elif token[0] == 'help' : print 'Commands:' print ' move [POSITION SOURCE] [POSITION DESTINATION]' print ' Example: move 1,3 3,3' print ' print' print ' printBoard (DEVELOPER COMMAND)' print ' help' print ' help' print ' newGame' elif token[0] == 'newGame' : newGame() printBoard(mGame) else: print 'Incorrect command'
a0931c3f4115963a99a097cff2ef1e150adef18b
dos09/PythonTest
/reference_code/functions01.py
1,204
3.75
4
# Functions ########### def inc01 (x): return x + 1 print("inc01(4): " + str(inc01(4))) inc02 = lambda x : x + 1 print("inc02(20): " + str(inc02(20))) print('------------------------------------------') def pass_parameters(_list, _str="default value"): _list.append("new item") _str = "some val" mystr = "mystr" mylist = ["a"] print("mylist: " + str(mylist)) print("mystr: " + mystr) pass_parameters(mylist, mystr) print("after pass_parameters(mylist, mystr)") print("mylist: " + str(mylist)) print("mystr: " + mystr) print('------------------------------------------') print('pass unknown count of arguments to function') def many_args(*args): print(type(args)) print(args) for item in args: print(item) def many_key_val_args(**kwargs): print(type(kwargs)) print(kwargs) for key in kwargs: print(kwargs[key]) for k, v in kwargs.items(): print(k,'-',v) many_args(1,3,'asda') many_key_val_args(one='edno', two=2) print('------------------------------------------') print('pass function as argument') def apply_math_operation(op, a, b): print(op(a,b)) def sum(a, b): return a + b apply_math_operation(sum, 1, 4)
5303ac5fcf2c0887634ab632a780fddf476655ce
Andi-Pleian/Analiza-Metodelor-de-Sortare
/insertie.py
1,886
3.625
4
import random import time import datetime def gen(limit): l = [] for i in range(0, limit): nr = random.randint(-2147483648, 2147483648) l.append(nr) return l def insertionSort(l): for i in range (1, len(l)): aux = l[i] j = i - 1 while j >= 0 and aux < l[j]: l[j + 1] = l[j] j -= 1 l[j + 1] = aux #liste mici l1 = gen(100) start = datetime.datetime.now() insertionSort(l1) end = datetime.datetime.now() time_diff = (end - start) print("100 elemente:") print(time_diff.total_seconds() * 1000) #milisecunde l2 = gen(300) start = datetime.datetime.now() insertionSort(l2) end = datetime.datetime.now() time_diff = (end - start) print("300 elemente:") print(time_diff.total_seconds() * 1000) #milisecunde l3 = gen(500) start = datetime.datetime.now() insertionSort(l3) end = datetime.datetime.now() time_diff = (end - start) print("500 elemente:") print(time_diff.total_seconds() * 1000) #milisecunde #liste mari #L1 = generate(1000) L1 = gen(1000) start = time.time() insertionSort(L1) end = time.time() print("1000 elemente:") print(end - start) #secunde #L2 = generate(10000) L2 = gen(10000) start = time.time() insertionSort(L2) end = time.time() print("10000 elemente:") print(end - start) #secunde #L3 = generate(100000) L3 = gen(100000) start = time.time() insertionSort(L3) end = time.time() print("100000 elemente:") print(end - start) #secunde #L4 = generate(1000000) L4 = gen(1000000) start = time.time() insertionSort(L4) end = time.time() print("1000000 elemente:") print(end - start) #secunde #L5 = generate(10000000) L5 = gen(10000000) start = time.time() insertionSort(L5) end = time.time() print("10000000 elemente:") print(end - start) #secunde #print(l1) #start = time.time() #end = time.time() #print(l1) #print() #print(end - start)
6e3c36016351840a5ac8f76ae6cac5c4bb1e55b3
thepros847/python_programiing
/lessons/operators.py
654
4.0625
4
# create a variable x and assign a value 10 x = 10 # create a variable y and assign a value 25 y = 25 print(x+y) print(x-y) print(x/y) print(x*y) print(x**y) # floor division #create a variable and assign a value 12.68 a = 12.68 #create a variable and assign b value 3 b = 3 print(a//b) print(a%b) print(-x) print(abs(-x)) string_1="Python" string_2="Programming" final_string=string_1 + string_2 print(final_string) print(string_1*4) print(x==y) print(x is 10) print(x == 10) print(x != y) print(x <= y) print(x >= 20) print(x < y) #print(a & b) #print(a | b) #print(a ^ b) #print(a << x) #print(a >> x) #print(~a)
0f68caef3e2297d6484ef91b3f585e7ffcdd4d42
Jinalshah12345/ScientificCalculator
/practice.py
1,703
3.515625
4
@staticmethod def calculate_median(l): l = sorted(l) l_len = len(l) if l_len < 1: return None if l_len % 2 == 0: return (l[(l_len - 1) // 2] + l[(l_len + 1) // 2]) // 2.0 else: return l[(l_len - 1) // 2] l = [1] print(calculate_median(l)) l = [3, 1, 2] print(calculate_median(l)) l = [1, 2, 3, 4] print(calculate_median(l)) # calculate Variance def population_variance(num): sumOfNumbers = 0 for t in num: sumOfNumbers = sumOfNumbers + t avg = sumOfNumbers / len(num) var = sum((t - avg) ** 2 for t in num) / len(num) return var print("The variance of List is", population_variance([19, 21, 46, 11, 18])) @staticmethod def stdev(df): mean = sum(df) / len(df) sample_variance = sum((x - mean) ** 2 for x in df) / (len(df) - 1) standard_deviation = sample_variance ** (0.5) return round(standard_deviation) print("The sample standard deviation of List is", stdev([19, 21, 46, 11, 18])) @staticmethod def populatuin_proportion_variance(num): for p in num: prop = p / sum(num) x = (prop * (1 - prop) / sum(num)) variance_of_pop_prop = x ** (0.5) return variance_of_pop_prop @staticmethod def correlationCoefficient(X, Y, n): sum_X = 0 sum_Y = 0 sum_XY = 0 squareSum_X = 0 squareSum_Y = 0 i = 0 while i < n: sum_X = sum_X + X[i] sum_Y = sum_Y + Y[i] sum_XY = sum_XY + X[i] * Y[i] squareSum_X = squareSum_X + X[i] * X[i] squareSum_Y = squareSum_Y + Y[i] * Y[i] i = i + 1 # use formula for calculating correlation # coefficient. corr = (n * sum_XY - sum_X * sum_Y) / (math.sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))) return corr
dd6baa7c0e5d4f7705891b5c5d1a1a3054157254
nishal18/hackrank_soln
/mini-max sum
452
3.765625
4
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): sm=[] for j in range(len(arr)): s=0 for i in range(len(arr)): if i==j: continue s+=arr[i] sm.append(s) sm.sort() print(sm[0],sm[-1]) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
7262674fc5f0c82fff93dae251283ec0d4ddd617
jtmyers1983/Algorithm-Class-Exercises
/algos/maxsum_iterative.py
558
3.5
4
# Iterative maxsum profits = [-20,50,-30,40,10,5,-50,40] def maxsum_iterative(L): if L==[]: return 0 maxsum = L[0] # look at all possible intervals (beg, end) for b in range(0, len(L)): for e in range(b, len(L)): # compute the current sum in this interval from index b to index e current_sum = 0 for i in range(b, e+1): current_sum = current_sum + L[i] # maintain a maxsum if current_sum > maxsum: maxsum = current_sum return maxsum for i in range(5): profits = (24,18,18,10) print(profits, maxsum_iterative(profits))
938b911819771c545d0324e230bec4694b0ef0ad
grwkremilek/leetcode-solutions
/python/0700.search-in-a-BST/search_in_BST.py
665
3.890625
4
#https://leetcode.com/problems/search-in-a-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def searchBST(root, val): if root is None or root.val == val: return root if root.val < val: return searchBST(root.right, val) return searchBST(root.left, val) def searchBST(root, val): if root and root.val == val: return root if root and root.val > val: return searchBST(root.left, val) if root and root.val < val: return searchBST(root.right, val)
a1ebe8fcef7e5d619528ecde93acc572f81879ae
sglavoie/code-snippets
/python/user_input/validate_choice.py
388
4.34375
4
def user_says_yes(message=""): """Check if user input is either 'y' or 'n'. Returns a boolean.""" while True: choice = input(message).lower() if choice == "y": choice = True break elif choice == "n": choice = False break else: print("Please enter either 'y' or 'n'.") return choice
ef8203aab234297694ad76265bb486195dadfe7e
ramirovazq/algorithmexamples
/merge_sort.py
2,291
3.875
4
''' O(nlgn) MERGE SORT PSEUDOCODE mergesort (A) mergesort(A, 0, len(A)-1) mergesort(A, lo, hi) if (hi-lo <= 0) return mid = (lo + hi) / 2 mergesort(A, lo, mid) mergesort(A, mid+1, hi) C = merge(A[lo:mid], A[mid+1,hi]) copy elements from C back into A ''' from merge import merge, mergethree def mergesort_three(A): if len(A) <= 1: # returns the list when is one element return A mid = len(A) // 3 if mid == 0: # case when list is 2 elements mid = 1 primera = mergesort_three(A[:mid]) segunda = mergesort_three(A[mid:mid*2]) tercera = mergesort_three(A[mid*2:]) return merge(merge(primera,segunda),tercera) def mergesortthree(A=[12,11,13,5,6,7,1,9,8,15]): # son 10 elementos return mergesort_three(A) # ............................ def mergesort_(A): if len(A) <= 1: # returns the list when is one element return A mid = len(A) // 2 primera = mergesort_(A[:mid]) segunda = mergesort_(A[mid:]) #print("primera {} segunda {}".format(primera, segunda)) return merge(primera, segunda) def mergesort(A=[12,11,13,5,6,7,1,9,8,15]): # son 10 elementos return mergesort_(A) # second way diveded in two functions def split(input_list): input_list_len = len(input_list) midpoint = input_list_len // 2 return input_list[:midpoint], input_list[midpoint:] def merge_sort(input_list): if len(input_list) <= 1: return input_list else: left, right = split(input_list) return merge(merge_sort(left), merge_sort(right)) if __name__ == "__main__": z = [12,11,13,5,6,7,1,9,8,15] answer_a = mergesort(z) print("mergesort ...................... answer") print(answer_a) answer_b = merge_sort(z) print("merge_sort ...................... answer ..............................") print(answer_b) # In merge sort we decided to split our list into two parts # and recurse on them. # In this question we will consider splitting our list into three parts. answer_c = mergesortthree(z) print("mergesortthree ...................... answer") print(answer_c) print("compare tree versiones ...................... answer ..............................") print(answer_a == answer_b == answer_c)
2978f511d35aca211d84f8ee70d6c439b351c7d5
prbarik/My_Py_Proj
/.vscode/method_function_lessions.py
2,029
4.09375
4
# Ex-1 # Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd # lesser_of_two_evens(2,4) --> 2 # lesser_of_two_evens(2,5) --> 5 def lesser_function(a,b): if a%2 == 0 and b%2 == 0: return min(a,b) else: return max(a,b) result = lesser_function(2,6) print(result) # Ex-2 # Write a function takes a two-word string and returns True if both words begin with same letter # animal_crackers('Levelheaded Llama') --> True # animal_crackers('Crazy Kangaroo') --> False def letter_function(word): word_list = word.split() return word_list[0][0] == word_list[1][0] result1 = letter_function('Crazy Kangaroo') print(result1) # Ex-3 # Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False # makes_twenty(20,10) --> True # makes_twenty(12,8) --> True # makes_twenty(2,3) --> False def int_function(i1,i2): return (i1 + i2) == 20 or i1 == 20 or i2 == 20 result3 = int_function(10,20) print(result3) # Ex-4 # Write a function that capitalizes the first and fourth letters of a name # old_macdonald('macdonald') --> MacDonald def cap_function(word): if len(word) > 3: return word[:3].capitalize() + word[3:].capitalize() else: return 'Word is too short' result4 = cap_function('macdonald') print(result4) # Ex-5 # Given a sentence, return a sentence with the words reversed # master_yoda('I am home') --> 'home am I' # master_yoda('We are ready') --> 'ready are We' def rev_function(sentence): return ' '.join(sentence.split()[::-1]) result5 = rev_function('Reverse the sentence') print(result5) # Ex-6 # Given an integer n, return True if n is within 10 of either 100 or 200 # almost_there(90) --> True # almost_there(104) --> True # almost_there(150) --> False # almost_there(209) --> True def compare_function(n): return abs(100 - n) <= 10 or abs(200 - n) <= 10 result6 = compare_function(49) print(result6)
db969dbbd7254968214e1f5c56c41265270013cf
boris-ulyanov/adventOfCode
/2017/day-04/2.py
476
3.84375
4
#!/usr/bin/python def check_phrase(words): sorted_words = [''.join(sorted(w)) for w in words] uniq_words = set(sorted_words) if len(words) == len(uniq_words): return 1 else: return 0 data_file = open('./data', 'r') lines = data_file.readlines() data_file.close() result = 0 for line in lines: words = line.split() uniq_words = set(words) if len(words) == len(uniq_words): result += check_phrase(words) print result
c9d3bdeb76128575427dc1d23046336c7ba7e494
malikyilmaz/Class4-PythonModule-Week6
/Create a subclass of Shape.py
3,874
4.59375
5
""" Create a class named Triangle and Rectangle. Create a subclass named Square inherited from Rectangle. Create a subclass named Cube inherited from Square. Create a subclass named Pyramid multiple inherited both from Triangle and Square. Two dimensional classes (Triangle, Rectangle and Square) should have: * its dimensions as attributes.(can be inherited from a superclass) * methods which calculate its area and perimeter separately. Three dimensional classes (Cube and Pyramid) should have: * its dimensions as attributes which are inherited from a superclass * its extra dimensions if there is. (hint: maybe for Pyramid) methods which calculate its volume and surface area separately. (surface area is optional, you may not do this) """ ''' class Shape(): def _init_(self,a,b,c): self.a = float(a) self.b = float(b) self.c = float(c) a= input("a=") b= input("b=") c= input("c=")''' class Triangle(): def __init__(self, a=0, b=0, c=0): self.a = float(input("ucgenin a kenar uzunlugunu giriniz=")) self.b = float(input("ucgenin b kenar uzunlugunu giriniz=")) self.c = float(input("ucgenin c kenar uzunlugunu giriniz=")) def get_area(self): # ucgen alanini hesaplar s = (self.a + self.b + self.c) / 2 return (s*(s-self.a)*(s-self.b)*(s-self.c)) ** 0.5 def get_perimeter(self): # ucgen cevresini hesaplar return self.a + self.b + self.c def __str__(self): print( "ucgenin alani : {} m2 \n" "ucgenin cevresi : {} m" .format(self.get_area(), self.get_perimeter())) class Rectangle(): def __init__(self, a=0, b=0): self.a = float(input("dikdortgenin a kenar uzunlugunu giriniz=")) self.b = float(input("dikdortgenin b kenar uzunlugunu giriniz=")) def get_area(self): # dikdortgenin alanini hesaplar return self.a*self.b def get_perimeter(self): # dikdortgenin cevresini hesaplar return (self.a + self.b)*2 def __str__(self): print( "dikdortgenin alani : {} m2 \n" "dikdortgenin cevresi : {} m" .format(self.get_area(), self.get_perimeter())) class Square(Rectangle): def __init__(self,a=0): self.a = float(input("karenin kenar uzunlugunu giriniz=")) self.b = self.a def __str__(self): print("karenin alani : {} m2 \n" "karenin cevresi : {} m" .format(self.get_area(), self.get_perimeter())) class Cube(Square): def __init__(self,a=0): self.a = float(input("kupun kenar uzunlugunu giriniz=")) self.b = self.a def get_volume(self): # kupun hacmini hesaplar return self.a**3 def __str__(self): print("kupun hacmi : {} m3 \n" "kupun alani : {} m2 \n" "kupun cevresi : {} m" .format(self.get_volume(), 6*self.get_area(), 3*self.get_perimeter())) class Pyramid (Square,Triangle): def __init__(self,a=0,pyramid_height=0): self.a = float(input("Kere Piramidin kenar uzunlugunu giriniz=")) self.pyramid_height = float(input("Kare Piramidin yuksekligini giriniz=")) self.b = self.a self.c = self.a def get_volume(self): # Piramidin hacmini hesaplar return self.a**2*self.pyramid_height/3 def __str__(self): print("Piramidin hacmi : {} m3 \n" "Piramidin alani : {} m2 \n" "Piramidin cevresi : {} m" .format(self.get_volume(), self.get_area(), self.get_perimeter())) #t = Triangle() #t.__str__() #d = Rectangle() #d.__str__() #k = Square() #k.__str__() #kk = Cube() #kk.__str__() p = Pyramid() p.__str__()
2b77192672bd92df58e2e1272437ebbba9b8ad01
NishaKaramchandani/NaturalLanguageProcessing
/TextSummerization-LexicalChains/lexical_chains_for_summary.py
4,690
3.5625
4
import nltk from nltk.corpus import wordnet File = open("input_text.txt") # open file lines = File.read() # read all lines sentences = nltk.sent_tokenize(lines) # tokenize sentences nouns = [] # empty to array to hold all nouns list_lexical_chains = [] #Extract all the nouns from the input text. for sentence in sentences: for word, pos in nltk.pos_tag(nltk.word_tokenize(str(sentence))): if (pos == 'NN' or pos == 'NNS'): nouns.append(word) print("\n\nList of nouns in the text::\n", nouns) # Creating first lexical chain dictionary_obj = {nouns[0]: 1} list_lexical_chains.append(dictionary_obj) for word in nouns[1:]: synonyms = [] antonyms = [] hypernyms = [] hyponyms = [] word_added_flag = 0 for synset in wordnet.synsets(word): for lemma in synset.lemmas(): synonyms.append(lemma.name()) if lemma.antonyms(): antonyms.append(lemma.antonyms()[0].name()) for synset_hyponyms in synset.hyponyms(): for nm in synset_hyponyms.lemma_names(): hyponyms.append(nm) for synset_hypernym in synset.hypernyms(): for nm in synset_hypernym.lemma_names(): hypernyms.append(nm) for a_lexical_chain_dictionary in list_lexical_chains: for dictionary_word in a_lexical_chain_dictionary: if dictionary_word == word: a_lexical_chain_dictionary[dictionary_word] = a_lexical_chain_dictionary[dictionary_word] + 1; word_added_flag = 1 break if dictionary_word in synonyms: a_lexical_chain_dictionary.update({word: 1}) word_added_flag = 1 break if dictionary_word in antonyms: a_lexical_chain_dictionary.update({word: 1}) word_added_flag = 1 break if dictionary_word in hypernyms: a_lexical_chain_dictionary.update({word: 1}) word_added_flag = 1 break if dictionary_word in hyponyms: a_lexical_chain_dictionary.update({word: 1}) word_added_flag = 1 break if word_added_flag == 0: new_dict_obj = {word: 1} list_lexical_chains.append(new_dict_obj) print("\n\nAll lexical chains::\n", list_lexical_chains) # Sorting lexical chains in descending order of lengths to get strong chains first list_lexical_chains.sort(key=lambda s: len(s), reverse=True) print(list_lexical_chains) strong_lexical_chain_list = [] # Filtering out strong chains based on the length of the chain. We know first chain in the list is strong chain as we sorted in descending order. length_for_strong_chain = len(list_lexical_chains[0]) strong_lexical_chain_list.append(list_lexical_chains[0]) for a_lexical_chain in list_lexical_chains[1:]: if len(a_lexical_chain) == length_for_strong_chain: strong_lexical_chain_list.append(a_lexical_chain) # print(strong_lexical_chain_list) # Filtering out strong chains based on the frequency of words. We know frequency of first chain in the list is strong as we sorted in descending order. for a_lexical_chain in list_lexical_chains: if sum(a_lexical_chain.values()) >= sum(strong_lexical_chain_list[0].values()): if a_lexical_chain not in strong_lexical_chain_list: strong_lexical_chain_list.append(a_lexical_chain) print("\n\nStrong chain final list:\n", strong_lexical_chain_list) #Assigning score or weight to every sentence in the text to find strong sentences for Summary. sentence_score = {} for sentence in sentences: new_dict_obj = {sentence: 0} sentence_score.update(new_dict_obj) for word in nltk.word_tokenize(str(sentence)): for a_lexical_chain in strong_lexical_chain_list: if word in a_lexical_chain: sentence_score[sentence] = sentence_score[sentence] + a_lexical_chain[word] print("\n\nSentence score dictionary:\n", sentence_score) sentence_score = sorted(sentence_score, key=sentence_score.get, reverse=True) #print("Sentence score dictionary sorted:", sentence_score) #assigning one third length of text as length for summary summary_length = int(len(sentences)/3) print("\n\nSummary Length:\n", int(len(sentences)/3)) #Strong sentence list with sentences to be added to summary. sentence_score = sentence_score[:summary_length] #Retrieving summary sentences in the order which they were found in the text to maintain cohersion. summary = "" for sentence in sentences: if sentence in sentence_score: summary = summary + sentence print("\n\nSummary:\n", summary)
0ed2ae93334fcbfc9eef794d99c6ec4e56c543a1
luckspt/prog2
/fichas/2_complexidade/complexidade.py
7,173
3.71875
4
import math #1 - Ordene as seguintes funções por taxa de crescimento assintótico: 4 n log n, 2^{10}, 2^{log_{10}n}, 3n + 100log n, 4^n, n^2 + 10n """ 2^{10} O(1) 2^{log_{10}n} O(n^c) => 2^{log_10 n} = 2^{log_2 n / log_2 10} = n^{1 / log_2 10} = n^0,30.. 3n + 100 log n O(n) 4 n log n O(n log n) n^2 + 10n O(n^c) 4^n O(c^n) """ #2 - Num dado computador, uma operação demora um milisegundo a ser executada. Considere um programa que realiza um número de operações dado pela função f(n) = n^5, para um qualquer parâmetro n. Qual o maior valor de n para o qual o programa é capaz de terminar os seus cálculos se o tempo disponível for (a) um ano; (b) uma década; (c) 15 mil milhões de anos (a idade do universo)? Nota: um ano tem aproximadamente 3.15*(10^7) segundos. def prob2(): anoMS = 3.15 * (10 ** 7) * 1000 decadaMS = 10 * anoMS universo = 15000000000 * anoMS print(f'1 ano: {round(anoMS ** (1/5))}') print(f'10 anos: {round(decadaMS ** (1/5))}') print(f'universo: {round(universo ** (1/5))}') #3 - Repita o exercício anterior para as seguintes funções: f(n) = 10n, f(n) = 1000n, f(n) =n^2 e f(n) = 2^n def prob3(): anoMS = 3.15 * (10 ** 10) decadaMS = 10 * anoMS universoMS = 15 * (10**9) * anoMS lst = [ anoMS, decadaMS, universoMS ] print('f(n) = 10n') for n in lst: print(round(n / 10)) print('f(n) = 1000n') for n in lst: print(round(n / 1000)) print('f(n) = n^2') for n in lst: print(round((n**(1/2) / 10))) print('f(n) = 2^n') for n in lst: print(round(math.log(n, 2))) #4 - Supponha que o tempo de execução de um algoritmo em inputs de tamanho 1000, 2000, 3000 e 4000 é de 5 segundos, 20 segundos, 45 segundos, e 80 segundos, respetivamente. Estime quanto tempo levará para resolver um problema de tamanho 5000. A taxa de crescimento assintótico do algoritmo é linear, log-linear, quadrática,cúbica ou exponencial? #5 - Apresente uma caracterização O do tempo de execução de cada uma das funções abaixo, em termos do input n. #O(n^2) def prog5_a(n): m = 0 for i in range(1, 10 * n): for j in range(1, n): m += 1 return m # O(1) def prog5_b(n): x = 0 for a in range(0, 2021): x += a * n return x #o(n^2) def prog5_c(n): b = n * n while b > n: if b % 2 == 0: b -= 1 else: b -= 2 return b # O(n) def prog5_d(n, v): soma = 0 for i in range(0, n): for j in range(1, 4): soma += v[i] return soma # O(log n) def prog5_e(n): x = n * n * n while x > 1: x /= 2 return x # O(1) def prog5_f(n): soma = n * n while soma % 2 == 0: soma -= 1 return soma # O(n^2) def prog5_g(n): c = 0 for i in range(0, n): for j in range(i, n): c += 1 return c # pior caso O(n*m), melhor caso O(n) def prog5_h(l1, l2): soma = 0 for x in l1: #O(n) if x % 2 == 0: soma += 1 else: for y in l2: #O(m) soma += y return soma #6 - Analise a complexidade assintótica da função diferenca. # O(len(l1) * len(l2)) def diferenca(l1, l2): """Devolve uma lista que contém os elementos de l1 que não estão em l2 Args: l1 (list): lista l2 (list): lista Returns: list: lista l1 \ l2 """ resultado = [] for x in l1: if x not in l2: resultado.append(x) return resultado #7 - Analise a complexidade assintótica da função unicos. # O(n) def unicos(lista): """Recebe uma lista ordenada e devolve uma outra lista contendo exatamente uma ocorrência de cada elemento da lista original Args: lista (list): lista original de valores Returns: list: lista resultado Requires: a lista original está ordenada Ensures: a lista resultado está ordenada """ return [] if not lista else( [lista[i] for i in range(len(lista)-1) if lista[i] != lista[i+1]] + [lista[-1]]) #8 - Analise a complexidade assintótica da função inverter. # O(n) def inverter(lista): """Inverte a ordem dos elementos de uma lista Args: lista (list): lista original Ensures: a lista é alterada, invertendo a ordem dos seus elementos """ for i in range(len(lista)//2): # O(n/2) = O(n) lista[i], lista[-1-i] = lista[-1-i], lista[i] # O(1) #9 - A função minimo devolve o valor mínimo de uma lista. def minimo(lista): copia = list(lista) # O(n) copia.sort() # O(n log n) return copia[0] # O(1) """ a) Analise a complexidade assintótica da solução dada. # O(n log n) b) Proponha uma solução linear """ def prob9b(lista): mini = lista[0] for num in lista: if num < mini: mini = num return num #10 - As funções sem_repetidos1 e sem_repetidos2 verificam se uma lista não tem repetidos def sem_repetidos1(l): # O(n^2) for i in range(len(l)): # O(n) if l[i] in l[(i+1):]: # O(n-1) return False # O(1) return True # O(1) def sem_repetidos2(l): # O(n log n) copia = list(l) # O(n) copia.sort() # O(n log n) for i in range(len(l) - 1): # O(n) if copia[i] == copia[i+1]: # O(1) return False # O(1) return True # O(1) """ a) Analise a complexidade assintótica de cada uma das soluções. 1 - O(n^2) 2 - O(n log n) b) Proponha uma solução linear. Sugestão: converta a lista num conjunto """ def prob10b(lst): return len(set(lst)) == len(lst) # O(n) def prob10b2(lst): dic = { i: False for i in len(lst)} # O(n) return len(dic) == len(lst) # O(1) #11 - A seguinte função calcula as médias dos prefixos de uma lista. def media_prefixos(l): """" Requires: uma lista de números Ensures: devolve uma lista m onde m[i] é a médiados elementos l[0] ,... , l[i-1] """ m = [] # O(1) for i in range(len(l)): # O(n) soma = 0.0 # O(n) for j in range(i + 1): # O(i) soma += l[j] # O(1) m.append(soma / (i + 1)) # O(1) return m # O(1) """ a) Verifique que a função tem um tempo de execução quadrático. b) Apresente uma solução com tempo linear. Sugestão: calcule incrementalmente a média de cada um dos prefixos através da seguinte fórmula { m[0] = l[0] { m[k+1] = (m[k] * (k + 1) + l[k+1]) / (k+2) """ def prob11b(l): m = [l[0]] # O(1) for k in range(1, len(l)): # O(n) m.append( (m[-1]*k + l[k]) / (k+1) ) # O(1) return m # O(1)
d9ef09458516042eb5a0d9286c1c056eeea54eb7
zanewebb/codebreakerspractice
/Fundamentals/reverse.py
452
4.3125
4
from LinkedList import LinkedList def reverse(linkedlist): cur = linkedlist.head.next prev = None while cur is not None: next = cur.next cur.next = prev prev = cur cur = next linkedlist.head.next = prev return linkedlist if __name__ == "__main__": linkedlist = LinkedList() for i in range(1,6): linkedlist.insertFront(i) print(linkedlist) print(reverse(linkedlist))
e1c27ea48ee5db3379333bff15953908d9dc2e27
amazed01/Polynomial_Multiplication
/main.py
1,820
4.03125
4
from helper import * import math def multiply(x,y): x,y = make_equal_length(x,y) if len(x) == 0: return [0] if len(x) == 1: unit = (x[0] * y[0]) % 10 carry = (x[0] * y[0]) // 10 if carry != 0: return [carry,unit] else: return [unit] print('###########################################') print('New Multiply Recursion Level') k = len(x) // 2 input('Break into Two Parts') x_left, x_right = x[:k], x[k:] y_left, y_right = y[:k], y[k:] input('a b c d') print(x_left,x_right,y_left,y_right) input('Starting P1 (a x c) calculation') P1 = multiply(x_left,y_left) input('Enter to see P1 (a x c)') print(P1) input('Starting P2 (b x d) calculation') P2 = multiply(x_right,y_right) input('Enter to see P2 (b x d)') print(P2) input('Starting P3 (a+b x c+d) calculation') P3 = multiply(add_array(x_left,x_right),add_array(y_left,y_right)) input('Enter to see P3 (a+b x c+d)') print(P3) input('Starting final calculation') k_dash = k if len(x) % 2 == 1: k_dash = k + 1 k = k + 1 print('CHANGED K DUE TO ODD LENGTH') l = add_array(P1,P2) print(l, ' P1 + P2', P1 + [0]*2*k_dash, P2) # K_dash added later l = sub_array(P3,l) print(l, ' P3 - P1 - P2 ___ Os', [0]*k) # print('@@@@@@@@@@@@@@@') # print(P1 + [0]*2*k, P2) q = add_array(P1 + [0]*2*k_dash,P2) print(q,' (P1 + [0]*2*k_dash) + P2', P1 + [0]*2*k_dash,P2 ) t = add_array(add_array(P1 + [0]*2*k_dash,P2) , sub_array(P3,add_array(P1,P2)) + [0]*k) input('Enter to see final calculation at this recursion level') print(t) return t a = [7,0,4,2]#[1,2,3,4] b = [6,7,3]#[1,5,6,2] print(multiply(a,b)) #print(add_array([1]+ [0]*2,[1,0]))
3c90d548a6c655f0b5f516d003e79dc565c3acca
DiegoHenriqueSouza/edutech-pr
/notas.py
407
3.890625
4
print("****** MÉDIA ******") primeira_media = int(input("Insira sua primeira nota do bimestre: ")) segunda_media = int(input("Insira sua segunda nota do bimestre: ")) terceira_media = int(input("Insira sua terceira nota do bimestre: ")) quarta_media = int(input("Insira sua quarta nota do bimestre: ")) print("Sua média foi de:" ,primeira_media + segunda_media + terceira_media + quarta_media/4)
90b188a80f691ab05cdc063ffeb54d5eaf3e2441
Pranshu46/Pro-106-Correlation
/Pro-106/student.py
237
3.546875
4
import plotly.express as px import csv with open ("Student Marks vs Days Present.csv") as csv_File: df = csv.DictReader(csv_File) fig = px.scatter(df,x="Roll No",y="Marks In Percentage",color="Days Present") fig.show()
1f5780d5ac883d29f275aa3f23ca8e347bb1075d
CoralieHelm/Python_Functions_Files_Dictionaries_University_of_Michigan
/11_8_Accumulating_the_Best_Key.py
1,430
4.125
4
#June 1 2020 #11.8. Accumulating the Best Key #Check your Understanding #1. Create a dictionary called d that keeps track of all the characters in the string placement and notes how many times each character was seen. Then, find the key with the lowest value in this dictionary and assign that key to min_value. placement = "Beaches are cool places to visit in spring however the Mackinaw Bridge is near. Most people visit Mackinaw later since the island is a cool place to explore." d = {} for character in placement: if character not in d: d[character] = 0 d[character] = d[character] + 1 keys =list(d.keys()) min_value = keys[0] for key in keys: if d[key] < d[min_value]: min_value = key print(min_value) #You passed: 100.0% of the tests print("******************") #5. Create a dictionary called lett_d that keeps track of all of the characters in the string product and notes how many times each character was seen. Then, find the key with the highest value in this dictionary and assign that key to max_value. product = "iphone and android phones" lett_d = {} for letter in product: if letter not in lett_d: lett_d[letter] = 0 lett_d[letter] = lett_d[letter] + 1 letter_keys = list(lett_d.keys()) max_value= letter_keys[0] for key in letter_keys: if lett_d[key] > lett_d[max_value]: max_value = key print(lett_d) print(letter) #You passed: 100.0% of the tests
9587a54e90fd68da9753c6465e5f9ecd0ed2425d
deepanshusadh/My-ML-projects
/bag of words.py
681
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from sklearn.feature_extraction.text import CountVectorizer # In[2]: cv=CountVectorizer() # In[29]: corpus=[ 'She is beautiful', 'World is so cruel', 'I am vegetarian', 'Hell I am in love' ] # In[30]: vectorized_form=cv.fit_transform(corpus).toarray() vectorized_form # In[31]: print(cv.vocabulary_) # In[32]: print(cv.inverse_transform(vectorized_form[3])) # In[34]: cv.vocabulary_["she"] # In[ ]: # this will actually clean the data using our predefined function of nlp notebook cv1=CountVectorizer(Tokenizer=nlp) #refer to function nlp notbook vc=cv1.fit_transform(corpus).toarray()
e0939ba80da9c7d508c9a5f0a04675f87606d3e8
tideburning/python_test1
/test1bai4/test1bai4.py
763
4
4
import threading # tạo một class con class SummingThread(threading.Thread): #init thực hiện trước, selt là con trỏ this trong java def __init__(self,low,high): #super gọi đến hàm parent của nó super(SummingThread, self).__init__() self.low=low self.high=high self.total=0 def run(self): for i in range(self.low,self.high): self.total+=i data = int(input('Enter your input:')) thread1 = SummingThread(0,round(data/2)+1) thread2 = SummingThread(round(data/2)+1,data) #Run the thread thread1.start() # This actually causes the thread to run thread2.start() #waits until the thread has completed thread1.join() thread2.join() print(thread1.total) print(thread2.total) result = thread1.total + thread2.total print (result)
6a7bf1a0eb601cf54e8c8db433ad6bffe8af9a6a
KANUBALAD/macgyver
/MacMaze2D.py
6,130
3.78125
4
import pygame import position as Position import perso as Perso from random import randint from labyManager import LabyManager from constantes import* """laby mean maze, as we have to know""" """declared outside of main () because used in methods""" continuePlaying = True gameEnded = False win = False pygame.init() screen = pygame.display.set_mode((cote_fenetre, cote_fenetre)) def text_objects(text, font): textSurface = font.render(text, True, WHITE) """text and color of the font""" """to declare his location after""" return textSurface, textSurface.get_rect() def message_display(text): """font = pygame.font.Font('freesansbold.ttf', 15)""" pygame.font.init() """initialize (inside the methode) the font module""" font = pygame.font.Font('fonts/3270Medium.ttf', 15) """creation of a fonte""" TextSurf, TextRect = text_objects(text, font) """TextSurf, TextRect = font.render(text, True, WHITE),textSurface.get_rect()""" TextRect.center = ((cote_fenetre / 2),(cote_fenetre / 2)) screen.blit(TextSurf, TextRect) pygame.display.update() def confirm_dialog(text): screen.fill(BLACK) message_display(text) """displayed message, text as parameter""" pygame.display.update() """update of the whole screen as there is no parameter""" isRunning = True """infinite loop : only yes to quit her""" answer = False while isRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: isRunning = False elif event.type == pygame.KEYDOWN: isRunning = False """Answer determine the start() or quit() in handle_game_end()""" if event.key == pygame.K_y: answer = True """1 funct° (inspite of 2 to manage 2 no) : yes as pivot value.""" return answer def wait_for_key_pressed(): """infinite loop : only to quit her => quit or any keydown""" isRunning = True while isRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: isRunning = False elif event.type == pygame.KEYDOWN: isRunning = False def quit_game(): screen.fill(BLACK) message_display("Thank you for playing Mac Maze. See you soon!") wait_for_key_pressed() screen.fill(BLACK) message_display("Press any key to quit.") wait_for_key_pressed() pygame.quit() def game_loop(): """global : variables will also be understood outside the method""" global win global continuePlaying global gameEnded continuePlaying = True win = False """instance "lm" has attributes and instance methods conferred by the class""" lm = LabyManager() lm.initializeGame() perso = Perso.Perso(lm.initPosition) """.txt changed by pictures, each location of 1*30 size (15 locati° : sprites)""" lm.displayLaby(screen) """Exit loop if perso on exitPos °, alive and with desire to play""" while not (perso.pos == lm.exitPosition) and perso.alive and continuePlaying: """Reloading after moving .txt dc images on locations""" lm.displayLaby(screen) """Title and counter (updated via the movement loop) of recovered objects""" pygame.display.set_caption("MacGyver have: " + lm.nbInGameObjets() + "/3 objects. Use arrows to move") """Update (re-loading images) in the pygame display""" pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: """Quit Generates Loop Output with Will to Quit""" continuePlaying = False break elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT : """classic movement command of perso, instance lm passed in parameter""" perso.goLeft(lm) """displacement method as a consequence of the movement""" elif event.key == pygame.K_RIGHT: perso.goRight(lm) elif event.key == pygame.K_UP: perso.goUp(lm) elif event.key == pygame.K_DOWN: perso.goDown(lm) elif event.key == pygame.K_ESCAPE: """Escape generates Loop Output with Will to Quit""" continuePlaying = False break """Values ​​returned if break""" """Otherwise returned if (exitPos ° + alive) or if (Death due to combat without objects)""" win = perso.alive #and perso.hasAllObjects() gameEnded = True def start_game(): global gameEnded gameEnded = False while not gameEnded: """directional method that also returns values ​​of win and gameEnded""" game_loop() handle_game_end() def handle_game_end(): """Have the output values ​​of the game_loop () thanks to the global""" global win global continuePlaying """if want stop i.e. quit or escape pressed in game_loop""" if not continuePlaying: confirmed = confirm_dialog("Are you sure you want to quit? (y / n)") if confirmed: quit_game() #with Yes pressed (yes as "pivot value") else: start_game() #with quit or any keydown** """Otherwise play = True, so test of win (so alive with the objects)""" else: if win: confirmed = confirm_dialog("Congratulations! You won! Play again? (y / n)") if confirmed: start_game() #with Yes pressed (yes as "pivot value") else: quit_game() #with quit or any keydown** """Otherwise, perso.alive = False i.e. lost guardian confrontation""" else: confirmed = confirm_dialog("You are dead, try again? (y / n)") if confirmed: start_game() else: quit_game() def main(): start_game() if __name__ == "__main__": main()
01b4aab7e5e8d5b43cd012f4188bdae30a4aad1a
wyaadarsh/LeetCode-Solutions
/Python3/0129-Sum-Root-to-Leaf-Numbers/soln-1.py
713
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumNumbers(self, root: TreeNode) -> int: self.ans = 0 def dfs(node, val): if node is not None: if node.left is None and node.right is None: self.ans += val * 10 + node.val else: if node.left is not None: dfs(node.left, val * 10 + node.val) if node.right is not None: dfs(node.right, val * 10 + node.val) dfs(root, 0) return self.ans
4a61d1d3a4c05cdf802d25fc5a13bbcd9eeabe6f
superstones/LearnPython
/Part1/week2/chapter10/exercise/common_words_10.10.py
680
4.1875
4
# 10.10常见单词 def count_words(file_name): try: with open(file_name, 'r', encoding='UTF-8') as f: f_read = f.read() contents = f_read.lower().split() except FileNotFoundError: pass # msg = "Sorry, the file " + file_name + " does not exist." # print(msg) else: num_words = contents.count('love') print("The file " + file_name + " has about " + str(num_words) + " words.") file_names = ['Alice’s Adventures in Wonderland.txt', 'Mary Wollstonecraft (Godwin) Shelley.txt', 'Pride and Prejudice.txt', 'The Great Gatsby.txt'] for file_name in file_names: count_words(file_name)
5baa23e3a1ce1fde6699de06aa1de7c7972d0710
atheenaantonyt9689/python_programs_part2
/fizz_buzz.py
320
3.984375
4
def fizz_buzz(number): i=1 for i in range(1,number+1): if i%3 ==0 and i%5 ==0: print("FIZZBUZZ") elif i % 3==0: print("FIZZ") elif i %5 ==0: print("BUZZ") else: print(i) number=int(input("enter the limit: ")) fizz_buzz(number)
1c62705b14090b24846a7ae9372b60e4ea611a9c
FrustratedGameDev/project2
/features/9-issue-per-milestone/IssueHandler.py
1,239
3.59375
4
# count num lines with 'action: ' and make a bucket for each 'user: {user-name}' users = {} def countUsers(): with open('../ourRepo.txt') as file: for line in file: if "action :" in line: parts = line.split(',') for part in parts: if "user :" in part: user = part.split("user : ")[1].rstrip() if user not in users: users[user] = 1 else: users[user] += 1 countUsers() sortedUsers = sorted(users, key=users.get) print("The list below identifies how much activity each user had on all issues:\n") with open('uneven-issue-handling.csv', 'w') as file: file.write('user, number of issues handled\n') for user in sortedUsers: count = str(users[user]) file.write(user + ", " + count +'\n') #Right now this tool gathers ones that don't have milestones. #This is identified as those with a new line behind it. print("\nThe person to close an issue is usually the one that fixed it.") print("The following list identifies the number of issues that a user was the last person to handle the issue:")
7822b2ae1e059df0cc10424b8421db79cfee056d
AntonioMagana/CMPE_131
/LeapYear.py
210
4.21875
4
year = float(input("What year would you like to check")) if year%4 == 0: print("Is leap year") if year%100 == 0 and year%400 == 0: print("Is leap year") else: print("Is not leap year")
72bfa708c91b17dd10b1afa07ddcc50f31c6fdf7
shokokb/personal-study
/env/opt/leetcode/0100/0118_Pascal's_Triangle.py
554
3.5
4
class Solution: def generate(self, numRows: int) -> List[List[int]]: triangle = [] for row_num in range(numRows): row = [None for _ in range(row_num + 1)] row[0] = row[-1] = 1 triangle.append(row) for row in range(numRows): l, r = 1, row - 1 while l <= r: triangle[row][l] = \ triangle[row][r] = \ triangle[row-1][l-1] + triangle[row-1][l] l += 1 r -= 1 return triangle
ea386a3776766ae2548d48297fbdb022cd1f7880
Patelbhavika199926/Patel_CISC610
/Q5.py
338
3.890625
4
import random list = [] upperLimit = 100 for i in range(1, upperLimit): list.insert (i, random.randrange(9999)) print ("Total items inserted into the list:" , len(list)) leastVal = list[0] for i in range(1, upperLimit - 1): if list[i] < leastVal: leastVal = list[i] print("Least value in the list: ", leastVal)
0ff5d8864c736903894b8b31880d003258c7178b
karstendick/advent-of-code
/2020/day2/day2.py
426
3.640625
4
valid_passwords = 0 with open('input.txt', 'r') as f: for line in f: min_max, letter_colon, password = line.split() pmin, pmax = [int(c) for c in min_max.split('-')] letter = letter_colon[0:1] num_letters = password.count(letter) if pmin <= num_letters and num_letters <= pmax: valid_passwords += 1 # print(f"{pmin} | {pmax} | {letter} | {password}") print(valid_passwords)
647f5d830aff93e5a12790036374d183ab5105a2
emcog/cc_wk5__project_week
/tests/test_address.py
397
3.65625
4
import unittest from models.address import Address class TestAddressClass(unittest.TestCase): def setUp(self): self.address_1 = Address('Knowledge Cottage', 'The Orchard', 'Crail', 'HE3 H11') self.address_2 = Address('Minotaur View', 'The Labyrinth', 'Crete-on-Fife', 'FL1 H07') def test_address_has_town(self): self.assertEqual('Crail', self.address_1.town_city)
c5a1e84f48bcde06f83f9d8112431b310f73e416
satyanshpandey/python-basic
/Factorial.py
245
4.21875
4
def factorial(n): if n==1: return n else: return n*factorial(n-1) num=int(input('enter number:')) print('the factorial is:',factorial(num)) # output:=> # enter number:5 # the factorial is: 120
2f2ef4870d764fd90ffcc5c8cdac7604feeee98e
chaifae/add-videos-to-your-page
/Python_practice/mindstorms.py
929
4.03125
4
import turtle def draw_square(a_turtle): for turn in range(1, 5): a_turtle.forward(100) a_turtle.right(90) def draw_triangle(a_turtle): for turn in range(1, 4): a_turtle.forward(100) a_turtle.right(120) def draw_stuff(): window = turtle.Screen() window.bgcolor("light blue") window.title("Stephanie's Pet Turtle") #turtle for brad draws a square brad = turtle.Turtle() brad.shape("turtle") brad.color("dark green", "green") brad.speed(1) draw_square(brad) #turtle for angie draws a circle angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) #turtle for sara draws a triangle sara = turtle.Turtle() sara.shape("turtle") sara.color("brown", "red") sara.right(100) draw_triangle(sara) window.exitonclick() draw_stuff()
890f7ff52f9955dda74d40f771d227ddd9280c87
raffmiceli/Project_Euler
/Problem 35.py
1,224
3.515625
4
from math import * from pyprimes import * def isPrime(n): x = 2 if n < 2: return False else: while x <= sqrt(n): if n%x == 0: return False x += 1 return True s = [2] ps = list(primes_below(1000000)) for p in ps: if any([not int(l)%2 for l in str(p)]): continue if p in s: continue temp = set([p]) sp = str(p) l = len(sp) for m in range(l-1): sp = sp[-1]+sp[:-1] temp.add(int(sp)) if int(sp) not in ps: break else: s = s+list(temp) print sorted(s), len(s) ##s = [2,3,5,7] ##for n in range(11,1000000,2): ## if any([not int(l)%2 for l in str(n)]): continue ## if is_prime(n): ## sn = str(n) ## l = len(sn) ## for m in range(l-1): ## sn = sn[-1]+sn[:-1] ## if not is_prime(int(sn)): break ## else: s.append(n) ##print s, len(s) ##t = 0 ##for n in range(1,1000000): ## if isPrime(n): ## sn = str(n) ## l = len(sn) ## for m in range(l-1): ## sn = sn[-1]+sn[:-1] ## if not isPrime(int(sn)): break ## else: ## t += 1 ## print n, t ##print t
d6cf4dbb6f731ca020608021cddb9245ef34b563
wojtekidd/Python101
/squares_function.py
160
3.796875
4
def squares(): """""" x = 1 result = "" while x<11: result = result + str(x**2) + " " x += 1 return result print(squares())
df0dac4d17e48dc05e4888c3c92c00fb9f69d8de
felipesantanadev/python
/Lesson 01/01_arithmetic_operators.py
598
4.25
4
# Arithmetic Operators # + (addition) # - (subtraction) # / (division) # * (multiplication) # % (mod -> rest of division) # ** (exponentiation) # // (divides two numbers and rounds down the result to the nearest integer) print(2 + 2) print(7 - 2) print(10 / 2) print(2 * 3) print(17 % 4) print(2 ** 2) print(7 // 2) # Python also follow the mathematics rules about the oder of operations # This will first sum the numbers and multiply after print((2 + 4 + 6) * 2) # This will first multiply 6*2 and sum the result of the multiplication with 2 + 4 print(2 + 4 + 6 * 2)
914c9a4d8bf78d45333bc757c6029e323c8b84eb
flaxdev/N-g.datamining
/src/iterators.py
2,195
3.671875
4
from src.geometry import Position class PropertyIterator(): """ Class PropertyIterator Linearly iterates over properties from start to end in n steps """ def __init__(self, iterators): self.iterators = iterators self.steps = sum(map(lambda x: x.steps, iterators)) self._currentIterator = self.iterators.pop(0) def __iter__(self): return self def __next__(self): if not self._currentIterator.active: if len(self.iterators) == 0: raise StopIteration self._currentIterator = self.iterators.pop(0) return self._currentIterator.__next__() class LinearPropertyIterator(): """ class LinearPositionIterator Returns an iterator that interpolates between start / end to simulate a moving anomaly """ def __init__(self, steps, props): self.steps = steps self.properties = dict(props) # Keep track of current step self._step = -1 def reversed(self): return LinearPropertyIterator(self.steps, {x: tuple(reversed(y)) for (x, y) in self.properties.items()}) @property def fields(self): return [*self.properties] def __getattr__(self, name): if name not in self.properties: raise KeyError("The property '%s' is not available in the iterator." % name) # Unpack the start and end of the linear interpolation try: (start, end) = self.properties.get(name) # Constant value just return the number except TypeError: return self.properties.get(name) frac = self._step / (self.steps - 1) # Explicitly handle Position classes if isinstance(start, Position) and isinstance(end, Position): x = start.x + frac * (end.x - start.x) y = start.y + frac * (end.y - start.y) z = start.z + frac * (end.z - start.z) return Position(x, y, z) return start + frac * (end - start) def __iter__(self): return self def __next__(self): if not self.active: raise StopIteration self._step += 1 return self @property def active(self): return self._step < (self.steps - 1) def __str__(self): return "\n".join(["<%s: %s>" % (x, self.__getattr__(x).__str__()) for x in self.properties.keys()])
a46f929c9bc0c3d15d212d0bec88f08a6331ad29
sadatrafsanjani/MIT-6.0001
/Lec02/for.py
123
3.828125
4
sum = 0 for i in range(5, 11): sum += i print(sum) print("\n") for i in range(1, 10, 3): print(i)
6679d9192b6d528baa62f5f1c307cb199502ab06
sukhvir786/Python-Day-6-Lists
/list19.py
278
4.3125
4
""" 10. Reverse """ L = ['red', 'green', 'blue'] L.reverse() print(L) # Prints ['blue', 'green', 'red'] L = [1, 2, 3, 4, 5] L.reverse() print(L) # Prints [5, 4, 3, 2, 1] L = ['red', 'green', 'blue'] for x in reversed(L): print(x) # blue # green # red
9337aace809834ea80933ce2a056939d81f7d098
liumg123/AlgorithmByPython
/43_左旋转字符串.py
597
3.875
4
# -*- coding:utf-8 -*- """ 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它! """ class Solution: def LeftRotateString(self, s, n): # write code here res='' if n>len(s) or n<0: return s return ''.join(s[n:])+''.join(s[:n])
e9849c529857c2c3c001c1eca2fd56a083d032f0
cloxnu/AlgorithmLandingPlan
/CodingInterviews/33. 二叉搜索树的后序遍历序列.py
942
3.8125
4
# 遇到后序遍历,先想到把后序反过来,就变成了 根-右-左 # [1, 3, 2, 6, 5] # [1, 6, 3, 2, 5] # 递归解法 def verifyPostorder(postorder: list) -> bool: def recur(left, right): if left >= right - 1: return True for i in range(left, right): if postorder[i] > postorder[right]: for j in range(i, right): if postorder[j] < postorder[right]: return False return recur(left, i-1) and recur(i, right-1) return recur(left, right - 1) return recur(0, len(postorder)-1) # 单调栈解法 def verifyPostorder2(postorder: list) -> bool: stack, root = [], None for i in reversed(postorder): if root is not None and i > root: return False while stack and stack[-1] > i: root = stack.pop() stack.append(i) return True print(verifyPostorder2([]))
a9e847b2dcaa769c2a764d6c107e5f1913e9322e
chemplife/Python
/python_core/json_serialization.py
6,827
3.59375
4
''' JSON: JavaScript Object Notation. Default: Serialization/Deserialization will not execute code so, it is consider safe compared to pickling/unpickling Datatype supported: "string" -> Double Quotes Delimiter And Unicode characters only. Numbers -> 100, 3.14, 3.14e-05, 3.14E+5 -> all are considered floats. No distinctions Boolean -> true, false -> No double quotes "true". That would be considered string Array -> [1,3.14, "python"] -> Ordered. Like List. Dictionary -> {"a":1, "b": "abc"} -> Keys = Strings, values = Any supported Datatype; UNORDERED Empty Value -> null *** Non-Standard Datatypes that are supported integer -> 100 floats -> 100.0, 3.14, NaN, Infinity, -Infinity JSON Dictionaires: { "Pascal" : [ { "Name" : "Pascal Made Simple", "price" : 700 }, { "Name" : "Guide to Pascal", "price" : 400 } ], "Scala" : [ { "Name" : "Scala for the Impatient", "price" : 1000 }, { "Name" : "Scala in Depth", "price" : 1300 } ] } JSON Dictionaries: Strings Python Dictionaries: Objects import json Methods: dump, dumps, load, loads Dict ----(Serialize using Dump/Dumps)----> File String ----(DeSerialize using Load/Loads)----> Dict Problems: 1. Json Keys must be Strings -> Python Keys needs to be hashable. (Can be of type other than strings) 2. Json Value Datatypes are limited -> Python values can be of any datatype. 3. Even if we Serialize these different datatypes using custom classes, how to deserialize them For the mentioned problems, we need to have CUSTOM Serializers/Deserializers ''' import json d1 = {'a': 100, 'b': 200} d1_json = json.dumps(d1) print('Type of d1: ', type(d1)) print('D1: ', d1) print('Type of d1_json: ', type(d1_json)) print('D1_json: ', d1_json) #d1_json is string and keys are double quotes. #Like pretty_print pprint() for dicts, we can do indent for json print('pretty_print json:\n',json.dumps(d1,indent=2)) d2 = json.loads(d1_json) print('Type of d2: ', type(d2)) print('D2: ', d2) print('Is D1 == D2: ', d1==d2) print('Is D1 same object as D2: ', d1 is d2) print('\n\n------------------ Integer Keys ------------------') d1 = {1: 100, 2: 200} d1_json = json.dumps(d1) print('D1: ', d1) print('D1_json: ', d1_json) #d1_json is numerical keys converted to strings in double quotes. d2 = json.loads(d1_json) print('D2: ', d2) print('Is D1 == D2: ', d1==d2) # Because the Keys of D2 are Strings and D1 Keys are numbers. print('\n\n------------------ Value Datatypes ------------------') d_json = {'a':(1,2,3)} ser = json.dumps(d_json) deser = json.loads(ser) print('Initial dict: ', d_json) print('Deserialized dict: ', deser) print('Is serialized dict and DeSerialized output equal: ', d_json==deser) # Tuple got converted to List. JSON doesn't know TUPLE print('\n\n------------------ Bad JSON ------------------') from decimal import Decimal d_json = '''{"a":(1,2,3)}''' print('Initial dict: ', d_json) try: deser = json.loads(d_json) except Exception as exc: print(f'Got Exception: {exc}') d_ser = {'a': 10, 'b': Decimal(10.234)} print('\nInitial dict: ', d_ser) try: ser = json.dumps(d_ser) except Exception as exc: print(f'Got Exception: {exc}') print('\n\n------------------ Custom Serialization ------------------') class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person(name={self.name}, age={self.age})' p = Person('John', 82) print('Person Object: ', p) try: print('\nJSON serialized', json.dumps({'John':p})) except Exception as exc: print(f'Got Exception: {exc}') # To make Person class Object serializable, we need to implement toJSON() method class Person_2: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person(name={self.name}, age={self.age})' #Python will call this function to get a serializable object. def toJSON(self): # or use # return vars(self) return dict(name=self.name, age=self.age) p_2 = Person_2('John', 82) print('\nPerson_2 Object: ', p_2) try: print('JSON serialized:\n', json.dumps({'John':p_2.toJSON()}, indent=2)) except Exception as exc: print(f'Got Exception: {exc}') ''' dumps(default=func) When JSON Encoder encounters a type that it doesn't know how to encode,it looks for a -> CALLABLE function in its DEFAULT argument -> CALLABLE function takes 1 argument. ''' from datetime import datetime current = datetime.utcnow() print('\n\nDatetime Object: ', current) try: print('JSON serialized:\n', json.dumps(current)) except Exception as exc: print('Got Exception: ', exc) #Custom Format Function def format_iso(dt): return dt.strftime('%Y-%m-%dT%H:%M:%S') #or #current.isoformat() log_record = {'Time1': datetime.utcnow().isoformat(), 'message': "This is test", 'Time2': format_iso(current) } try: print('JSON serialized:\n', json.dumps(log_record, indent=2)) except Exception as exc: print('Got Exception: ', exc) log_record = {'Time1': datetime.utcnow(), 'message': "This is test", 'Time2': current } try: print('JSON serialized with Default:\n', json.dumps(log_record, indent=2, default=format_iso)) except Exception as exc: print('Got Exception: ', exc) # Custom Formatter to be used as Default def json_custom_formatter(arg): if isinstance(arg, datetime): return arg.isoformat() elif isinstance(arg, set) or isinstance(arg, tuple): return list(arg) elif isinstance(arg, Decimal): return float(arg) elif isinstance(arg, Person_2): return arg.toJSON() log_record_2 = {'Time': datetime.utcnow(), 'message': "This is test", 'types': {'a', 1, 1.34, Decimal(1.12)}, 'tval': (1,2,3, Decimal(3.456)) } try: print('\n\nJSON serialized with custom formatter:\n', json.dumps(log_record_2, indent=2, default=json_custom_formatter)) except Exception as exc: print('Got Exception: ', exc) from functools import singledispatch from fractions import Fraction # MAKE the Custom Formatter MORE GENERIC # Custom Formatter to be used as Default # We can use singledispatch here to register more datatype support as well. @singledispatch def json_custom_formatter(arg): if isinstance(arg, datetime): return arg.isoformat() elif isinstance(arg, set) or isinstance(arg, tuple): return list(arg) elif isinstance(arg, Decimal): return float(arg) else: try: return arg.toJSON() except AttributeError: try: return vars(arg) except TypeError: return str(arg) @json_custom_formatter.register(Fraction) def _(arg): return f'Fraction({str(arg)})' #Now, Fraction is also covered in the json_custom_formatter() function.
0e8b3bf73698f6edd1c5a6b9b8994dc820bdcf80
lic34/leetCoding
/leetcode/longest_substring.py
857
3.625
4
'''https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/''' class Solution: def lengthOfLongestSubstring(self, s: str, retrun=None) -> int: length_of_sub_str = 0 if s is None: return length_of_sub_str sub_str = str() current_length = 0 for char in s: if char not in sub_str: current_length += 1 sub_str += char else: length_of_sub_str =max(length_of_sub_str, len(sub_str)) char_index = sub_str.index(char) sub_str_right = sub_str[char_index+1:] sub_str = sub_str_right + char current_length = len(sub_str) length_of_sub_str = max(current_length,length_of_sub_str) return length_of_sub_str
9dddb5bc9f8f7a52e7a1db0432b515bb7464e965
Almenon/couchers
/app/backend/src/couchers/utils.py
1,152
3.515625
4
from datetime import datetime, timedelta, timezone import pytz from google.protobuf.timestamp_pb2 import Timestamp utc = pytz.UTC def Timestamp_from_datetime(dt: datetime): pb_ts = Timestamp() pb_ts.FromDatetime(dt) return pb_ts def to_aware_datetime(ts: Timestamp): """ Turns a protobuf Timestamp object into a timezone-aware datetime """ return utc.localize(ts.ToDatetime()) def now(): return datetime.now(utc) def largest_current_date(): """ Get the largest date that's possible now. That is, get the largest date that is in effect in some part of the world now, somewhere presumably very far east. """ # This is not the right way to do it, timezones can change # at the time of writing, Samoa observes UTC+14 in Summer return datetime.now(timezone(timedelta(hours=14))).strftime("%Y-%m-%d") def least_current_date(): """ Same as above for earliest date (west) """ # This is not the right way to do it, timezones can change # at the time of writing, Baker Island observes UTC-12 return datetime.now(timezone(timedelta(hours=-12))).strftime("%Y-%m-%d")
27fda4cf93689c8a5e416b95c3cd32d92bd3e95b
soo-youngJun/pyworks
/run_turtle/figure2.py
341
3.96875
4
# 도형 그리기 (반복문) import turtle as t t.shape('turtle') # 사각형 그리기 n = 8 for i in range(n): t.forward(100) t.right(360 / n) # 삼각형 그리기 t.color('red') t.pensize(2) for i in range(0, 3): t.forward(100) t.left(120) # 원 그리기 t.color('blue') t.pensize(3) t.circle(50) t.mainloop()
4c4d433057c998587c6321895a70a8d8b8b2ade8
malluri/python
/30.py
503
3.71875
4
""" 30. Take actuual string, soucrce string, destination string. replce first nth occurances of soucestring with destination string of actual string """ str=raw_input("string") source=raw_input("sourcestring") dest=raw_input("destination") n=input("occurence") count=0 s=" " l=len(str)-len(source)+1 for i in range(0,l): #print(str[i:(len(s)+i)]) if(str[i:(len(source)+i)]==source): count+=1 if(count==n): str=str[:i]+dest+str[i+len(dest):] #print(count) print(str)
98f55453c6665bb001fe9c654f3f3e93659b67cc
MandoMirsh/LCalc-Loan_Calculator
/Topics/Elif statement/Calculator/main.py
612
4.0625
4
DIVISION = "/ div mod" first_num = float(input()) second_num = float(input()) operation = input() if operation in DIVISION: if second_num == 0: print("Division by 0!") elif operation == '/': print(first_num / second_num) elif operation == 'mod': print(first_num % second_num) else: print(first_num // second_num) else: if operation == '+': print(first_num + second_num) elif operation == '-': print(first_num - second_num) elif operation == '*': print(first_num * second_num) else: print(pow(first_num, second_num))
929426d0d621477072c9424248e93a65a979eb4a
davcodee/conjuntos
/Conjuntos.py
2,325
4
4
option = int(input('Seleccciona una opción: ')) conjunto1 = [1,2,4,5,6] conjunto2 = [1,2,4,5,6] def menu(): if (option == 1 ): print('Elementos del cojunto 1') for i in range(len(conjunto1)): print(i) print('Elementos del cojunto 2') for i in range(len(conjunto2)): print(i) elif (option == 2): # agregamos los elementos al primer cojunto print('Ingresa los elementos del cojunto1: ') print('Si deseas ya no agregar elementos pon 0') bandera = True while(bandera): entrada = int( input('')) if entrada == 0: bandera = False else: conjunto1.append(entrada) # agregamos los elemetos al segundo conjunto print('Ingresa los elementos del cojunto2: ') print('Si deseas ya no agregar elementos pon 0') bandera = True while(bandera): entrada = int( input('')) if entrada == 0: bandera = False else: conjunto1.append(entrada) elif (option == 3): print('Selecciona una opcion:') print('1. intersección') print('2. Union') print('3. Diferencia') print('4. salir') # Conjunto auxiliar donde almacenaremos nuestros datos aux = [] bandera = True while(bandera): entrada = int(input()) if (entrada == 1): #relalizamos la intersección for i in range(len(conjunto1)): if i in conjunto2: aux.append(i) bandera = False elif(entrada == 2): # Operación union #agregamos a nuestro cojunto auxiliar nuestro primeros elementos for i in range(conjunto1): if i not in aux: aux.append(i) bandera = False # Agregamos los elementos de nuestro segundo cojunto for i in range(conjunto2): if i not in aux: aux.append(i) bandera = False elif(entrada == 3): # realizamos la diferencia para A/B for i in range(len(conjunto1)): if i not in conjunto2: aux.append(i) bandera = False elif(entrada == 4): bandera = False """ Imprimimos los elementos de nuestro arreglo auxiliar """ for i in range(len(aux)): print(i) menu()
506cf0ea8f1d6b34b8fa79db5c93f18705530344
gorsheninii/zed_a._shaw
/Exercise5.py
551
3.921875
4
my_name = "Gorshenin Ivan" my_age = 34 my_height = 173 my_weight = 72.9 my_eyes = "grayish blue" my_teeth = "yellowish" my_hair = "fair" print(f"Let's speak about a human named {my_name}.") print(f"His height is {my_height} sm.") print(f"His weight is {my_weight} kg.") print("Actually this isn't much") print(f"He has got {my_eyes} eyes and {my_hair} hair.") print(f"His teeth are always {my_teeth}, because he likes sweets very much") #bullshit total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height} and {my_weight}, it is {total}.")
866d4a5bf7d1c955ee9fd18467de33ef28435622
clstrni/pythonBrasil
/EstruturaDeDecisao/26.py
231
3.78125
4
liters = float(raw_input('How many liters?\n')) fuel = raw_input('Type of fuel: (A-ethanol, G-gasoline)\n').upper() if (fuel == 'A'): tot = liters * 1.9 elif (fuel == 'G'): tot = liters * 2.5 print "Amount to pay R$%f" % (tot)
4bdf6b0c0861d26fab60b80b32fe60d3c97e1f5e
ShiaoZhuang/Homework-2
/main.py
1,129
4.25
4
# Author: Shiao Zhuang sqz5328@psu.edu def getGradePoint(Grade): if Grade == 'A': Grade = 4.0 elif Grade == 'A-': Grade = 3.67 elif Grade == 'B+': Grade = 3.33 elif Grade == 'B': Grade = 3.0 elif Grade == 'B-': Grade = 2.67 elif Grade == 'C+': Grade = 2.33 elif Grade == 'C': Grade = 2.0 elif Grade == 'D': Grade = 1.0 else : Grade = 0.0 return Grade def run(): Grade = input("Enter your course 1 letter grade: ") C1 = float(input("Enter your course 1 credit: ")) print(f"Grade point for course 1 is: {getGradePoint(Grade)}") P1 = float(getGradePoint(Grade)) Grade = input("Enter your course 2 letter grade: ") C2 = float(input("Enter your course 2 credit: ")) print(f"Grade point for course 2 is: {getGradePoint(Grade)}") P2 = float(getGradePoint(Grade)) Grade = input("Enter your course 3 letter grade: ") C3 = float(input("Enter your course 3 credit: ")) print(f"Grade point for course 3 is: {getGradePoint(Grade)}") P3 = float(getGradePoint(Grade)) print(f"Your GPA is: {(C1*P1+C2*P2+C3*P3)/(C1+C2+C3)}") if __name__ == "__main__": run()
a40a436ba2856c2e884069f040daed538844b025
ZabretRok/HW7_Guess_the_secret_number
/secret_game.py
1,435
3.84375
4
import datetime import json import random player = input("Hi, what is your name? ") secret = random.randint(1, 30) attempts = 0 with open("score_list.txt", "r") as score_file: score_list = json.loads(score_file.read()) print("Top scores: " + str(score_list)) top_3 = sorted(score_list, key=lambda x: x['attempts'])[:3] for score_dict in top_3: print("Player: " + score_dict.get("player_name") + ", attempts: " + str(score_dict.get("attempts")) + ", date: " + score_dict.get("date") + ", number was " + str(score_dict.get("secret_number")) + ". These were the wrong guesses: " + str(score_dict.get("wrong_guesses"))) wrong_guesses = [] while True: guess = int(input("Guess the secret number (between 1 and 30): ")) attempts += 1 if guess == secret: score_list.append({"player_name": player, "attempts": attempts, "date": str(datetime.datetime.now()), "secret_number": secret, "wrong_guesses": wrong_guesses}) with open("score_list.txt", "w") as score_file: score_file.write(json.dumps(score_list)) print("You've guessed it - congratulations! It's number " + str(secret)) print("Attempts needed: " + str(attempts)) break elif guess > secret: print("Your guess is not correct... try something smaller") elif guess < secret: print("Your guess is not correct... try something bigger") wrong_guesses.append(guess)
3878d3ce3d9008fed5abcfb77baf709de119e958
clonetwin26/TwitterPoemBot
/src/wordChecker.py
883
3.75
4
#class to hold all functionality between words import urllib2 class WordChecker: #returns true if the two words match, false otherwise #this is accomplished by making a request to http://stevehanov.ca/cgi-bin/poet.cgi?WORD rhymeRequest = "http://stevehanov.ca/cgi-bin/poet.cgi?" def isRhyme(self, word1, word2): #make a request for word1 req1 = urllib2.Request(self.rhymeRequest + word1) response1 = urllib2.urlopen(req1) page1 = response1.read() lines1 = page1.splitlines() #make a request for word 2 req2 = urllib2.Request(self.rhymeRequest + word2) response2 = urllib2.urlopen(req2) page2 = response2.read() lines2 = page2.splitlines() #if the two words have a word incommon they must rhyme if(lines1[1] == lines2[1]): return True return False
6e2111e9e2bcc729139fab25360d626328b113c1
bshruti7/algorithms
/selectionSort.py
838
4
4
# set the first element as minimum element # find real minimum element # swap with minimum element # proceed with setting second element as new minimum def selection_sort(arr): min_elem_index = 0 while min_elem_index < len(arr)-1: found_min_elem_index = None min_elem = arr[min_elem_index] start = min_elem_index + 1 for i in range(start, len(arr)): if arr[i] < min_elem: min_elem = arr[i] found_min_elem_index = i if found_min_elem_index: arr[found_min_elem_index], arr[min_elem_index] = arr[min_elem_index], arr[found_min_elem_index] min_elem_index += 1 return arr input_array = [3, 44, 38, 5, 47, 37, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48] print(f'input array={input_array}') print(selection_sort(input_array))
5ee4734d8d006dd91a13db4332513b7f9f869b73
JoeyDing/PythonWebsite
/TriviaMVA/LoopsModule/LoopsModule.py
2,202
4.375
4
import turtle """ turtle.color('green') turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) """ """ turtle.color('green') for step in range(4): turtle.forward(100) #turtle.right(90) #not indented, not a part of the loop turtle.color('red') #turtle.forward(300) #turtle.right(500) """ """ # draw a "tian" in chiense turtle.color('green') for step in range(4): turtle.forward(100) turtle.right(90) for moresteps in range(4): turtle.forward(50) turtle.right(90) turtle.forward(200) # draw 五方 turtle.color('red') for step in range(5): turtle.forward(100) turtle.right(360/5) for moresteps in range(5): turtle.forward(50) turtle.right(360/5) turtle.left(90) turtle.forward(200) turtle.color('black') for step in range(4): turtle.forward(10) turtle.right(360/4) for moresteps in range(4): turtle.forward(50) turtle.right(360/4) #draw triangle turtle.left(90) turtle.forward(200) turtle.color('purple') for step in range(4): turtle.forward(100) turtle.right(360/3) """ """ #draw custom shape nbrsides = 20 turtle.color('green') for steps in range(nbrsides): turtle.forward(50) turtle.right(360/nbrsides) for moresteps in range(nbrsides): turtle.forward(30) turtle.right(360/nbrsides) """ #print 0,1,2 for steps in range(3): print(steps) #print 1,2,3 , never reach the higher number for steps in range(1,4): print(steps) #print 1,3,5,7,9 ,third parameter skip by for steps in range(1,10,2): print(steps) # foreach loop for steps in [1,2,3]: print(steps) # foreach loop for color in ['red','black','green','blue']: turtle.color(color) turtle.forward(100) turtle.right(90) # while loop : do sth while a condition is true. #this is where while loop shines, as long as they keep getting this answer we will stayhere until they get this right answer = '0' while answer != '4': #since input function will return string, so initilize the anser a string '0'. noy s number answer = input('What is 2+2 ? ') print('Yes! 2+2 = 4')
f01c4ed90f57f0ce0eb89f8b99f7789e58c53246
pvperez1/file-management-with-python
/create_file_listings.py
994
3.71875
4
#import necessary libraries from datetime import datetime import os import pathlib #this function will be used later to make .st_mtime #a more readable date format for humans def convert_date(timestamp): d = datetime.utcfromtimestamp(timestamp) formatted_date = d.strftime('%d-%b-%Y') return formatted_date #Enter '.' if you want to create listings in the current Directory #Otherwise, enter 'directory_name/subdirectory_name' basepath = input("Enter Directory:") cur_directory = pathlib.Path(basepath) #Creates a CSV file named listings.csv filename = "listings.csv" fhandler = open(filename,'w') fhandler.write("Filename,Last Modified,File Size (bytes)\n") #loop through the files in the specified directory dir_entries = os.scandir(cur_directory) for entry in dir_entries: if entry.is_file(): info = entry.stat() fhandler.write(entry.name+","+str(convert_date(info.st_mtime))+","+str(info.st_size)+"\n") #save and close the file listing fhandler.close()
57b2ac2d6ec0bc8f8722a7e3ffe7db9c9101a175
here0009/LeetCode
/Python/SelfDividingNumbers.py
1,347
4.21875
4
""" A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] Note: The boundaries of each input argument are 1 <= left <= right <= 10000. """ class Solution: def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ ans = [] for num in range(left, right+1): if self.selflDividNum(num): ans.append(num) return ans def selflDividNum(self, num): """ return true if num is self dividable """ num_original = num while (num): remainder = num % 10 if not remainder or num_original%remainder != 0: #remainder == 0 or num_original can not divided by reminder return False num = num // 10 return True s = Solution() left = 1 right = 22 print(s.selfDividingNumbers(left, right))
d160922e4bf0f212b76c094edab2d317697b6616
djphan/Prog-Problems
/Advent-Code/2017/spiralnum.py
3,096
3.609375
4
from itertools import cycle test1 = 1 test2 = 12 test3 = 23 test4 = 1024 inputNum = 277678 # Helper Functions to Make a Grid for Number Spiral def moveRight(x, y): return x+1, y def moveDown(x, y): return x, y-1 def moveLeft(x, y): return x-1, y def moveUp(x, y): return x, y+1 moves = [moveRight, moveDown, moveLeft, moveUp] def generateGrid(endPoint): _moves = cycle(moves) n = 1 pos = 0,0 times_to_move = 1 yield n,pos while True: for _ in range(2): move = next(_moves) for _ in range(times_to_move): if n >= endPoint: return pos = move(*pos) n+=1 yield n,pos times_to_move+=1 # print list(generateGrid(277678)) def generateSumGrid(endPoint): # grid is [x_coord, y_coord] : [grid_value, sum_value] grid = {(0,0) : [1,1]} _moves = cycle(moves) pos = 0,0 times_to_move = 1 n = 1 # This is gross please don't do this next time lololo breakFlag = 0 while True: if (breakFlag): break for _ in range(2): if (breakFlag): break move = next(_moves) for _ in range(times_to_move): if (breakFlag): break if n >= endPoint: return # Summation includes previous value + other adjacent values summedValue = 0 pos = move(*pos) n+=1 # Up if ((pos[0], pos[1]+1) in grid): summedValue += grid[(pos[0], pos[1]+1)][1] # Right if ((pos[0]+1, pos[1]) in grid): summedValue += grid[(pos[0]+1, pos[1])][1] # Down if ((pos[0], pos[1]-1) in grid): summedValue += grid[(pos[0], pos[1]-1)][1] # Left if ((pos[0]-1, pos[1]) in grid): summedValue += grid[(pos[0]-1, pos[1])][1] # Top Left if ((pos[0]-1, pos[1]+1) in grid): summedValue += grid[(pos[0]-1, pos[1]+1)][1] # Top Right if ((pos[0]+1, pos[1]+1) in grid): summedValue += grid[(pos[0]+1, pos[1]+1)][1] # Bottom Right if ((pos[0]+1, pos[1]-1) in grid): summedValue += grid[(pos[0]+1, pos[1]-1)][1] # Bottom Left if ((pos[0]-1, pos[1]-1) in grid): summedValue += grid[(pos[0]-1, pos[1]-1)][1] if summedValue > endPoint: print "THIS IS IT" print summedValue breakFlag = 1 break grid.update({pos : [n, summedValue]}) print grid times_to_move+=1 print grid return grid print generateSumGrid(277678)
ac8cab96033864051705d021370a3ada16f3efc2
Ratatou2/Algorithm_Interview
/10-2. 배열 파티션1.py
1,331
3.5625
4
# 해당 코드는 박상길 저자의 '파이썬 알고리즘 인터뷰'를 공부하며 적은 내용입니다 # 근데 이렇게 풀다보니 사실 리스트의 짝수번째에 있는 놈들만 더해도 될 것 같다(0부터 시작이니까) # 왜냐면 정렬된 상태에선 항상 짝수번째에 작은 값이 위치하기 때문 def arrayPartition(target_list:list): sum = 0 target_list.sort() for i in range(0, len(target_list)): if i % 2 == 0: sum += target_list[i] return sum t_list = [1,4,3,2] print(arrayPartition(t_list)) ''' - 위 코드가 내가 짠 코드인데 수정해줄 곳이 몇군데 있다 - 일단 내가 준 배열은 정렬되어 있지만, 랜덤 인풋을 받을 경우 정렬되어있지 않을 확률이 더 높기에 sort가 필요하다는 점 - 둘째로 enumerate를 써도 된다는 점 <enumerate> - 리스트가 있는 경우 순서와 리스트의 값을 전달하는 기능을 가짐 - enumerate : 열거하다 - 보통 for문과 자주 씀 - 다음 코드를 테스트해보면 얼추 어떤 기능인지 알수 있음 nums = [1,2,3,4,5,6,7] for i, n in enumerate(nums): print(i) print(n) - n을 따로 주지 않으면, i하나에 인덱스와 값 모두가 들어간다 '''
149b07f8eaea999a5ac4b9451dca3d1e5a2ae994
lxngoddess5321/python3crawler
/数据存储/JSON存储/CSV存储.py
1,168
3.796875
4
import csv # 引入csv库 with open('data.csv', 'w') as csvfile: # 列表的写入方式 # 初始化写入对象,传入该键柄 # 利用delimiter 可以修改列与列之间的分隔符 writer = csv.writer(csvfile, delimiter='*') writer.writerow(['id', 'name', 'age']) writer.writerow(['10001', 'mike', '18']) writer.writerows(['10001', 'mike', '18']) # writer.writerows([['10001', 'mike', '18'],['10001', 'mike', '18'],['10001', 'mike', '18']]) with open('data2.csv', 'w', encoding='utf8') as csvfile: # 将字典保存在csv文件中 # 先定义头部字段 fieldnames = ['id', 'name', 'age'] # 利用DicWriter 初始化一个字典写入对象 writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # 先写入头部信息 writer.writeheader() writer.writerow({'id': "10001", 'name': '杨超越', 'age': "alee"}) # 读取 with open('data2.csv', 'r', encoding='utf8') as csvfile: reader = csv.reader(csvfile) print(type(reader)) print(reader) for row in reader: print(type(row)) # <class 'list'> print(row) # ['10001', '杨超越', 'alee']
db81e65e39c816cb933d0ded6909835ce0e42b3f
jumbokh/pyclass
/code/jPB371/ch11ok/define_class.py
456
3.859375
4
class Person: #定義方法一:取得姓名和年齡 def setData(self, name, age): self.name = name self.age = age #定義方法二:輸出姓名和年齡 def showData(self): print('姓名:{0:6s}, 年齡:{1:4s}'.format( self.name, self.age)) # 產生物件 boy1=Person()#物件1 boy1.setData('John', '16') boy1.showData() #呼叫方法 boy2=Person()#物件2 boy2.setData('Andy', '14') boy2.showData()
324a6169cbce0ffc55d33affba7efa8d73a5871a
DanielBaquero28/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
229
3.703125
4
#!/usr/bin/python3 class MyList(list): """ Inherits from list. """ def print_sorted(self): """ Prints a list in ascendent order. """ new_list = self.copy() new_list.sort() print(new_list)
0c3810df3877baa04473125eaede0efa91de9d1d
mjtat/Boston_311
/Boston_311/data_pull.py
3,945
3.71875
4
from urllib import request import urllib import json from json import * import pandas as pd class Data_Pull(object): """ This object retrieve Boston 311 data. It is initialized with the following information: url: A CKAN url from data.boston.gov num_records: The number of records to retrieve case_status: "Open", "Closed", or "all" neighborhood: A Boston neighborhood, e.g. "Jamaica Plain", "Roxbury". "all" by default. case_type: A 311 case_type e.g. "Parking Enforcement", "Requests for Street Cleaning" calculate_diff: True or False. If true, time difference between open and close dates is generated as a column in the resulting data frame. """ def __init__(self, url, num_records, case_status = 'all', department = 'all', neighborhood = 'all', case_type = 'all', calculate_diff = False): self.url = url self.num_records = num_records self.case_status = case_status self.department = department self.neighborhood = neighborhood self.case_type = case_type def read_url(self): """ read_url() takes a CKAN url, then translates the resulting json into a pandas dataframe. """ url = str(self.url) num_records = str(self.num_records) url = url[0:-1] + num_records fileobj = urllib.request.urlopen(url) file = json.loads(fileobj.read().decode('utf-8')) df = pd.DataFrame.from_dict(file['result']['records']) return df def get_cases(self): """ get_cases() takes a data frame of 311 results, and subsets it such that all the results are open, closed, or both. """ #print('Getting {} cases...'.format(self.num_records)) df = self.read_url() if self.case_status == 'all': return df elif self.case_status == 'Open': df = df[df['CASE_STATUS'] == 'Open'] return df else: df = df[df['CASE_STATUS'] == 'Closed'] return df def list_case_types(self): df = self.get_cases() case_types = df['TYPE'].unique() for case_type in case_types: if case_type is None: continue else: print(case_type) def list_neighborhoods(self): df = self.get_cases() neighborhoods = df['neighborhood'].unique() for neighborhood in neighborhoods: if neighborhood is None: continue else: print(neighborhood) def select_department(self, df): df = df if self.department == 'all': print('Selecting from all departments...') return df else: print('Selecting from {} deparment...'.format(self.department)) df = df[df['SUBJECT'] == self.department] return df def select_case_type(self, df): print('Selecting {}'.format(self.case_type)) if self.case_type == 'all': df = df return df else: df = df df = df[df['TYPE'] == self.case_type] return df def select_neighborhood(self, df): print('Selecting cases in {}'.format(self.neighborhood)) if self.neighborhood == 'all': return df else: df = df df = df[df['neighborhood'] == self.neighborhood] return df def return_data(self): print('Retrieving data...') df = self.get_cases() df = self.select_department(df) df = self.select_case_type(df) df = self.select_neighborhood(df) print('{} number of entries retrieved after case and neighborhood selection'.format(len(df))) return df
ed71b218d347cae4816fef856f0ef55764ddf059
antoniorcn/fatec-2019-2s
/djd-prog2/manha-aula4/ordenacao3.py
401
4.15625
4
print("Ordenação de 3 números") n1 = int(input("Digite o 1º numero")) n2 = int(input("Digite o 2º numero")) n3 = int(input("Digite o 3º numero")) if n1 <= n2 <= n3: print(n1, n2, n3) elif n1 <= n3 <= n2: print(n1, n3, n2) elif n2 <= n1 <= n3: print(n2, n1, n3) elif n2 <= n3 <= n1: print(n2, n3, n1) elif n3 <= n1 and n1 <= n2: print(n3, n1, n2) else: print(n3, n2, n1)
a538ce131072f3d84017aacef3ebedecfc425f11
TetianaHrunyk/DailyCodingProblems
/challenge97.py
2,630
4.125
4
"""Write a map implementation with a get function that lets you retrieve the value of a key at a particular time. It should contain the following methods: set(key, value, time): sets key to value for t = time. get(key, time): gets the key at t = time. The map should work like this. If we set a key at a particular time, it will maintain that value forever or until it gets set at a later time. In other words, when we get a key at a time, it should return the value that was set for that key set at the most recent time. Consider the following examples: d.set(1, 1, 0) # set key 1 to value 1 at time 0 d.set(1, 2, 2) # set key 1 to value 2 at time 2 d.get(1, 1) # get key 1 at time 1 should be 1 d.get(1, 3) # get key 1 at time 3 should be 2 d.set(1, 1, 5) # set key 1 to value 1 at time 5 d.get(1, 0) # get key 1 at time 0 should be null d.get(1, 10) # get key 1 at time 10 should be 1 d.set(1, 1, 0) # set key 1 to value 1 at time 0 d.set(1, 2, 0) # set key 1 to value 2 at time 0 d.get(1, 0) # get key 1 at time 0 should be 2 """ class Map: def __init__(self): self.obj = dict() def _set(self, key, val, time): if key in self.obj.keys(): self.obj[key][time] = val else: self.obj[key] = dict() self.obj[key][time] = val def get(self, key, time): if key not in self.obj.keys(): return None if time < min(self.obj[key].keys()): return None if time in self.obj[key].keys(): return self.obj[key][time] most_recent_time = max(self.obj[key].keys()) for time_choice, val in self.obj[key].items(): option = time - time_choice if option < most_recent_time: if option > 0: most_recent_time = time_choice return self.obj[key][most_recent_time] if __name__ == "__main__": d = Map() d._set(1, 1, 0) # set key 1 to value 1 at time 0 d._set(1, 2, 2) # set key 1 to value 2 at time 2 assert d.get(1, 1) == 1 # get key 1 at time 1 should be 1 assert d.get(1, 3) == 2 # get key 1 at time 3 should be 2 d = Map() d._set(1, 1, 5) # set key 1 to value 1 at time 5 assert d.get(1, 0) == None # get key 1 at time 0 should be null assert d.get(1, 10) == 1# get key 1 at time 10 should be 1 d = Map() d._set(1, 1, 0) # set key 1 to value 1 at time 0 d._set(1, 2, 0) # set key 1 to value 2 at time 0 assert d.get(1, 0) == 2 # get key 1 at time 0 should be 2
955240d9352665946e2c728014c5613c3579f5d6
th9195/PythonDemo01
/Demo08_String.py
6,397
3.765625
4
str1 = "0123456789" print(str1[2:5:1]) print(str1[2:5:2]) print(str1[2:5]) print(str1[:6]) print(str1[2:]) print(str1[::-1]) print(str1[2::-1]) print(str1[:6:-1]) print(str1[-4:-1:-1]) print(str1[-1:-4:-1]) ''' 字符串的方法 str.find(str, beg=0, end=len(string)) 方法检测字符串中是否包含子字符串 str , 如果指定 beg(开始) 和 end(结束) 范围, 则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1 str.rfind(str, beg=0 end=len(string)) 返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。 str.index(str, beg=0, end=len(string)) 方法检测字符串中是否包含子字符串 str , 如果指定 beg(开始) 和 end(结束) 范围, 则检查是否包含在指定范围内, 该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。 str.rindex(str, beg=0 end=len(string)) 返回子字符串 str 在字符串中最后出现的位置, 如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间 str.count(sub, start= 0,end=len(string)) 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置. str.replace(old, new[, max]) 方法把字符串中的 old(旧字符串) 替换成 new(新字符串), 如果指定第三个参数max,则替换不超过 max 次。 str.split(str="", num=string.count(str)). 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串 str.join(sequence) 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。 str.capitalize() 将字符串的第一个字母变成大写,其他字母变小写。对于 8 位字节编码需要根据本地环境。 注意:转换后,只有第一个字符大写,其他的字符全部改为小写 str.title(); 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。 str.istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。 str.lower() 方法转换字符串中所有大写字符为小写。 str.islower() 方法检测字符串是否由小写字母组成。 str.upper() 将字符串中的小写字母转为大写字母。 str.isupper() 检测字符串中所有的字母是否都为大写。 str.strip([chars]); 去首尾字符 用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 str.lstrip([chars]) 去首字符 用于截掉字符串左边的空格或指定字符。 str.rstrip([chars]) 去尾字符 删除 string 字符串末尾的指定字符(默认为空格). str.ljust(width[, fillchar]) 左填充 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。 如果指定的长度小于原字符串的长度则返回原字符串。 str.rjust(width[, fillchar]) 右填充 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。 如果指定的长度小于字符串的长度则返回原字符串。 str.center(width[, fillchar]) 居中 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。 str.startswith(str, beg=0,end=len(string)); 用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。 如果参数 beg 和 end 指定值,则在指定范围内检查。 str.endswith(suffix[, start[, end]]) 用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。 可选参数"start"与"end"为检索字符串的开始与结束位置。 str.isalpha() 判断是否为全字母 检测字符串是否只由字母组成 str.isdigit() 判断是否全是数字 检测字符串是否只由数字组成。 str.isalnum() 判断是否只有字母和数字组成的字符串 检测字符串是否由字母和数字组成。 str.isspace() 判断是否只有空格 检测字符串是否只由空格组成。 ''' str2 = "hello world and itcast and itheima and Python" new0 = str2.replace("and","he") new1 = str2.replace("and","he",1) print(str2) print(new0) print(new1) list1 = str2.split("and") list2 = str2.split("and",2) print(list1) print(list2) joinStr = "-".join(["aaa","bbb","ccc"]) print(joinStr) str = "hello world and itcast and itheima and Python" str1 = str.capitalize() print(str1) str2 = str.title() print(str2) print(str2.istitle()) str3 = str.upper() print(str3) print(str3.isupper()) str4 = str.lower() print(str4) print(str4.islower()) str = " 删除 string 字符串末尾的指定字符(默认为空格) " print(str) str1 = str.lstrip() str2 = str.rstrip() str3 = str.strip() print(str1) print(str2) print(str3) str = "0000删除 string 字符串末尾的指定字符(默认为空格)00000" print(str) str1 = str.lstrip('0') str2 = str.rstrip('0') str3 = str.strip('0') print(str1) print(str2) print(str3) str = "hello world and itcast and itheima and Python" print(str.startswith("hello")) print(str.startswith("and", 12, len(str))) print(str.endswith("and",0,-7)) str1 = "hello13441" str2 = "hello" str3 = "6547654" print(str1.isdigit()) print(str1.isalpha()) print(str1.isalnum()) print(str2.isalpha()) print(str3.isdigit()) str = " " str2 = "1 2 3 " print(str.isspace()) print(str2.isspace())
db97ae5c53330f0d062b63aa88b0742087e95012
LDPGG/dm
/ZXYJ_GG-master/PyCharm/Wdpc/Wddyzpc.py
1,317
3.546875
4
# Python小白的挣扎 # 大神轻锤 # 小白的第一个爬虫 # 这里导入要先导入BeautifulSoup和requests from bs4 import BeautifulSoup import requests # 这里是你要爬取的网页路径,我这里爬的是糗事百科 url = 'https://www.qiushibaike.com/pic/' # 用requests.get方法获得网页,并把它存储 we_data = requests.get(url) # 用BeautifulSoup 解析网页,用.text方法使得网页可读 soup = BeautifulSoup(we_data.text, 'html.parser') # 爬取的元素标签,(看其标签中共有属性) titles = soup.select('div.content span') # 爬取想要图片的链接(在图片路径没有设置宽度的情况下) # 不要听信百度用煞笔正则,我研究了一上午正则,一直报错说正则不是str类型,我又研究怎么加转型 imgs = soup.select('div.thumb a img') # 对比上面的,爬取想要的图片的链接(在图片路径有设置宽度的情况下) # imgs = soup.select('img[width="200"]') # 用循环输出结果 for title, imgs in zip(titles, imgs): # 设置字典存放你爬取到的内容 data = { # 用户输入的内容 '内容': title.get_text('span'), # 用户上传的图片路径 '图片路径': imgs.get('src') } # 输出你爬到的东西 print(data)
17c68324bc12d5fc8c823e79bbf533072c5acae3
squashmeister99/PythonProjects
/GuessNumber/GuessNumber/GuessNumber.py
650
4.125
4
import random numberOfAttempts = 0 def main(): print("Hello, what is your name") name = input() number = random.randint(1,20) print('Well, ' + name + ', I am thinking of a number from 1 to 20') for numberOfAttempts in range(6): print("Take a guess") guess = int(input()) if guess < number: print('Your guess is too low') if guess > number: print('Your guess is too high') if guess == number: print("Good job, {0:s}, you guessed the number in {1:d} tries".format(name, numberOfAttempts + 1)) break; if __name__ == "__main__": main()
992d9d031a59e6c02ec4c781f31eee6a89098097
AvinashBonthu/Python-lab-work
/lab8/lab8.h.py
218
3.71875
4
def count (i,a,c): if i<len(a): if a[i]=='a': c=c+1 i=i+1 count(i,a,c) else: print 'count of a is',c a=raw_input('enter the string') i=0 c=0 count(i,a,c)
0de76d58f7dc4901846617adb97c613aa6300b39
gagigante/Python-exercises
/List 05/12.py
666
4.5
4
# Questão 12. Construa uma função que receba uma string como parâmetro # e devolva outra string com os carateres emba- ralhados. Por exemplo: # se função receber a palavra python, pode retornar npthyo, ophtyn ou # qualquer outra combinação possível, de forma aleatória. Padronize em # sua função que todos os caracteres serão devolvidos em caixa alta ou # caixa baixa, independentemente de como foram digitados. import random def Shuffler(palavra): shuffled = list(palavra.lower()) random.shuffle(shuffled) shuffled = ''.join(shuffled) print(f'A palavra embaralhada é {shuffled}') word = input('Digite uma palavra: ') Shuffler(word)
cf544ebd459055d16d1f6cfb870cb9e50c63faca
Zismo/blessrng
/FirstLess.py
1,727
3.84375
4
#k=x=1 #x=1 #lol = 'программа' #print(f'{x} {k} {lol}', end=';\n') #print('{0}\n{1}'.format(x, k)) #k=-2 #if k>0: # print('Hello world!') #elif k<0: # print('k<0') #else: # print('k=0') #arr = [1,2,3] #for item in arr: # print(item, end=' ') # print() # for item2 in range(len(arr)): # print(item2, end=' ') #print() #for i in range(len(arr)): # print(i, end=' ') #j=0 #while j<10: # j +=1 # print(j, end=' ') #def add(a: int, b: int): # if not(isinstance(a, int)) or not(isinstance(b, int)): # print('not int') # return None # return a + b #print(add(1, 2)) #print(add('123','12')) #a = {} - Словарь #a[123] = 'Artem' #a[1] = 'Ilya' #print(a[123]) #b = { # '123': 'Artem' # '546': 'fsgsgsdgsdg' #} #print(a) #print(b) #a = [] #a.append(1) #a.append(2) #b=[4, 34, 9] #def foo(): # print('xm xm xm.. I am doing something') #def getNewFoo(f): # def decorator(): # print('Hello world!') # f() # print('end') # return decorator #if _name_ == '_main_' #class MyClass(object): # def __init__(self, number: int): # self.number = number # self._number = number + 1 # self.__number = number + 2 # def add(self, number2: int) -> int: # return self.number + number2 # def __str__(self): # return 'kek' #a = MyClass(1) #a.MyClass__number #b = MyClass(2) #print(str(a)) #print('Enter name of file: ', end=' ') #nameFile = input() #try: # file = open(nameFile, 'r') #except IOError as error: # print(str(error)) #else: # with file: # for line in file: # print(line, end=' ') # print() # print(f'file is closed: {file.closed}')
66453ac89c4a52dfd92b610d5bb988967a749efe
tony-ml/jiuzhangAlgo
/Joe Zheng/week 4/433. Number of Islands.py
2,167
3.8125
4
class Solution: """ @param grid: a boolean 2D matrix @return: an integer """ def numIslands(self, grid): # write your code here # exception # number of rows r = len(grid) if r == 0: return 0 # number of coloumns c = len(grid[0]) visited = [[False for _ in range(c)] for __ in range(r)] # print(visited) """ check outofbound, if it is 1, if it is visited @param row and col: index to the location @return: Boolean """ def check(row, col): # print(row >= 0 and row < r) # print(col >= 0 and col < c) return (row >= 0 and row < r and col >= 0 and col < c and grid[row][col] and visited[row][col] == False) """ mark the one's negibhor visited @param row and col: index to the location @return: nothing, """ def bfs(row, col): travers = [ (1, 0), (0, 1), (-1, 0), (0, -1) ] # points that need to be traversed points = [(row, col)] while len(points) > 0: # take out the first one in that queue _x = points[0][0] _y = points[0][1] points.pop(0) for i in range(4): newx = _x + travers[i][0] newy = _y + travers[i][1] if check(newx, newy): # set the point to be visted, also add it into the queue # to continue travers print((newx, newy)) visited[newx][newy] = True points.append((newx, newy)) counts = 0 # find all 1 for row in range(r): for col in range(c): if check(row, col): # c.append((row, col)) visited[row][col] = True bfs(row, col) counts += 1 return counts
c860cb2b48fb157739227c8badd445ed1a7c34d6
MarioPezzan/ExerciciosGuanabaraECurseraPyCharm
/Exercícios curso em video/Exercicios/ex056.py
1,126
3.625
4
media = 0 velho = 0 nom1 = '' mulhermaisvelha = 0 sexom = 0 for c in range(1, 5): print(5*'-', f'{c}° PESSOA', '-'*5) nome = str(input('Nome: ')) idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')) media += idade if c == 1 and sexo in 'Mm': velho = idade nom1 = nome if sexo in 'Mm' and idade > velho: velho = idade nom1 = nome if sexo in 'Ff': sexom += 1 if c == 1 and sexo in 'Ff': mulhermaisvelha = idade if sexo in 'Ff' and idade > mulhermaisvelha: mulhermaisvelha = idade print(f'A média de idade do grupo é de {media/4}') print(f'a idade do mais velho é de {velho} e seu nome é {nom1}') if mulhermaisvelha < 20 and sexom > 1: print(f'Ao todo são {sexom} mulheres com menos de 20 anos') if mulhermaisvelha > 20 and sexom > 1: print(f'Ao todo são {sexom} mulheres com idade maior que 20 anos') if mulhermaisvelha < 20 and sexom == 1: print(f'á somente {sexom} mulher com menos de 20') if mulhermaisvelha > 20 and sexom == 1: print(f'Ao todo são {sexom} mulher com idade maior que 20 anos')
4324be37533579c20502e30bafe8336c1c24ce5e
yaronlevi1/CDcode
/Python/python_fundamentals/ScoresandGrades.py
417
3.875
4
import random def myfunc(): print ("Scores and Grades") for i in range(10): a = random.randint(60, 100) if a>=60 and a<70: b = "D" elif a>=70 and a<80: b = "C" elif a>=80 and a<90: b = "B" elif a>=90 and a<=100: b = "A" print("Score:",a,"; Your grade is ", b) print("End of program. Bye!") myfunc()
1970947818e8114843d68e881d66197fea737de6
ifosch/advent-of-code
/scratchpad/inputparsing.py
745
4.09375
4
#!/usr/bin/env python filename = 'input.txt' # Open Multiline File and iterate line by line filename = 'input.txt' with open(filename, 'r') as fp: lines = (l.strip() for l in fp) for line in lines: i = int(line) print(line, i) # Open Single Line File and iterate char by char filename = 'input.txt' with open(filename, 'r') as fp: line = fp.readline().strip() for char in line: print(char) chars = [char for char in line] # Open Single Line File and iterate (split by comma) filename = 'input.txt' with open(filename, 'r') as fp: line = fp.readline().strip() for item in line.split(','): print(item) items = [item for item in line.split(',')] items_num = [int(item) for item in line.split(',')]
f2d2ce4cdd27d285bff8cb253b1aad7d48fc0f46
sonyarpita/ptrain
/Modules/user_module1_me.py
311
4.09375
4
import swap try: a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) a,b=swap.swape(a,b) print("values after swap= ",a,",",b) except ValueError: print("ValueError:Exception Handler") print("Invalid input: Only integers are allowed") finally: print("Swapped")
d6c5a4ba014cd1388dd4c2334ff2438090019e22
LuuckyG/CS50x
/pset6/cash.py
657
4.0625
4
# Get change input while True: change = input("Change owed: ") try: change = float(change) except: continue # Check if height is in correct range if change > 0.00: # To overcome floating point precision limitations change *= 100 break # Available coins coins = [25, 10, 5, 1] # Number of coins returned as change num_coins = 0 # Calculate number of returned coins for coin in coins: n = change // coin if n >= 1.00: num_coins += n # Update remaining change change -= n * coin if change == 0.00: break # Print result print(int(num_coins))
c33e7b6bb5c7198a3f5fb690f62818274ea78dae
EugenMorarescu/IS211_Assignment9
/nfl_games.py
1,040
3.5
4
from bs4 import BeautifulSoup import urllib.request url = "http://www.footballlocks.com/nfl_point_spreads.shtml" page = urllib.request.urlopen(url) soup = BeautifulSoup(page.read(),features='lxml') #print(soup.prettify()) games = [] table = soup.find("table",{'cols': '4'}) rows = table.findChildren(['tr']) for td in rows: games.append(td.text.strip().split('\n')) teamList = [ 'Philadelphia','NY Giants', 'Cleveland','Cincinnati', 'Dallas','Washington', 'Atlanta','Detroit', 'New Orleans','Carolina', 'Buffalo','NY Jets', 'Green Bay','Houston', 'Seattle','Arizona', 'New England','San Francisco', 'Kansas City','Denver', 'Tampa Bay','Las Vegas', 'Tennessee','Pittsburgh', 'LA Chargers','Jacksonville'] for i in teamList: print(i) inp = input("Enter Team: ") inp = inp.lower() for i in games: if inp in i[3].lower() or inp in i[1].lower(): print('Favorite: {} | Underdog: {} | Spread: {}'.format(i[1],i[3],i[2]))
4a6e262eb3986cc6903fdb75376f633444ecc209
fossnik/python-exercises
/pangram/pangram.py
213
3.703125
4
def is_pangram(sentence): seen = set() for x in sentence.lower(): if x.isalpha(): seen.add(x) alphabet = "abcdefghijklmnopqrstuvwxyz" for c in alphabet: if not c in seen: return False return True
121ac64ba845af4c314b816cae74c7e8da3f7646
loafer18/numBomb
/identifyInteger.py
345
4.25
4
number1 = input("Please input a integer number:") while True: if number1.isdecimal(): print("The number is good to go.") break else: print("Your input was not integer number, please enter int number.") number1 = input("Please input a good int number:") print("Now the number is:" +number1)
8210c2b7fd6e1c300ce46f5daffa6c8f28636dd1
Bhawana3/Data-Structures
/stack/specialStack.py
2,361
4.09375
4
""" Make a special stack class which has same push,pop methods plus one additional method to show minimum value of stack in Time complexity of O(1)""" class Node: def __init__(self): self.value = 0 self.next = None class Stack: def __init__(self): self.top = None def push(self,value): temp = Node() temp.value = value current = self.top if current is not None: temp.next = current self.top = temp else: self.top = temp def pop(self): current = self.top if current is not None: temp = current.next self.top = temp current.next = None return current.value else: return "underflow" def printStack(self): current = self.top if self.top is not None: while current != None: print current.value,"-->", current = current.next print None else: print "Empty Stack" class SpecialStack: def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def insert_node(self,value): if self.stack2.top is not None and self.stack1.top is not None: print self.stack2.top.value if self.stack2.top.value > value: self.stack2.push(value) self.stack1.push(value) else: self.stack1.push(value) print self.stack1.top.value else: self.stack1.push(value) self.stack2.push(value) def pop_node(self): if self.stack1.top is not None and self.stack2.top is not None: if self.stack2.top.value == self.stack1.top.value: self.stack1.pop() self.stack2.pop() else: self.stack1.pop() else: print "Empty stack" def print_stack(self): self.stack1.printStack() self.stack2.printStack() def getMin(self): if self.stack2.top is not None: return self.stack2.top.value else: return "Empty Stack" if __name__ == "__main__": specialStack = SpecialStack() print "Menu : " print "1 - push node into special stack" print "2 - pop node from special stack" print "3 - print stack" print "4 - get minimum value in stack" n = raw_input("Choose 1/2/3/4 : ") while True: if n == '1': value = input("Enter value to push into stack : ") specialStack.insert_node(value) elif n == '2': print specialStack.pop_node() elif n == '3': specialStack.print_stack() elif n == '4': print specialStack.getMin() else: print "Invalid option choosen. Exiting..." break n = raw_input("Choose 1/2/3/4 : ")
36ec82b51c591245d456632e79dfe1afa64804e3
Chrisaor/StudyPython
/GeeksforGeeks/Practice/2. Basic/55.MaximumChar.py
388
3.984375
4
def maximum_char(char1): count_list = list() temp = list() for i in char1: count_list.append(char1.count(i)) max_count = max(count_list) for i in char1: if char1.count(i) == max_count: temp.append(i) return sorted(temp)[0] t = int(input()) for i in range(t): char1 = input() char1 = list(char1) print(maximum_char(char1))
326c589233b587927aad6cfea19b4eb44fe2aebe
msdnqqy/ML
/西瓜书/K紧邻算法.py
588
3.703125
4
#使用sklearn实现K近邻算法 import numpy as np; from sklearn import datasets; from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNeighborsClassifier #导入花数据集 iris=datasets.load_iris() iris_x=iris.data iris_y=iris.target print(iris_x[:2,:]) #切分验证集和训练集并打乱顺序 x_train,x_test,y_train,y_test=train_test_split(iris_x,iris_y,test_size=0.3) print(y_train) #定义使用模型 knn=KNeighborsClassifier() knn.fit(x_train,y_train) prediction=knn.predict(x_test) #输出预测结果 print(prediction) print(y_test)