blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
840f4b5f3d7dbb11fd65e266fbff83561e4f729b
kancha-supriya/python_samples
/test2.py
1,139
4.25
4
""" Return true for palidrome test with case sensitive and non case sensitive EG : Madam """ import string class Palindrome: @staticmethod def is_palindrome(word): if word[::-1] == word: return True if word[::-1].lower() == word.lower(): return True return False @staticmethod def is_palindrome_method_2(word): str = '' for i in word: str = i + str if word == str: return True if word.lower() == str.lower(): return True return False print("Method 1 Check Case-sensitivity : ", Palindrome.is_palindrome('Madam')) print("Method 1 Check Non-Case-sensitivity : ", Palindrome.is_palindrome('Madam')) print("Method 1 Check for non palindrome : ", Palindrome.is_palindrome('test')) print("Method 2 Check Case-sensitivity : ", Palindrome.is_palindrome_method_2('Madam')) print("Method 2 Check Non-Case-sensitivity : ", Palindrome.is_palindrome_method_2('Madam')) print("Method 2 Check for non palindrome : ", Palindrome.is_palindrome_method_2('test'))
false
a662d0ba108c778eabc880a98c81767894b9e31e
jon-rutledge/Notes-For-Dummies
/Python/ListsAndStrings.py
1,198
4.1875
4
#strings and lists testList = list('Hello') print(testList) print(testList) #strings are immutable data types, they cannot be modified #if you need to modify a string value, you need to create a new string based the original #References #with one off variables you can do something like this spam = 42 cheese = spam spam = 100 print(cheese) #cheese retains the value of 42 as it is not a reference to 'spam' but #instead its own variable and value #with lists this does not work spam = [0,1,2,3,4,5] cheese = spam cheese[1] = 'TEST' print(cheese) print(spam) #spam also changes because the REFERENCES to the list is in both spam and cheese #think of you assigning an set of addresses to spam and cheese #by changing the value of something in the list, the addresses stay the same #import Copy #by using the copy module we can actually truly copy a list and act on it #without modifiying the original list import copy spam = [1,2,3,4] cheese = copy.deepcopy(spam) cheese.append('TEST') print(cheese) print(spam) #lists can also exist on multiple lines spam = [1, 2, 3] #also can conitnue on new lines by using \ print('This is line 1 and ' + \ 'this is line 2')
true
3cdc151abf8b3d094b0efe4b833ffee6d05866e9
nikhil-kamath/Scheduling
/DateTimeInput.py
1,685
4.1875
4
import datetime as dt class DateTimeInput: def __init__(self): pass def input_date(self) -> dt.date: '''gets input from console and returns DATE object''' goal_date_str = input("Enter a date at which our code should run: ").split() if goal_date_str[0] == 'today': return dt.date.today() goal_date_data = [int(a) for a in goal_date_str] goal_date: dt.date while True: try: if goal_date_str == 'today': goal_date = dt.date.today() break goal_date = dt.date(*goal_date_data) break except ValueError: print("invalid date") goal_date_str = input( "Enter a date at which our code should run: ").split() goal_date_data = [int(a) for a in goal_date_str] return goal_date def input_time(self) -> dt.time: '''gets input from console and returns TIME object''' goal_time_str = input("Enter a time at which our code should run: ").split() if goal_time_str[0] == 'now': return dt.datetime.now().time() goal_time_data = [int(a) for a in goal_time_str] goal_time: dt.time while True: try: goal_time = dt.time(*goal_time_data) break except ValueError: print("invalid time") goal_time_str = input( "Enter a time at which our code should run: ").split() goal_time_data = [int(a) for a in goal_time_str] return goal_time
false
d4a8bd4e8e212950b246d5b1a2dba83eb08c669e
mhipo1364/takh
/test.py
1,008
4.1875
4
__author__ = 'moefar' def is_divisible(x, y): """ Check if x is divided by y :param x: int :param y: int :return: bool """ if x % y == 0: return True def divisible_by_three(x): """ Returns proper string if x is divided by 3 :param x: int :return: str/None """ if is_divisible(x, 3): if is_divisible(x, 5): return '{} Big Bang \n'.format(x) return '{} Big \n'.format(x) def divisible_by_five(x): """ Returns proper string if x is divided by 5 :param x: int :return: str/None """ if is_divisible(x, 5): if is_divisible(x, 3): return '{} Big Bang \n'.format(x) return '{} Bang \n'.format(x) def main(x): """ Decision Maker :param x: int :return: str/None """ result = divisible_by_three(x) if not result: result = divisible_by_five(x) return result start = 4 end = 146 for i in range(start, end): print(main(i))
false
34f8a256264e0da898d07b32d613371bc0fecde5
SACHSTech/ics2o1-livehack-2-Kyle-Lue
/problem2.py
1,066
4.5
4
""" ------------------------------------------------------------------------------- Name: problem2.py Purpose: Determine the sides of the traingle and determine if it is a triangle Author: Lue.Kyle Created: 23/02/2021 ------------------------------------------------------------------------------ """ #Input the lengths of the three sides print ("Welcome to the Triangle Checker") side_1 = int(input("Enter the length of the first side: ")) side_2 = int(input("Enter the length of the second side: ")) side_3 = int(input("Enter the length of the third side: ")) #Calculate if it is a triangle depending on the sides and output the result if side_3 > side_2 + side_1: print ("The figure is not a triangle") elif side_2 > side_3 + side_1: print ("The figure is not a triangle") elif side_1 > side_2 + side_3: print ("The figure is not a triangle") elif side_1 <= side_2 + side_3: print ("The figure is a triangle") elif side_2 <= side_1 + side_3: print ("The figure is a triangle") elif side_3 <= side_1 + side_3: print ("The figure is a triangle")
true
5ba6cfe289b2cec8dd68df78d11253cbb7a5ec0c
ashutosh4336/python
/coreLanguage/ducktyping/lambda.py
1,324
4.28125
4
""" --> What is Lambda function ? Lambda function are Namesless or Anonymous functions 'lambda' is not a function it is a keywork in python --> Why they are Used. One-Time-Use ==> Throw away function as they're only used Once IO of other function ==> They're also passed as inputs or returned as outputs of other High-Order function Reduce Code Size ==> The body of Lambda function is written in a single line --> Syntax lambda arguments: expression lambda : 'Specify purpose' lambda a1: "Specify use of a1" lambda a1...n: "Specify use of a1...n" """ # x = lambda a: a * a # # def x(a): return a * a # print(x(3)) """ Anonymous function with in user defined function """ def a(x): return(lambda y: x + y) # s = a(5) # print(s(5)) # # c = a(10) # print(c(8)) ''' filter() ==> used to filter the given iterables(list, set, etc) with the help of another function passed as an argument to test all the elements to be true or false ''' ''' # lambda with filter mylist = [1,5,3,5,4,6] newlist = list(filter(lambda x: (x % 2 == 0), mylist)) # print(newlist) ''' ''' # lambda with Map() mylist = [1, 2 ,3, 4, 5, 6, 7, 8, 9] newlist = list(map(lambda x: (x / 3 != 2), mylist)) print(newlist) ''' # lambda with reduce() import functools a = functools.reduce(lambda x,y: x+y, [23, 56, 48, 91, 1]) print(a)
true
90b19ba814eb586ddae8d0b97068b71901a8627c
Satishchandra24/CTCI-Edition-6-Python3
/chapter1/oneAway.py
2,799
4.15625
4
"""There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple-> true pales, pale -> true pale,bale-> true pale,bake-> false""" def oneAway(str1,str2): #In this function based on the length of the str2 comapared to str1 one we will call delete,replace or insert len1=len(str1) len2=len(str2) if len1==len2+1: return checkDelete(str1,str2) elif len1==len2: return checkReplace(str1,str2) elif len1==len2-1: return checkInsert(str1,str2) else: return False def checkDelete(str1,str2):#This function will see if two strings are same after we delete on char a={}#define map b={} for i in range(len(str1)): a[i]=str1[i] #In this map we will have key->val pair For the first string 1->'first char in string' ... for i in range(len(str2)):#In this map we will have key->val pair for the second string if str1[i]==str2[i]:#We will add a char at pos i if the char at the position is same as in str1 b[i]=str2[i] else: b[i+1]=str2[i]#We will add the char at pos i+1 since it will be same at that pos count=0 for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: return False if count==len(str2): #We will count the same vals for keys in both map and return true if the count is same return True return False def checkInsert(str1,str2): a={} b={} for i in range(len(str1)): #a[str1[i]]=i a[i]=str1[i] for i in range(len(str2)): if i==len(str2)-1: b[i]=str2[i] break if str1[i]==str2[i]: #b[str2[i]]=i b[i]=str2[i] else: #b[str2[i]]=i+1 b[i]=str2[i+1] count=0 print(a) print(b) for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: pass print(count) if count==len(str2)-1: return True return False def checkReplace(str1,str2): a={} b={} for i in range(len(str1)): a[i]=str1[i] for i in range(len(str2)): if str1[i]==str2[i]: b[i]=str2[i] else: #b[str2[i]]=i+1 b[i]=str2[i] count=0 for i in b.keys(): try: if b[i]==a[i]: count=count+1 except: pass if count==len(str2)-1: return True return False str1="ppqr" str2="pppr" output=oneAway(str1,str2) if output: print("Yes they are on edit away") else: print("No, they are not one edit away")
true
bd897223c898fe68168a467fd41f7b1923bcf6ee
rwedema/master_ontwikkeling
/informatica_start/jupyter_notebooks/informatics01/WC_05/random_dna_template.py
1,231
4.21875
4
#!/usr/bin/env python3 #imports import sys import random def calc_gc(seq): #calculates the percentage of GC in the sequence #finish this function yourself pass def generate_dna(len_dna): #generates random DNA with GC percentage between 50 and 60% #some comments removed. Write your own comments! gc_perc = ? while gc_perc < ? ? gc_perc > ?: bases = ? #make an empty list (avoid string concatenation) dna = ? #start for loop to make random letter for i in range(?): #add a random letter to the list dna.append(?) #make a string from the list sequence = "".join(?) #calculate GC percentage. If this is either < 50 or > 60, the loop will start again! #if this is between 50 and 60 the loop will stop! gc_perc = ?(?) #pack both sequence and GC percentage in a tuple and return return (?, ?) def main(): #generate a dna sequence with length 20 dna = generate_dna(20) #print first element from tuple. This is the sequence. print("sequence:", dna[0]) #print second element from tuple. This is the GC percentage. print("GC percentage:", dna[1]) return main()
true
ea4d338b844b370f06bdfd9368fac0c1f154a8a7
rwedema/master_ontwikkeling
/informatica_start/jupyter_notebooks/informatics01/WC_03/03_dna_convert_functions_solution.py
1,748
4.15625
4
#!/usr/bin/env python3 #solution for DNA convert #imports import sys def is_valid_dna(seq): #checks if all letters of seq are valid bases valid_dna = "ATCG" for base in seq: if not base in valid_dna: #the break statement is not needed anymore as return automatically breaks the loop. return False #the loop is finished so we are sure no non-valid bases were encountered. #we can return True now return True def reverse_dna(seq): #reverse string rev_dna = seq[::-1] return rev_dna def complement_dna(seq): #return complement dna bases = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} comp_dna_list = [] for base in seq: comp_base = bases[base] comp_dna_list.append(comp_base) comp_dna = "".join(comp_dna_list) return comp_dna def reverse_complement_dna(seq): rev_dna = (reverse_dna(seq)) rev_comp_dna = (complement_dna(seq)) return rev_comp_dna def main(): #catch command line arguments args = sys.argv #check if sequence is given if len(args) < 2: print("please provide a sequence") print("Program stopping...") sys.exit() #dna string is second argument dna = args[1] #now convert to upper: dna = dna.upper() #check if bases are valid: if not is_valid_dna(dna): print("Non-valid characters found") print("Program stopping...") sys.exit() #call functions rev_dna = reverse_dna(dna) comp_dna = complement_dna(dna) rev_comp_dna = reverse_complement_dna(dna) #print output print("original:", dna) print("reverse:", rev_dna) print("complement:", comp_dna) print("reverse complement:", rev_comp_dna) main()
true
74d8061cc74328a6c65d08ff91ec679347bb76f3
abaldeg/EjerciciosPython
/Simulacro Segundo Parcial Segundo Cuatrimestre Segundo ejercicio.py
472
4.21875
4
"""2) Desarrollar una función recursiva que reciba un número binario y lo devuelva convertido a base decimal. Creando una excepción o generando ValueError en caso de recibir un número que no es binario o un número negativo con el mensaje aclaratorio correspondiente a cada error. Resolver utilizando raise o assert.""" def convertirBaD(cadena): if not cadena: return 0 print(cadena[:-1]) return convertirBaD(cadena[:-1]) * 2 + (cadena[-1] == '1')
false
d2040f23880631d72fa1f90eca9374c012ac0db5
abaldeg/EjerciciosPython
/PROGRAMACION I TP 2 EJ 7.py
803
4.15625
4
#Escribir una función que reciba una lista como parámetro y devuelva True si la lista #está ordenada en forma ascendente o False en caso contrario. Por ejemplo, #ordenada([1, 2, 3]) retorna True y ordenada(['b', 'a']) retorna False. Desarrollar #además un programa para verificar el comportamiento de la función. #Funciones def analizaOrdenLista(lista): ordenada=True if len(lista) <= 1: # print ("La lista esta vacía o tiene un solo elemento. ", end="") ordenada=False else: for i in range(len(lista)-1): if lista[i]>lista[i+1]: ordenada=False return(ordenada) #Programa Principal lista=[1,2,3] print(analizaOrdenLista(lista)) lista=[2,1,3] print(analizaOrdenLista(lista)) lista=[2] print(analizaOrdenLista(lista))
false
e977567aa32b21b6b0a557963a5cd3a01982bca1
boluwaji11/Py-HW
/HW4/HW4-5_Boluwaji.py
674
4.5
4
# This program calculates the factorial of nonnegative integer numbers # Start # Get the desired number from the user # Use a repetition control to calculate the factorial # End # ============================================================== print('Welcome!') number = int(input('\nPlease enter the desired positive number: ')) # Input validation while number <= 0: print("Please ensure the number is a positive whole number") number = int(input('\nPlease enter the desired positive number: ')) factorial = 1 # The accumulator for occurance in range(1, number+1, 1): factorial *= occurance print() print('The Factorial(!) of', number, 'is', factorial)
true
adf9d5898e666f01c6fb4e8c5a7976fe0242283f
boluwaji11/Py-HW
/HW3/HW3-4_Boluwaji.py
1,191
4.4375
4
# This program converts temperature in degrees Celsius to Fahrenheit. # Start # Get the temperature in celsius from the user # Calculate the Fahrenheit equivalent of the inputted temperature # Check the result # If the result is more than 212F # Display "Temperature is above boiling water temperature" # If the result is less than 32F # Display "Temperature is below freezing temperature" # End BOILING_TEMP = 212 # A Named Constant for boiling temperature FREEZING_TEMP = 32 # A Named Constant for freezing temperature celsius_temperature = float(input("Please enter the temperature to convert (in Celsius): ")) convert_fahrenheit = (celsius_temperature * 1.8) + 32 print("\nThe Converted Temperature is ", format(convert_fahrenheit,'.2f'), "F", sep='') if convert_fahrenheit > BOILING_TEMP: print(format(convert_fahrenheit,'.2f'), "F", " is above boiling water temperature", sep='') elif convert_fahrenheit < FREEZING_TEMP: print(format(convert_fahrenheit,'.2f'), "F", " is below freezing temperature", sep='') else: print(format(convert_fahrenheit,'.2f'), "F", " is neither below freezing nor above boiling temperatre", sep='')
true
0cd27f6603efb0bea65eb78aceff2e0ccb25a884
boluwaji11/Py-HW
/HW5/HW5-3_Boluwaji.py
1,712
4.1875
4
# This program calculates dietary information # Start # Define main function # In the main function,get fat and carbohydrate information from the user # Pass fat to calories_fat and call it # Pass carbohydrate to calories_carbs and call it # Call calories_fat and calories_carbs in main # Define the calories_fat function # Calculates the calories using fat and displays the result # Define the calories_carbs function # Calculates the calories using carbohydrate and displays the result # Call the main function # End #================================================================== # The welcome message and header print('Welcome! This program calculates dietary information') print('------------------------------------------------------') print() # Define the global constants FAT_CONVERSION_FACTOR = 9.0 CARB_CONVERSION_FACTOR = 4.0 # Define the main function of the program def main(): fat = float(input('Please enter your daily fat consumption (in grams): ')) carbohydrate = float(input('Please enter your daily carbohydrate consumption (in grams): ')) print() calories_fat(fat) calories_carb(carbohydrate) # Define the calories_fat function def calories_fat(fat_amount): calories_from_fat = fat_amount * FAT_CONVERSION_FACTOR print('The Amount of Calories in', fat_amount, 'gram(s) of Fat consumed is', format(calories_from_fat, '.2f')) # Define the calories_carb function def calories_carb(carbs): calories_from_carbs = carbs * CARB_CONVERSION_FACTOR print('The Amount of Calories in', carbs, 'gram(s) of Carbohydrate consumed is', format(calories_from_carbs, '.2f')) # Call the main function main()
true
2eece337929e5f114a7a8a2e4dc0e33d4634906b
boluwaji11/Py-HW
/HW6/HW6-1-a_Boluwaji.py
1,476
4.15625
4
# This program saves different video running times for Kevin to the video_running_times.txt file. # Start # Define the main function # Ask Kevin for the number of short videos he's working with # Open a file to save the videos # Enter the different times and write it to file # Close the file # Notify Kevin of the written file # Call the main function # End # ================================================================================================== # The headers and introductory message print('Welcome, Kevin! This program saves a sequence of videos running times into file.') print('--------------------------------------------------------------------------------') print() # Define the main funtion def main(): num_videos = int(input('To begin, how many videos do you have in this project, Kevin?: ')) # Number of short videos to be saved video_file = open('video_running_times.txt', 'w') # Creates the file to save the running times # For loop to get each video's running time and write it to the video_running_times.txt file. print('Please enter the running time for each video') print() for count in range(1, num_videos + 1): run_time = float(input('Video #' + str(count) + ': ')) video_file.write(str(run_time) + '\n') # Close the file. video_file.close() print() print('The video times have been saved to video_running_times.txt') # Call the main function. main()
true
fafcd54d9ca7df23aa71d59fa7dde85b0b153aee
JasoSalgado/python-problems
/first-week/first-exercises/problem_16.py
836
4.34375
4
""" Pedir el día, mes y año de una fecha e indicar si la fecha es correcta. Con meses de 28, 30 y 31 días. Sin años bisiestos. """ instructions = "***** Enter a valid date. For instance: dd/mm/yyyy *****" print(instructions.center(50, "*")) day = int(input("Write a day: \n")) month = int(input("Write a month: \n")) year = int(input("Write a year: \n")) if year == 0: print(f"This {year} does not exist.") else: if month == 2 and day >= 1 and day <= 28: print(f"This {month} does not have the day you entered") else: if month ==1 or month == 3 or month == 7 or month == 8 or month == 10 or month == 12 and day >= 1 and day <= 31: print(f"{day}/{month}/{year} is a correct date.") else: print(f"{day}/{month}/{year} is an incorrect date. Try again, please.")
false
a35aa8b96d8fa8820556790e4ebb69552e569d5b
JasoSalgado/python-problems
/second-week/first-exercise-poo/account.py
1,595
4.1875
4
class Account(): def __init__(self, account_holder, amount): self.__account_holder = input("Enter an account holder: \n") self.__amount = float(input("Enter an amount: \n")) @property def account_holder(self): return self.__account_holder @property def amount(self): return self.__amount @account_holder.setter def name(self, account_holder): self.__account_holder = account_holder @amount.setter def amount(self, amount): if amount < 0: print("I think, you are entering negative numbers.") else: self.__amount = amount def deposit(self, deposit): deposit = float(input("How much do you want to deposit? \n")) if deposit < 0: print(f"{deposit} is an incorrent amount. ") else: self.__amount += deposit print(f"You have deposited {deposit}") def withdraw(self, amount): withdraw = float(input("How much do you want to withdraw? \n")) if withdraw > self.__amount: print("You cannot withdraw that amount of money.") else: self.__amount -= amount print(f"You have withdrawn {withdraw} ") class Executable(Account): print("\n") title = " New account information " print(title.center(40, "*")) print("\n") account = Account(Account.account_holder, Account.amount) print("\n") print(account.deposit(0)) print("\n") print(account.withdraw(0))
false
6a1288f7eb4c1d9934ec25f3b6d1c71451f58819
JasoSalgado/python-problems
/first-week/first-exercises/problem_18.py
787
4.125
4
""" Ídem que el ej. 17, suponiendo que cada mes tiene un número distinto de días (suponer que febrero tiene siempre 28 días). """ instructions = "***** Enter a valid date. For instance: dd/mm/yyyy *****" print(instructions.center(50, "*")) day = int(input("Write a day: \n")) month = int(input("Write a month: \n")) year = int(input("Write a year: \n")) def next_date(year, month, day): if month in (1, 3, 5, 7, 8, 10, 12): month_days = 31 elif month == 2: month_days = 28 else: month_days = 30 if day < month_days: day += 1 else: day = 1 if month == 12: month = 1 year += 1 else: month += 1 return (year, month, day) print(next_date(year, month, day))
false
9f4e5d5c93d94f01f61e924974c34d869a5fa0b1
piyush546/Machine-Learning-Bootcamp
/Basic Python programs/listreverse.py
341
4.21875
4
# -*- coding: utf-8 -*- """ A program to demonstrate list content reversing and optimizing the reversing method of string """ # To take user name input in single command using split name = input().split() # to print the name string after reversing name = name[::-1] name = " ".join(name) print(name) # Input = piyush kumar # Output = kumar piyush
true
68742eb158b913e6e9f3f85f80d669eef018fa2d
piyush546/Machine-Learning-Bootcamp
/Basic Python programs/style.py
290
4.15625
4
# -*- coding: utf-8 -*- """ A program to use some str methods """ # variables to store strings to be styled First_string = input("Enter the string:") # To print the strings after styling print(str.upper(First_string)) print(str.lower(First_string)) print(str.capitalize(First_string))
true
34b635354da1a433f5a0ebc96a481141bf48f1be
Neeraj-Chhabra/Class_practice
/task2.py
454
4.125
4
def square_root(a): z=1 x=a/2 while(z==1): y = (x + (a/x)) / 2 if (abs(y-x) < 0.0000001): print(x) z=2 return(x) else: x=y # print("new value not final", x) # print(y) def test_square_root(a): return(math.sqrt(a)) root=int(input("enter the number for the squareroot")) import math d=square_root(root) print(type(d)) b=test_square_root(root) print(type(b)) c=abs(d-b) print(type(c)) print(root,"\t", d, "\t", b ,"\t", c)
true
30822abe9cc556240dca0da5ade9f60371c89676
RayNieva/Python
/printTable.py
2,165
4.4375
4
#!/usr/bin/env python """Project Table Printer Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:""" import pprint def main(): tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] tableData firstColumn=tableData[0] firstColumn secondColumn=tableData[1] secondColumn thirdColumn=tableData[2] thirdColumn thirdColumn[0] len(firstColumn[0]) numOfColumnWidths1=len(firstColumn) numOfColumnWidths2=len(secondColumn) numOfColumnWidths3=len(thirdColumn) columnWidths1=[] columnWidths2=[] columnWidths3=[] #columnWidths.append(n) for i in range(numOfColumnWidths1): print(len(firstColumn[i])) n=len(firstColumn[i]) columnWidths1.append(n) print(columnWidths1) columnWidths1.sort(reverse=True) columnWidths1[0] for i in range(numOfColumnWidths2): print(len(secondColumn[i])) n=len(secondColumn[i]) columnWidths2.append(n) print(columnWidths2) columnWidths2.sort(reverse=True) print(columnWidths2[0]) for i in range(numOfColumnWidths3): print(len(thirdColumn[i])) n=len(thirdColumn[i]) columnWidths3.append(n) print(columnWidths3) columnWidths3.sort(reverse=True) print(columnWidths3[0]) # 'A String'.rjust(columnWidths[0] + 2) """ for i in range(numOfColumnWidths): print(firstColumn[i],secondColumn[i],thirdColumn[i]) """ for i in range(numOfColumnWidths1): print(firstColumn[i].rjust(columnWidths1[0] + 2),secondColumn[i].rjust(columnWidths2[0] + 2),thirdColumn[i].rjust(columnWidths3[0] + 2)) if __name__ == '__main__': main()
true
cd7ce1b61e2223f77e45a8ff3960dcf8114b40fa
european-54/python_algos_gb
/Урок 4. Практическое задание/task_3.py
1,326
4.3125
4
""" Задание 3. Приведен код, формирующий из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Сделайте профилировку каждого алгоритма через cProfile и через timeit Сделайте вывод, какая из трех реализаций эффективнее и почему """ def revers(enter_num, revers_num=0): if enter_num == 0: return else: num = enter_num % 10 revers_num = (revers_num + num / 10) * 10 enter_num //= 10 revers(enter_num, revers_num) def revers_2(enter_num, revers_num=0): while enter_num != 0: num = enter_num % 10 revers_num = (revers_num + num / 10) * 10 enter_num //= 10 return revers_num def revers_3(enter_num): enter_num = str(enter_num) revers_num = enter_num[::-1] return revers_num from cProfile import run from time import sleep def fast(): print("Я быстрая функция") def slow(): sleep(3) print("Я очень медленная функция") def medium(): sleep(0.5) print("Я средняя функция...") def main(): fast() slow() medium() run('main()')
false
e3d1598b8864ed8a3bd40b2e9f41894b5028c326
nuneza6954/cti110
/M4T4 P4HW2_ PoundsKilos _AliNunez.py
951
4.3125
4
# Program will display a table of pounds starting from 100 through 300 # (with a step value of 10) and their equivalent kilograms. # The formula for converting pounds to kilograms is: # kg= lb/2.2046 # Program will do a loop to display the table. # 03-07-2019 # CTI-110 P4HW2 - Pounds to Kilos Table # Ali Nunez # Declare Variables pounds = 0 kilogram = 0 # Get input from user pounds = float(input("Enter weight in pounds:")) # Calculation: convert pounds to kilograms kilogram = pounds/2.2046 for pounds in range(100, 300, 10): kilogram = pounds / 2.2046 print("Pounds:", pounds, " Kilograms:" ,format(kilogram,'.2f'),sep="") # Declared my variables # pounds = 0 # kilogram = 0 # Prompt user for input to "Enter weight in pounds" # Used a calculation to pounds to kilograms # kilogram = pounds / 2.2046 # Displayed conversion for every tenth value strarting at 100 to 300 # using a for loop.
true
6c3e99015bf3c5a132b18f7d55dddf6b7e9952d5
narasimhareddyprostack/Ramesh-CloudDevOps
/Python/Fours/Set/four.py
208
4.40625
4
s = {1,2,3} s.update('hello') print(s) #The Python set update() method updates the set, adding items from other iterables. ''' adding items form other iterable objects, such as list, set, dict, string '''
true
ff61d43320ab6abbbd0c233a72d80420be6e8a7d
narasimhareddyprostack/Ramesh-CloudDevOps
/Python/Fours/Dict/Dict-Exe/seven.py
289
4.15625
4
''' Create a new dictionary by extracting the following keys from a below dictionary keys = ["name", "salary"] ''' sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } keys = ["name", "salary"] newDict = {k:sampleDict[k] for k in keys} print(newDict)
false
96be9ec136c4bd58d90e56a1f1b6b7e07a08f23a
djndl1/CSNotes
/algorithm/introAlgorithm/python-implementation/bubble_sort.py
1,005
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import operator def optimized_bubble_sort(arr, comp=operator.le): if len(arr) < 2: return arr n = len(arr) while n > 1: next_n = 0 for i in range(1, n): if not comp(arr[i-1], arr[i]): # if out of order, then swap arr[i-1], arr[i] = arr[i], arr[i-1] next_n = i n = next_n # any pair between [next_n:] is in order and will remain unchanged # arr[next_n] is greater than arr[:next_n] so that swapping occurs # only in arr[:next_n] return arr def naive_bubble_sort(arr, comp=operator.le): if len(arr) < 2: return arr while True: swapped = False for j in range(1, len(arr)): if not comp(arr[j-1], arr[j]): # swap whenever out of order arr[j-1], arr[j] = arr[j], arr[j-1] swapped = True if not swapped: # until not swapped break return arr
true
99b71f3b737456b6916d801929159ba767e85a55
TBobcat/Leetcode
/CountPrimes.py
1,234
4.25
4
def countPrimes( n): """ :type n: int :rtype: int """ prime_list=is_prime(n) # print(prime_list) return len(prime_list) def is_prime(n): # based on Sieve of Eratosthenes result = [] if n <=1 : return [] # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n , p): prime[i] = False p += 1 prime[0]= False prime[1]= False # Print all prime numbers for p in range(n): if prime[p]: result.append(p) #Use print(p) for python 3 return result if __name__ == '__main__': num1=10 num2=0 num3=1 # print(is_prime(0)) # print(is_prime(1)) # print(is_prime(2)) print(countPrimes(num1)) print(countPrimes(num2)) print(countPrimes(num3)) else: pass
true
e19d001fa89e189159f02bc70314c4dbdc4ebe6f
pierredepascale/PyED
/src/pyed/fundamental.py
2,376
4.15625
4
# # PyED -- an emacs like text editor in Python # # Copyright 2011 Pierre De Pascale (pierre.depascale _AT_ gmail.com) # from keymap import * from mode import * from command import * from editor import * FUNDAMENTAL_MAP = Keymap() FUNDAMENTAL_MODE = Mode("Fundamental", "Fundamental mode", FUNDAMENTAL_MAP) @interactive def self_insert(): """Insert the last key pressed at the current point position""" insert_char(last_key()) @interactive def next_line(): """Move the point to the next line""" set_point(point().next_line()) @interactive def previous_line(): """Move the point to the previous line""" set_point(point().previous_line()) @interactive def forward_character(): """Move the point to the next character""" set_point(point()+1) @interactive def backward_character(): """Move the point to the previous character""" set_point(point().offset(-1)) @interactive def insert_newline(): """Insert a line break at the current point position""" insert_char("\n") @interactive def end_of_line(): """Move the current point to the end of line""" set_point(point().end_of_line()) @interactive def begining_of_line(): """Move the current point to the begining of the line""" set_point(point().begining_of_line()) @interactive def delete_forward(): """Delete the next character""" point().delete_right_char() @interactive def delete_backward(): """Delete the previous character""" point().delete_left_char() set_point(point().offset(-1)) @interactive def quit_editor(): """quit the editor""" raise "END" FUNDAMENTAL_MAP.bind("down", "pyed.fundamental.next_line") FUNDAMENTAL_MAP.bind("up", "pyed.fundamental.previous_line") FUNDAMENTAL_MAP.bind("left", "pyed.fundamental.backward_character") FUNDAMENTAL_MAP.bind("right", "pyed.fundamental.forward_character") FUNDAMENTAL_MAP.bind("return", "pyed.fundamental.insert_newline") FUNDAMENTAL_MAP.bind("^C", "pyed.fundamental.quit_editor") FUNDAMENTAL_MAP.bind("delete", "pyed.fundamental.delete_forward") FUNDAMENTAL_MAP.bind("backspace", "pyed.fundamental.delete_backward") FUNDAMENTAL_MAP.bind("end", "pyed.fundamental.end_of_line") FUNDAMENTAL_MAP.bind("home", "pyed.fundamental.begining_of_line") for ch in range(ord(' '), ord('z')): FUNDAMENTAL_MAP.bind(chr(ch), "pyed.fundamental.self_insert")
false
b4ab5c05860d95676bdc24b9813226002a49fc0f
fgarcialainez/RabbitMQ-Python-Tutorial
/rabbitmq/tutorial1/receive.py
1,191
4.3125
4
#!/usr/bin/env python """ In this part of the tutorial we'll write two small programs in Python; a producer (sender) that sends a single message, and a consumer (receiver) that receives messages and prints them out. It's a "Hello World" of messaging. https://www.rabbitmq.com/tutorials/tutorial-one-python.html """ import pika def callback(ch, method, properties, body): print(" [x] Received %r" % body.decode("utf-8")) def main(): # Open a connection with RabbitMQ server connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() # Create a 'hello' queue from which the messages will be received channel.queue_declare(queue='hello') # Receive messages from 'hello' queue in the callback function channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) # Enter a never-ending loop that waits for data and runs callbacks whenever necessary print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() # Main script if __name__ == '__main__': try: main() except KeyboardInterrupt: print('[*] Interrupted')
true
a7b0001a9a204a24607419abd86197464487e184
oskip/IB_Algorithms
/Merge.py
1,152
4.1875
4
# Given two sorted integer arrays A and B, merge B into A as one sorted array. # # Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. # TIP: C users, please malloc the result into a new array and return the result. # If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n # # Example : # # Input : # A : [1 5 8] # B : [6 9] # # Modified A : [1 5 6 8 9] class Solution: # @param A : list of integers # @param B : list of integers # @return A modified after the merge def merge(self, A, B): if len(A) == 0: return B if len(B) == 0: return A result = [] i = 0 j = 0 while i < len(A) and j < len(B): if A[i] <= B[j]: result.append(A[i]) i += 1 else: result.append(B[j]) j += 1 for a in range(i, len(A)): result.append(A[a]) for b in range(j, len(B)): result.append(B[b]) return result
true
81afe70547b88e2216f90d93e901d89282ae7628
oskip/IB_Algorithms
/RevListSample.py
914
4.25
4
# Reverse a linked list. Do it in-place and in one-pass. # # For example: # Given 1->2->3->4->5->NULL, # # return 5->4->3->2->1->NULL. # # PROBLEM APPROACH : # # Complete solution code in the hints # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list def reverseList(self, A): if A == None: return None head = A previous = A A = A.next while A != None: nextEl = A.next self.delete(A, previous) head = self.insertAtHead(A, head) A = nextEl return head def insertAtHead(self, node, head): node.next = head return node def delete(self, node, previous): previous.next = node.next node.next = None
true
9431f2f8c0c10c09878199baf743b0d1f3510781
pr1malbyt3s/Py_Projects
/Advent_of_Code/2021/1_2021.py
1,183
4.4375
4
# AOC 2021 Day 1 import sys # This function is used to read a file input from the command line. It returns the file contents as a list of lines. def read_file() -> list: if len(sys.argv) != 2: print("Specify puzzle input file") sys.exit(-1) else: # Open file at command line position 1: with open(sys.argv[1], 'r') as f: # Append each stripped line to a list: input_list = [line.strip() for line in f] return input_list # Part 1: Count the number of times a depth measurement increases from the previous measurement. def sonar_count(input_list:list) -> int: count = 0 for a, b in zip(input_list, input_list[1:]): if(b>a): count += 1 return count # Part 2: Count the number of times the sum of measurements in a three-measurement sliding window increases. def sliding_window(input_list:list) -> int: count = 0 for a, b in zip(input_list, input_list[3:]): if(b>a): count += 1 return count def main(): input_list = list(map(int, read_file())) print(sonar_count(input_list)) print(sliding_window(input_list)) if __name__ == "__main__": main()
true
abbda68a1e2777bae2bdc1ec1903232c81d7d42f
pr1malbyt3s/Py_Projects
/Runcode.ninja/Simple_Addition.py
1,116
4.1875
4
#!/usr/bin/env python3 # This script accepts an input file of mixed value pairs separated by lines. # It check that each value pair can be added and if so, prints the corresponding sum. import sys from decimal import Decimal # Create a master list of all number pairs. numList = [] # Type check function to determine if value is integer or decimal. # After determining type, value is translated and returned. def type_check(x): try: if isinstance(int(x), int) == True: return int(x) except ValueError: try: if isinstance(float(x), float) == True: return Decimal(x) except ValueError: return # Read file contents. with open(sys.argv[1], 'r') as f: for line in f: # Create a sublist of the number pair on each line. subNumList = [] # Perform type_check on each number pair. for num in line.split(): subNumList.append(type_check(num)) # Ensure appended line has two values and None is not one of them. if len(subNumList) == 2 and None not in subNumList: numList.append(subNumList) # Print the subList pairs. for subList in numList: print(subList[0] + subList[1])
true
dd49bbd3212bd1c77674f3b8f68ef134a6f7b253
pr1malbyt3s/Py_Projects
/Runcode.ninja/Simple_Cipher.py
579
4.28125
4
#!/usr/bin/env python3 # This script is used to decode a special 'cipher'. # The cipher pattern is each first word in a new sentence. import sys # Create a list to store each parsed first word from an input file. message = [] with open(sys.argv[1], 'r') as f: cipher = f.read() # While reading file, split the file by the '.' character, appending each first word (index 0) to the message list. cipherSplit = cipher.split(". ") for i in range(len(cipherSplit)): message.append(cipherSplit[i].split()[0]) # Print the message via the message list. print(*message, sep = " ")
true
ac0ef21febfd8f26eeec7ae27c2bee55b35ab46f
pr1malbyt3s/Py_Projects
/Runcode.ninja/Third_Letter_Is_A_Charm.py
946
4.21875
4
#!/usr/bin/env python3 # This script accepts an input file containing words with misplaced letters. # Conveniently, the misplaced letter is always from the third position in the word and is at the beginning. import sys # rotate function to perform letter rotation on a provided string. # It first checks to ensure the string is at least three letters long. # If not, it inserts the first letter of the provided word into the third (i[2]) spot. def rotate(s): if(len(s) < 3): return s c = s[0] #print(c) a = s[1:3] #print(a) b = s[3::] #print(b) f = a + c + b return f def main(): # Read file input. with open(sys.argv[1], 'r') as f: for line in f: # List that will be used for each line. inputList = [] # Append each word to the list, rotate it, and print all words once done. for word in line.split(): inputList.append(rotate(word)) print(*inputList) f.close() if __name__ == "__main__": main()
true
812a8a7dac1e22b1bdbd9e47f3c59113b303aa0c
seaboltthomas19/Monty-Hall-Problem
/monty-hall-sim.py
1,111
4.1875
4
import random switch_was_correct = 0 no_switch_was_correct = 0 print("====================================" + "\n" + "*** Monty Hall Problem Simulator ***" + "\n" + "====================================") print("Doors to choose from: ") doors = int(input()) print("Iterations to run: ") iterations = int(input()) for i in range(0, iterations): door_array = list(range(1, doors + 1)) # make a list of every door # select a correct door at random; this will simulate the door with a prize behind it correct_door = random.randint(1, doors) # select an initial choice at random; this will simulate the door the contestant has chosen initially initial_choice = random.randint(1, doors) if initial_choice == correct_door: no_switch_was_correct = no_switch_was_correct + 1 else: switch_was_correct = switch_was_correct + 1 print("Results: \n") print("Switching was correct " + str(switch_was_correct) + " times.\n") print("The initial choice was correct " + str(no_switch_was_correct) + " times.")
true
d61a5fe6d5b68073a738d19b93e24a35695cc1d4
luckymime28/Skyjam
/skyjam.py
1,851
4.1875
4
print("- If you need more info or you're confused type 'help'") def help(): print("\n-So basically, this is my first exploit I ever created \n-My name is luckymime28, and this is my exploit skyjam.py \n-skyjam.py is a password combination maker and list creator \n-Simply follow the instructions on screen and you should be fine \n-Any questions? Ask via instagram luckymime28, sorry if I take a while.\nAlso I am in no way, shape, or form responsible if any damages occur from\nyou using my product.\n") def more_info(): print("- Level 1 is typically for those who have easy passwords\n You might want to save this one for the older people\n Typically just combines words together and generates a bunch of numbers\n") print("- Level 2 is more complex, it will include special symbols usually\n This might include weird letters in the end, beginning, special characters\n It will also generate or replace letters as numbers\n") print("- Level 3 is used for more specifics, for example,\n You know what the wording is, however not what might be the last character \n Try it out in case you forgot your password\n") print("NOTE: For more success, make sure to find more research on your target\nDon't just use this tool and input randoms as you'll be less successful!") con = input("- Push Enter To continue to the Options\n> ") if con.lower() == 'help': help() while True: con2 = input("Which exploit would you like to navigate to?\n{a} Level 1\n{b} level 2\n{c} level 3\nIf you need more info for these types\ntype 'info'\n>> ") if con2.lower() == 'a': import skyjam4 elif con2.lower() == 'b': import skyjam3 elif con2.lower() == 'c': import skyjam2 elif con2.lower() == "info": more_info() else: print("\n INVALID TRY AGAIN \n")
true
1c2ac0372cd46f24e4a6a18d3fb7808154166a31
EthanCornish/AFPwork
/Chapter4-Functions-Tutorial#1.py
759
4.125
4
# Function Tutorial # Creating a main function # In the main function print instructions and ask for a value def main(): print('Hello') print('This program will ask you for a temperature\nin fahrenheit.') print('-----------------------------------------------------------') value = int(input('Enter a value')) # Calls the other function inside the main function print(ftoc(value)) # Create a function to convert fahrenheit to celsius # All the function does is execute a specific job def ftoc(fah): #fah = int(input('Enter a tempreature')) cel = (fah-32) * (5/9) # The :.2f is rounding it too 2dp print('{0}° Fahrenheight = {1:.2f}° Celcius'.format(fah, cel)) return cel # Runs the function main()
true
5fc5f217581a224b9f22be8c91a204a7936a8885
seanmortimer/udemy-python
/python-flask-APIs/functions.py
856
4.1875
4
def hello(name): print(f'Heeyyy {name}') hello('Sean ' * 5) # Complete the function by making sure it returns 42. . def return_42(): # Complete function here return 42 # 'pass' just means "do nothing". Make sure to delete this! # Create a function below, called my_function, that takes two arguments and returns the result of its two arguments multiplied together. def my_function(x, y): return x * y print(my_function(5, 10)) # Unpacking arguments def show(*args): print (args[1]) show(1, 2, 3) def add(x, y): return x + y nums = [3, 5] print(add(*nums)) nums_dict = {'x': 7, 'y': 9} print(add(**nums_dict)) # Unpacking keyword arguments def named(**kwargs): print(kwargs) named(name="Sean", age=36) def named2(name, age): print(name, age) details = {'name': 'Caitlin', 'age': 33} named2(**details)
true
832adbc3d78e3496afb1bb180fc1e8ed42be1b76
LiamWoodRoberts/HackerRank
/Anagrams.py
741
4.125
4
'''Solution to: https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem function finds the number of anagrams contained in a certain string''' def substrings(word): strings=[] for l in range(1,len(word)): sub = [word[i:i+l] for i in range(len(word)-l+1)] strings.append(sub) return strings def anagrams(word): count = 0 #create a list of all possible words at each length words = substrings(word) for i in range(len(words)): for j in range(len(words[i])): gram = sorted(words[i][j]) for k in range(j+1,len(words[i])): if gram == sorted(words[i][k]): count+=1 return count word = 'kkkk' anagrams(word)
true
4a0e8b5efeb37c0b538ed7b264f9a39ad9d67440
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/class_inheritence.py
953
4.15625
4
class rectangle: def __init__(self, width, length): self.width = width self.length = length def area(self): return self.width * self.length def present_figure(self): return f'This figure has a width of {self.width}, a length of {self.length} and an area of {self.area()}' class square(rectangle): # pass def __init__(self, side): super().__init__(side, side) # def present_square(self): # return self.present_figure() def present_figure(self): return f'{super().present_figure()}. The figure is a square.' def main(): # first_rectangle = rectangle(10, 5) # print(first_rectangle.area()) # print(first_rectangle.present_figure()) # first_square = square(10, 10) first_square = square(10) print(first_square.area()) print(first_square.present_figure()) # print(first_square.present_square()) if __name__ == '__main__': main()
true
77b412d9121baf177d930b1072f9870b7f7f6b79
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/donor_models.py
2,082
4.34375
4
#!/bin/python3 ''' Sample implementation of a donor database using classes ''' class Person: ''' Attributes common to any person ''' def __init__(self, donor_id, name, last_name): self.donor_id = donor_id self.name = name self.last_name = last_name class Donation: ''' Attributes for a donation can be easily extended to support more complex properties ''' def __init__(self, amount): self.amount = amount class Donor(Person): ''' Attributes for a person who is also a donor ''' def __init__(self, donor_id, name, last_name): self.donations = [] super().__init__(donor_id, name, last_name) class DonorDB(): ''' A collection of donors ''' def __init__(self): self.all_donors = {} def add_donor(donor_collection): ''' Creates a new donor and adds it to collection ''' donor_id = input("Enter donor ID: ") name = input("Enter donor's name: ") last_name = input("Enter donor's lastname: ") new_donor = Donor(donor_id, name, last_name) if donor_id not in donor_collection.all_donors: donor_collection.all_donors[donor_id] = new_donor else: print("ERROR: Donor ID already exists") def add_donation(donor_collection): ''' Creates a new donation and adds it to a donor ''' donor_id = input("Enter donor ID: ") if donor_id not in donor_collection.all_donors: print("ERROR: Donor ID does not exist") return donation_amount = int(input("Enter the donation amount: ")) new_donation = Donation(donation_amount) donor_collection.all_donors[donor_id].donations.append(new_donation) def print_db(donor_collection): ''' Prints all donors / donations in a collection ''' for donor_info in donor_collection.all_donors.values(): print(f"Donor ID: {donor_info.donor_id}") print(f"Donor: {donor_info.name} {donor_info.last_name}") for donation_info in donor_info.donations: print(f"Donation: {donation_info.amount}")
true
38ce46230cc6f2c490b97ef27681975750f48ed7
Rockwell70/GP_Python210B_Winter_2019
/examples/office_hours_code/sunday_puzzle.py
1,425
4.1875
4
''' From: https://www.npr.org/2019/01/20/686968039/sunday-puzzle-youre-halfway-there This week's challenge: This challenge comes from listener Steve Baggish of Arlington, Mass. Take the name of a classic song that became the signature song of the artist who performed it. It has two words; five letters in the first, three letters in the second. The letters can be rearranged to spell two new words. One is a feeling. The other is an expression of that feeling. What song is it? ''' def open_song_list(song_list_file): ''' Opens a file containing song names and returns a list ''' with open(song_list_file) as text_file: song_list = text_file.read().splitlines() return song_list def find_candidates(song_list): ''' Splits each song in the list into a list of words. Checks if the song has two words and if they are the right size. Returns a list of candidate songs ''' candidate_list = [] for song in song_list: song_words = song.split(' ') if (len(song_words) == 2)and(len(song_words[0]) == 5)and(len(song_words[1]) == 3): candidate_list.append(song) return candidate_list def main(): ''' Our main execution function ''' song_file = 'signature_song.txt' top_song_list = open_song_list(song_file) candidate_songs = find_candidates(top_song_list) print(candidate_songs) if __name__ == '__main__': main()
true
7d85e7b88b3ba9ffce5d21164dcbba0fea78aa2c
petrarka/bmstu_tisd
/some files we do/1sem/2/dz2.py
1,357
4.21875
4
# Программа для вычисления квадратного уравнения # Сангинов Азамат ИУ7-11Б from math import sqrt # a, b, c - коэфициенты уравнения # d - дискриминант # x - корень квадратного уравнения print('Квадратное уравнение имеет вид: a*x^2 + b*x + c = 0') a = float(input('Введите коэффициент a: ')) b = float(input('Введите коэффициент b: ')) c = float(input('Введите коэффициент c: ')) # Проверка коэффициентов и вывод результатов if(a != 0): d = b*b - 4*a*c if (d == 0): x = -b/2*a print('Корень кратности 2: x = ','{:.3f}' .format(x)) elif (d > 0): x = (-b + sqrt(d))/2*a print('x1 = ','{:.3f}' .format(x)) x = (-b - sqrt(d))/2*a print('x2 = ','{:.3f}' .format(x)) elif (d < 0): print('Нет действительных решений') elif( a == 0 and b != 0): x = -c/b print('Линейное уравнение: x = ','{:.3f}' .format(x)) elif( a == 0 and b == 0 and c == 0): print('x - любое число') elif( a == 0 and b == 0 and c != 0): print('Нет решений')
false
eb3057689fc57e496ee0e3f64cf50ef1ef723fe1
Cody-Hayes97/Sprint-Challenge--Algorithms
/recursive_count_th/count_th.py
706
4.25
4
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): # return zero if the ength of the word is less than 2 if len(word) < 2: return 0 # if the word begins with th, recurse and search for th given everything in the word after the second index elif word[:2] == "th": return count_th(word[2:]) + 1 # otherwise keep recursing through the word, taking off the first index each time until it matches the above case else: return count_th(word[1:])
true
0a1bf196667cd63dc6f5fe840a88b74aa9593883
RutujaWanjari/Python_Basics
/RenameFileNames/rename_filenames.py
885
4.375
4
# This program demonstrates how to access files from relative path. # Also it changes alphanumeric file names to totally alphabetic names. # To successfully run this program create a directory "AllFiles" and add multiple files with alphanumeric names. from pathlib import Path import os # Path is a class from "pathlib" package. Below we are calling init() function of Path class which initializes it and # makes some memory for our work. p = Path('../RenameFileNames/AllFiles/') def rename(): for x in p.iterdir(): if x.is_file(): print(x.name) file = x.name result = ''.join([i for i in file if not i.isdigit()]) # rename is a function from "os" package rename(os.path.join(p, x.name), os.path.join(p, result)) def print_output(): for x in p.iterdir(): print(x.name) rename() print_output()
true
6d210d6f2ab4cad68112fd06c8704b62352f5d03
DmitryVlaznev/leetcode
/296-reverse-linked-list.py
1,871
4.21875
4
# 206. Reverse Linked List # Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could # you implement both? # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None from typing import List class Solution: @staticmethod def fromArray(values: List) -> ListNode: l = len(values) if not l: return None head = ListNode(values[0]) cur = head for i in range(1, l): cur.next = ListNode(values[i]) cur = cur.next return head @staticmethod def toArray(head: ListNode) -> List: arr = [] cur = head while cur: arr.append(cur.val) cur = cur.next return arr def reverseList(self, head: ListNode) -> ListNode: prev = None cur = head while cur: next = cur.next cur.next = prev prev = cur cur = next return prev def reverseListRecursive(self, head: ListNode) -> ListNode: return self._reverseRecursive(None, head); def _reverseRecursive(self, parent: ListNode, node: ListNode) -> ListNode: if not node: return parent head = self._reverseRecursive(node, node.next) node.next = parent return head test = Solution() # test from-to array print("[] >> ", test.toArray(test.fromArray([]))) print("[1, 2, 3] >> ", test.toArray(test.fromArray([1, 2, 3]))) # test iterative algorithm print("[3, 2, 1] >> ", test.toArray(test.reverseList(test.fromArray([1, 2, 3])))) # test recursive algorithm print("[3, 2, 1] >> ", test.toArray(test.reverseListRecursive(test.fromArray([1, 2, 3]))))
true
020377082a10915fae20031ccf7b0dc1d6424a3b
DmitryVlaznev/leetcode
/328-odd-even-linked-list.py
2,474
4.34375
4
# 328. Odd Even Linked List # Given a singly linked list, group all odd nodes together followed by # the even nodes. Please note here we are talking about the node number # and not the value in the nodes. # You should try to do it in place. The program should run in O(1) space # complexity and O(nodes) time complexity. # Example 1: # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # Example 2: # Input: 2->1->3->5->6->4->7->NULL # Output: 2->3->6->7->1->5->4->NULL # Note: # * The relative order inside both the even and odd groups should remain # as it was in the input. # * The first node is considered odd, the second node even and so on ... from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: @staticmethod def fromArray(values: List) -> ListNode: l = len(values) if not l: return None head = ListNode(values[0]) cur = head for i in range(1, l): cur.next = ListNode(values[i]) cur = cur.next return head @staticmethod def toArray(head: ListNode) -> List: arr = [] cur = head while cur: arr.append(cur.val) cur = cur.next return arr def oddEvenList(self, head: ListNode) -> ListNode: if not head: return head head_odd = head head_even = head_odd.next if not head_even or not head_even.next: return head p_odd = head_odd tail_odd = p_odd p_even = head_even while p_odd: next_odd = p_even.next if p_even else None next_even = next_odd.next if next_odd else None p_odd.next = next_odd if next_odd: tail_odd = next_odd p_odd = next_odd if p_even: p_even.next = next_even p_even = next_even tail_odd.next = head_even return head_odd test = Solution() print("[1, 3, 5, 2, 4] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2, 3, 4, 5])))) print("[1, 3, 2, 4] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2, 3, 4])))) print("[1, 2] >> ", test.toArray(test.oddEvenList(test.fromArray([1, 2])))) print("[1] >> ", test.toArray(test.oddEvenList(test.fromArray([1])))) print("[] >> ", test.toArray(test.oddEvenList(test.fromArray([]))))
true
f542f1f5c756600310e472c711f84dc787cefc2d
DmitryVlaznev/leetcode
/1329-sort-the-matrix-diagonally.py
1,513
4.21875
4
# 1329. Sort the Matrix Diagonally # Medium # A matrix diagonal is a diagonal line of cells starting from some cell # in either the topmost row or leftmost column and going in the # bottom-right direction until reaching the matrix's end. For example, # the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 # matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. # Given an m x n matrix mat of integers, sort each matrix diagonal in # ascending order and return the resulting matrix. # Example 1: # Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] # Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] # Constraints: # m == mat.length # n == mat[i].length # 1 <= m, n <= 100 # 1 <= mat[i][j] <= 100 from typing import List class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: import heapq rows, cols = len(mat), len(mat[0]) r, c = rows - 1, 0 d = [-1, 0] while c < cols: hq = [] ri, ci = r, c while ri < rows and ci < cols: heapq.heappush(hq, mat[ri][ci]) ri += 1 ci += 1 ri, ci = r, c while ri < rows and ci < cols: mat[ri][ci] = heapq.heappop(hq) ri += 1 ci += 1 r += d[0] c += d[1] if r < 0: r, c, d = 0, 1, [0, 1] return mat t = Solution() print(t.diagonalSort([[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]]))
true
c4d5b792263bd949ebe3b6bb5186121c8832307f
DmitryVlaznev/leetcode
/246-strobogrammatic-number.py
1,077
4.15625
4
# 246. Strobogrammatic Number # Easy # Given a string num which represents an integer, return true if num is # a strobogrammatic number. # A strobogrammatic number is a number that looks the same when rotated # 180 degrees (looked at upside down). # Example 1: # Input: num = "69" # Output: true # Example 2: # Input: num = "88" # Output: true # Example 3: # Input: num = "962" # Output: false # Example 4: # Input: num = "1" # Output: true # Constraints: # 1 <= num.length <= 50 # num consists of only digits. # num does not contain any leading zeros except for zero itself. class Solution: def isStrobogrammatic(self, num: str) -> bool: complements = { "1": "1", "6": "9", "8": "8", "9": "6", "0": "0", } p, q = 0, len(num) - 1 while p <= q: if num[p] not in complements or num[q] not in complements: return False if complements[num[p]] != num[q]: return False p, q = p + 1, q - 1 return True
true
2d94fb484758fb8e9d8c079a8cfa4d94fe03ebaf
DmitryVlaznev/leetcode
/702-search-in-a-sorted-array-of-unknown-size.py
1,982
4.125
4
# 702. Search in a Sorted Array of Unknown Size # Given an integer array sorted in ascending order, write a function to # search target in nums. If target exists, then return its index, # otherwise return -1. However, the array size is unknown to you. You # may only access the array using an ArrayReader interface, where # ArrayReader.get(k) returns the element of the array at index k # (0-indexed). # You may assume all integers in the array are less than 10000, and if # you access the array out of bounds, ArrayReader.get will return # 2147483647. # Example 1: # Input: array = [-1,0,3,5,9,12], target = 9 # Output: 4 # Explanation: 9 exists in nums and its index is 4 # Example 2: # Input: array = [-1,0,3,5,9,12], target = 2 # Output: -1 # Explanation: 2 does not exist in nums so return -1 # Constraints: # You may assume that all elements in the array are unique. # The value of each element in the array will be in the range [-9999, 9999]. # The length of the array will be in the range [1, 10^4]. # """ # This is ArrayReader's API interface. # You should not implement it, or speculate about its implementation # """ class ArrayReader: def __init__(self, arr): self.arr = arr def get(self, index: int) -> int: if index >= len(self.arr): return 2147483647 return self.arr[index] from utils import checkValue class Solution: def search(self, reader, target): l, r = -1, 10 ** 4 while r - l > 1: mid = l + (r - l) // 2 if reader.get(mid) >= target: r = mid else: l = mid return r if reader.get(r) == target else -1 t = Solution() reader = ArrayReader([-1, 0, 3, 5, 9, 12]) checkValue(4, t.search(reader, 9)) reader = ArrayReader([-1, 0, 3, 5, 9, 12]) checkValue(-1, t.search(reader, 2)) reader = ArrayReader([34]) checkValue(0, t.search(reader, 34)) reader = ArrayReader([43]) checkValue(-1, t.search(reader, 34))
true
aefd7af360fdf3d158e5be8fdf16a3deb939b6b9
DmitryVlaznev/leetcode
/1423-maximum-points-you-can-obtain-from-cards.py
2,553
4.125
4
# 1423. Maximum Points You Can Obtain from Cards # Medium # There are several cards arranged in a row, and each card has an # associated number of points The points are given in the integer array # cardPoints. # In one step, you can take one card from the beginning or from the end # of the row. You have to take exactly k cards. # Your score is the sum of the points of the cards you have taken. # Given the integer array cardPoints and the integer k, return the # maximum score you can obtain. # Example 1: # Input: cardPoints = [1,2,3,4,5,6,1], k = 3 # Output: 12 # Explanation: After the first step, your score will always be 1. # However, choosing the rightmost card first will maximize your total # score. The optimal strategy is to take the three cards on the right, # giving a final score of 1 + 6 + 5 = 12. # Example 2: # Input: cardPoints = [2,2,2], k = 2 # Output: 4 # Explanation: Regardless of which two cards you take, your score will # always be 4. # Example 3: # Input: cardPoints = [9,7,7,9,7,7,9], k = 7 # Output: 55 # Explanation: You have to take all the cards. Your score is the sum of # points of all cards. # Example 4: # Input: cardPoints = [1,1000,1], k = 1 # Output: 1 # Explanation: You cannot take the card in the middle. Your best score # is 1. # Example 5: # Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3 # Output: 202 # Constraints: # 1 <= cardPoints.length <= 10^5 # 1 <= cardPoints[i] <= 10^4 # 1 <= k <= cardPoints.length from typing import List class Solution: # O(k^2) def maxScore2(self, cardPoints: List[int], k: int) -> int: import functools @functools.lru_cache(maxsize=None) def getMax(start, end, k): if k == 1: return max(cardPoints[start], cardPoints[end]) return max( cardPoints[start] + getMax(start + 1, end, k - 1), cardPoints[end] + getMax(start, end - 1, k - 1), ) return getMax(0, len(cardPoints) - 1, k) # O(k) def maxScore(self, cardPoints: List[int], k: int) -> int: l = len(cardPoints) leftPrefixSum = [0] * (k + 1) rightPrefixSum = [0] * (k + 1) for i in range(1, k + 1): leftPrefixSum[i] = leftPrefixSum[i - 1] + cardPoints[i - 1] rightPrefixSum[i] = rightPrefixSum[i - 1] + cardPoints[l - i] res = 0 for i in range(0, k + 1): res = max(res, leftPrefixSum[i] + rightPrefixSum[k - i]) return res t = Solution() t.maxScore([1, 2, 3, 4, 5, 6, 1], 3)
true
284ec6e03f5edb54d8ba5903235f37a74a4d4b32
DmitryVlaznev/leetcode
/902-numbers-at-most-n-given-digit-set.py
1,719
4.21875
4
# 902. Numbers At Most N Given Digit Set # Hard # Given an array of digits, you can write numbers using each digits[i] # as many times as we want. For example, if digits = ['1','3','5'], we # may write numbers such as '13', '551', and '1351315'. # Return the number of positive integers that can be generated that are # less than or equal to a given integer n. # Example 1: # Input: digits = ["1","3","5","7"], n = 100 # Output: 20 # Explanation: # The 20 numbers that can be written are: # 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. # Example 2: # Input: digits = ["1","4","9"], n = 1000000000 # Output: 29523 # Explanation: # We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, # 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, # 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. # In total, this is 29523 integers that can be written using the digits array. # Example 3: # Input: digits = ["7"], n = 8 # Output: 1 # Constraints: # 1 <= digits.length <= 9 # digits[i].length == 1 # digits[i] is a digit from '1' to '9'. # All the values in digits are unique. # 1 <= n <= 109 class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: n_as_string = str(n) n_length = len(n_as_string) dp = [0] * n_length + [1] for i in range(n_length - 1, -1, -1): for d in digits: if d < n_as_string[i]: dp[i] += len(digits) ** (n_length - i - 1) elif d == n_as_string[i]: dp[i] += dp[i + 1] return dp[0] + sum(len(digits) ** i for i in range(1, n_length))
true
aa350a3b28ad670e494ba35e8865ad519ecb1f14
DmitryVlaznev/leetcode
/701-insert-into-a-binary-search-tree.py
2,224
4.1875
4
# Insert into a Binary Search Tree # You are given the root node of a binary search tree (BST) and a value # to insert into the tree. Return the root node of the BST after the # insertion. It is guaranteed that the new value does not exist in the # original BST. # Notice that there may exist multiple valid ways for the insertion, as # long as the tree remains a BST after insertion. You can return any of # them. # Example 1: # Input: root = [4,2,7,1,3], val = 5 # Output: [4,2,7,1,3,5] # Explanation: Another accepted tree is: # Example 2: # Input: root = [40,20,60,10,30,50,70], val = 25 # Output: [40,20,60,10,30,50,70,null,null,25] # Example 3: # Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 # Output: [4,2,7,1,3,5] # Constraints: # The number of nodes in the tree will be in the range [0, 104]. # -108 <= Node.val <= 108 # All the values Node.val are unique. # -108 <= val <= 108 # It's guaranteed that val does not exist in the original BST. from utils import TreeNode, checkList, treeFromArray, treeToArray class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: p = root if not p: return TreeNode(val) while(True): if p.val < val: if not p.right: p.right = TreeNode(val) break else: p = p.right else: if not p.left: p.left = TreeNode(val) break else: p = p.left return root # checkList([4,2,7,1,3], treeToArray(treeFromArray([4,2,7,1,3], 0))) # checkList([40,20,60,10,30,50,70], treeToArray(treeFromArray([40,20,60,10,30,50,70], 0))) # checkList([40,20,60,10,30,50,70,None,None,25], treeToArray(treeFromArray([40,20,60,10,30,50,70,None,None,25], 0))) t = Solution() checkList([4,2,7,1,3,5], treeToArray(t.insertIntoBST(treeFromArray([4,2,7,1,3], 0), 5))) checkList([40,20,60,10,30,50,70,None,None,25], treeToArray(t.insertIntoBST(treeFromArray([40,20,60,10,30,50,70], 0), 25))) checkList([42], treeToArray(t.insertIntoBST(None, 42))) checkList([4,2,7,1,3,5], treeToArray(t.insertIntoBST(treeFromArray([4,2,7,1,3,None,None,None,None,None,None], 0), 5)))
true
665b37f3e85a2bdffac567069351cfb071b1322e
DmitryVlaznev/leetcode
/970-powerful-integers.py
1,683
4.15625
4
# 970. Powerful Integers # Medium # Given three integers x, y, and bound, return a list of all the # powerful integers that have a value less than or equal to bound. # An integer is powerful if it can be represented as x^i + y^j for some # integers i >= 0 and j >= 0. # You may return the answer in any order. In your answer, each value # should occur at most once. # Example 1: # Input: x = 2, y = 3, bound = 10 # Output: [2,3,4,5,7,9,10] # Explanation: # 2 = 2^0 + 3^0 # 3 = 2^1 + 3^0 # 4 = 2^0 + 3^1 # 5 = 2^1 + 3^1 # 7 = 2^2 + 3^1 # 9 = 2^3 + 3^0 # 10 = 2^0 + 3^2 # Example 2: # Input: x = 3, y = 5, bound = 15 # Output: [2,4,6,8,10,14] # Constraints: # 1 <= x, y <= 100 # 0 <= bound <= 10^6 from typing import List from utils import checkList class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: yy = [1] if y > 1: c = 1 while c < bound: yy.append(c) c *= y res = set() c = 1 while c < bound: p = 0 while p < len(yy) and c + yy[p] <= bound: res.add(c + yy[p]) p += 1 c *= x if x > 1 else float("inf") return list(res) t = Solution() checkList([2, 3, 4, 5, 7, 9, 10], sorted(t.powerfulIntegers(2, 3, 10))) checkList([2, 4, 6, 8, 10, 14], sorted(t.powerfulIntegers(3, 5, 15))) checkList([], sorted(t.powerfulIntegers(3, 5, 0))) checkList([], sorted(t.powerfulIntegers(3, 5, 1))) checkList([2], sorted(t.powerfulIntegers(3, 5, 2))) checkList([2], sorted(t.powerfulIntegers(3, 5, 2))) checkList([2, 3, 5, 9, 17, 33, 65], sorted(t.powerfulIntegers(1, 2, 100)))
true
6ad55eb0f4b036b0c33b0f00dc24de6cd29714cb
DmitryVlaznev/leetcode
/116-populating-next-right-pointers-in-each-node.py
2,141
4.125
4
# 116. Populating Next Right Pointers in Each Node # You are given a perfect binary tree where all leaves are on the same # level, and every parent has two children. The binary tree has the # following definition: # struct Node { # int val; # Node *left; # Node *right; # Node *next; # } # Populate each next pointer to point to its next right node. If there # is no next right node, the next pointer should be set to NULL. # Initially, all next pointers are set to NULL. # Follow up: # You may only use constant extra space. # Recursive approach is fine, you may assume implicit stack space does # not count as extra space for this problem. # Example 1: # Input: root = [1,2,3,4,5,6,7] # Output: [1,#,2,3,#,4,5,6,7,#] # Explanation: Given the above perfect binary tree (Figure A), your # function should populate each next pointer to point to its next right # node, just like in Figure B. The serialized output is in level order # as connected by the next pointers, with '#' signifying the end of each # level. # Constraints: # The number of nodes in the given tree is less than 4096. # -1000 <= node.val <= 1000 # Definition for a Node. class Node: def __init__( self, val: int = 0, left: "Node" = None, right: "Node" = None, next: "Node" = None, ): self.val = val self.left = left self.right = right self.next = next class Solution: def connect(self, root: "Node") -> "Node": if not root: return None from collections import deque dq = deque() dq.append(root) while dq: l = len(dq) last_sibling = dq.popleft() if last_sibling.left: dq.append(last_sibling.left) dq.append(last_sibling.right) l -= 1 while l: n = dq.popleft() last_sibling.next = n last_sibling = n l -= 1 if last_sibling.left: dq.append(last_sibling.left) dq.append(last_sibling.right) return root
true
e4f730d10a30032bce93d1b61c55e741cde27889
DmitryVlaznev/leetcode
/1704-determine-if-string-halves-are-alike.py
1,730
4.15625
4
# 1704. Determine if String Halves Are Alike # Easy # You are given a string s of even length. Split this string into two # halves of equal lengths, and let a be the first half and b be the # second half. # Two strings are alike if they have the same number of vowels ('a', # 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains # uppercase and lowercase letters. # Return true if a and b are alike. Otherwise, return false. # Example 1: # Input: s = "book" # Output: true # Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. # Therefore, they are alike. # Example 2: # Input: s = "textbook" # Output: false # Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. # Therefore, they are not alike. # Notice that the vowel o is counted twice. # Example 3: # Input: s = "MerryChristmas" # Output: false # Example 4: # Input: s = "AbCdEfGh" # Output: true # Constraints: # 2 <= s.length <= 1000 # s.length is even. # s consists of uppercase and lowercase letters. class Solution: def halvesAreAlike2(self, s: str) -> bool: vowels = set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) mid = len(s) // 2 left = right = 0 for l in s[0:mid]: if l in vowels: left += 1 for l in s[mid:]: if l in vowels: right += 1 return left == right def halvesAreAlike(self, s: str) -> bool: vowels = set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]) v = 0 for i in range(len(s)): d = -1 if i >= len(s) // 2 else 1 if s[i] in vowels: v += d return v == 0 t = Solution() t.halvesAreAlike("Ieai")
true
9e0bd15c3f7a2e572618ffc85fdffde3d8579b0a
MicheSi/cs-bw-unit2
/balanced_brackets.py
2,142
4.125
4
''' Write function that take string as input. String can contain {}, [], (), || Function return boolean indicating whether or not string is balance ''' table = { ')': '(', ']':'[', '}':'{' } for _ in range(int(input())): stack = [] for x in input(): if stack and table.get(x) == stack[-1]: stack.pop() else: stack.append(x) print("NO" if stack else "YES") open_list = ["[","{","("] close_list = ["]","}",")"] # Function to check parentheses def check(myStr): stack = [] for i in myStr: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if ((len(stack) > 0) and (open_list[pos] == stack[len(stack)-1])): stack.pop() else: return "Unbalanced" if len(stack) == 0: return "Balanced" else: return "Unbalanced" def isBalanced(expr): if len(expr)%2!=0: return False opening=set('([{') match=set([ ('(',')'), ('[',']'), ('{','}') ]) stack=[] for char in expr: if char in opening: stack.append(char) else: if len(stack)==0: return False lastOpen=stack.pop() if (lastOpen, char) not in match: return False return len(stack)==0 def is_matched(expression): if len(expression) % 2 != 0: return False opening = ("(", "[", "{") closing = (")", "]", "}") mapping = {opening[0]:closing[0], opening[1]:closing[1], opening[2]:closing[2]} if expression[0] in closing: return False if expression[-1] in opening: return False closing_queue = [] for letter in expression: if letter in opening: closing_queue.append(mapping[letter]) elif letter in closing: if not closing_queue: return False if closing_queue[-1] == letter: closing_queue.pop() else: return False return True
true
c317269d86f21534edc00ce2e66e14e2e3b790bd
MicheSi/cs-bw-unit2
/search_insert_position.py
1,016
4.125
4
''' Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 ''' class Solution: def searchInsert(self, nums: List[int], target: int) -> int: # use binary search to loop through array start = 0 end = len(nums) - 1 while start <= end: mid = (start + end) // 2 # if middle num is target, return it's index if nums[mid] == target: return mid # if middle num < target, move to 2nd half of array if nums[mid] < target: start = mid + 1 # target doesn't exit, add it to end of array else: end = mid - 1 return start
true
88cf81dc127010d9bec8fd09d916a1ddeee26a8e
akimi-yano/algorithm-practice
/tutoring/mockClassmates/officehour_mock2.py
819
4.28125
4
# Valid Palindrome Removal # Return true if the input is a palindrome, or can be a palindrome with no more than one character deletion. # Zero characters can be added. # Return false if the input is not a palindrome and removing any one character from it would not make it a palindrome. # Must be done in constant space and linear time. # Example input 1: 'bbabac' # output: true # Deleting either a letter b or the letter c would make this a palindrome if it were reordered correctly. # Example input 2: 'carracers' # output: carerac rc false def is_palin(s): memo = {} for c in s: if c not in memo: memo[c]=1 else: memo[c]+=1 odd_counter = 0 for v in memo.values(): if v%2!=0: odd_counter+=1 return odd_counter<3 print(is_palin('bbabac')) print(is_palin('carracers'))
true
2b0f70093994c026f521f5936967fcc887c74444
akimi-yano/algorithm-practice
/lc/1870.MinimumSpeedToArriveOnTime.py
2,783
4.21875
4
# 1870. Minimum Speed to Arrive on Time # Medium # 152 # 49 # Add to List # Share # You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. # Each train can only depart at an integer hour, so you may need to wait in between each train ride. # For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark. # Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. # Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. # Example 1: # Input: dist = [1,3,2], hour = 6 # Output: 1 # Explanation: At speed 1: # - The first train ride takes 1/1 = 1 hour. # - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. # - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. # - You will arrive at exactly the 6 hour mark. # Example 2: # Input: dist = [1,3,2], hour = 2.7 # Output: 3 # Explanation: At speed 3: # - The first train ride takes 1/3 = 0.33333 hours. # - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. # - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. # - You will arrive at the 2.66667 hour mark. # Example 3: # Input: dist = [1,3,2], hour = 1.9 # Output: -1 # Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. # Constraints: # n == dist.length # 1 <= n <= 105 # 1 <= dist[i] <= 105 # 1 <= hour <= 109 # There will be at most two digits after the decimal point in hour. # This solution works: class Solution: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: def helper(speed): total = 0 for i in range(len(dist) - 1): way = dist[i] total += math.ceil(way/speed) total += dist[-1]/speed return total <= hour left = 1 right = 10**7 while left < right: mid = (left+right)//2 if helper(mid): right = mid else: left = mid+1 return left if helper(left) else -1
true
683bd029ec511e1c2868af454303d95065e93c23
akimi-yano/algorithm-practice
/lc/438.FindAllAnagramsInAString.py
1,687
4.25
4
# 438. Find All Anagrams in a String # Medium # 6188 # 235 # Add to List # Share # Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # Example 1: # Input: s = "cbaebabacd", p = "abc" # Output: [0,6] # Explanation: # The substring with start index = 0 is "cba", which is an anagram of "abc". # The substring with start index = 6 is "bac", which is an anagram of "abc". # Example 2: # Input: s = "abab", p = "ab" # Output: [0,1,2] # Explanation: # The substring with start index = 0 is "ab", which is an anagram of "ab". # The substring with start index = 1 is "ba", which is an anagram of "ab". # The substring with start index = 2 is "ab", which is an anagram of "ab". # Constraints: # 1 <= s.length, p.length <= 3 * 104 # s and p consist of lowercase English letters. # This soluion works: from collections import Counter class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: goal= Counter(p) cur = Counter() ans = [] count = 0 for i in range(len(s)): cur[s[i]] += 1 count += 1 if count == len(p): if goal == cur: ans.append(i+1-count) cur[s[i+1-count]] -= 1 count -=1 return ans ''' s "cbaebabacd" p "abc" goal {a:1, b:1, c:0} cur {c:1, b:1, a:1} ans [] count 0 1 2 '''
true
beda2c8b84bfa3be65e93edacf33c71c524f2718
akimi-yano/algorithm-practice
/lc/isTreeSymmetric.py
2,043
4.34375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 101. Symmetric Tree # Easy # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.traverse(root.left, root.right) def traverse(self, left, right): if left is None or right is None: return left is None and right is None return left.val == right.val and self.traverse(left.left, right.right) and self.traverse(left.right, right.left) # the solution below did not work for cases where there are null and structure is not even # class Solution: # def __init__(self): # self.leftArr=[] # self.rightArr=[] # def isSymmetric(self, root: TreeNode) -> bool: # if root is None: # return True # print(self.leftInorder(root.left,self.leftArr)) # print(self.rightReverseInorder(root.right,self.rightArr)) # if len(self.leftArr)!= len(self.rightArr): # return False # for i in range(len(self.leftArr)): # if self.leftArr[i]!=self.rightArr[i]: # return False # return True # def leftInorder(self, current, arr): # if current is None: # return self.leftArr # self.leftInorder(current.left,arr) # self.leftArr.append(current.val) # self.leftInorder(current.right,arr) # return self.leftArr # def rightReverseInorder(self, current, arr): # if current is None: # return self.rightArr # self.rightReverseInorder(current.right,arr) # self.rightArr.append(current.val) # self.rightReverseInorder(current.left,arr) # return self.rightArr
true
0f4bfcbc1f59afbb95c2a2d112b72e1f34c798d0
akimi-yano/algorithm-practice
/lc/111.MinimumDepthOfBinaryTree.py
2,149
4.125
4
# 111. Minimum Depth of Binary Tree # Easy # 1823 # 759 # Add to List # Share # Given a binary tree, find its minimum depth. # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # Note: A leaf is a node with no children. # Example 1: # Input: root = [3,9,20,null,null,15,7] # Output: 2 # Example 2: # Input: root = [2,null,3,null,4,null,5,null,6] # Output: 5 # Constraints: # The number of nodes in the tree is in the range [0, 105]. # -1000 <= Node.val <= 1000 ''' since the definition of leef is not having left or right child, we need to find the min level in which the node does not have right node or left node I did BFS using queue to find that, keeping track of the level ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 queue = deque([(root, 1)]) while queue: node, level = queue.popleft() if not node.left and not node.right: return level if node.left: queue.append((node.left, level+1)) if node.right: queue.append((node.right, level+1)) ''' I can do this using DFS as well !!! ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: def helper(cur): if not cur.left and not cur.right: return 1 left = right = float('inf') if cur.left: left = helper(cur.left) if cur.right: right = helper(cur.right) return min(left,right) +1 if not root: return 0 return helper(root)
true
a770ed5446cb22606122f0d55488d58aff374679
akimi-yano/algorithm-practice
/examOC/examWeek1.py
2,868
4.15625
4
# Week1 Exam # Complete the 'mergeArrays' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # merge two sorted arrays def mergeArrays(a, b): ans = [] i = 0 k = 0 while len(a)>i and len(b)>k: if a[i]>= b[k]: ans.append(b[k]) k+=1 else: ans.append(a[i]) i+=1 while len(b)>k: ans.append(b[k]) k+=1 while len(a)>i: ans.append(a[i]) i+=1 return ans # # Complete the 'dnaComplement' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # AT are complement # CG are complement # Rotate the input string and swap each element with its complement # return string def dnaComplement(s): ans="" for i in range(len(s)-1,-1,-1): if s[i] == "A": ans+="T" elif s[i] == "T": ans+="A" elif s[i] == "C": ans+="G" else: ans+="C" return ans # # Complete the 'minimumStepsToOne' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER num as parameter. # # take aways:::: output has to be a variable name that is different from the input !! # //recursion passing in count - dont do it if you want to turn it into memorization # def minimumStepsToOne(num): # def helper(n,count): # if n == 1: # return count # new_count = helper(n-1,count+1) # if n%2==0: # new_count = min(new_count,helper(n//2,count+1)) # if n%3==0: # new_count = min(new_count,helper(n//3,count+1)) # return new_count # return helper(num,0) # print(minimumStepsToOne(4)) # print(minimumStepsToOne(3)) # print(minimumStepsToOne(2)) # //memorization solution - still hit the max recursion depth # def minimumStepsToOne(num): # memo = {} # def helper(n): # if n in memo: # return memo[n] # if n == 1: # return 0 # new_count = 1 + helper(n-1) # if n%2==0: # new_count = min(new_count,1 + helper(n//2)) # if n%3==0: # new_count = min(new_count,1 + helper(n//3)) # memo[n] = new_count # return new_count # return helper(num) # print(minimumStepsToOne(4)) # print(minimumStepsToOne(3)) # print(minimumStepsToOne(2)) # print(minimumStepsToOne(5400)) # // tabulation solution def minimumStepsToOne(num): tab = {1: 0} for n in range(2,num+1): temp = tab[n-1] if n%2==0: temp = min(temp,tab[n//2]) if n%3==0: temp = min(temp,tab[n//3]) temp +=1 tab[n]=temp return tab[num] print(minimumStepsToOne(8))
true
94d942c6bc11ceb1a8919f193e31a186f1a90658
akimi-yano/algorithm-practice
/lc/154.FindMinimumInRotatedSortedAr.py
2,593
4.15625
4
# 154. Find Minimum in Rotated Sorted Array II # Hard # 2147 # 315 # Add to List # Share # Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: # [4,5,6,7,0,1,4] if it was rotated 4 times. # [0,1,4,4,5,6,7] if it was rotated 7 times. # Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. # Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. # You must decrease the overall operation steps as much as possible. # Example 1: # Input: nums = [1,3,5] # Output: 1 # Example 2: # Input: nums = [2,2,2,0,1] # Output: 0 # Constraints: # n == nums.length # 1 <= n <= 5000 # -5000 <= nums[i] <= 5000 # nums is sorted and rotated between 1 and n times. # Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why? # This solution works: ''' The idea is to use Binary Search, but here we can have equal numbers, so sometimes we need to find our minimum not in one half, but in two halves. Let us consider several possible cases of values start, mid and end. nums[start] < nums[mid] < nums[end], for example 0, 10, 20. In this case we need to search only in left half, data is not shifted. nums[mid] < nums[end] < nums[start], for example 20, 0, 10. In this case data is shifted and we need to search in left half. nums[end] < nums[start] < nums[mid], for example 10, 20, 0. In this case data is shifted and we need to search in right half. nums[end] = nums[mid], it this case we need to check the value of nums[start], and strictly speaking we not always need to search in two halves, but I check in both for simplicity of code. Complexity: time complexity is O(log n) if there are no duplicates in nums. If there are duplicates, then complexity can be potentially O(n), for cases like 1,1,1,...,1,2,1,1,....1,1. Additional space complexity is O(1). ''' class Solution: def findMin(self, nums): def bin_dfs(start, end): if end - start <= 1: self.Min = min(nums[start], nums[end], self.Min) return mid = (start + end)//2 if nums[end] <= nums[mid]: bin_dfs(mid + 1, end) if nums[end] >= nums[mid]: bin_dfs(start, mid) self.Min = float("inf") bin_dfs(0, len(nums) - 1) return self.Min
true
448467cb0445f9e81c67e1c29ff29d4545a47b88
akimi-yano/algorithm-practice
/lc/UniquePaths.py
2,518
4.40625
4
# latice path unique path problems are different problems ! # difference : # lattice path - counting the edges # robot unique path - counting the boxes (so -1) # also for lattice path, # instead of doing this ---- # if m == 0 and n == 0: # return 1 # elif m<0 or n<0: # return 0 # you can just do this --- which is more efficient # if m == 0 or n == 0: # return 1 # 1. Lattice Paths # # Prompt: Count the number of unique paths to travel from the top left # corder to the bottom right corner of a lattice of M x N squares. # # When moving through the lattice, one can only travel to the # adjacent corner on the right or down. # # Input: m {Integer} - rows of squares # Input: n {Integer} - column of squares # Output: {Integer} # # Example: input: (2, 3) # # (2 x 3 lattice of squares) # __ __ __ # |__|__|__| # |__|__|__| # # output: 10 (number of unique paths from top left corner to bottom right) # # Resource: https://projecteuler.net/problem=15 # def latticePaths(m, n): # if m == 0 and n == 0: # return 1 # elif m<0 or n<0: # return 0 # return latticePaths(m-1, n) + latticePaths(m,n-1) # # Write your code here # print(latticePaths(2,2)) # print(latticePaths(2,3)) def latticePaths(m, n): if m == 0 or n == 0: return 1 return latticePaths(m-1, n) + latticePaths(m,n-1) # Write your code here print(latticePaths(2,2)) print(latticePaths(2,3)) # 2.Unique Paths # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach # the bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? # Above is a 7 x 3 grid. How many possible unique paths are there? # Example 1: # Input: m = 3, n = 2 # Output: 3 # Explanation: # From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: # 1. Right -> Right -> Down # 2. Right -> Down -> Right # 3. Down -> Right -> Right class Solution: def __init__(self): self.memo = {} def uniquePaths(self, m: int, n: int) -> int: if m==1 or n==1: return 1 if (m, n) not in self.memo: self.memo[(m, n)] = self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1) return self.memo[(m, n)]
true
201e5eb0545be43fceece844312c43566b1e0818
akimi-yano/algorithm-practice
/oc/328_Odd_Even_Linked_List.py
2,239
4.1875
4
# 328. Odd Even Linked List ''' Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Time O(N) Space O(1) Example 1: index. 1 2. 3. 4. 5 Input: 1->2->3->4->5->NULL 1. 3. 5. 2 4 Output: 1->3->5->2->4->NULL Example 2: 1 2. 3. 4. 5 Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL ''' # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next ''' ex1) 1 2 3 4 5 [1][2][3][4][5] odd -> even 1 3 5 2 4 none ex2) 2 1 3 5 6 4 7 [1][2][3][4][5][6][7] 2 3 6 7 1 5 4 [1][3][5][7][2][4][6] possible edge case: head node could be none 0<len<10,000 return head node Time O(N) Space O(1) 1 - check which one is odd and even - temp_odd - first node - tail temp_even - second node 2 merge the 2 temp ones and return head head ---> result_head = odd even_head = even connect temp odd tail and head of the temp even ''' # incomplete code # def oddEvenList(self, head: ListNode) -> ListNode: # if head is None: # return None # temp_odd = odd_tail = head # temp_even = even_tail = head.next # result_head = odd. ----> return # even_head = even. ---> join # runner = head.next.next # counter = 3 # while runner is not None: # if counter%2!=0: # odd_tail.next = runner # odd_tail = odd_tail.next # else: # even_tail.next = runner # even_tail = even_tail.next # runner = runner.next # solution that works ! def oddEvenList(self, head: ListNode) -> ListNode: if not head: return None odd = head even = head.next result_head = odd even_head = even while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return result_head # print(oddEvenList())
true
241ca9304d4b204bfa717ea366abdb73046e7547
akimi-yano/algorithm-practice
/lc/1338.ReduceArraySizeToTheHalf.py
1,686
4.15625
4
# 1338. Reduce Array Size to The Half # Medium # 767 # 64 # Add to List # Share # Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. # Return the minimum size of the set so that at least half of the integers of the array are removed. # Example 1: # Input: arr = [3,3,3,3,5,5,5,2,2,7] # Output: 2 # Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). # Possible sets of size 2 are {3,5},{3,2},{5,2}. # Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array. # Example 2: # Input: arr = [7,7,7,7,7,7] # Output: 1 # Explanation: The only possible set you can choose is {7}. This will make the new array empty. # Example 3: # Input: arr = [1,9] # Output: 1 # Example 4: # Input: arr = [1000,1000,3,7] # Output: 1 # Example 5: # Input: arr = [1,2,3,4,5,6,7,8,9,10] # Output: 5 # Constraints: # 1 <= arr.length <= 10^5 # arr.length is even. # 1 <= arr[i] <= 10^5 # This solution works: class Solution: def minSetSize(self, arr: List[int]) -> int: counts = {} for num in arr: if num not in counts: counts[num] = 0 counts[num] += 1 nums = list(counts.values()) nums.sort() cur_size = len(arr) goal_size = cur_size // 2 removed = 0 while nums and cur_size > goal_size: len_lost = nums.pop() cur_size -= len_lost removed += 1 return removed
true
323585745e2d7f83533a0c8b7273619c21b8ff2b
akimi-yano/algorithm-practice
/lc/1936.AddMinimumNumberOfRungs.py
2,606
4.28125
4
# 1936. Add Minimum Number of Rungs # Medium # 123 # 9 # Add to List # Share # You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. # You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. # Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. # Example 1: # Input: rungs = [1,3,5,10], dist = 2 # Output: 2 # Explanation: # You currently cannot reach the last rung. # Add rungs at heights 7 and 8 to climb this ladder. # The ladder will now have rungs at [1,3,5,7,8,10]. # Example 2: # Input: rungs = [3,6,8,10], dist = 3 # Output: 0 # Explanation: # This ladder can be climbed without adding additional rungs. # Example 3: # Input: rungs = [3,4,6,7], dist = 2 # Output: 1 # Explanation: # You currently cannot reach the first rung from the ground. # Add a rung at height 1 to climb this ladder. # The ladder will now have rungs at [1,3,4,6,7]. # Example 4: # Input: rungs = [5], dist = 10 # Output: 0 # Explanation: # This ladder can be climbed without adding additional rungs. # Constraints: # 1 <= rungs.length <= 105 # 1 <= rungs[i] <= 109 # 1 <= dist <= 109 # rungs is strictly increasing. # This solution works: class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: cur = 0 ans = 0 for rung in rungs: if cur+dist<rung: ans += (rung-cur-1) // dist cur = rung return ans # This solution also works: class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: ''' [1,3,5,10], dist = 2 0 1 3 5 7 9 [4,8,12,16] 3 0 3 (+1) 7 (+1) 11 (+1) 15 (+1) 0 3 (+1) ''' print("PPPP") cur = 0 ans = 0 for rung in rungs: # while cur + dist < rung: # ans += 1 # cur += dist # dist * x + cur = rung // dist # x = (-cur +rung)//dist if cur+dist<rung: ans += math.ceil((rung-cur) / dist)-1 cur = rung return ans
true
a316b2d14a524e00985fd59c54d58595f3c2c4a7
ARWA-ALraddadi/python-tutorial-for-beginners
/02-How to Use Pre-defined Functions Demos/2-random_numbers.py
1,626
4.53125
5
#--------------------------------------------------------------------- # Demonstration - Random Numbers # # The trivial demonstrations in this file show how the # functions from the "random" module may produce a different # result each time they're called # Normally when we call a function with the same parameters # it produces the same answer print('The maximum of 3 and 9 is', max(3, 9)) print('The maximum of 3 and 9 is still', max(3, 9)) print('The maximum of 3 and 9 remains', max(3, 9)) print() # The random functions are the exception because they may # produce a different result each time they're called from random import randint print('A random number between 3 and 9 is', randint(3, 9)) print('Another random number between 3 and 9 is', randint(3, 9)) print('A third random number between 3 and 9 is', randint(3, 9)) print() # As a slightly more realistic example, imagine that you # needed to schedule a meeting on a certain day. Any time # between 9am and 4pm is available except 12pm, when you # have lunch. The following code will produce a random # time for the meeting that never conflicts with your # lunch break. The outcome is printed in 24-hour time. from random import choice # Pick a time between 9am and 11am, inclusive morning_time = randint(9, 11) morning_option = str(morning_time) + 'am' # Pick a time between 1pm and 4pm, inclusive afternoon_time = randint(1, 4) afternoon_option = str(afternoon_time) + 'pm' # Choose between the morning and afternoon options final_choice = choice([morning_option, afternoon_option]) #Display the outcome print("We'll meet at", final_choice)
true
15e88757e99a4285445e4641ff9e86df0c9ff134
ARWA-ALraddadi/python-tutorial-for-beginners
/03-Workshop/Workshop-Solutions/fun_with_flags.py
1,564
4.28125
4
#-------------------------------------------------------------------- # # Fun With Flags # # In the lecture demonstration program "stars and stripes" we saw # how function definitions allowed us to reuse code that drew a # star and a rectangle (stripe) multiple times to create a copy of # the United States flag. # # As a further example of the way functions allow us to reuse code, # in this exercise we will import the flag_elements module into # this program and create a different flag. In the PDF document # accompanying this file you will find several flags which can be # constructed easily using the "star" and "stripe" functions already # defined. Choose one of these and try to draw it. # # First we import the two functions we need (make sure a copy of file # flag_elements.py is in the same folder as this one) from flag_elements import star, stripe # Import the turtle graphics functions from turtle import * # Here we draw the Panamanian flag as an illustration. # # Comment: Since this is such a small example, we've hardwired all # the numeric constants below. For non-trivial programs, however, # such "magic numbers" (i.e., unexplained numeric values) are best # avoided. Named, fixed values should be defined instead. # Set up the drawing environment setup(600, 400) bgcolor("white") title("Panama") penup() # Draw the two rectangles goto(0, 200) stripe(300, 200, "red") goto(-300, 0) stripe(300, 200, "blue") # Draw the two stars goto(-150, 140) star(80, "blue") goto(150, -60) star(80, "red") # Exit gracefully hideturtle() done()
true
de5d83e72f9e97e33665e635fd5099dcfb4bec07
ARWA-ALraddadi/python-tutorial-for-beginners
/06-How to Create User Interfaces Demos/02-frustrating_button.py
1,076
4.40625
4
#---------------------------------------------------------------- # # Frustrating button # # A very simple demonstration of a Graphical User Interface # created using Tkinter. It creates a window with a label # and a frustrating button that does nothing. # # Import the Tkinter functions from tkinter import * # Create a window the_window = Tk() # Give the window a title the_window.title('Tk demo') # Create a label widget (some fixed text) whose parent # container is the window the_label = Label(the_window, text = ' Frustration! ', font = ('Arial', 32)) # Create a button widget whose parent container is the # window (the button's text turns red when active) the_button = Button(the_window, text = ' Push me ', activeforeground = 'red', font = ('Arial', 28)) # Call the geometry manager to "pack" the widgets onto # the window (using default settings for now) the_label.pack() the_button.pack() # Start the event loop to react to user inputs (in this # case by doing nothing at all) the_window.mainloop()
true
d49423bc7fc93a65763555efc2a9e6aec0ccf1a1
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V5.py
2,361
4.46875
4
#--------------------------------------------------------------------# # # Mars lander example - Exception handling # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # In this version exception handling code is added to the # main loop to catch any kind of altimeter failure and # respond with a default action. # # Import the regular expression match function from re import match # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Assertion to raise an exception if air pressure is negative assert barometer_reading >= 0, 'Barometer failure detected!' # Return the result (if we make it this far!) return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude > 0: # The default action for any kind of altimeter failure # is to assume we are at a low altitude - it's better # to waste fuel than crash! try: # Calculate the lander's altitude, if possible altitude = altimeter(int(input('Enter barometer reading: '))) except ValueError: print('** Altimeter type error - Firing retros! **') retros_on() except AssertionError: print('** Altimeter range error - Firing retros! **') retros_on() else: # Decide whether or not the retros should be firing if altitude <= 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true
15eaf7c1be83f2636e171211a049ceda21eb2fe5
ARWA-ALraddadi/python-tutorial-for-beginners
/03-Workshop/Workshop-Solutions/olympic_rings.py
2,327
4.5625
5
#------------------------------------------------------------------------- # # Olympic Rings # # In this folder you will find a file "olympic_rings.pdf" which shows # the flag used for the Olympics since 1920. Notice that this flag # consists of five rings that differ only in their position and colour. # If we want to draw it using Turtle graphics it would therefore be # a good idea to define a function that draws one ring and reuse it # five times. # # Complete the code below to produce a program that draws a reasonable # facsimile of the Olympic flag. (NB: In the real flag the rings are # interlocked. Don't try to reproduce this tricky feature, just draw # rings that overlap.) # #------------------------------------------------------------------------- # Step 1: Function definition # # Define a function called "ring" that takes three parameters, an # x-coordinate, a y-coordinate and a colour. When called this function # should draw an "olympic ring" of the given colour centred on the # given coordinates. (Note that Turtle graphic's "circle" function # draws a circle starting from the cursor's current position, not # centred on the cursor's position.) Since all the circles are the # same size you can define the radius and thickness of the circle # within the function def olympic_ring(x_coord, y_coord, colour): ring_radius, ring_width = 110, 20 # pixels penup() goto(x_coord + ring_radius, y_coord) # easternmost point setheading(90) # face north width(ring_width) color(colour) pendown() circle(ring_radius) # walk in a circle to create the ring #------------------------------------------------------------------------- # Step 2: Calling the function # # Now write code to call the function five times, each time with # different coordinates and colours, to create the flag. To get # you started we have provided some of the Turtle framework. # Import the Turtle functions from turtle import * # Create the drawing window setup(1000, 650) title('"... and it\'s gold, Gold, GOLD for Australia!"') # Draw the five rings olympic_ring(-250, 60, "blue") olympic_ring(0, 60, "black") olympic_ring(250, 60, "red") olympic_ring(-125, -60, "yellow") olympic_ring(125, -60, "green") # Shut down the drawing window hideturtle() done()
true
43aaf6575d5a423e006fbe4360972d2868e7a8ff
ARWA-ALraddadi/python-tutorial-for-beginners
/08-How to Find Things Demos/08-replacing_patterns.py
2,598
4.3125
4
## Replacing patterns ## ## The small examples in this demonstration show how regular ## expressions with backreferences can be used to perform ## automatic modifications of text. from re import sub ## This example shows how to "normalise" a data representation. ## A common problem at QUT is that student numbers are ## represented in different ways, either n7654321, N7654321, ## 07654321 or 7654321. Here we show how to change all student ## numbers in some text into a common zero-prefixed format. ## (The pattern used is not very robust; it is reliable only ## if there are no numbers other than student numbers in the ## text.) student_nos = \ '''Student 02723957 is to be commended for high quality work and similarly for student n1234234, but student 1129988 needs to try harder.''' print(sub('[nN0]?([0-9]{7})', r'0\1', student_nos)) # prints "Student 02723957 is to be commended for high quality # work and similarly for student 01234234, but student # 01129988 needs to try harder." print() ## As another example of substitution and backreferencing, we ## return to the copyeditor's problem of identifying accidently ## duplicated words in text. Not all such phrases are mistakes ## so they need to be checked manually. The following script ## identifies doubled-words as before, but now surrounds them with ## asterisks to draw them to the attention of the proofreader. ## It also allows the two words to be separated by not only ## blank spaces but newline characters because such errors ## often occur at line breaks. Notice that both ends of the ## pattern are required to contain non-alphabetic characters to ## ensure that we don't match parts of words. ## The following paragraph contains several instances of accidental ## word duplication. unedited_text = \ '''Some of the great achievements of of recording in recent years have been carried out on on old records. In the the early days of gramophones, many famous people including Florence Nightingale, Tennyson, and and Mr. Glastone made records. In most cases these records, where they could be found, were in a very bad state; not not that they had ever been very good by today's standards. By applying electrical re-recording, engineers reproduced the now now long-dead voices from the wax cylinders in to to new discs, and these famous voices which were so nearly lost forever are now permanently recorded.''' print(sub(r'([^a-z])(([a-z]+)[ \n]+\3)([^a-z])', r'\1**\2**\4', unedited_text)) # prints "Some of the great achievements **of of** recording in # recent years ..."
true
d69866a1cf193e6eed2cc8abfad5b9a5c6653777
ARWA-ALraddadi/python-tutorial-for-beginners
/01-Workshop/Workshop-Solutions/cylinder_volume.py
939
4.4375
4
# Volume of a cylinder # # THE PROBLEM # # Assume the following values have already been entered into the # Python interpreter, denoting the measurements of a cylindrical # tank: radius = 4 # metres height = 10 # metres # Also assume that we have imported the existential constant "pi" # from the "math" library module: from math import pi # Write an expression, or expressions, to calculate the volume # of the tank. Print the result in a message to the screen. # A SOLUTION # # 1. Calculate the area of the end of the cylinder # (The area of a circle of radius r is pi times r squared) area = pi * (radius ** 2) # metres squared # 2. Multiply the cylinder's area by its height volume = area * height # metres cubed # 3. Print the volume in a message to the screen print("The cylinder's volume is", round(volume, 2), "metres cubed") # about 502 # Quick quiz: Why is "volume" a floating point number instead of # an integer?
true
4a1039d67f5927daf41b2aa86fde4cf9d7ead6a8
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V0.py
2,269
4.34375
4
#--------------------------------------------------------------------# # # Mars lander example - No error handling # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # Here, in the program's original form, if the barometer produces # incorrect numbers when the lander is near the ground it may # hit the surface without the retro rockets being on, destroying # the craft. # # Also, if the barometer produces non-number values the whole # program will crash and control of the retro rockets will be # entirely lost. # # Finally, there's a weakness in the way the loop is programmed # which means that if the lander doesn't stop at a height of # exactly zero (e.g., if it lands in a deep crater) the retro # rockets will fire while it's on the ground, possibly toppling # the craft over. # # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Return the result return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude != 0: # Read from the barometer (the user in this case!) air_pressure = int(input('Enter barometer reading: ')) # Calculate the lander's altitude altitude = altimeter(air_pressure) # Decide whether or not the retros should be firing if altitude == 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true
70d2912f7acbaa964fa09f0d17f11f96a5e3fb26
ARWA-ALraddadi/python-tutorial-for-beginners
/05-How to Repeat Actions demos/09-uniqueness.py
1,090
4.46875
4
#--------------------------------------------------------------------# # # Uniqueness test # # As an example of exiting a loop early, here we develop a small # program to determine whether or not all letters in some text # are unique. It does so by keeping track of each letter seen and # stopping as soon as it sees a letter it has encountered before. # # Define the text to be analysed text = 'The quick brown fox jumps over the lazy dog' # Create a list of letters already seen already_seen = [] # Examine each character for character in text: # Only consider alphabetic characters if character.isalpha(): # Make the comparison case insensitive uppercase_letter = character.upper() if uppercase_letter in already_seen: # Alert the user to the duplicate and stop print('Duplicate letter found:', uppercase_letter) break else: # Tell the user that a new letter has been found and continue print('New letter found:', uppercase_letter) already_seen.append(uppercase_letter)
true
101c4d993889264c4e592564584242cb96e85754
ARWA-ALraddadi/python-tutorial-for-beginners
/12-How to do more than one thing Demos/B_scribbly_turtles.py
1,501
4.71875
5
#--------------------------------------------------------------------# # # Scribbly turtles # # As a simple example showing that we can create two independent # Turtle objects, each with their own distinct state, here # we create two cursors (turtles) that draw squiggly lines on the # canvas separately. # # To develop this program from the beginning you can # # 1) Develop code to draw a single squiggly line using the # anonymous "default" turtle, # # 2) Modify the code to use a named Turtle object, and # # 3) Copy the code to create another named Turtle object. # from turtle import * from random import randint # Set up the drawing canvas and hide the default turtle setup() title('Two scribbly turtles') hideturtle() # Hide the default turtle since we don't use it # Create the two Turtle objects red_turtle = Turtle() blue_turtle = Turtle() # Define the characteristics of the red turtle red_turtle.color('red') red_turtle.turtlesize(2) red_turtle.width(4) red_turtle.pendown() red_turtle.speed('fast') # Define the characteristics of the blue turtle blue_turtle.color('blue') blue_turtle.turtlesize(3) blue_turtle.width(6) blue_turtle.pendown() blue_turtle.speed('fast') # Make the two turtles appear to draw at the same # time by interleaving their actions for steps in range(200): # Move the red turtle red_turtle.left(randint(-90, 90)) red_turtle.forward(15) # Move the blue turtle blue_turtle.left(randint(-45, 45)) blue_turtle.forward(5) # Exit done()
true
0598e5896c2b92261ac342485f300d5b0af7c907
ARWA-ALraddadi/python-tutorial-for-beginners
/09-Workshop/print_elements.py
2,663
4.84375
5
#--------------------------------------------------------- # # Print a table of the elements # # In this exercise you will develop a Python program that # accesses an SQLite database. We assume that you have # already created a version of the Elements database using # the a graphical user interface. You can do so by executing # the elements.sql script provided. # # Your tasks: # # 1) Browse the database's contents in an interactive interface # to ensure that you're familiar with its two tables and # their columns. # # 2) In your interactive interface, develop a SELECT query which # prints all available details of the elements in the database. # The result set should be ordered by atomic number as follows: # # No Name Symbol # 1 Hydrogen H # 2 Helium He # 3 Lithium Li # 4 Beryllium Be # 5 Boron B # 6 Carbon C # 7 Nitrogen N # 8 Oxygen O # 9 Fluorine F # 10 Neon Ne # 11 Sodium Na # 12 Magnesium Mg # 13 Aluminium Al # 14 Silicon Si # 15 Phosphorous P # 16 Sulphur S # 17 Chlorine Cl # 18 Argon Ar # 19 Potassium K # 20 Calcium Ca # [There may be more entries here if you did the # first "elements" exercise] # 121 Kryptonite Kr # 122 Dalekanium Dk # # 3) Using this SELECT query, write a Python program to print # all the element details in the database. Recall that after an # SQLite query has been executed on a database "cursor", method call # "cursor.fetchall()" will return a list of all rows in the # result set, and you can then use a FOR-EACH loop to process each # row in the list. # #--------------------------------------------------------- # Import the SQLite functions from sqlite3 import * # Connect to the elements database and print the atomic # number, name and symbol for each element. # 1. Make a connection to the elements database connection = connect(database = "elements.db") # 2. Get a cursor on the database elements = connection.cursor() # 3. Construct the SQLite query query = "SELECT atomic_number, symbols.element_name, symbol \ FROM atomic_numbers, symbols \ WHERE atomic_numbers.element_name = symbols.element_name \ ORDER BY atomic_number" # 4. Execute the query elements.execute(query) # 5. Get the result set and print it out print('No Name Symbol') rows = elements.fetchall() for no, name, symbol in rows: print(str(no).ljust(3) + ' ' + name.ljust(11) + ' ' + symbol.ljust(2)) # 6. Close the cursor and connection elements.close() connection.close()
true
189cbe4c2f6cb9b263e5c6f7fba1571040478428
ARWA-ALraddadi/python-tutorial-for-beginners
/08-How to Find Things Demos/01-wheres_Superman.py
1,804
4.65625
5
#--------------------------------------------------------------------- # # Where's Superman? # # To illustrate how we can find simple patterns in a text file using # Python's built-in "find" method, this demonstration searches for # some patterns in an HTML file. # # Read the contents of the file as a single string text_file = open('documents/Superman.html') text = text_file.read() text_file.close() # Make sure we've read the text properly print("Number of characters read:", len(text)) print() # Find the first occurrence of the word 'Superman' in the text print("Superman's name first occurs at position", text.find('Superman')) print() # Find the first occurrence of the word 'Batman' in the text print("Batman's name first occurs at position", text.find('Batman')) print() # Find all occurrences of the word 'Superman' in the text print("Superman's name appears in the following positions:") location = text.find('Superman') # Find first occurrence, if any while location != -1: print(location) location = text.find('Superman', location + 1) # Find next occurrence, if any print() # Find and display all names that have been strongly emphasised in the text, i.e., # those appearing between the HTML tags <strong> and </strong>. print("Names which are strongly emphasised in the text are:") start_tag = '<strong>' end_tag = '</strong>' start_location = text.find(start_tag) # Find first occurrence of start tag, if any while start_location != -1: end_location = text.find(end_tag, start_location) # Find matching end tag print(text[start_location + len(start_tag) : end_location]) # Print text between the tags start_location = text.find(start_tag, end_location) # Find next occurrence of start tag, if any # This last example is MUCH simpler with regular expressions!
true
5c6f7af9847b7112297337f1dd5199f9ba6bb97e
ARWA-ALraddadi/python-tutorial-for-beginners
/04-How to Make Decisions Demos/15-un-nesting.py
1,389
4.40625
4
#--------------------------------------------------------------------- # # "Un-nesting" some conditional statements # # There are usually multiple ways to express the # same thing in program code. As an instructive # exercise in using conditional statements, consider # the code below which decides whether or not # an applicant will get a mortgage based on their # income and their job status. Your challenge # is to change the code so that it does exactly the # same thing but only uses a single IF statement. # In other words, you must "un-nest" the two nested # IF statements. To do so you will not only need # to change the IF statements, you will also need # to devise new Boolean expressions involving the # AND connector. # Some test values - uncomment as necessary # An applicant who doesn't earn enough salary = 25000 years_in_job = 3 ### An applicant who doesn't have a steady job ##salary = 45000 ##years_in_job = 1 ### An applicant who qualifies for a loan ##salary = 55000 ##years_in_job = 3 # Two nested IF statements to be "flattened" into one if salary >= 30000: if years_in_job >= 2: print('You qualify for the loan') else: print('You must have worked in your', 'current job for at least two', 'years to qualify for a loan') else: print('You must earn at least $30,000', 'to qualify for a loan')
true
3a2ad3460b8151fc7df5ae3232b315b6c5dc9cab
ARWA-ALraddadi/python-tutorial-for-beginners
/03-How to Create Reusable Code Demos/07-ref_transparency.py
1,735
4.21875
4
#--------------------------------------------------------------------- # # Demonstration - Referential transparency # # The small examples in this file illustrate the meaning of # "referentially transparent" function definitions. A # function that is referentially transparent always does this # same thing when given the same arguments. In general, it is # easier to understand programs that use only referentially- # transparent functions. # # Functions that are NOT referentially transparent usually # return random values or, as in the example below, use a # global variable to "remember" their previous state. # #--------------------------------------------------------------------- # # The following function is referentially transparent because it # always gives the same answer when given the same argument: # # Returns the given number less five def take_5(minuend): subtrahend = 5 # constant to be subtracted return minuend - subtrahend # Some tests: print(take_5(10)) print(take_5(10)) print(take_5(10)) print(take_5(10)) print(take_5(10)) print() #--------------------------------------------------------------------- # # The following function is NOT referentially transparent because it # gives different answers when given the same argument: # subtrahend = 5 # global variable to remember how much to subtract # Returns the given number less five or more def take_at_least_5(minuend): global subtrahend # allow assignment to global variable subtrahend = subtrahend + 1 # increment amount to be subtracted return minuend - subtrahend # Some tests: print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10)) print(take_at_least_5(10))
true
d8d0afeca8c35fdfa370f32af41f0ce66e670e58
ARWA-ALraddadi/python-tutorial-for-beginners
/01-Workshop/Workshop-Questions/01_repair_cost.py
854
4.21875
4
# Total repair cost # # THE PROBLEM # # Assume the following values have already been entered into the # Python interpreter, representing the vehicle repair costs in dollars # from several suppliers following a motor accident, and the deposit # paid for the work: panel_beating = 1500 mechanics = 895 spray_painting = 500 tyres = 560 deposit = 200 # Write an expression to calculate the total cost outstanding # after the deposit has been paid, and the repairs completed. # Then print an appropriate message to screen including the # amount owing. # Use the following problem solving strategy: # 1. Calculate the sum of all the costs costssum= panel_beating + mechanics + spray_painting +tyres # 2. Deduct the amount of the deposit already paid remaincost = costssum - deposit # 3. Display the result print("the remain cost is " + str(remaincost))
true
072d4198ea1dea7962646af90a14f36fc72bbf81
ARWA-ALraddadi/python-tutorial-for-beginners
/10-How to Stop Programs Crashing Demos/0-mars_lander_V1.py
2,045
4.65625
5
#--------------------------------------------------------------------# # # Mars lander example - Checking input validity # # This simple program allows us to experiment with defensive # programming, assertions and exception handling. It is based on # a real-life example in which a software failure caused # a Mars lander to crash. # # To run the program the user is meant to simulate a barometer # and enter an increasing series of air pressure readings # between 0 and 100, e.g., 1, 4, 10, 50, 80, 100. # # Retro rockets will fire while the pressure equals or # exceeds 75 and will stop when the pressure reaches 100, # which is assumed to be the air pressure at ground level. # # In this version the program checks to ensure that the # barometer reading received is an integer and requests # another if it isn't. # # Import the regular expression match function from re import match # Two utility functions to tell us whether the retro rockets # are on or off def retros_on(): print("-- Retro rockets are firing --") def retros_off(): print("-- Retro rockets are off --") altitude = 1000000 # initialise with a big number pressure_at_surface = 100 # constant # Calculate altitude based on atmospheric # pressure - higher pressure means lower altitude def altimeter(barometer_reading): # Return the result return pressure_at_surface - barometer_reading # Main program to decide when to fire the retros while altitude != 0: # Read a valid integer from the barometer (the user in this case!) raw_air_pressure = input('Enter barometer reading: ') while match('^-?[0-9]+$', raw_air_pressure) == None: raw_air_pressure = input('Re-enter barometer reading: ') air_pressure = int(raw_air_pressure) # Calculate the lander's altitude altitude = altimeter(air_pressure) # Decide whether or not the retros should be firing if altitude == 0 or altitude > 25: retros_off() else: retros_on() # We made it! print('Houston, the Eagle has landed!')
true
d4e19d058a7a7ea4f0d66467c19c15cfd3d510d9
DiogoBispo/python
/funcao_duplicados.py
1,575
4.28125
4
""" -> é uma lista de listas de numeros inteiros -> as listas internas tem o tamanho de 10 elementos -> as listas internas contem numeros entre 1 a 10 e eles podem ser duplicados Exercicio -> Crie uma função que controla o primeiro duplicado considerando o segundo numero como a duplicação: requisitos: A ordem do numero duplicado é considerada a partir da segunda ocorrencia do numero, ou seja, o numero duplicado em si. Exemplo: [1, 2, 3, ->3<-, 2, 1] >> 1, 2 e 3 são duplicados Se não encontrar duplicadaos na lista, retorne -1 """ lista_de_listas_de_inteiros = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [9, 1, 3, 5, 7, 2, 4, 6, 8, 10], [5, 4, 2, 3, 10, 6, 8, 9, 7, 1], [8, 7, 3, 7, 5, 6, 7, 8, 9, 10], [5, 1, 6, 5, 7, 6, 4, 6, 8, 10], [5, 4, 5, 5, 6, 6, 8, 9, 7, 10], [5, 2, 3, 4, 5, 6, 7, 8, 9, 10], [9, 1, 3, 3, 7, 2, 4, 6, 8, 3], [5, 4, 2, 2, 1, 6, 8, 9, 7, 10], [1, 2, 3, 4, 5, 6, 6, 8, 9, 6], [9, 1, 2, 5, 1, 1, 4, 6, 8, 10], [5, 4, 1, 1, 2, 2, 8, 1, 7, 10], ] def encontra_primeiro_duplicado(param_lista_de_inteiros): numeros_checados = set() primeiro_duplicado = -1 for numero in param_lista_de_inteiros: if numero in numeros_checados: primeiro_duplicado = numero break numeros_checados.add(numero) return primeiro_duplicado for lista_de_inteiros in lista_de_listas_de_inteiros: print(lista_de_inteiros, encontra_primeiro_duplicado(lista_de_inteiros))
false
3b1778872c9c7cf1a01f97d34413637fbd846720
n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020
/unit_01_algorithms_intro/hw/hw_01_5.py
311
4.125
4
""" Пользователь вводит номер буквы в алфавите. Определить, какая это буква. """ letter_pos = int(input('Введите номер латинской буквы в алфавите: ')) print(f'Ваша буква: {chr(letter_pos + ord("a") - 1)}')
false
73febf1c1bf6a8d35dc50afbedd76b2df8bb2da4
RohanNankani/Computer-Fundamentals-CS50
/Python/mad_lib_theatre.py.py
2,357
4.25
4
# Author: Rohan Nankani # Date: November 11, 2020 # Name of Program: MadLibTheater # Purpose: To create a mad lib theater game which ask user for input, store their input using list, and print the story. # Intializing the list grammar = [] # List of prompts that describe the category of the next word # to be substituted in the story prompts = [ "an adjective: ", "an another adjective: ", "a type of bird: ", "a room in a house: ", "a past tense verb: ", "a verb: ", "a name: ", "a noun: ", "a type of liquid: ", "a verb ending in -ing: ", "a plural part of the body: ", "a plural noun: ", "a verb ending in -ing: ", "a noun: " ] # Function to ask user for input for each of the prompts def grammar_input(): for prompt in prompts: grammar.append(input("Enter " + prompt)) # Function to print the story with the user's input def story_template(): print("It was a " + grammar[0] + ", cold November day.") print("") print("I woke up to the " + grammar[1] + " smell of " + grammar[2] + " roasting in the " + grammar[3] + " downstairs.") print("") print("I " + grammar[4] + " down the stairs to see if I could help " + grammar[5] + " the dinner.") print("") print("My mom said, 'See if " + grammar[6] + " needs a fresh " + grammar[7] + ".'") print("") print("So I carried a tray of glasses full of " + grammar[8] + " into the " + grammar[9] + " room.") print("") print("When I got there, I couldn't believe my " + grammar[10] + "! There were " + grammar[11] + " " + grammar[12] + " on the " + grammar[13] + "!") # Greeting the user at the beginning of program print("Welcome to the Mad Lib Theater!".center(53)) print("") print("I want you to give me the first word that comes to your mind for described category.") print("") print("Are you ready?") print("") input("Press enter to continue: ") print("".center(48, "-")) # Calling the grammar input function to get input from user grammar_input() print("") # Calling story template function to print the story story_template() # Using while loop to ask the user if they want to play again while True: print("") userResponse = input("Do you want to play again (Y/N)? ") if userResponse == "Y": print("".center(48, "-")) grammar = [] grammar_input() print("") story_template() else: print("".center(48, "-")) print("Thank you for playing!".center(53)) break
true
17856f57c910a767dfc433a16fbe31b365e3e870
sp3arm4n/OpenSource-Python
/assignment_01/src/p10.py
364
4.46875
4
# step 1. asks the user for a temperature in Fahrenheit degrees and reads the number number = float(input("please enter Fahrenheit temperature: ")) # step 2. computes the correspodning temperature in Celsius degrees number = (number - 32.0) * 5.0 / 9.0 # step 3. prints out the temperature in the Celsius scale. print("Celsius temperature is %f"%(number))
true
45497bbe4e6c706c4f79e8be82bc586cc78331e3
DarkCodeOrg/python-learning
/list.py
288
4.21875
4
#!/bin/python python3 """ creating an empty list and adding elements to it""" list = [] list.append(200) list.append("salad") list.append("maths") print(list) print("this is your initial list") new = input("Enter something new to the list: ") list.append(new) print(list)
true
192af36327e7984ba16c57dac945182bc92de21a
2u6z3r0/automate-boaring-stuff-with-python
/inventory.py
1,171
4.1875
4
#!/usr/bin/python3 #chapter 5 exercise stuff = {'gold coin': 42, 'rope': 1} def displayInventory(stuff): ''' :param stuff: It takes a dictionary of item name as key and its quantity as value :return: Nothing, but it prints all items and respective quantity and total quantity(sum of all itmes qty) ''' print("Inventory:") totalCount = 0 for k, v in stuff.items(): print(v,k) totalCount += v print('Total number of items ' + str(totalCount)) dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def addToInventory(inventory, addItems): ''' This function takes existing inventoy(dict) and new items to be added to inventory. :param inventory: existing inventory(dictionay of item_name:qty) :param addItems: list of items to be added to existing inventory :return: updated inventory dict by adding new items or if item exists already, qty will be increased by 1 ''' for item in addItems: inventory.setdefault(item, 0) #initialize qty to 0 if item does not exist already inventory[item] += 1 addToInventory(stuff, dragonLoot) displayInventory(stuff)
true
a767fd70f5fedac106f3aca0b8b48b41d38a2a8e
NATHAN76543217/BtCp_D00
/ex03/count.py
1,005
4.28125
4
import string def text_analyzer(*text): """ This function counts the number of upper characters, lower characters, punctuation and spaces in a given text. """ if len(text) > 1: print("ERROR") return if len(text) == 0 or isinstance(text[0], str) == 0: text = [] text.append(input("What is the text to analyse?\n>> ")) ponctu_list = string.punctuation nb_upper = 0 nb_lower = 0 nb_ponct = 0 nb_spaces = 0 letters = 0 for char in text[0]: letters += 1 if char == ' ': nb_spaces += 1 elif char.isupper(): nb_upper += 1 elif char.islower(): nb_lower += 1 elif char in ponctu_list: nb_ponct += 1 print("The text contains {} characters:" .format(letters), '\n') print("-", nb_upper, "upper letters\n") print("-", nb_lower, "lower letters\n") print("-", nb_ponct, "punctuation marks\n") print("-", nb_spaces, "spaces")
true
75e70e3300181dfb1dd71800fa0bc5d7ca4f2aa2
valdialva/Topicos-1
/Labs/Lab1.py
1,610
4.1875
4
#1. Create first name and add last name with join print ("1") n = "Alvaro" print (n) n = ''.join([n, " Valdivieso"]) print (n) #2. convert tu uppercase print ("2") n = n.upper() print (n) #3. create list with n print ("3") l = list(n) print (l) print (len(l)) #4. create string from l print ("4") m = ''.join(l) print (m) #5. take last name from first name print ("5") k = m.split() print (k) #6. reverse 1st and 2nd elements of list print ("6") l[0], l[1] = l[1], l[0] print (l) #6. reverse 1st and 2nd elements of list print ("7") def switch(l): l[0], l[1] = l[1], l[0] return l #8. lo mismo print ("8") def switchf(l): m = l #return l[1:2]+x[0:1]+x[2:] return switch(m) #9. apply 7 to n print ("9") print (switch(n)) #Se cambia el orden de los primeros elementos la lista #10. apply 8 to n print ("10") print (switchf(n)) #la lista original se queda intacta y se retorna un arreglo con los elementos cambiados #11. 10 con strings print ("11") def switchsf(n): m = list(n) return switch(m) #12. es posible modificar switch para q trabaje con strings print ("12") #directamente no se puede modificar los strings, hay q convertirlos a listas #13. switchsf a l print ("13") print (l) print(switchsf(l)) #14. cuantas a tiene l print ("14") #cuanta las a mayuscula - el nombre esta todo en mayusculas print (l.count('A')) #15. sort n alphabetically print ("15") print (sorted(set(l))) #16. separa un parrafo en oraciones print ("16") def separate(parrafo): return parrafo.split(".") print (separate("primera oracion. segunda oracion. tercera oracion"))
false
cf2553bafad225366a58d08ab9a8edc6b4daa9d2
Ayush900/django-2
/advcbv2/basic_app/templates/basic_app/pythdjango/oops.py
807
4.40625
4
#class keyword is used to create your own classes in python ,just like the sets,lists,tuples etc. .these classes are also known as objects and this type of programming involving the creation of your own classes or objects is known as object oriented programming or oops....# class football_team: #Here the new object created is the football_team which contain an attribute which tells about the league of the football team # def __init__(self,league,pos): self.league=league self.pos=pos arsenal=football_team(league = 'bpl',pos=4) barca=football_team(league = 'la_liga',pos=1) print('Arsenal play in {} and its position in league is {}'.format(arsenal.league,arsenal.pos)) print('FC Barcelona play in {} and its position in league is {}'.format(barca.league,barca.pos))
true
e98ba84add2519f4c3858cef105c6e5de54f57fb
jonathangriffiths/Euler
/Page1/SumPrimesBelowN.py
612
4.15625
4
__author__ = 'Jono' from GetPrimeN import isPrime #basic method to estimate how long it will take like this def get_sum_primes_below_n(n): sum=2 for i in range(3, n+1, 2): if isPrime(i): sum+=i return sum print get_sum_primes_below_n(2000000) #note: Erastosthenes seive useful for speed #1. Make a list of all numbers from 2 to N. #2. Find the next number p not yet crossed out. This is a prime. If it is greater than √N, go to 5. #3. Cross out all multiples of p which are not yet crossed out. #4. Go to 2. #5. The numbers not crossed out are the primes not exceeding N
true
af32475e446f1ddc7e65cb90040a567a21ac5d85
tchaitanya2288/pyproject01
/Simple if.py
421
4.15625
4
#1. The 1. if 2. if..else , 3. elif and 4. neasted elif #1. IF Statement: my_var=50 #50 < 100: if my_var<100: print(my_var,'is less then 100') print ("We are out of the if statement") #The if statement is used for conditional execution: #if_stmt ::= "if" expression ":" suite #(or) my_var=50 if my_var<100: print ("Yes") print (my_var,"is less then 100") print ("We are out of the if statement")
false
6f5e0be8179eee4ea15eeb31baf53954cf803678
tchaitanya2288/pyproject01
/simple Elseif.py
699
4.15625
4
""" 3. NESTED IF-ELSE STATEMENT : >>> ord('A') 65 >>> ord("Z") 90 >>> ord('a') 97 >>> ord("z") 122 """ char=input("Please enter any charcter : ") if ord(char)>=65 and ord(char)<=90: print ("You entered an upper case alphabet") if char in ['A','E','I','O','U']: print ("You entered A vowel.",char) else: print ("You entered a consonant.", char) elif ord(char)>=97 and ord(char)<=122: print ("You entered an Lower case alphabet") if char in ['a','e','i','o','u']: print ("You entered a vowel.",char) else: print ("You entered a consonant.",char) else: print (char,"You did not enter an alphabet.") print ("We are out of the if..elif block")
false
3dbaed02def20cc1c27d7ed07cce6be97942b78b
za-webdev/Python-practice
/score.py
425
4.25
4
#function that generates ten scores between 60 and 100. Each time a score is generated,function displays what the grade is for a particular score. def score_grade(): for x in range(1,11): import random x=(random.randint(60,100)) if x >60 and x<70: z="D" elif x>70 and x<80: z="C" elif x>80 and x<90: z="B" elif x>90 and x<100: z="A" print "Score:{},Your grade is {}".format(x,z) score_grade()
true