blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ce0cfdebf310432f6641ef77c298ebefefa2d2d6
gihs-rpc/01-Sleeping-In
/challenge-1-sleeping-in-MoseliaTemp3/1.1 ~ Sleeping In.py
1,612
4.34375
4
#Repeatedly used things defined here for ease of modification. EndBool = "\n (Y/N) > " Again = "Incorrect input." #Begin Program. while True: print("\n") #Is tomorrow a school day? SchoolTomorrow = input("Do you have school tomorrow?" + EndBool) print() #Repeat question until answer is "y" or "n". while not (SchoolTomorrow.lower() == "y" or SchoolTomorrow.lower() == "n"): print(Again) SchoolTomorrow = input("Do you have school tomorrow?" + EndBool) print() #If tomorrow is a school day, is it a Wednesday? if SchoolTomorrow.lower() == "y": TomorrowWednesday = input("Is today Tuesday?" + EndBool) print() #Repeat question until answer is "y" or "n". while not (TomorrowWednesday.lower() == "y" or TomorrowWednesday.lower() == "n"): print(Again) TomorrowWednesday = input("Is today Tuesday?" + EndBool) print() if SchoolTomorrow.lower() == "n": #If there is no school. print("You do not have school tomorrow, so you can sleep in as long as you want.") elif TomorrowWednesday.lower() == "y": #If there is school, but its a late Wednesday. print("You have school tomorrow, but it is a Wednesday so you can sleep in a bit.") else: #If there is school and it is not a late Wednesday. print("You have school tomorrow and cannot sleep in.") #Repeat program or break loop? print() if input("Run again?" + EndBool).lower() != "y": print() break
true
05b72faac13f324605cb62bf3c1fff7258260e28
itsamanyadav/Python
/unittest使用.py
2,237
4.4375
4
#断言 编写代码时,我们总是会做出一些假设,断言就是用于在代码中捕捉这些假设,可以将断言看作是异常处理的一种高级形式。 #assert代表断言,假设断言的条件为真,如果为假诱发AssertionError #assert 断言的条件,错误的提升 # a = 0 # assert a,"a is false" # print(a) #上面的断言代码类似下面的if语句 # a = 1 # if not a: # raise AssertionError("a is false") # print(a) # import unittest # # #unittest使用的方法 # class OurTest(unittest.TestCase): # """ # 继承编写测试的基础类 # """ # def setUp(self): # """ # 类似于类的init方法,在测试执行之初制动执行,通常用来做测试数据的准备 # """ # def test_add(self): # """ # 具体测试的方法,使用testcase编写具体测试的方法,函数名称必须以test开头 # 函数当中的内容通常是获取预期值,和运行结果值 # 然后对两个值进行断言 # """ # def tearDown(self): # """ # 类似类的del方法,用来回收测试的环境 # """ # # if __name__ == "__main__": # unittest.main() import unittest #举个栗子 class OurTest(unittest.TestCase): """ 继承编写测试的基础类 """ def setUp(self): """ 类似于类的init方法,在测试执行之初制动执行,通常用来做测试数据的准备 """ self.a = 1 #测试使用的参数1 self.b = 1 #测试使用的参数2 self.result = 3 #预期的结果 def test_add(self): """ 具体测试的方法,使用testcase编写具体测试的方法,函数名称必须以test开头 函数当中的内容通常是获取预期值,和运行结果值 然后对两个值进行断言 unittest模块已经封装好了更多的断言方法 """ run_result = self.a + self.b self.assertEqual(run_result,self.result,"self.a+self.b不等于3") #断言两个值相等 def tearDown(self): """ 类似类的del方法,用来回收测试的环境 """ if __name__ == "__main__": unittest.main()
false
2d9ca18c7b90af0ac266f5f8b8b684492c2bbc4e
laurendayoun/intro-to-python
/homework-2/answers/forloops.py
2,846
4.40625
4
""" Reminders: for loop format: for ELEMENT in GROUP: BODY - ELEMENT can be any variable name, as long as it doesn't conflict with other variables in the loop - GROUP will be a list, string, or range() - BODY is the work you want to do at every loop range format is: range(start, stop, step) or range(start, stop) or range(stop) - if step not given, step = 1; if start not given, start = 0 - if step is negative, we decrease """ def forloop_1(): '''Create a for loop that prints every element in the list numbers''' numbers = [5, 10, 15, 20, 25, 30] ### Your code here ### for n in numbers: print(n) def forloop_1_2(): '''Create a for loop that prints every multiple of 5 from 5 to 30''' # Hint: Use range. You are not allowed to use a list! ### Your code here ### for n in range(5, 31, 5): print(n) def forloop_2(): '''Create a for loop that adds together all of the strings in words. Your final string should be: My name is <name>. Replace <name> with your name in the list!''' words = ["My ", "name ", "is ", "Lauren"] sentence = "" ### Your code here ### for s in words: sentence += s print("The string is: " + sentence) def forloop_2_2(): '''Create a for loop that adds together all of the strings in words. Every time you add a word, add a space (" ") so that the sentence is easy to read! Your final string should be: My name is <name>. Replace <name> with your name in the list!''' words = ["My", "name", "is", "Lauren"] sentence = "" ### Your code here ### for s in words: sentence += s + " " print("The string is: " + sentence) def forloop_3(): '''Create a for loop that doubles (multiplies by 2) the variable a 7 times. The final value of a should be 128.''' a = 1 ### Your code here ### for i in range(7): a *= 2 print("Your result is: " + str(a)) def forloop_4(): '''Create a for loop that prints the numbers, and then the letters in mixed_list The order of things printed should be: 1, 3, 5, b, d, f''' mixed_list = [1, 'b', 3, 'd', 5, 'f'] ### Your code here ### for i in range(0, 6, 2): print(mixed_list[i]) for i in range(1, 7, 2): print(mixed_list[i]) def forloop_5(): '''Challenge Question (optional): Code 2 different programs that print: 5 4 3 2 1 Take off! Hint: Use a list in one program, and range in another. ''' ### Your code here ### for i in range(5, 0, -1): print(i) print("Take off!") ### for i in [5, 4, 3, 2, 1, 'Take off!']: print(i) def main(): print("Question 1:") forloop_1() print("\nQuestion 1.2:") forloop_1_2() print("\nQuestion 2:") forloop_2() print("\nQuestion 2.2:") forloop_2_2() print("\nQuestion 3:") forloop_3() print("\nQuestion 4:") forloop_4() print("\nQuestion 5:") forloop_5()
true
e8412e95f1b1b094e5d24c286c18f240e72401be
taruntalreja/Training_Toppr
/Python Basics/OOPs Concepts/class_object.py
700
4.25
4
class Sparrow: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age #instance method def eats(self,food): return "{} eats {}".format(self.name,food) # instantiate the Parrot class fanny = Sparrow("Fanny", 5) dora = Sparrow("Dora", 8) # access the class attributes print("Fanny is a {}".format(fanny.__class__.species)) print("Dora is also a {}".format(dora.__class__.species)) # access the instance attributes print("{} is {} years old".format( fanny.name, fanny.age)) print("{} is {} years old".format( dora.name, dora.age)) print(fanny.eats("peanuts")) print(dora.eats("rice"))
false
a345955cc7dabc0e6551f6f0e47e88b36c43ad26
Leomk1998/AyudantiasFP-ESPOL
/FP2020-2/Clase01/Ayudantia1.py
2,158
4.1875
4
# 23/10/2020 # Ayudante: Leonardo Mendoza #Ejercicio 1 """ f = int(input("Escriba un temperatura en grados Farhenheit: ")) c = ((f-32)*5)/9 print("%d grados Farhenheit son %f grados centigrados"%(f,c)) # %d numeros enteros %s strings %f numeros decimales """ #Ejercicio 2 """ numero = int(input("Ingrese un numero: ")) mod = numero%2 validacion = mod==0 print("El numero {} es par? {}".format(numero,validacion)) """ #Ejercicio 3 """ segundosUsuario = int(input("Ingrese una cantidad de segundos:")) horas = segundosUsuario//3600 minutos = (segundosUsuario%3600)//60 #minutos = (segundosUsuario-(horas*3600))%60 segundos = segundosUsuario%60 print("%d segundos son %d hora(s), %d minuto(s),%d segundo(s)"%(segundosUsuario,horas,minutos,segundos)) """ #Ejercicio 4 """ print("Convetidor de dolares a Euros") dolares = float(input("Ingrese una cantidad de dolares: ")) valorEuro = 0.885 euros = valorEuro*dolares print("%.2f dolares son %.2f euros"%(dolares,euros)) """ #Ejercicio 5 """ print("Convetidor de euros a dolares") euros = float(input("Ingrese una cantidad de euros: ")) valorEuro = 0.885 dolares = euros/valorEuro print("%.2f euros son %.2f dolares"%(euros,dolares)) """ #Ejercicio 6 """ print("*******Programa para ver si estas RP******") par1= int(input("Ingrese su nota de 1par: ")) par2= int(input("Ingrese su nota de 2par: ")) prac= int(input("Ingrese su nota de practica: ")) mej= int(input("Ingrese su nota de mejoramiento: ")) clases= int(input("Ingrese la cantidad de clases: ")) faltas= int(input("Ingrese la cantidad de faltas: ")) promedioTeorico = max((par1+par2)/2,(par1+mej)/2,(mej+par2)/2) # min mean promedioGeneral = promedioTeorico*0.8 + prac *0.2 porcentajeDeAsistencia = ((clases-faltas)/clases)*100 validacion = promedioGeneral<60 or porcentajeDeAsistencia<60 print("Su promedio general es %.1f y su porcentaje de asistencia es %.1f "%(promedioGeneral,porcentajeDeAsistencia)) print("Reprobado?",validacion) """ #Ejercicio 7 #\ """ print(""" # Este es un mensaje # # Que usa caracteres especiales # # En un solo print """) """ print("Este es un mensaje \n\n\tQue usa caraccteres especiales \n\nEn un solo print")
false
8a93636bd5b7b955f431bc4f351583b742fe14cf
senavarro/function_scripts
/functions.py
947
4.40625
4
#Create a function that doubles the number given: def double_value(num): return num*2 n=10 n=double_value(n) print(n) -------------------------------------- #Create a recursive function that gets the factorial of an undetermined number: def factorial(num): print ("Initial value =", num) if num > 1: num = num * factorial(num -1) print ("Final value =", num) return num print (factorial(5)) -------------------------------------- #Create a function that makes a countdown: def countdown(num): while num > 0: num -=1 print(num) else: print("It's the final countdown") countdown(5) -------------------------------------- #Create a function that allows undetermined args and kwargs: def indetermined_position(*args, **kwargs): t=0 for arg in args: t+=arg print("the total amount of args is:", t) for kwarg in kwargs: print(kwarg, kwargs[kwarg]) indetermined_position(1,2,3,4,5,6,7,8,9, name="Sergi", age=24)
true
d48b8e88545ebcf87820f63294285c9b0d370331
kingdunadd/PythonStdioGames
/src/towersOfHanoi.py
2,977
4.34375
4
# Towers of Hanoi puzzle, by Al Sweigart al@inventwithpython.com # A puzzle where you must move the disks of one tower to another tower. # More info at https://en.wikipedia.org/wiki/Tower_of_Hanoi import sys # Set up towers A, B, and C. The end of the list is the top of the tower. TOTAL_DISKS = 6 HEIGHT = TOTAL_DISKS + 1 # Populate Tower A: completeTower = list(reversed(range(1, TOTAL_DISKS + 1))) TOWERS = {'A': completeTower, 'B': [], 'C': []} def printDisk(diskNum): # Print a single disk of width diskNum. emptySpace = ' ' * (TOTAL_DISKS - diskNum) if diskNum == 0: # Just draw the pole of the tower. print(emptySpace + '||' + emptySpace, end='') else: # Draw the disk. diskSpace = '@' * diskNum diskNumLabel = str(diskNum).rjust(2, '_') print(emptySpace + diskSpace + diskNumLabel + diskSpace + emptySpace, end='') def printTowers(): # Print all three towers. for level in range(HEIGHT - 1, -1, -1): for tower in (TOWERS['A'], TOWERS['B'], TOWERS['C']): if level >= len(tower): printDisk(0) else: printDisk(tower[level]) print() # Print the tower labels A, B, and C. emptySpace = ' ' * (TOTAL_DISKS) print('%s A%s%s B%s%s C\n' % (emptySpace, emptySpace, emptySpace, emptySpace, emptySpace)) print('The Towers of Hanoi') print('Move the tower, one disk at a time, to another pole.') print('Larger disks cannot rest on top of a smaller disk.') while True: # Main program loop. # Display the towers and ask the user for a move: printTowers() print('Enter letter of "source" and "destination" tower: A, B, C, or QUIT to quit.') print('(For example, "AB" to move the top disk of tower A to tower B.)') move = input().upper() if move == 'QUIT': sys.exit() # Make sure the user entered two letters: if len(move) != 2: print('Invalid move: Enter two tower letters.') continue # Put the letters in move in more readable variable names: srcTower = move[0] dstTower = move[1] # Make sure the user entered valid tower letters: if srcTower not in 'ABC' or dstTower not in 'ABC' or srcTower == dstTower: print('Invalid move: Enter letters A, B, or C for the two towers.') continue # Make sure the src disk is smaller than the dst tower's topmost disk: if len(TOWERS[srcTower]) == 0 or (len(TOWERS[dstTower]) != 0 and TOWERS[dstTower][-1] < TOWERS[srcTower][-1]): print('Invalid move. Larger disks cannot go on top of smaller disks.') continue # Move the top disk from srcTower to dstTower: disk = TOWERS[srcTower].pop() TOWERS[dstTower].append(disk) # Check if the user has solved the puzzle: if completeTower in (TOWERS['B'], TOWERS['C']): printTowers() # Display the towers one last time. print('You have solved the puzzle! Well done!') sys.exit()
true
0b0329ee3244562c8c7aa7abb3068f2c06737bde
codesheff/DS_EnvTools
/scripts/standard_functions.py
706
4.21875
4
#!/usr/bin/env python3 def genpassword(forbidden_chars:set={'!* '} , password_length:int=8) -> str: """ This function will generate a random password Password will be generated at random from all printable characters. Parameters: forbidden_chars: Characters that are not allowed in the password passwordLenght: Length of the password to be generated """ import random import string characters=set(string.printable) for character in forbidden_chars: characters.discard(character) str_characters=''.join(characters) new_password = ''.join(random.choice(str_characters) for i in range(password_length)) return new_password
true
97defbcbd96034d5ac170250340d05d18732da78
willpxxr/python
/src/trivial/sorting/quicksort.py
2,527
4.25
4
from math import floor from typing import List def _medianOf3(arr: List, begin: int, end: int) -> (int, int): """ Brief: Help method to provide median of three functionality to quick sort An initial pivot is selected - then adjusted be rotating the first index, center index and end index into the correct order. The pivot is then moved to the penultimate index Args: arr: List being sorted begin: The first index in scope end: The final index in scope Returns: Pivot Value - The value being used at the pivot Pivot Index - The index which contains the pivot value """ center = floor((begin + end) / 2) if arr[center] < arr[begin]: arr[begin], arr[center] = arr[center], arr[begin] if arr[end] < arr[begin]: arr[end], arr[begin] = arr[begin], arr[end] if arr[end] < arr[center]: arr[center], arr[end] = arr[end], arr[center] arr[center], arr[end - 1] = arr[end - 1], arr[center] return arr[end - 1], end - 1 # Pivot is not at end - 1 def _partition(arr: List, begin: int, end: int) -> int: """ Brief: Partition an array around a pivot point - with larger values moving to the RHS, and smaller values to the LHS Args: arr: List being sorted begin: The first index in scope end: The final index in scope Returns: The index held by the pivot """ primary_pivot, pivot_index = _medianOf3(arr, begin, end) tortoise = begin for hare in range(begin, pivot_index): if arr[hare] < primary_pivot: arr[tortoise], arr[hare] = arr[hare], arr[tortoise] tortoise += 1 arr[tortoise], arr[pivot_index] = ( arr[pivot_index], arr[tortoise], ) # Restore the pivot return tortoise def _recursiveQuickSort(arr: List, begin: int, end: int) -> None: """ Brief: Recursive implementation of Quicksort following the median of three rule, to provide a more optimal pivot selection Args: arr: List being sorted begin: The first index in scope end: The final index in scope Returns: None """ if begin < end: index = _partition(arr, begin, end) _recursiveQuickSort(arr, begin, index - 1) _recursiveQuickSort(arr, index + 1, end) def quickSort(arr: List) -> None: _recursiveQuickSort(arr, 0, len(arr) - 1) if __name__ == "__main__": raise NotImplementedError("There is no main programme")
true
52d309fa9f4cca8b527da7850fca9256a34c2b6c
hannahbishop/AlgorithmPuzzles
/Arrays and Strings/rotateMatrix.py
1,244
4.25
4
def rotate_matrix(matrix, N): ''' Input: matrix: square, 2D list N: length of the matrix Returns: matrix, rotated counter clockwise by 90 degrees Example: Input: [a, b] [c, d] Returns: [b, d] [a, c] Efficiency: O(N^2) ''' for layer in range(N): for index in range(layer, N - 1 - layer): temp = matrix[layer][index] #store right in top matrix[layer][index] = matrix[index][N - 1 - layer] #store bottom in right matrix[index][N - 1 - layer] = matrix[N - 1 - layer][N - 1 - index] #store left in bottom matrix[N - 1 - layer][N - 1 - index] = matrix[N - 1 - index][layer] #store temp in left matrix[N - 1 - index][layer] = temp return matrix def print_matrix(matrix, N): for i in range(N): print(matrix[i]) def main(): print("start matrix:") N = 9 matrix = [[x for x in range(N)] for y in range(N)] print_matrix(matrix, N) print("rotated matrix:") matrix_rotated = rotate_matrix(matrix, N) print_matrix(matrix_rotated, N) if __name__ == "__main__": main()
true
e72fe631c3633f59c643e7a58de5ab3c9c564eb9
Ziiv-git/HackerRank
/HackerRank23.py
1,987
4.1875
4
''' Objective Today, we’re going further with Binary Search Trees. Check out the Tutorial tab for learning materials and an instructional video! Task A level-order traversal, also known as a breadth-first search, visits each level of a tree’s nodes from left to right, top to bottom. You are given a pointer, , pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree. Hint: You’ll find a queue helpful in completing this challenge. Input Format The locked stub code in your editor reads the following inputs and assembles them into a BST: The first line contains an integer, (the number of test cases). The subsequent lines each contain an integer, , denoting the value of an element that must be added to the BST. Output Format Print the value of each node in the tree’s level-order traversal as a single line of space-separated integers. Sample Input 6 3 5 4 7 2 1 Sample Output 3 2 5 1 4 7 ''' import sys class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def levelOrder(self, root): queue = [root] while len(queue) is not 0: curr = queue[0] queue = queue[1:] print(str(curr.data) + " ", end="") if curr.left is not None: queue.append(curr.left) if curr.right is not None: queue.append(curr.right) T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) myTree.levelOrder(root)
true
53cecd207777cb4b81667a0869fc3318f8673f47
mciaccio/pythonCode
/udacityPythonCode/classes/inheritance.py
2,075
4.34375
4
# class name first letter uppercase "P" class Parent(): # constructor def __init__(self, last_name, eye_color): print("Parent Constructor called\n") self.last_name = last_name self.eye_color = eye_color # super class instance method def show_info(self): print('Parent class - show_info instance method self.last_name is -> {}'.format(self.last_name)) print('Parent class - show_info instance method self.eye_color is -> {}\n'.format(self.eye_color)) # class name first letter uppercase "C" # "Parent" specified as super class class Child(Parent): # constructor def __init__(self, last_name, eye_color, number_of_toys): print("Child Constructor called") Parent.__init__(self,last_name,eye_color) # invoke (and populate) super class constructor self.number_of_toys = number_of_toys # subclass instance method # method overriding - same name in super Parent class def show_info(self): print('Child class - show_info instance method self.last_name is -> {}'.format(self.last_name)) print('Child class - show_info instance method self.eye_color is -> {}'.format(self.eye_color)) print('Child class - show_info instance method self.number_of_toys is -> {}\n'.format(self.number_of_toys)) print("\nBegin inheritance.py module\n") # Parent class instance billy_cyrus = Parent("Cyrus", "blue") print('billy_cyrus.last_name is -> {}'.format(billy_cyrus.last_name)) print('billy_cyrus.eye_color is -> {}\n'.format(billy_cyrus.eye_color)) billy_cyrus.show_info() # Child class instance miley_cyrus = Child("Cyrus", "Green", 5) print('miley_cyrus.eye_color is -> {}'.format(miley_cyrus.eye_color)) print('miley_cyrus.last_name is -> {}'.format(miley_cyrus.last_name)) print('miley_cyrus.number_of_toys is -> {}\n'.format(miley_cyrus.number_of_toys)) # Child instance calls inherited super class instance method - when instance method not defined in Child class miley_cyrus.show_info() print("End inheritance.py module\n")
true
8ad0f485fbad4f5edc9df95ba3a4b21257add7bc
ashwin-magalu/Python-OOPS-notes-with-code
/access.py
713
4.28125
4
class Employee: name = "Ashwin" # public member _age = 27 # protected member __salary = 10_000 # private member --> converted to _Employee__salary def showEmpData(self): print(f"Salary: {self.__salary}") class Test(Employee): def showData(self): print(f"Age: {self._age}") # print(f"Salary: {self.__salary}") # error ashwin = Employee() print(ashwin.name) print(ashwin._age) # print(ashwin.__salary) # error print(ashwin._Employee__salary) # no error, this way we can access private variable t = Test() t.showData() ashwin.showEmpData() """ Python don't have private or protected, we use these naming conventions to make the members private, public or protected """
true
5761bda1dc5763f3e0acae42b4b98c928c84fb19
pr0d33p/PythonIWBootcamp
/Functions/7.py
422
4.21875
4
string = "The quick Brow Fox" def countUpperLower(string): lowerCaseCount = 0 upperCaseCount = 0 for letter in string: if letter.isupper(): upperCaseCount += 1 elif letter.islower(): lowerCaseCount += 1 print("No. of Upper case characters: {}".format(upperCaseCount)) print("No. of Lower case Characters: {}".format(lowerCaseCount)) countUpperLower(string)
true
c5c7b363243db27bacf7ff7405229cf0edf77018
jodaruve/Parcial
/ejercicio 68.py
818
4.125
4
## 68 print("Este programa le mostrara la cantidad de nmeros positivos, negativos, pares, impares y multiplos de ocho ingresados. Recuerde que cuando no desee ingresar ms nmeros debe escribir -00") t_positivos=0 t_negativos=0 t_pares=0 t_impares=0 mult=0 num=float(input("Por favor ingrese un numero ")) while num!=-00: if num>0: t_positivos=t_positivos+1 else: t_negativos=t_negativos+1 if num%2==0: t_pares=t_pares+1 else: t_impares=t_impares+1 if num%8==0 mult=mult+1 num=float(input("Por favor ingrese un numero ")) print("La cantidad de positivos es de:", t_positivos) print("la cantidad de negativos es de:", t_negativos) print("La cantidad de pares es de:", t_pares) print("La cantidad de impares es de:", t_impares) print("Los numeros multiplos de ocho fueron:", mult)
false
2df2b53ec9f62cb221fe8ac78e13b9d14a9ad3df
NurbekSakiev/Essential_Algorithms
/merge_Sort.py
550
4.15625
4
// Algorithms // Merge Sort // author: Nurbek Sakiev def mergeSort(list_): if (len(list_) <= 1): return list_ mid = len(list_)//2 first = mergeSort(list_[:mid]) second = mergeSort(list_[mid:]) return list(merge(first,second)) def merge(list1, list2): i=j=0 last = [] while (i <len(list1) and j<len(list2)): if(list1[i] < list2[j]): last.append(list1[i]) i=i+1 else: last.append(list2[j]) j = j+1 if list1: last.extend(list1[i:]) if list2: last.extend(list2[j:]) return last test = [5,3,2,6,7,8,1,9] print mergeSort(test)
false
8ec919cee9c1ce1c5a1a92e94e661e153449b5cd
axisonliner/Python
/del_files.py
1,854
4.125
4
# Script for deleting files from a folder using the command line: # command line: python del_files.py arg1 arg2 # - arg1 = folder path # - arg2 = file extention # Example: python del_files.py C:\Desktop\folder_name .exr import os import sys import math def get_size(filename): st = os.stat(filename) return st.st_size def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "{0} {1}".format(s, size_name[i]) def del_files(path, file): files_size = 0 file_num = 0 try: directory = str(sys.argv[1]) ext_file = str(sys.argv[2]) for root, dirs, files in os.walk(directory): path = root.split(os.sep) for file in files: if file.endswith(ext_file): path_to_file = '/'.join(path) + '/' + file files_size += get_size(path_to_file) print("delete file: {}".format(path_to_file)) os.remove(path_to_file) file_num += 1 if not file_num: print("'{}' files not found".format(ext_file)) else: print print("{} - files have been deleted".format(file_num)) print("{} - total file size".format(convert_size(files_size))) except IndexError: print("Please, please provide two arguments:") print("arg1 = folder path") print("arg2 = file extention") print("Example: python del_files.py C:/Desktop/folder_name .exr") if __name__ == '__main__': path = "" file = "" print del_files(path, file)
true
2a0f013ad2aac2a67e9eafb1fa8a009d9aa663a8
ESROCOS/tools-pusconsole
/app/Utilities/Database.py
2,907
4.375
4
import sqlite3 as sq3 from sqlite3 import Error class Database(object): """ This class represents a database object. It implements some methods to ease insertion and query tasks """ def __init__(self, dbname: str): """ This is the constructor of the class :param dbname: The name of the database to open """ self.db = None self.cursor = None self.open_db(dbname) def create_dump_table(self, table_name: str = "packages"): """ This method creates a table in the database with the name passed as argument :param table_name: The name of the table """ query = """CREATE TABLE IF NOT EXISTS """ + table_name + """( type text, serv_id integer, msg_id integer, time text, src integer, des integer, seq integer, status text, info text, rest_of_data json );""" self.cursor.execute(query) def create_history_table(self, table_name: str = "history"): """ This method creates a table in the database with the name passed as argument :param table_name: The name of the table """ query = """CREATE TABLE IF NOT EXISTS """ + table_name + """( name text, packets json );""" self.cursor.execute(query) def open_db(self, db_name: str): """ This method opens the database with the name passed as an argument :param db_name: The name of the database to be opened """ try: self.db = sq3.connect(db_name) self.cursor = self.db.cursor() except Error as e: print(e) def query_db(self, query: str, _list: tuple = None): """ This methods execute a query or an insertion in the db :param query: Query using prepared statement :param _list: Parameters of the prepared statement :return: Results of the query """ if _list is None: return self.cursor.execute(query) else: return self.cursor.execute(query, _list) #REVISAR: SE ANADIERON DOS PARÁMETROS MAS A CADA ELEMENTO DE LA TABLA #QUE NO TIENEN QUE SER INSERTADOS. ESTOS SON EL INDICE Y EL PAQUETE #EN FORMA DE PAQUETE. def insert_db(self, query: str, elem): """ This methods execute an insertion in the db :param query: Query using prepared statement :param elem: Parameters of the prepared statement """ self.cursor.executemany(query, elem) self.db.commit()
true
e7eea0e92c5c8cf7c537f545b05a17a819b4d108
pab2163/pod_test_repo
/Diana/stock_market_challenge.py
1,221
4.25
4
# Snippets Challenge # Playing with the stock market. # Write code to take in the name of the client as the user input name = input("Hi there!\nWhat is your name?: ") print("Hello "+ name + "!" ) # Write code to get user input savings" and personalize message with "name" savings =int(input("What are your current savings?")) print(f"Wow, thats amazing, you have $ {savings} to invest.") stock = input("The avaible stocks are Apple, Amazon, Facebook, Google and Microsoft.\nWhich of these would you like to see the breakdown on?" ) print(f"Great choice {name}! We love {stock}. ") Amazon = 3000 Apple = 100 Facebook = 250 Google = 1400 Microsoft = 200 if stock == "Amazon": price = (3000) shares = (savings / Amazon) elif stock == "apple": price = (100) shares = (savings / Apple) elif stock == "facebook": price = (250) shares = (savings / Facebook) elif stock == "google": price = (1400) shares = (savings / Google) elif stock == "microsoft": price = (200) shares = (savings / Microsoft) print(f"Based on your selection, you are able to purchase {shares} of {stock}.The current market price is {price} per share.") #else # Perform user-specific calculation
true
d3db4c2dbb599de13e7396db16f96912d335b126
Abdullahalmuhit/BT_Task
/BT_Solution.py
548
4.125
4
value = int (input("How many time you want to run this program?: ")) def check_palindromes(value): charecter = input("Enter Your One Character: ") my_str = charecter+'aDAm' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("It is palindrome") else: print("It is not palindrome") for x in range(value): check_palindromes(value)
true
9297bd49c2a7ddd20007b3d0f599ce7a15cfa670
rajatkashyap/Python
/make_itemsets.py
564
4.21875
4
'''Exercise 3 (make_itemsets_test: 2 points). Implement a function, make_itemsets(words). The input, words, is a list of strings. Your function should convert the characters of each string into an itemset and then return the list of all itemsets. These output itemsets should appear in the same order as their corresponding words in the input.''' def make_itemsets(words): words_l=words.split() print words_l make_itemsets=[] for w in words_l: make_itemsets.append(set(w)) return make_itemsets print make_itemsets("Hi how are you Rajat")
true
8095f1c33d099fcdad65003a2f4add5d07bd5090
orionbearduo/Aizu_online_judge
/ITP1/ITP_1_6_A.py
539
4.28125
4
""" Reversing Numbers Write a program which reads a sequence and prints it in the reverse order. Input The input is given in the following format: n a1 a2 . . . an n is the size of the sequence and ai is the ith element of the sequence. Output Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element). """ n = int(input()) table = list(map(int, input().split())) table.reverse() print(' '.join(map(str, table)))
true
0935e6a46fdd933261931fa71727206015745918
orionbearduo/Aizu_online_judge
/ITP1/ITP_1_5_C.py
824
4.28125
4
""" Print a Chessboard Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. #.#.#.#.#. .#.#.#.#.# #.#.#.#.#. .#.#.#.#.# #.#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Input The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space. The input ends with two 0 (when both H and W are zero). Output For each dataset, print the chessboard made of '#' and '.'. Print a blank line after each dataset. """ while True: H, W = map(int, input().split()) if H == 0 and W == 0: break for i in range(H): for j in range(W): if (i + j) % 2 == 0: print("#", end = '') else: print(".", end = '') print() print()
true
bdff89efc61f5158b6d87dd6b5eeb5f11e91b898
orionbearduo/Aizu_online_judge
/ITP1/ITP_1_8_A.py
245
4.3125
4
# Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string. # Sample Input # fAIR, LATER, OCCASIONALLY CLOUDY. # Sample Output # Fair, later, occasionally cloudy. n = str(input()) print(n.swapcase())
true
dd8e680dc6602a27517af06f09319447b4256735
renuit/renu
/factor.py
226
4.125
4
n=int(input("Enter a number:")) fact=1 if(n<0): print("No factorial for -Ve num") elif(n==0): print("factorial of 0 is 1") else: for i in range(1,n+1): fact=fact*i print("factorial of", n,"is",fact)
true
7c94602bbc0ce53124f4e2c892c85d24dcbd0331
garima-16/Examples_python
/occurrence.py
260
4.4375
4
#Program to find the occurrences of a character in a string string1=input("enter any string ") ch=input("enter a character ") count=0 for i in string1: if ch==i: count+=1 print("number of occurrences of character in string ",count)
true
c310929561622e694202ce37ffcd91d77ef4551c
Dinesh-Sivanandam/Data-Structures
/Linked List/insert_values.py
1,664
4.375
4
#Creating the class node class Node: def __init__(self, data=None, next=None): self.data = data self.next = next #Creating the class for linked list class LinkedList: #this statement initializes when created #initializing head is none at initial def __init__(self): self.head = None """ Function for printing the linked list if the head is none the link list is empty else initializing the itr value as head and incrementing iterating until the itr is none and printing the values """ def print(self): if self.head is None: print("Linked list is empty") return itr = self.head llstr = '' while itr: llstr += str(itr.data)+' --> ' if itr.next else str(itr.data) itr = itr.next print(llstr) """ function to insert the set of values in the linked list this function gets the list of values then iterate through the list values one by one then insering the value to the end by insert_at_end function """ def insert_values(self, data_list): self.head = None for data in data_list: self.insert_at_end(data) def insert_at_end(self, data): if self.head is None: self.head = Node(data, None) return itr = self.head while itr.next: itr = itr.next itr.next = Node(data, None) if __name__ == '__main__': ll = LinkedList() ll.insert_values(["banana","mango","grapes","orange"]) ll.print()
true
8cf94f263fe14f4f2487f41f0446e8b968f3f9c6
maor90b/Bartov
/project2-master/package1/דוגמה 4 תנאים.py
911
4.28125
4
grade =int(input("enter number: ")) if grade<0 or grade>100: print("the grade is between 0 and 100") if grade>=0 and grade<=100: # דרך נוספת if 90<=grade<=100: print("very good") if grade<90 and grade>=80: print("good") if grade<80 and grade>=70: print("ok") if grade<70 print("failed") else: print("invaild grade") if grade>=0 and grade<=100: if grade>=90: print("very good") else: if grade>=80: print("good") else: if grade>=70: print("ok") else: print("failed") else: print("invaild grade") if grade>=0 and grade<=100: if grade>=90: print("very good") elif grade>=80: print("good") elif grade>=70: print("ok") else: print("failed") else: print("invaild grade")
false
0693111789c72af4db96730c3caa7b0cf4422571
sachinasy/oddevenpython
/prac1.py
268
4.34375
4
# program to identify the even/odd state of given numbers # function to print oddeven of given number #oddeven function number = int(input("enter a number: ")) if number % 2== 0: print ("the entered number is even") else: print ("the entered number is odd")
true
e3459e66daea9d2747d6b5e5f05db326b8f2a127
epangar/python-w3.exercises
/String/1-10/5.py
343
4.125
4
""" 5. Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. """ def style_str(str1, str2): answer1 = str2[0:2] + str1[2:] answer2 = str1[0:2] + str2[2:] answer = answer1 + " " + answer2 return answer print(style_str('abc', 'xyz'))
true
3f12cfba4069f64e2c4218935ae0649fbb5d05bd
epangar/python-w3.exercises
/String/1-10/2.py
327
4.28125
4
""" 2. Write a Python program to count the number of characters (character frequency) in a string. """ def count_char(str): dict = {} for i in range(0, len(str)): key = str[i] if key in dict: dict[key] += 1 else: dict[key] = 1 return dict
true
2afa17246ba3754f0694b361e4d8f6cbc0df047d
pdshah77/Python_Scripts
/Input_Not_Required/PreFixMapSum.py
776
4.28125
4
''' Write a Program to Implement a PrefixMapSum class with the following methods: insert(key: str, value: int): Set a given key's value in the map. If the key already exists, overwrite the value. sum(prefix: str): Return the sum of all values of keys that begin with a given prefix. Developed By: Parth Shah Python Version: Python 3.7 ''' class PrefixMapSum: map_dict = {} def insert(self,key,value): self.map_dict[key] = value def sum(self,prefix): sum = 0 leng = len(prefix) for key,value in self.map_dict.items(): if key[:leng] == prefix: sum += value print(sum) mapsum = PrefixMapSum() mapsum.insert("columnar", 3) mapsum.sum("col") #assert mapsum.sum("col") == 3 mapsum.insert("column", 2) mapsum.sum("col") #assert mapsum.sum("col") == 5
true
35615a6933af9421794d96c35d06310a87ac0562
Flact/python100
/Codes/day_02.py
2,417
4.3125
4
# it will print "H" # print("Hello"[0]) # --------------------------- # type checking # num_char = len(input("What is your name? ")) # this print function will throw a erorr # print("Your name has " + num_char + " Characters") # ----------------------------------------------------- # print(type(num_char)) # the fix # new_num_char = str(num_char) # print("Your name has " + new_num_char + " Characters") # ----------------------------------------------------------- # this will print 112 # print(1_2 + 100) # ------------------------------------- # a = float(124) # print(type(a)) # print(70 + float("100.12")) # --------------------------------- # entering two digits numer and add those two digits # num = input("Enter two digits number: ") # print("\n" + str(int(num[0]) + int(num[1]))) # ----------------------------------------------------- # print(2 ** 3) # print(type( 6 / 2)) # ------------------------------- # PEMDAS # Parentheses () # Exponents ** # Multiplication/Division * / # Addition/Subtraction + - # print(3 * 3 + 3 / 3 - 3) # --------------------------------- # BMI Calculator # weight = float(input("Input weight in kg: ")) # height = float(input("Enter hheight in m: ")) # print(int(weight / height ** 2)) # ----------------------------------------------- # ROUND # print(round(8 / 3, 2)) # print(round(2.66666666, 2)) # ------------------------------------------ # floor division --*** # print(8 // 3) # print(type(8 // 3)) # ----------------------------------- # f-string # score = 100 # height = 1.8 # iswinning = True # print(f"Your score is {score} and your height is {height} You are winng is {iswinning}") # ------------------------------------------------------------------------------------------- # Years to live calculator(if you live 90yrs) # age = int(input("Enter your age :")) # years_remain = 90 - age # print(f"You have {years_remain * 365} days, {years_remain * 52} weeks, {years_remain * 12} months") # ------------------------------------------------------------------------------------------------------- # Tip calculator total_bill = float(input("Welcome to tip claculator\nWhat was the total bill? $")) precentage = int(input("What precentage whould you like to tip 10, 12 or 15: ")) people = int(input("How many people to split the bill? ")) print(f"Each person should pay {round((total_bill / people) * (1 + precentage / 100) , 2)}")
true
edd17e6ae441888ea4ea37c64c203075231f5e79
Flact/python100
/Codes/day_05/loop_with_range.py
292
4.28125
4
# for number in range(1, 10): # print(number) # this will print 1 - 9 (not include 10, but include 1) # this will print 1 - 10 numbers step by 3 # for number in range(1, 11, 3): # print(number) # total up to 100 total = 0 for num in range(1, 101): total += num print(total)
true
f229875b6fbae36c226b1df10b1ec46a724d3383
kalpanayadav/python
/cosine.py
802
4.34375
4
def myCos(x): ''' objective: to compute the value of cos(x) input parameters: x: enter the number whose cosine value user wants to find out approach: write the infinite series of cosine using while loop return value: value of cos(x) ''' epsilon=0.00001 multBy=-x**2 term=1 total=1 nxtInSeq=1 while abs(term)>epsilon: divBy=nxtInSeq*(nxtInSeq+1) term=term*multBy/divBy total+=term nxtInSeq+=2 return total def main(): ''' objective: to compute the value of cos(x) input parameters: x: enter the number whose cosine value user wants to find out return value: cos(x) ''' x=float(input('Enter a number :')) print('cos(x) = ',myCos(x)) if __name__=='__main__': main()
true
91556089e400cd90ab55f495d2103f93eed3da35
namratab94/LeetCode
/flipping_an_image.py
1,428
4.125
4
''' Problem Number: 832 Difficulty level: Easy Link: https://leetcode.com/problems/flipping-an-image/ Author: namratabilurkar ''' ''' Example 1: Input: [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] Example 2: Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] ''' class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ final_list = list() for sub_list in A: temp = list() sbl_len = len(sub_list) for i in range(sbl_len): if sub_list[i] == 0: val = 1 elif sub_list[i] == 1: val = 0 temp.append(val) t2 = [] for i in range(len(temp)-1,-1,-1): t2.append(temp[i]) final_list.append(t2) return final_list obj = Solution() # op = obj.flipAndInvertImage(A=[[1,1,0],[1,0,1],[0,0,0]]) op = obj.flipAndInvertImage(A=[[1,1,0],[1,0,1],[0,0,0]]) # op = obj.flipAndInvertImage(A=[[1,0,1]]) print(op==[[1,0,0],[0,1,0],[1,1,1]])
false
5eea6c767938f2599f4cef18c1fe1d6b746aa3e1
Hollow-user/Stepik
/unit3/task6.py
515
4.15625
4
""" Напишите программу, которая подключает модуль math и, используя значение числа π из этого модуля, находит для переданного ей на стандартный ввод радиуса круга периметр этого круга и выводит его на стандартный вывод. Sample Input: 10.0 Sample Output: 62.83185307179586 """ import math r = float(input()) p = math.pi*r*2 print(p)
false
8967563182a4074837916a98d18613789071cdb5
ikemerrixs/Au2018-Py210B
/students/jjakub/session03/list_lab.py
1,244
4.28125
4
#!/usr/bin/env python3 ### Series 1 list_fruit = ["Apples", "Pears", "Oranges", "Peaches"] print(list_fruit) user_fruit = input("Which fruit would you like to add? ") list_fruit.append(user_fruit) print(list_fruit) user_num = input("Provide the number of the fruit to return: ") print(user_num + " " + list_fruit[int(user_num)-1]) user_fruit_02 = input("Which fruit would you like to add? ") list_fruit = [user_fruit_02] + list_fruit print(list_fruit) user_fruit_03 = input("Which fruit would you like to add? ") list_fruit.insert(0,user_fruit_03) print(list_fruit) for frt in list_fruit: if frt[0] == "P": print(frt) ### Series 2 print(list_fruit) list_fruit = list_fruit[:-1] print(list_fruit) del_fruit = input("Which fruit would you like to delete? ") list_fruit.remove(del_fruit) print(list_fruit) ### Series 3 mod_list = list_fruit[:] for frt in list_fruit: user_pref = input("Do you like " + frt.lower() + "? ") while user_pref.lower() not in ("yes", "no"): user_pref = input("Please answer yes or no: ") if user_pref.lower() == 'no': mod_list.remove(frt) print(mod_list) rev_lst = [frt[::-1] for frt in list_fruit] list_fruit.remove(list_fruit[-1]) print(list_fruit) print(rev_lst)
false
35fe7adbad7d0928347a52e7bc91f0fd2b4662a5
ikemerrixs/Au2018-Py210B
/students/arun_nalla/session02/series.py
1,900
4.375
4
#!use/bin/env python def fibo(n): '''Write a alternative code to get the nth value of the fibonacci series using type (list) 0th and 1st position should return 0 and 1 and indexing nth position should return SUM of previous two numbers''' if n ==0: return 0 elif n ==1: return 1 my_list = [0,1] for x in range(2,n+1): y = my_list[-2] + my_list[-1] my_list.append(y) return my_list[-1] print (fibo (5)) print (fibo (10)) print ('Done with fibonacci series') def lucas(n): '''a code to get the nth value of the Lucas series using type (list) indexing the 0th and 1st position should return 2 and 1,respectively and indexing nth position should return SUM of previous two numbers''' if n ==0: return 2 elif n ==1: return 1 my_list2 = [2,1] for x in range(2,n+1): y = my_list2[-2] + my_list2[-1] my_list2.append(y) return my_list2[-1] print (lucas (5)) print (lucas(10)) print ('Done with lucas series') def sum_series(n, a=0, b=1): list_sum_series = [a,b] if n ==0: return a elif n ==1: return b for x in range (2,n+1): y = list_sum_series[-2] + list_sum_series[-1] list_sum_series.append(y) return list_sum_series[-1] print (sum_series (10)) print (sum_series(10,2)) print (sum_series(10,2,1)) print (sum_series(10,1)) print (sum_series(10,3,5)) print ('Next is assertion statements') if __name__ == "__main__": # run some tests assert fibo(0) == 0 assert fibo(1) == 1 assert fibo(2) == 1 assert fibo(3) == 2 assert fibo(4) == 3 assert fibo(5) == 5 assert fibo(6) == 8 assert fibo(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 assert sum_series(5) == fibo(5) # test if sum_series matched lucas assert sum_series(5, 2, 1) == lucas(5) print("tests passed")
true
c69af38ba8fc630402d9e5415d128a00948cb973
ikemerrixs/Au2018-Py210B
/students/ejackie/session04/trigrams.py
843
4.3125
4
#!/usr/bin/env python3 import sys from collections import defaultdict words = "I wish I may I wish I might".split() def build_trigrams(words): """ build up the trigrams dict from the list of words returns a dict with: keys: word pairs values: list of followers """ trigrams = defaultdict(list) # build up the dict here! for i in range(len(words)-2): pair = words[i:i + 2] follower = words[i + 2] #if tuple(pair) in trigrams: trigrams[tuple(pair)].append(follower) #list(trigrams[tuple(pair)]).append(follower) #trigrams[tuple(pair)] = [trigrams[tuple(pair)], follower] #else: # trigrams[tuple(pair)] = [follower] return trigrams if __name__ == "__main__": trigrams = build_trigrams(words) print(trigrams)
true
6886b16e533f10be42a0cf60f0a8381c805eb6ad
KarmanyaT28/Python-Code-Yourself
/59_loopq4.py
424
4.21875
4
# Write a program to find whether a given number is prime or not number=int(input("enter your number which has to be checked")) # i=2 # for i in range(2,number): # if(number%i==0): # break # print("Not a prime number") prime = True for i in range(2,number): if(number%i==0): prime=False break if prime: print("Prime number") else: print("not a prime bro")
true
812e5fb56f013781312790cd6b4a2a20cc255647
KarmanyaT28/Python-Code-Yourself
/17_playwithstrings.py
1,014
4.40625
4
# name = input("Enter your name\n") # print("Good afternoon, " + name) # --------------------------------------------------------------------------- # Write a program to fill in a letter template given below # letter = '''Dear <Name> , you are selected ! <DATE>''' # letter = ''' # Greetings from TalkPy.org # Dear <|NAME|>, # You are selected ! # Date : <|DATE|> # With regards # ''' # name = input("Enter your name\n") # date = input("Enter date\n") # letter = letter.replace("<|NAME|>",name) # letter = letter.replace("<|DATE|>",date) # print(letter) #------------------------------------------------------------------------- # Write a program to detect double spaces in a string without using conditional statements st = "A string with double spaces" doubleSpaces = st.find(" ") print(doubleSpaces) #----------------------------------------------------------------------- #Replacing the double space with single spaces st = st.replace(" "," ") print(st)
true
027170862720a141e62cd700cc30dc11db0a3b73
KarmanyaT28/Python-Code-Yourself
/45_conditionalq3.py
542
4.25
4
# A spam comment is defined as a text containing following keywords: # "make a lot of money" , "buy now","subscribe this", # "click this". # Write a program to detect these spams. text= input("Enter the text") spam = False if("make a lot of money" in text): spam = True elif("buy now" in text): spam = True elif("subscribe this" in text): spam=True elif("click this" in text): spam = True else: spam=False if(spam): print("This text is spam") else: print("This text is not spam")
true
a0b6a8921da7aa3562a1441fbe826bf528aa5ed6
RealMrRabbit/python_workbook
/exercise_3.py
2,794
4.5
4
#Exercise 3: Area of a Room #(Solved—13 Lines) #Write a program that asks the user to enter the width and length of a room. Once #the values have been read, your program should compute and display the area of the #room. The length and the width will be entered as floating point numbers. Include #units in your prompt and output message; either feet or meters, depending on which #unit you are more comfortable working with. from time import sleep print("Hello and welcome to Room Calculator!") def calculator(x): if x.upper() == "M": width_meters = input("What's the width (in meters)? ") length_meters = input("What's the length (in meters)? ") area_meters = str(float(width_meters) * float(length_meters)) return area_meters if x.upper() == "F": width_feet = input("What's the width (in feet)? ") length_feet = input("What's the length (in feet)? ") area_feet = str(float(width_feet) * float(length_feet)) return area_feet def interface(): start = True while start: user_choice_unit = input("Do you want to calulate in meters (M) or feet (F), or exit enter (x). ") area = calculator(user_choice_unit) #convert meters if user_choice_unit.upper() == "M": print("Your area is: " + area + " M^2") user_choice = input("Would you like to convert to feet (y/n), or start over (x)? ") if user_choice.lower() == "x": continue if user_choice.lower() == "y": print("Your area in feet is: " + str(float(area) ** 3.28084) + " ft^2") continue if user_choice.lower() == "n": print("Thank you for using this calculator!") sleep(2) print("calculator shutting down...") sleep(2) start = False #convert feet if user_choice_unit.upper() == "F": print("Your area is: " + area + " ft^2") user_choice = input("Would you like to convert to meters (y/n), or start over (x)? ") if user_choice.lower() == "x": continue if user_choice.lower() == "y": print("Your area in meters is: " + str(float(area) ** 0.3048) + " M^2") continue if user_choice.lower() == "n": print("Thank you for using this calculator!") sleep(2) print("calculator shutting down...") sleep(2) start = False if user_choice_unit.lower() == "x": print("Thank you for using this calculator!") sleep(2) print("calculator shutting down...") sleep(2) start = False print(interface())
true
6a003911cc1f0f89c481611305ffc7b7d8359f53
Vikramjitsingh0001/assingnments
/assingnment_4.py
2,482
4.15625
4
#Q1 a=(1,2,3,4,5,'car','bike') #take tupil which contains different types of data type print(len(a)) #print the lenth of tupil eg number of varriable #Q2 v=(1,5,3,7,33,9) #take a tupil which contain n number print(max(v)) #from n numbers find the largest one from tupil and print the larest one print(min(v)) #from n numbers find the smallest one from tupil and print the smallest one #Q3 t=(1*2*3*4) #take a tupil and multipe it print(t) #print the product of elementspresent in tupil #Q4(a) s1=set((1,2,3,4,5,6,7)) #take a set s1 s2=set((1,3,6)) #take a set s2 s3=s1-s2 #cmp s1 and s2 to have set s3 print(s3) #print s3 set #(b) a1=set((1,2,3,4,5,6,7,8)) #take set a1 a2=set((2,4,5,7)) #take set a2 a3=a1>=a2 #if a1>=a2 then a1 is a super set of a2 print("a1 is super set of a2") #print print(a3) #print the set a3 a4=a1<=a2 #if a1<=a2 the a1 is a1 issub set of a2 print("a1 is a subset of a2 ") #print print(a4) #print set a4 #(c) b1=set((1,2,3,4,5,6,7)) #take a set b1 b2=set((2,4,7,9)) #take set b2 b3=b1&b2 #take intersetion of two sets print(b3) #print the interrsetion set print("this is the intersection set") #print b4=b1|b2 #take union of two sets print(b4) #print the union of set print("this is the unoin set") #print #Q5 a=input("enter the name") #enter the name you want b=input("enter marks") #enter the marks d={'name':'a','marks':'b'} #make a dicitionary d print(d) #print the dictionary #Q6 #Q7 l=('mississippi') #take a tupil which contains a sting in which there is a repeation of same letters check_for_m=l.count('m') #count the number of m check_for_i=l.count('i') #count the number of i check_for_s=l.count('s') #count the number of s check_for_p=l.count('p') #count the number of p d={'number of m':check_for_m,'number of i':check_for_i,'number of s':check_for_s,'number of p':check_for_p} print(d) #print the dictionary d
false
ad060056fb45d250683cf24300c69c5fc5527dbb
Nubstein/Python-exercises
/Condicionais e Loop/Ex6.py
512
4.125
4
#Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, #sabendo que a decisão é sempre pelo mais barato. p1=float(input("Insira o preco do produto 1: R$ ")) p2=float(input("Insira o preco do produto 2: R$ ")) p3=float(input("Insira o preco do produto 3: R$ ")) if p1<p2 and p1<p3: print(" O menor preço é: ", p1, "R$") elif p2<p3 and p2<p1: print("O menor preço é: ", p2, "R$") elif p3<p2 and p3 <p1: print("O menor preço é: ", p3, "R$")
false
cf35e65f5ed0def55723e846fea1366d42d61a5b
Nubstein/Python-exercises
/Strings/Ex8_strings.py
490
4.25
4
#Verificação de CPF. # Desenvolva um programa que solicite a digitação de um número de CPF # no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido # através da validação dos dígitos verificadores edos caracteres de formatação. cpf=input(" Insira o numero de cpf no formato xxx.xxx.xxx-xx ") if (cpf[3]!=".") or (cpf[7]!=".") or (cpf[11]!="-"): input(" O cpf deve estar no formato xxx.xxx.xxx-xx ") else: print (" O cpf está no formato correto")
false
91be40cb62c28dc236b72ffbcc967239531c4eec
Nubstein/Python-exercises
/Repeticao/Ex1_repet.py
326
4.25
4
#Faça um programa que peça uma nota, entre zero e dez. # Mostre uma mensagem caso o valor seja inválido # e continue pedindo até que o usuário informe um valor válido. nota=float(input("Insira uma nota entre 0 e 10: ")) while nota<0 or nota>10: nota=float(input("Valor incorreto! A nota deve ser de 0 á 10 "))
false
e2fcaedd0a0ac22274ada8167ad5c6050f78bc9e
Nubstein/Python-exercises
/Funcoes/Ex11_funcao.py
436
4.34375
4
# Exercício 3 - Crie uma função que receba como parâmetro uma lista de 4 elementos, adicione 2 elementos a lista e # imprima a lista def funcaoex3 (lista): #defina a função print(lista.append (5)) # insira os elementos que quer adicionar print(lista.append (6)) lista1=[1,2,3,4] #identifique os elementos da lista funcaoex3 (lista1) #atualize a lista com a função print (lista1)
false
12853d4c6fbd6325541bce74c1307871c28bf8f9
z0k/CSC108
/Exercises/e2.py
1,960
4.1875
4
# String constants representing morning, noon, afternoon, and evening. MORNING = 'morning' NOON = 'noon' AFTERNOON = 'afternoon' EVENING = 'evening' def is_a_digit(s): ''' (str) -> bool Precondition: len(s) == 1 Return True iff s is a string containing a single digit character (between '0' and '9' inclusive). >>> is_a_digit('7') True >>> is_a_digit('b') False ''' return '0' <= s and s <= '9' # Write your three function definitions here: def time_of_day(hours, minutes): ''' (int, int) -> str Return the value MORNING if the time is before 12:00, NOON if it is 12:00, AFTERNOON if it is after 12:00 and before 17:00, and EVENING otherwise. >>> time_of_day(12, 0) 'noon' >>> time_of_day(8, 59) 'morning' ''' if hours < 12: return MORNING elif hours == 12 and minutes == 0: return NOON elif hours == 12 and not minutes == 0: return AFTERNOON elif 12 < hours < 17: return AFTERNOON else: return EVENING def closest_time(time1, time2, actual_time): ''' (str, str, str) -> str Return the parameter between time1 and time2 that is closest to actual_time. >>> closest_time('11:59', '12:01', '12:00') '11:59' >>> closest_time('01:40', '13:40', '05:40') '1:40' ''' time1_mins = int(time1[:2]) * 60 + int(time1[-2:]) time2_mins = int(time2[:2]) * 60 + int(time2[-2:]) actual_time_mins = int(actual_time[:2]) * 60 + int(actual_time[-2:]) if abs(time1_mins - actual_time_mins) <= abs(time2_mins - actual_time_mins): return time1 return time2 def sum_digits(string): ''' (str) -> int Return the sum of the values of each integer digit that appears in string. >>> sum_digits('CSC108H1S') 10 >>> sum_digits('2') 2 ''' total = 0 for e in string: if is_a_digit(e): total = total + int(e) return total
true
f23776b0ea7d95b86dc0ab31d15f208657050d50
Tavheeda/python-programs
/lists.py
1,882
4.25
4
# fruits = ['apple','orange','mango','apple','grapes'] # print(fruits) # print(fruits[1]) # import math # for fruit in fruits: # print(fruit) # numbers = [1,2,3,4,5,8,9,10] # print(numbers[2:5]) # print(numbers[3:]) # for number in numbers: # print(number) # i = 0 # while i < len(numbers): # print(numbers[i]) # i +=1 # SNAKE CASING # float_numbers = [12.2,34.1,22.5] # employees = ["tanveer ahmad baba",580000.80,28] # for employee in employees: # print(employee) # python basic data structure - sequence # subjects = ["physics","chemistry","bilogy"] # other_subjects = ["english","urdu"] # # print(subjects) # print(subjects[2]) # subjects[2]="biology" # print(subjects) # subjects.append("english") # print(subjects) # subjects.insert(1,"Atlas") # print(subjects) # subjects.remove("english") # print(subjects) # print(len(subjects)) # all_subjects = subjects + other_subjects # print(all_subjects) # repitions = subjects*3 # print(repitions) # for i in ["physics","chemistry","bilogy"]: # print(i) # INDEXING # print(all_subjects[3:]) # print(all_subjects[:4]) # print(all_subjects[2:4]) # print(all_subjects[:-2]) # print(all_subjects[-5:-3]) # print(all_subjects[2:-4]) # print(cmp(subjects,other_subjects)) # print(all_subjects.count("urdu")) # list1 = [1,2,3,4,5] # list2 = ["eng","phy","chem","bio","zoo"] # list3 = ["tavheeda",14,90] # print(list1) # print(list2) # print(list3) # print(list1*2) # print(list1[:3]) # print(list2[1:5]) # print(list3[-3:-1]) # list1[2]="urdu" # print(list1) # list1.append("6") # print(list1) # list1.insert(3,"his") # print(list1) # del list1[2] # print(list1) # print(list1*3) # print(list1) # # list1.reverse() # print(list1) # a=30 # b=3 # a//b=c # a/b=d # print(c) # print(d) # n = 5 # i = 0 # while i<=n: # print(i*i) # i +=1 # WRTE A PROGRAM TO CONVERT LIST INTO TUPLE l = [1,2,3,4] t = tuple(l) print(t) print(l)
true
a57ab223342720dbd0dd8b49e95a0bc849b307e3
marcelosoliveira/trybe-exercises
/Modulo_4_Ciencia da Computacao/Bloco 35: Programação Orientada a Objetos e Padrões de Projeto/dia_1: Introdução à programação orientada a objetos/conteudo/primeira_entidade.py
816
4.1875
4
class User: def __init__(self, name, email, password): """ Método construtor da classe User. Note que o primeiro parâmetro deve ser o `self`. Isso é uma particularidade de Python, vamos falar mais disso adiante!""" self.name = name self.email = email self.password = password def reset_password(self): print("Envia email de reset de senha") # Para invocar o método construtor, a sintaxe é NomeDaClasse(parametro 1, parametro 2) # Repare que o parâmetro self foi pulado -- um detalhe do Python. meu_user = User("Valentino Trocatapa", "valentino@tinytoons.com", "Grana") # A variável `meu_user` contém o objeto criado pelo construtor da classe User! print(meu_user) print(meu_user.name) print(meu_user.email) print(meu_user.password) meu_user.reset_password();
false
125f1dfaffb6403114b58246d6f16dd7f10c76f6
marcelosoliveira/trybe-exercises
/Modulo_4_Ciencia da Computacao/Bloco 38: Estrutura de Dados II: Listas, Filas e Pilhas/dia_2: Deque/exercicios/exercicio_3.py
1,179
4.25
4
# Exercício 3: Desafio do Palíndromo - Uma palavra é um palíndromo se a sequência de # letras que a forma é a mesma, quer seja lida da esquerda para a direita ou vice-versa. # Crie um algorítimo que, ao receber uma sequencia de caracteres, indique se ela é # ou não um palíndromo. Para este exercício iremos considerar todas os caracteres # como minúsculos e desconsiderar espaços, pontuação e caracteres especiais. # Use a tabela a seguir como exemplo para seus testes: # Tabela exercício 3. # Para esse desafio a maior preocupação é na inserção dos dados, pois não devem ser # considerados caracteres especiais e espaços. Assim como tornar todos os # caracteres minúsculos (ou maiúsculos, o que importa é o padrão), pós inserção, # deve ser realizado a comparação do resultado do pop de cada extremidade. def isPalindromo(terms): deque = Deque() for character in terms: if character.isalpha(): deque.push_back(character.lower()) while len(deque) > 1: front_item = deque.pop_front() back_item = deque.pop_back() if front_item != back_item: return False return True
false
1d675bd4f0271c09a8998b7ea02f4b2d3110b6cf
powerlego/Main
/insertion_sort.py
1,053
4.125
4
""" file: insertion_sort.py language: python3 author: Arthur Nunes-Harwitt purpose: Implementation of insertion sort algorithm """ def insertion_sort(lst): """ insertionSort: List( A ) -> NoneType where A is totally ordered effect: modifies lst so that the elements are in order """ for mark in range(len(lst) - 1): insert(lst, mark) def insert(lst, mark): """ insert: List( A ) * NatNum -> NoneType where A is totally ordered effect: moves the value just past the mark to its sorted position """ for index in range(mark, -1, -1): if lst[index] > lst[index + 1]: swap(lst, index, index + 1) else: return def swap(lst, i, j): """ swap: List( A ) * NatNum * NatNum -> NoneType where A is totally ordered effect: swaps the values in lst at positions i and j """ (lst[i], lst[j]) = (lst[j], lst[i]) if __name__ == "__main__": L = [1, 5, 3, 4, 2, 2, 7, 5, 3, 4, 9, 0, 1, 2, 5, 4, 76, 6] insertion_sort(L) print(L)
true
a0dbb5f621dd2a58469e0d26bf9190f45dfc86d8
Rossorboss/Python_Functions_Prac
/map,filter,lambda.py
2,621
4.5625
5
#map, lambda statements def square(num): return num ** 2 my_nums = [1,2,3,4,5] for x in map(square,my_nums): #the map function allows it to be used numerous times at once print(x) # Luke i am your father example--using map to call all 3 at the same time def relation_to_luke(name): if name == 'Darth Vader': return('Luke, I am your father') elif name == 'Leia': return('Luke, I am your sister') elif name == 'Han': return('Luke, I am your brother in law') else: return('Luke, I dont know you') relation = ['Darth Vader', 'Leia', 'Han'] for item in map(relation_to_luke,relation): print(item) #age(years) to days now using map to calculate numerous ages at once def calc_age(x): days_old = x * 365 return(days_old) ages = [10,20,30] for age in map(calc_age,ages): print(age) #------------- #lamba function you only use once...no need to def function to use it #return the first letter names_of_people =['Ross', 'Chelsea', 'Hallie', 'Bonnie'] list(map(lambda letter: letter[0],names_of_people)) #this would return ['R','C','H','B'] names_of_people =['Ross', 'Chelsea', 'Hallie', 'Bonnie'] list(map(lambda letter: letter[::-1],names_of_people)) #this would return ['ssoR','aeslehC','eillaH','einnoB'] my_numbers = [1,2,3,4,5] double_num = list(map(lambda num: num *2,my_numbers)) #will return a list of nums in my_numbers print(double_num) #will print the list #------------------- #filter allows you to filter results def check_even(num): return num%2 == 0 mynums = [1,2,3,4,5,6,7,8,9,10] for n in filter(check_even,mynums): #the filter function will only retur n even numbers while if we used the map() it would return either true or false for all numbers in mynums print(n) #count upper lower, .isupper() .islower() def up_low(s): lowercase = 0 uppercase = 0 for char in s: if char.isupper(): uppercase += 1 elif char.islower(): lowercase += 1 else: pass print(f'Original String : {s}') print(f'No. of Upper case characters : {uppercase}') print(f'No. of Lower case characters : {lowercase}') #^^^^^^^^^but using a dictionary def up_low(s): d = {'uppercase': 0,'lowercase': 0} for char in s: if char.isupper(): d['uppercase']+= 1 elif char.islower(): d['lowercase'] += 1 else: pass print(f'Original String : {s}') print(f'No. of Upper case characters : {d["uppercase"]}') print(f'No. of Lower case characters : {d["lowercase"]}')
true
67065afeef4f82ff240a6920f642cc739a486010
dearwendy714/web-335
/week-8/Portillo_calculator.py
645
4.625
5
# ============================================ # ; Title: Assignment 8.3 # ; Author: Wendy Portillo # ; Date: 9 December 2019 # ; Modified By: Wendy Portillo # ; Description: Demonstrates basic # ; python operation # ;=========================================== # function that takes two parameters(numbers) and adds them together def add(x, y): return x + y # function that takes two parameters(numbers) and finds the difference def subtract(x, y): return x - y # function that takes two parameters(numbers) and finds the quotient of them def divide(x, y): return x / y print(add(10, 10)) print(subtract(10, 10)) print(divide(10, 10))
true
84f611ef059a51b87074835a430eedf3da9f346c
davestudin/Projects
/Euler Problems/Euler Problems/Question 6.py
529
4.34375
4
from math import * input = int(raw_input("Enter sum of the desired Pythagorean Triple: ")) def pythag(sum): a,b,c=0.0,0.0,0.0 for a in range (1,sum): for b in range(a,sum): c=sqrt(a*a+b*b) if c%1==0 and a%1==0 and b%1==0: if (a+b+c)==sum: return 'The Pythagorean triple with sides that add up to '+ str(sum) + ', is a = ' + str(a) + ', b = ' +str(b) + ', c = ' +str(int(c)) + '.' else: return 'There is no Pythagorean triple with sides that add up to '+ str(sum) print pythag(input)
true
4b3f447c832012f1baf5aa17d52049ba1a6a442e
asharma567/practice_problems
/codeeval/easy/longest_word.py
988
4.1875
4
''' https://www.codeeval.com/open_challenges/111/ ''' import sys def find_longest_word_greedy(sent): #Greedy: O(n) if sent == '' : return None longest_word = None for word in sent.split(): if not longest_word or longest_word < len(word): longest_word = word return longest_word def find_longest_word_sort(sent): #O(nlogn) return sorted(sent.split(), key=lambda x:len(x), reverse=True)[0] def find_longest_word_dict(sent): from collections import defaultdict sent_dict= defaultdict(list) if sent == '' : return None for word in sent.split(): print word sent_dict[len(word)].append(word) return sent_dict[max(sent_dict)][0] def find_longest_word_max(sent): if sent == '' : return None return max(line.split(), key=lambda x: len(x)) if __name__ == '__main__': with open(sys.argv[1], 'r') as f: for line in f: print find_longest_word_max(line.strip())
false
0e06bc1f938f34183388ac64c76def7a328c4ba1
BNHub/Python-
/Made_Game.py
495
4.40625
4
#1. Create a greeting for your program. print("Welcome to the best band name game!") #2. Ask the user for the city that they grew up in. city = input("What is name of the city you grew up in?\n") #3. Ask the user for the name of a pet. pet_name = input("What's your pet's name?\n") #4. Combine the name of their city and pet and show them their band name. print("Your band name could be " + city + " " + pet_name) #5. Make sure the input cursor shows on a new line, see the example at:
true
1689f5917ee66e8fbdc904983a506f0afdfb06fc
tochukwuokafor/my_chapter_4_solution_gaddis_book_python
/bug_collector.py
285
4.15625
4
NUMBER_OF_DAYS = 5 total = 0 for day in range(NUMBER_OF_DAYS): print('Enter the number of bugs collected on day #' + str(day + 1) + ': ', sep = '', end = '') bugs_collected = int(input()) total += bugs_collected print('The total number of bugs collected is', total)
true
0d1890ddd1b000d26c4f5433970f2db1dc26090a
tochukwuokafor/my_chapter_4_solution_gaddis_book_python
/average_word_length.py
372
4.25
4
again = input('Enter a sentence or a word: ') total = 0 words_list = [] while again != '': words = again.split() for word in words: words_list.append(word) total += len(word) again = input('Enter another sentence or another word: ') average = total / len(words_list) print('The average length of the words entered is', round(average))
true
742ecea8c97e08e476b86cd4f5dcc38cab2bb947
era153/pyhton
/her.py
456
4.21875
4
name=int(input("no days employee1 work")) print("no days hour" , name) name1=int(input("no of hour employee1 work in first day")) print("no days hour" , name1) name2=int(input("no days hour employee1 work in second day")) print("no days hour" , name2) name3=int(input("no hour employee1 work in third day")) print("no days hour" , name3) print("you have work", name1+name2+name3, "hour") print("your average work", ((name1+name2+name3)/3), "in total days")
true
9cb8f89c34398fac7ee7d01a90c67f776eb9c5f7
Linkney/LeetCode
/SwordOffer/O27.py
2,023
4.40625
4
# Again 2020年11月12日17:08:14 二叉树 """ 请完成一个函数,输入一个二叉树,该函数输出它的镜像。 例如输入:      4    /   \   2     7  / \   / \ 1   3 6   9 镜像输出:      4    /   \   7     2  / \   / \ 9   6 3   1 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BasicTree: def showTree(self, root): if root is not None: print("root.val:", root.val) else: print("root.val: None") return self.showTree(root.left) self.showTree(root.right) class Solution: # def mirrorTree(self, root: TreeNode) -> TreeNode: def mirrorTree(self, root): # 函数功能:返回一个 镜像化(以root为根节点的二叉树) 的二叉树 # 如果 节点为空 (都没有左右子树了 就不用镜像化了) # root的right , root的left = 镜像化 (root的left) , 镜像化 (root的right) if root is None: return None # 等式右边被打包成元组 同时赋值 给左侧多个变量 root.right, root.left = self.mirrorTree(root.left), self.mirrorTree(root.right) # 等价于下面 3 行 # tmp = root.left # 左子树先存 # root.left = self.mirrorTree(root.right) # 新(镜像后)的树 的 左子树 是 右子树的镜像 # root.right = self.mirrorTree(tmp) # --- return root # 1 # 2 3 if __name__ == '__main__': tree = TreeNode(4) tree.left = TreeNode(2) tree.right = TreeNode(7) tree.left.left = TreeNode(1) tree.left.right = TreeNode(3) tree.right.left = TreeNode(6) tree.right.right = TreeNode(9) bt = BasicTree() bt.showTree(tree) print("-----------------Mirror-----------------") mtree = Solution().mirrorTree(tree) bt.showTree(mtree)
false
e6e5ebeb12fa3fb2a199ca2eff6ed08acee9953a
Linkney/LeetCode
/SwordOffer-3/O11.py
1,420
4.1875
4
""" 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。 例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。   示例 1: 输入:[3,4,5,1,2] 输出:1 示例 2: 输入:[2,2,2,0,1] 输出:0 """ class Solution: # def minArray(self, numbers: List[int]) -> int: # 寻找逆序对 def minArray(self, numbers): for index in range(len(numbers)-1): if numbers[index] > numbers[index+1]: return numbers[index+1] # 0个元素被旋转 return numbers[0] # 二分法 大 min 小 升序 def minArray2(self, numbers): left, right = 0, len(numbers) - 1 while left < right: print(left, right) # mid = (left + right) // 2 mid = left + (right - left) // 2 if numbers[mid] > numbers[right]: left = mid + 1 elif numbers[mid] < numbers[right]: right = mid else: return min(numbers[left:right]) return numbers[left] if __name__ == '__main__': # numbers = [3, 4, 5, 1, 2] numbers = [1, 3, 5, 6, 8] print(Solution().minArray(numbers)) print(Solution().minArray2(numbers)) print(Solution().minArray3(numbers))
false
18b42aa3c505c566d905393bce4c031ce26320bc
Linkney/LeetCode
/SwordOffer/O26.py
1,938
4.28125
4
# Again 2020年11月11日11:12:00 二叉树匹配 """ 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A:      3     / \    4   5   / \  1   2 给定的树 B:    4    /  1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 输入两棵树 进行check是否符合 A主树 B小树 def check(self, A, B): if B is None: return True if A.val != B.val or A is None: return False ans1 = self.check(A.left, B.left) ans2 = self.check(A.right, B.right) return ans1 and ans2 def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: if A is None or B is None: return False ans1 = self.isSubStructure(A.left, B) ans2 = self.isSubStructure(A.right, B) return self.check(A, B) or ans1 or ans2 if __name__ == '__main__': A = TreeNode(1) A.left = TreeNode(2) A.right = TreeNode(3) A.left.left = TreeNode(1) # A.left.right = TreeNode(2) B = TreeNode(3) # B.left = TreeNode(1) print(Solution().isSubStructure(A, B)) # def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: # def recur(A, B): # if not B: return True # if not A or A.val != B.val: return False # return recur(A.left, B.left) and recur(A.right, B.right) # # return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))
false
db03e6f78b9d00381d5a99494591c51d37273f82
Linkney/LeetCode
/LeetCodeAnswer/O11.py
645
4.15625
4
""" 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。 例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。   示例 1: 输入:[3,4,5,1,2] 输出:1 示例 2: 输入:[2,2,2,0,1] 输出:0 """ # def minArray(self, numbers: List[int]) -> int: class Solution: def minArray(self, numbers): # 憨傻题 for i in range(len(numbers)-1): if numbers[i] > numbers[i+1]: return numbers[i+1] return numbers[0]
false
1504008a8d33a1bc1fcd9dcca04fcb05221e1eb6
hiteshpindikanti/Coding_Questions
/DCP/DCP140.py
950
4.125
4
""" This problem was asked by Facebook. Given an array of integers in which two elements appear exactly once and all other elements appear exactly twice, find the two elements that appear only once. For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does not matter. Follow-up: Can you do this in linear time and constant space? """ def get_odd_elements(array: list) -> tuple: xor = 0 for element in array: xor = xor ^ element set_bit_index = 0 while not xor & (1 << set_bit_index): set_bit_index += 1 group1_xor = 0 group2_xor = 0 for element in array: if element & (1 << set_bit_index): # Group 1 group1_xor = group1_xor ^ element else: # Group 2 group2_xor = group2_xor ^ element return group1_xor, group2_xor if __name__ == "__main__": print(get_odd_elements([2, 4, 6, 8, 10, 2, 6, 10]))
true
9484cc99d76ae1d45dced6765fb9d850210ed1bc
hiteshpindikanti/Coding_Questions
/DCP/DCP9.py
1,348
4.21875
4
""" This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-up: Can you do this in O(N) time and constant space? """ def largest_sum(arr): odd_max = float('-inf') even_max = float('-inf') if len(arr) <= 2: return max(arr) else: even_max = arr[0] odd_max = arr[1] index = 2 while index < len(arr): if index % 2 == 0: odd_max = max(odd_max, even_max) if odd_max < 0: odd_max = 0 even_max = max(even_max, even_max + arr[index]) if even_max < 0: even_max = 0 else: even_max = max(odd_max, even_max) if even_max < 0: even_max = 0 odd_max = max(odd_max, odd_max + arr[index]) if odd_max < 0: odd_max = 0 index += 1 if max(odd_max, even_max) <= 0: return max(arr) else: return max(odd_max, even_max) print(largest_sum([5, 1, 1, 5])) print(largest_sum([2, 4, 6, 2, 5])) print(largest_sum([0, 0, 9, 10, 8, 0, 0])) print(largest_sum([-1, -10, -1, -5, 10]))
true
1f7e0f8e5af1f2f26af8d46cfdc55a235fed2168
hiteshpindikanti/Coding_Questions
/DCP/DCP61.py
512
4.25
4
""" This problem was asked by Google. Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. """ def pow(base: int, power: int) -> int: extra = 1 while power > 1: if power % 2: extra *= base power -= 1 base *= base power //= 2 base *= extra return base pow(2, 100)
true
fcedd0fd56b0b84c51738c5e1fff640a6d79ffd5
hiteshpindikanti/Coding_Questions
/DCP/DCP46.py
1,148
4.1875
4
""" This problem was asked by Amazon. Given a string, find the longest palindromic contiguous substring. If there are more than one with the maximum length, return any one. For example, the longest palindromic substring of "aabcdcb" is "bcdcb". The longest palindromic substring of "bananas" is "anana". """ from copy import deepcopy def get_longest_palindrom_substring(s: str) -> str: lps_length_table = [[1] * len(s) for _ in range(len(s))] lps = "" for row in range(len(s) - 1, -1, -1): for col in range(len(s) - 1, row, -1): if lps_length_table[row + 1][col - 1] == (col - 1) - (row + 1) + 1: # s[row+1:col] is a palindrome if s[row] == s[col]: # s[row:col+1] is a palindrome lps_length_table[row][col] = col - row + 1 if len(lps) < col - row + 1: lps = s[row:col + 1] else: lps_length_table[row][col] = lps_length_table[row + 1][col - 1] return lps print(get_longest_palindrom_substring("aabcdcb")) print(get_longest_palindrom_substring("bananas"))
true
890055af08088ea6a059a404b41f58f5a858cd0c
hiteshpindikanti/Coding_Questions
/DCP/DCP102.py
684
4.125
4
""" This problem was asked by Lyft. Given a list of integers and a number K, return which contiguous elements of the list sum to K. For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9. """ from queue import Queue def get_sublist(l: list, k: int) -> list: result_list = Queue() current_sum = 0 for element in l: if current_sum < k: result_list.put(element) current_sum += element if current_sum > k: current_sum -= result_list.get() if current_sum == k: return list(result_list.queue) return [] print(get_sublist([1, 2, 3, 4, 5], 9))
true
7134e0ee6a87054c906298ed87461d2e0d7af0eb
hiteshpindikanti/Coding_Questions
/DCP/DCP99.py
1,089
4.15625
4
""" This problem was asked by Microsoft. Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ def get_longest_consecutive_sequence_length(arr: list): arr_set = set(arr) visited = set() max_count = 0 for index in range(len(arr)): if arr[index] not in visited: count = 1 # Back search num = arr[index] - 1 while num in arr_set: visited.add(num) num -= 1 count += 1 # Forward Search num = arr[index] + 1 while num in arr_set: visited.add(num) num += 1 count += 1 max_count = max(max_count, count) return max_count if __name__ == "__main__": lst = [100, 4, 200, 1, 3, 2] print(get_longest_consecutive_sequence_length(lst)) # answer=4
true
56fe3e955cecc18c2ce1fb1542cfe33b9847ad76
hiteshpindikanti/Coding_Questions
/LeetCode/72.py
1,567
4.125
4
""" Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character """ import heapq def edit_distance(word1: str, word2: str) -> int: if len(word1) < len(word2): word1, word2 = word2, word1 pq = [(0, -0, -0, len(word1) - len(word2))] heapq.heapify(pq) while pq: # print(pq) distance, i, j, diff = heapq.heappop(pq) i = abs(i) j = abs(j) # print("HEAP MIN: {}".format((distance, i, j, diff))) if i == len(word1) and j == len(word2) and diff == 0: return distance elif (i == len(word1) or j == len(word2)) and diff == 0: continue heapq.heappush(pq, (distance + 1, (-(i + 1) if i < len(word1) else -i), (-(j + 1) if j < len(word2) else -j), diff)) heapq.heappush(pq, (distance + 1, (-(i + 1) if i < len(word1) else -i), -j, diff - 1)) # print("Pushed: {}".format(((distance + 1,(-(i + 1) if i<len(word1) else -i), -j, diff - 1)))) if i < len(word1) and j < len(word2) and word1[i] == word2[j]: heapq.heappush(pq, (distance, -(i + 1), -(j + 1), diff)) if diff < len(word1): heapq.heappush(pq, ((distance + 1), -i, -(j + 1), diff + 1)) print(edit_distance("horse", "ros")) print(edit_distance("execution", "intention")) print(edit_distance("trinitrophenylmethylnitramine", "dinitrophenylhydrazine"))
false
793efcdcacb8e3d8865cfcca067fd02c52479fda
hiteshpindikanti/Coding_Questions
/DCP/DCP57.py
1,263
4.15625
4
""" This problem was asked by Amazon. Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less. You must break it up so that words don't break across lines. Each line has to have the maximum possible amount of words. If there's no way to break the text up, then return null. You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word. For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10. """ def break_up(s: str, k: int) -> list: words = s.split(" ") result = [] i = 1 line = words[0] while i < len(words): line_copy = line line += " " + words[i] if len(line) > k: result.append(line_copy) line = words[i] elif len(line) == k: result.append(line) i += 1 line = words[i] i += 1 else: if line: result.append(line) return result sentence = "the quick brown fox jumps over the lazy dog" print(break_up(sentence, k=10))
true
0c03e2f41fce4059b7b56ba1433af5ad221e4c3b
justinembawomye/python-fun
/conditionals.py
265
4.25
4
conditional statements x = 1 y = 5 if x < y: print('x is less than y') else: print('x is not less than y') # Else if if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x is equal to y')
false
b2e4f714b5309331cf1be2e1c3acc9827f1edb99
INF1007-2021A/c03_ch4_exercices-NickLopz
/exercice.py
1,570
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_even_len(string: str) -> bool: total = len(string) if total%2 == 0: return True def remove_third_char(string: str) -> str: list1 = list(string) del(list1[2]) string = ''.join(list1) return string def replace_char(string: str, old_char: str, new_char: str) -> str: newString = string.replace(old_char, new_char) return newString def get_nb_char(string: str, char: str) -> int: count = 0 x = len(string) for x in string : if x == char : count+=1 return count def get_nb_words(sentence: str) -> int: space = ' ' count = 0 x = len(sentence) for x in sentence : if x == space : count+=1 count+=1 final = str (count) return final def main() -> None: string = "Bonjour!" parity = 'pair' if is_even_len(string) else 'impair' print(f"Le nombre de caractère dans la chaine '{string}' est {parity}") string = "Sam est cool!" print(f"On supprime le 3e caratère dans la chaine '{string}'. Résultat: {remove_third_char(string)}") string = "hello world!" print(f"On remplace le caratère w par le caractère z dans la chaine: '{string}'. Résultat: {replace_char(string, 'w', 'z')}") print(f"Le nombre d'occurrence de l dans hello world! est : {get_nb_char(string, 'l')}") string = "Baby shark doo doo doo doo doo doo" print(f"Le nombre de mots dans la chaine {string} est: {get_nb_words(string)}") if __name__ == '__main__': main()
false
1bec2c55f061c3fd1f367ba492d0b580950583e3
santosh1561995/python-practice
/python-variables.py
429
4.125
4
print("For the datatypes in python an variable declaration") #in python data type will be calculated automtically no need to declare explicitly #integer type x=5 print(x) #float f=5.5 print(f) #multiple assignment to variable a=b=c=10 print(a,b,c) #assign values in one line a,b=1,"India" print(a,b) #Swapping the values x,y="X","Y" y,x=x,y print(x,y) #Strings in python x='String 1' y="String 2" print(x,y)
true
69cba86251ad064401c15b3a52c496026f0e8d3a
aliensmart/in_python_algo_and_dat_structure
/Code_1_1.py
738
4.46875
4
print('Welcome to GPA calculator') print('Please enter all your letter grades, one per line') print('Enter a blank line to designate the end.') #map from letter grade to point value points = { 'A+':4.0, 'A':4.0, 'A-':3.67, 'B+':3.33, 'B':3.0, 'B-':2.67, 'C+':2.33, 'C':2.0, 'C':1.67, 'D+':1.33, 'D':1.0, 'F':0.0 } num_courses = 0 total_point = 0 done = False while not done: grade = input() if grade == '': done = True elif grade not in points: print("Unknown grade '{0}' being ignored".format(grade)) else: num_courses +=1 total_point +=points[grade] if num_courses > 0: print('Your GPA is {0:.3}'.format(total_point/num_courses))
true
5a60265d56d150d6934174bdfc59481c84073191
Mukesh656165/Listobj
/tricklist4.py
1,364
4.53125
5
#nested list a_list = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] # to access single item which is in this case[a,g,j] print(a_list[0],a_list[2],a_list[4]) #to access [bb,[ccc,ddd],ee,ff] print(a_list[1]) #to access [hh,jj] print(a_list[3]) #to access bb print(a_list[1][0]) #to access [ccc,ddd] print(a_list[1][1]) #to access ccc print(a_list[1][1][0]) #to access ddd print(a_list[1][1][1]) a_list = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] #to access ee print(a_list[1][2]) #to access ff print(a_list[1][3]) #to print [hh,ii] print(a_list[3]) #to access hh print(a_list[3][0]) #to access ii print(a_list[3][1]) #to print only last item print(a_list[4]) # access in diffrent way x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] # to access ddd print(x[1]) #then access [ccc,ddd] print(x[1][1]) # now access ddd print(x[1][1][-1]) # now some more tricks slicing print(x[1]) #to access [ccc,ddd] print(x[1][1:2]) # to reverse [hh,ii] #to print [hh,ii] print(x[3]) #then reverse the list print(x[3][::-1])# Great techniqui to handson slicing and indexing x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j'] print(len(x)) print(x[0]) print(x[1]) print(x[2]) print(x[3]) print(x[4]) print('ddd' in x) print('ddd' in x[1]) print('ddd' in x[1][1])# not it achives the target
false
792c526926b6d81f5ea0eb32bb87e1415959baa4
yangliu2/cards
/cards/card.py
1,063
4.15625
4
class Card: def __init__(self, suit, value): self.suit = suit self.value = value self.rank = -1 self.name = self.convert_value_to_name(value) def __str__(self): """give back string name""" return f"{self.name} of {self.suit}" def __repr__(self): return f"{self.name} of {self.suit}" def __eq__(self, other): return f"{self.name} of {self.suit}" == f"{other.name} of {other.suit}" @staticmethod def convert_value_to_name(value) -> str: """Map the value to a string""" value_to_name = { 1: "Ace", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 13: "King" } return value_to_name[value] def show(self): print(f"{self.name} of {self.suit}")
false
633cf9adaadad858607db184e9495e9a69d41937
aZuh7/Python
/oop.py
1,440
4.25
4
# Python Object-Oriented Programming class Employee: raise_amount = 1.04 num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@company.com" Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * Employee.raise_amount) # Class is a blueprint for creating instances emp_1 = Employee('Corey', 'Schafer', 50000) emp_2 = Employee('Test', 'User', 60000) print(Employee.num_of_emps) emp_1.raise_amount = 1.05 print(emp_1.__dict__) print(Employee.raise_amount) print(emp_1.raise_amount) print(emp_2.raise_amount) # emp_1.apply_raise() # print(emp_1.pay) # # emp_1.raise_amount # # Employee.raise_amount # Instnce variables contain data that is unique to each instance #emp_1.first = "Corey" #emp_1.last = "Schafer" #emp_1.email = 'Corey.Schaer@company.com' #emp_1.pay = 60000 #emp_2.first = "Test" #emp_2.last = "User" #emp_2.email - 'Test.User@company.com' #emp_2.pay = 60000 # We want the abililty to perform some action # can do manually like: #print('{} {}'.format(emp_1.first, emp_1.last)) # or create a method in our class. # print(emp_1.fullname()) # print(emp_1.email) # print(emp_2.email) # can also run these methods by using the class itself # emp_1.fullname() # print(Employee.fullname(emp_1))
true
567c3b801b9679d4b30733df891d558e947fb65a
archisathavale/training
/python/basic_progs/min_max_nums.py
904
4.3125
4
#funtion of finding the minimum number def find_min_val(array): # assigning 1st element of array to minval minval=array[0] # traversing through the array for element in array: # to check whether the next element is smaller than the current if element < minval: # if yes assigning that number to minval minval = element return minval #funtion of finding the maximum number def find_max_val(array): # assigning 1st element of array to maxval maxval=array[0] # to check whether the next element is greater than the current for element in array: # to check whether the next element is greater than the current if element > maxval: #if yes assigning that number to maxval maxval = element return maxval if __name__ == '__main__': print (find_min_val([2, 3, 4])) print (find_min_val([55,83,14,-4])) print (find_max_val([2,3,4])) print (find_max_val([55,83,14,-4]))
true
cee62cc8bd73c1f9be83e55fdc5e4c4ceb920a55
archisathavale/training
/python/Archis/addressbook.py
790
4.1875
4
addressbook={} # Empty Dictionary # Function of adding an address # email is the key and name is the value def add_address(email , name): addressbook [email] = name #print (addressbook) return (email, name) # Function of deleting an address # only key is enough to delete the value in a dictionary def dele_address(email): del addressbook[email] #print (addressbook) return (email) # Function of printing the addressbook def print_address(): print (addressbook) return (addressbook) # Passing parameters if __name__ == '__main__' : add_address('archisathavale', 'Archis') add_address('avinashathavale', 'Avinash') add_address('arnavathavale','Arnav') dele_address('arnavathavale') dele_address('avinashathavale') add_address('pankajaathavale', 'Pankaja') print_address()
true
93d48b9b89f9ebaabe098bf46fcea589a96cd384
GuySK/6001x
/minFixPaymentCent.py
2,218
4.125
4
# This program calculates the minimum fixed payment to the cent # for cancelling a debt in a year with the interest rate provided. # minFixPaymentCent.py # def annualBalance(capital, annualInterestRate, monthlyPayment): ''' Calculates balance of sum after one year of fixed payments. Takes capital, interst rate and payment as int or floats. ''' period = 0 interest = 0.0 newBalance = capital # for period in range(1,13): newBalance -= monthlyPayment # update balance with payment interest = newBalance * (annualInterestRate/12.0) # calculate interest newBalance += interest # and add it to next period"s balance return newBalance # final balance # end of function # # Main while True: # The following lines must be commented before submitting to grader # balance = float(raw_input('Enter capital: ')) annualInterestRate = float(raw_input('Enter rate: ')) # # validate input if balance < 0 or annualInterestRate < 0: print('Error. Balance, interest rate cannot be negative.') break monthlyInterestRate = annualInterestRate/12.0 # monthly rate lowerPayment = balance / 12.0 # lower limit is for no interest upperPayment = (balance * (1 + monthlyInterestRate)**12)/12 # upper limit loopCounter = 0 # just to know how many iterations takes payment = lowerPayment + (upperPayment - lowerPayment) / 2.0 # starting point # while abs(annualBalance(balance,annualInterestRate,payment)) > 0.01: loopCounter +=1 # count how many iterations if (annualBalance(balance,annualInterestRate,payment) > 0.0): # not enough lowerPayment = payment # set new lower limit else: upperPayment = payment # set new upper limit payment = lowerPayment + (upperPayment - lowerPayment)/2 # recalculate # print('Iter no: ' + str(loopCounter)) # print('Lower limit: ' + str(lowerPayment)) # print('Upper limit: ' + str(upperPayment)) # print('New Payment: ' + str(payment)) # print('Number of iterations: ' + str(loopCounter)) print('Lowest payment: ' + str(round(payment,2))) break # finish main loop # end of code
true
e19161d4378b326e7c2e9f2c0a570d1952f9fd2b
GuySK/6001x
/PS6/Answer/reverseString.py
524
4.46875
4
def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ if len(aStr) == 0: return '' elif len(aStr) == 1: return aStr else: return aStr[-1] + reverseString(aStr[:-1]) # end of code for reverseString
true
4e7410fee77d106caab46c92cb6e9d978bfb4376
GuySK/6001x
/PS6/Answer/buildCoder.py
661
4.40625
4
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers, and spaces. shift: 0 <= int < 26 returns: dict """ import string lowcase = string.ascii_lowercase upcase = string.ascii_uppercase codeDict = {} i = 0 for letter in lowcase: codeDict[lowcase[i]] = lowcase[(i+shift)%26] i += 1 i = 0 for letter in upcase: codeDict[upcase[i]] = upcase[(i+shift)%26] i += 1 return codeDict # end of code for buildCoder
true
2d9b308bb95891e46a2f5d6cf8b9a46e7f18e54b
GuySK/6001x
/PS4/Answers/bestWord.py
839
4.28125
4
def bestWord(wordsList): ''' Finds the word with most points in the list. wordsList is a list of words. ''' def wordValue(word): ''' Computes value of word. Word is a string of lowercase letters. ''' SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } value = 0 for letter in word: value += SCRABBLE_LETTER_VALUES[letter] return value # end of code topL = ['', 0] for word in wordsList: value = wordValue(word) if value > topL[1]: topL[1] = value topL[0] = word return topL # end of code
true
cec85a8e1acb2412389030e89ec6722bd9c83fbb
Mariappan/LearnPython
/codingbat.com/list_2/centered_average.py
977
4.125
4
# Return the "centered" average of an array of ints, which we'll say is the mean average of the values, # except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, # ignore just one copy, and likewise for the largest value. # Use int division to produce the final average. You may assume that the array is length 3 or more. # centered_average([1, 2, 3, 4, 100]) → 3 # centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 # centered_average([-10, -4, -2, -4, -2, 0]) → -3 def centered_average(nums): large = nums[0] for i in nums: if i > large: large = i small = nums[0] for i in nums: if i < small: small = i count = 0 sum = 0 leave = False for i in nums: if i == small: small = 0 leave = True if i == large: large = 0 leave = True if leave == False: sum += i count += 1 leave = False return sum//count
true
3bd5b189e5a3beb450efad8e39a346d7cd9300c3
lynellf/learing-python
/collections/slices.py
1,944
4.4375
4
# Sometimes we don't want an entie list or string, just a part. # A slice is a new list or string made from a previous list or string favorite_things = ['raindrops on roses', 'whiskers on kittens', 'bright coppeer kettles', 'warm woolen mittens', 'bright paper packages tied up with string', 'cream colored ponies', 'crisp apple strudels'] # The number before the colon is the starting point. The number after is the end-point some_favorite_things = favorite_things[0:2] template = 'Some of my favorite things include {}' print(template.format(some_favorite_things)) # we can omit the first number to always start from the first item some_favorite_things = favorite_things[:2] print(template.format(some_favorite_things)) # we can omit the second number to always select through the last item some_favorite_things = favorite_things[3:] print(template.format(some_favorite_things)) # copy a list new_favorite_things = favorite_things[:] print(template.format(new_favorite_things)) # Step through a sliced list (like every odd or even number) # We can go from left to right with a positive number, or reverse with a negative number numbered_list = list(range(21)) print(numbered_list[::-2]) # [20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0] # We can use slices to delete or replace values letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] del letters[4:8] # ['a', 'b', 'c', 'd', 'i', 'j', 'k', 'l', 'm', 'n'] letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] letters[2:4] = ['hmm'] print(letters) apple = ['a', 'p', 'p', 'l', 'e'] banana = ['b', 'a', 'n', 'a', 'n', 'a'] def sillycase(string): length = len(string) breakpoint = int(length / 2) first_half = string[:(breakpoint)].lower() second_half = string[breakpoint:length].upper() output = first_half + second_half return output print(sillycase('BANANA'))
true
5fd6323dab3a5e3221775e1be76bab49f7f3f68f
lynellf/learing-python
/python_basics/numbers.py
587
4.34375
4
# Numeric Data three = 1 + 2 print('The number %s' %(three)) # Rounding numbers _float = 0.233 + .442349 rounded = round(_float) print('A number is %s, and a rounded number is %s' %(_float, rounded)) # Converting strings to numbers string_num = '12' int_num = int(string_num) float_num = float(string_num) string_num_type = type(string_num) int_num_type = type(int_num) float_num_type = type(float_num) print('The type of the variable "string_num" is %s. The type of variable "float_num" is %s. The type of variable "int_num" is %s.' %(string_num_type, float_num_type, int_num_type))
true
6203dd89bad719a8003dd573f08865acb6301e10
arsummers/python-data-structures-and-algorithms
/challenges/comparator/comparator.py
1,060
4.3125
4
""" Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields: name: a string. score: an integer. Given an array of n Player objects, write a comparator that sorts them in order of decreasing score. if 2 or more players have the same score, sort those players alphabetically ascending by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. example: input = [[Smith, 20], [Jones, 15], [Jones, 20]] output = [[Jones, 20],[Smith, 20], [Jones, 15]] """ """ works on a -1, 0, 1 scale to sort with comparators. """ class Player: def __init__(self, name, score): self.name = name self.score = score def comparator(a, b): if a.score != b.score: return b.score - a.score return (a.name > b.name) - (a.name < b.name)
true
b937852ce70a3d673ec5d34f7d9b9f6f87a73617
arvakagdi/Basic-Algos
/IterativeBinarySearch.py
1,139
4.25
4
def binary_search(array, target): ''' Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: if the target is not found ''' startarr = 0 endarr = len(array)-1 while startarr <= endarr: midlen = (startarr + endarr)//2 mid = array[midlen] if mid == target: return array[midlen] if target > mid: startarr = mid+1 else: endarr = mid-1 return -1 def test_function(test_case): answer = binary_search(test_case[0], test_case[1]) if answer == test_case[2]: print("Pass!") else: print("Fail!") array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 6 index = 6 test_case = [array, target, index] test_function(test_case) array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 11 index = -1 test_case = [array, target, index] test_function(test_case)
true
e030ab9fb1bb852ddaf84ccf10408a57eb543912
deek11/practice_python
/CheckTicTacToe.py
950
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script is used to find a winner of Tic Tac Toe from a 3x3 matrix. """ def main(): mx = [['x', 'x', 'x'], [0, 'o', 0], ['o', 0, 'x']] winner = find_winner(mx) if winner != 0: print "Winner = {0}".format(winner) else: print "No winner" def find_winner(mx): # Rows for i in range(0, 3): row = set([mx[i][0], mx[i][1], mx[i][2]]) if len(row) == 1 and mx[i][0] != 0: return mx[i][0] # Columns for i in range(0, 3): column = set([mx[0][i], mx[1][i], mx[2][i]]) if len(column) == 1 and mx[0][i] != 0: return mx[0][i] # Diagonals diag1 = set([mx[0][0], mx[1][1], mx[2][2]]) diag2 = set([mx[0][2], mx[1][1], mx[2][2]]) if (len(diag1) == 1 or len(diag2) == 1) and mx[1][1] != 0: return mx[1][1] return 0 if __name__ == '__main__': main()
false
16f1014c570a7fc288f820f38343e2caf8ef3e07
deek11/practice_python
/OddEven.py
286
4.1875
4
def find_odd_even(num): if num % 2 == 0: return True return False def main(): num = input("Enter number : ") if find_odd_even(num): print "{0} is even".format(num) else: print "{0} is odd".format(num) if __name__ == '__main__': main()
false
0d27c9844e556d3ae480c4b33b5e20bab7f61164
deek11/practice_python
/RockPaperScissors.py
1,502
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script is used to Make a two-player Rock-Paper-Scissors game. """ def main(): print "Rock Paper Scissors!" print "Rules :- \n" \ "0 - Rock \n" \ "1 - Paper \n" \ "2 - Scissors" continue_play = "y" while continue_play == "y": player1 = input("Player 1, enter your move ") player2 = input("Player 2, enter your move ") sinput1 = get_object(player1) sinput2 = get_object(player2) print "Player1 - {0} | Player2 - {1} \n".format(sinput1, sinput2) if (sinput1 == "Invalid Input") or (sinput2 == "Invalid Input"): print "Invalid Input" else: if (player1 == 0 and player2 == 2) or (player1 == 1 and player2 == 0) or (player1 == 2 and player2 == 1): winner = "Player 1" print winner elif (player2 == 0 and player2 == 2) or (player2 == 1 and player1 == 0) or (player2 == 2 and player1 == 1): winner = "Player 2" else: winner = "None. It is tie!" print "The winner is {0} \n".format(winner) continue_play = raw_input("Press y to continue , n to exit.. \n") def get_object(user_input): if user_input == 0: return "Rock" elif user_input == 1: return "Paper" elif user_input == 2: return "Scissors" else: return "Invalid Input" if __name__ == '__main__': main()
false
01dd8d67ceaad408cb442d882cf3c4c08f3eb445
eduardomrocha/dynamic_programming_problems
/tabulation/python/06_can_construct.py
1,574
4.25
4
"""Can construct. This script implements a solution to the can construct problem using tabulation. Given a string 'target' and a list of strings 'word_bank', return a boolean indicating whether or not the 'target' can be constructed by concatenating elements of 'word_bank' list. You may reuse elements of 'word_bank' as many times as needed. """ from typing import List def can_construct(target: str, word_bank: List[str]) -> bool: """Check if a given target can be constructed with a given word bank. Args: target (str): String that must be constructed. word_bank (List[str]): List of strings that can possibly construct the target. Returns: bool: Returns True if it can be constructed or False if it cannot. """ table: List = [False] * (len(target) + 1) table[0] = True for i in range(len(target)): if table[i]: suffix = target[i:] for word in word_bank: if suffix.startswith(word): table[i + len(word)] = True return table[len(target)] if __name__ == "__main__": print(can_construct("abcdef", ["ab", "abc", "cd", "def", "abcd"])) # True print( can_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) ) # False print( can_construct("enterapotentpot", ["a", "p", "ent", "enter", "ot", "o", "t"]) ) # True print( can_construct( "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", ["e", "ee", "eee", "eeee", "eeeee", "eeeeee"], ) ) # False
true
326a3bc0283e5864a9b7f1930410749884f3fdbc
eduardomrocha/dynamic_programming_problems
/tabulation/python/08_all_construct.py
2,053
4.34375
4
"""All construct. This script implements a solution to the all construct problem using tabulation. Given a string 'target' and a list of strings 'word_bank', return a 2D list containing all of the ways that 'target' can be constructed by concatenating elements of the 'word_bank' list. Each element of the 2D list should represent one combination that constructs the 'target'. You may reuse elements of 'word_bank' as many times as needed. """ from typing import List, Union def all_construct(target: str, word_bank: List[str]) -> Union[List[List], List]: """Count in how many ways the target can be constructed with a given word bank. Args: target (str): String that must be constructed. word_bank (List[str]): List of strings that can possibly construct the target. Returns: List[List[str]]: int: Returns the number of ways that 'target' can be constructed by concatenating elements of the 'word_bank' list. """ table: List = [[] for _ in range(len(target) + 1)] table[0].append([]) for i in range(len(target)): if len(table[i]) > 0: suffix = target[i:] for word in word_bank: if suffix.startswith(word): for combination in table[i]: new_combination = combination + [word] table[i + len(word)].append(new_combination) return table[len(target)] if __name__ == "__main__": print(all_construct("purple", ["purp", "p", "ur", "le", "purpl"])) """ [ ["purp", "le"], ["p", "ur", "p", "le"] ] """ print(all_construct("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"])) """ [ ["ab", "cd", "ef"], ["ab", "c", "def"], ["abc", "def"], ["abcd", "ef"] ] """ print( all_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]) ) # [] print( all_construct("aaaaaaaaaaz", ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"],) ) # []
true
f6d6484b84550580fe2941e92fee20054c66d468
aakhedr/algo1_week2
/part3/quickSort3.py
2,470
4.21875
4
def quickSort(A, fileName): quickSortHelper(A, 0, len(A) - 1, fileName) def quickSortHelper(A, first, last, fileName): if first < last: pivot_index = partition(A, first, last, fileName) quickSortHelper(A, first, pivot_index - 1, fileName) quickSortHelper(A, pivot_index + 1, last, fileName) def partition(A, first, last, fileName): ''' The partition around the pivot element part - Pivot is chosen according to MEDIAN OF THREE pivot rule fileName parameter refers to the file that will be written to calculate the comparisons and the number of paritions ''' ### File writing part ### Not related to the algorith f = open("count_" + fileName, "a") f.write(str(last - first) + '\n') f.close() ### # choose a MEDIAN OF THREE pivot element from the array passed if (last - first + 1) % 2 == 0: mid = ((last - first + 1) / 2) - 1 + first else: mid = ((last - first)/ 2 + first) three = sorted([A[first], A[mid], A[last]]) # pick the median of three three = sorted([A[first], A[mid], A[last]]) median = three[1] ## swap the median with the first element of the aray if median == A[mid]: A[first], A[mid] = A[mid], A[first] if median == A[last]: A[first], A[last] = A[last], A[first] pivot = A[first] i, j = first + 1, first + 1 while j <= last: if A[j] < pivot: A[j], A[i] = A[i], A[j] i += 1 j += 1 A[first], A[i - 1] = A[i -1], A[first] return i - 1 import os def count(dataFile): '''count the number of comparisons and the number of partitions (recurisve calls) ''' inFile = open(dataFile, "r") total = [int(line) for line in inFile] comparisons, partitions = sum(total), len(total) os.remove(dataFile) return comparisons, partitions def sort(): ''' Computes the number of comparisons and the number of partitions (i.e. recurisve calls) in quickSort algorithm ''' files= ['10.txt', '100.txt', '1000.txt', '10000.txt'] result = [] for aFile in files: inFile = open(aFile, "r") intArray = [int(line) for line in inFile] quickSort(intArray, aFile) comparisons, partitions = count("count_" + aFile) result.append((comparisons, partitions)) return result print sort() # import timeit # t = timeit.Timer(sort) # print 'pivot median', t.timeit(number=1)
true
f66e6d8773c886adb6c1932f8904ef545b2e2476
YuSheng05631/CrackingInterview
/ch4/4.5.py
1,184
4.15625
4
""" Implement a function to check if a binary tree is a binary search tree. """ import Tree def isBST(bt): if bt.left is None and bt.right is None: return True if bt.left is not None and bt.left.data > bt.data: return False if bt.right is not None and bt.right.data < bt.data: return False if bt.left is None: return isBST(bt.right) if bt.right is None: return isBST(bt.left) return isBST(bt.left) and isBST(bt.right) def isBST2(bt): return isBST2_a(bt, -99999, 99999) def isBST2_a(bt, min, max): if bt is None: return True if bt.data <= min or bt.data > max: return False if not isBST2_a(bt.left, min, bt.data) or not isBST2_a(bt.right, bt.data, max): return False return True bt = Tree.Node(1) bt.left = Tree.Node(0) bt.right = Tree.Node(20) Tree.levelorderTraversal(bt) print() print(isBST(bt)) print(isBST2(bt)) bt2 = Tree.Node(10) bt2.left = bt Tree.levelorderTraversal(bt2) print() print(isBST(bt2)) # wrong print(isBST2(bt2)) bt2 = Tree.Node(10) bt2.left = bt bt2.right = Tree.Node(9) Tree.levelorderTraversal(bt2) print() print(isBST(bt2)) print(isBST2(bt2))
true
1c428f7cf06fa3b6113b2571221becade498a030
fire-ferrets/cipy
/cipy/alphabet/alphabet.py
1,452
4.46875
4
""" The Alphabet class provides a general framework to embed alphabets It takes a string of the chosen alphabet as attribute. This provides the encryption and decryption functions for the ciphers with a performance boost. """ class Alphabet(): def __init__(self, alphabet): """ Initialise an Alphabet Attributes ---------- alphabet : str The alphabet string """ self.alphabet = alphabet self._length = len(alphabet) self._numbers_to_alphabet = dict(enumerate(self.alphabet)) self._alphabet_to_numbers = dict((v, k) for k,v in self._numbers_to_alphabet.items()) def __repr__(self): return self.alphabet def __len__(self): return self._length def __len_hint__(self): return self._length def __getitem__(self, key): if key in self._numbers_to_alphabet: return self._numbers_to_alphabet[key] elif key in self._alphabet_to_numbers: return self._alphabet_to_numbers[key] def __missing__(self,key, value): raise KeyError("Key not found in Alphabet") def __iter__(self): return self._alphabet_to_numbers.items() def __reversed__(self): return reversed(self._alphabet_to_numbers.keys()) def __contains__(self, item): if item in self._alphabet_to_numbers.keys(): return True else: return False
true