blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9f7a5977df4e57f7c7c5518e4e3bc42f517d1856
matthew-lu/School-Projects
/CountingQueue.py
1,823
4.125
4
# This program can be called on to create a queue that stores pairs (x, n) where x is # an element and n is the count of the number of occurences of x. # Included are methods to manipulate the Counting Queue. class CountingQueue(object): def __init__(self): self.queue = [] def __repr__(self): return repr(self.queue) def add(self, x, count=1): if len(self.queue) > 0: xx, cc = self.queue[-1] if xx == x: self.queue[-1] = (xx, cc + count) else: self.queue.append((x, count)) else: self.queue = [(x, count)] def get(self): if len(self.queue) == 0: return None x, c = self.queue[0] if c == 1: self.queue.pop(0) return x else: self.queue[0] = (x, c - 1) return x def isempty(self): return len(self.queue) == 0 def countingqueue_len(self): """Returns the number of elements in the queue.""" l = self.queue count = 0 for x, i in l: for y in range(i): count += 1 return count def countingqueue_iter(self): """Iterates through all the elements of the queue, without removing them.""" l = self.queue for i, x in l: for y in range(x): yield i def subsets(s): """Given a set s, yield all the subsets of s, including s itself and the empty set.""" temp = list(s) if len(s) == 0: return [[]] subset = list(subsets(temp[1:])) answer = list(subset) for x in subset: answer.append(x+[temp[0]]) return answer return s
true
421acdd0c0bd12526592bed9d95c9578552f188e
Daoud-Hussain/Python-Rock-Paper-Scissor-game
/game.py
1,112
4.28125
4
while True: print( "*****Rock Paper Scissor Game****") import random comp = random.randint(1,3) if comp == 1: computer = 'r' elif comp == 2: computer = 'p' else: computer = 's' player = input("Enter 'r' for rock, 's' for scissor, 'p' for paper: ") if player == 'r': if computer == 's': print("You win ") elif computer == 'p': print("You Lose ") else: print("It is a tye! Try again") elif player == 'p': if computer == 'r': print("You win ") elif computer == 's': print("You Lose ") else: print("It is a tye! Try again") elif player == 's': if computer == 'p': print("You win ") elif computer == 'r': print("You Lose ") else: print("It is a tye! Try Again ") else: print("It is tye! Try again ") print(f"Computer enter {computer}, You enter {player}") play_again = input("Play again? (yes/no): ") if play_again.lower() != "yes": break
false
8464016eb57ab1d72628555c417586a544038d0d
Dennysro/Python_DROP
/8.5_DocStrings.py
880
4.3125
4
""" Documentando funções com Docstrings - Serve para deixar o código mais claro para que for ler. - Podemos ter acesso à documentação de uma função em Python utilizando 2 formas: 1. __doc__ como no exemplo: print(diz_oi.__doc__) 2. print(help(diz_oi)) """ def diz_oi(): """Uma função simples que retorna a string 'Oi!'""" return 'Oi!' print(diz_oi()) print(help(diz_oi)) def exponencial(numero, potencia=2): """ Função que retorna por padrão o quadrado de 'numero', ou 'numero' à 'potencia' informada :param numero: Número que desejamos gerar o exponencial :param potencia: Potência que queremos gerar o exponencial. Por padrão é 2 :return: Retorna o exponencial de 'numero' por 'potencia' """ return numero ** potencia print(exponencial(2)) print(help(exponencial))
false
c698040822bc3cdec690b166ad4a930bba3207bf
Dennysro/Python_DROP
/10.0_Utilizando_Lambdas.py
1,720
4.875
5
""" Utilizando Lambdas Conhecidas por expressões Lambdas ou simplesmente lambdas, são funções sem nome. Ou seja, anônimas. #Função em Python: def soma(a, b): return a+b def funcao(x): return 3 * x + 1 print(funcao(4)) """ # Expressão Lambda lambda x: 3 * x + 1 # E como utilizar a expressão lambda? calc = lambda x: 3 * x + 1 print(calc(4)) print(calc(7)) # Podemos ter Expressões lambdas com multiplas entradas nome_completo = lambda nome, sobrenome: nome.strip().title() + " " + sobrenome.strip().title() print(nome_completo('angelina ', 'JOLIE')) print(nome_completo(' FELICITY', 'JoneS')) # Em funções Python, podemos ter nenhuma ou várias entradas. Lambdas também amar = lambda: 'Como não amar Python?' uma = lambda x: 3 * x + 1 duas = lambda x, y: (x * y) ** 0.5 tres = lambda x, y, z: 3 / (1/x + 1/y + 1/z) # n = lambda x1, x2, ..., xn: <expressão> print(amar()) print(uma(6)) print(duas(5, 7)) print((tres(3, 6, 9))) # OBS: Se passarmos mais argumentos do que parâmetros esperados, teremos TypeError # Outro Exemplo: Ordenando uma lista de por ordem alfabetica de sobrenomes autores = ['Isaac Asimov', 'Ray Bradbury', 'Robert Heinlein', 'Arthur C Clarke', 'Frank Herbert', 'Orson Scott Card', 'Douglas Adams', 'H.G. Wells', 'Leigh Brackett'] print(autores) autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) # Função Quadrática # f(x) = ax^2 + bx + c # Definindo a função def geradora_funcao_quadratica(a, b, c): return lambda x: a*x**2 + b*x + c teste = geradora_funcao_quadratica(1, 1, 1) print(teste(0)) print(teste(1)) print(teste(2)) # OU: print(geradora_funcao_quadratica(1, 1, 1)(1))
false
717e07ce6e76ff6606bf902af61dd31db3457ffb
vgswn/lab_codes
/SIX/COD/Lab/Q1.py
959
4.125
4
_end = '_end_' def make_trie(*words): root = dict() for word in words: current_dict = root for letter in word: current_dict = current_dict.setdefault(letter, {}) current_dict[_end] = _end return root def in_trie(trie, word): current_dict = trie for letter in word: if letter in current_dict: current_dict = current_dict[letter] else: return False else: if _end in current_dict: return True else: return False def check_keyword(word): if in_trie(root,word) : print "is a keyword" else: print "is not a keyword" root = make_trie('prateek','auto','double','int','struct','break','else','long','switch','case','enum','register','typedef','char','extern','return','union','const','float','short','unsigned','continue','for','signed','void','default','goto','sizeof','volatile','do','if','static','while') input_keyword = str(raw_input()) check_keyword(input_keyword)
false
8949fd91df9d848465b03c7024e7516738e72c8e
jtew396/InterviewPrep
/linkedlist2.py
1,651
4.21875
4
# Linked List Data Structure # HackerRank # # # Node class class Node: # Function to initialize the node object def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: # Function to initialize the LinkedList class def __init__(self): self.head = None # Function to append a Node object to the LinkedList object def append(self, data): if self.head == None: self.head = Node(data) return current = self.head while current.next != None: current = current.next current.next = Node(data) # Function to prepend a Node object to the LinkedList object def prepend(self, data): newHead = Node(data) newHead.next = self.head self.head = newHead # Function to delete a Node object from the LinkedList object def deleteWithValue(self, data): if self.head == None: return if self.head.data == data: self.head = self.head.next return current = self.head while current.next != None: if current.next.data == data: current.next = current.next.next return current = current.next def printList(self): temp = self.head while temp: print(temp.data) temp = temp.next if __name__=='__main__': llist = LinkedList() llist.append(1) llist.append(2) llist.append(3) llist.printList() llist.prepend(0) llist.printList() llist.deleteWithValue(0) llist.printList()
true
a624e3d14acd2154c5dc156cfaa092ab1767d6a5
jtew396/InterviewPrep
/search1.py
1,154
4.25
4
# Cracking the Coding Interview - Search # Depth-First Search (DFS) def search(root): if root == None: return print(root) root.visited = True for i in root.adjacent: if i.visited == false: search(i) # Breadth-First Search (BFS) - Remember to use a Queue Data Structure def search(root): queue = Queue() # Declare a Queue object root.marked = True # Set the root node marked parameter equal to True queue.enqueue(root) # Add to the end of the queue while not queue.isEmpty(): # While the Queue is not empty r = queue.dequeue() # Remove from the front of the queue print(r) # Print the returned dequeued node for i in r.adjacent: # for every node in the adjacent nodes if i.marked == False: # if they are marked as False i.marked = True # set them to True queue.enqueue(i) # Add them to the Queue # Bidirectional Search Uses 2 Breadth-First Searches # This is used for to find the shortest path ebetween a source and destination node
true
78e04dee445264cd06b68053f1944def79f1746d
jtew396/InterviewPrep
/mergesort3.py
1,617
4.15625
4
# Python program for implementation of MergeSort # Merges two subarrays of arr[]. # First subarray is arr[l..m] # Second subarray is arr[m+1..r] def merge(arr, left, middle, right): n1 = middle - left + 1 n2 = right - middle # create temp arrays LeftArr = [0] * (n1) RightArr = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0 , n1): Left[i] = arr[left + i] for j in range(0 , n2): Right[j] = arr[middle + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2 : if Left[i] <= Right[j]: arr[k] = Left[i] i += 1 else: arr[k] = Right[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = Left[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = Right[j] j += 1 k += 1 # l is for left index and r is right index of the # sub-array of arr to be sorted def mergeSort(arr,left,right): if left < right: # Same as (l+r)//2, but avoids overflow for # large l and h middle = (left + (right - 1)) // 2 # Sort first and second halves mergeSort(arr, left, middle) mergeSort(arr, middle + 1, right) merge(arr, left, middle, right) # Driver code to test above arr = [12, 11, 13, 5, 6, 7] n = len(arr) print ("Given array is") for i in range(n): print ("%d" %arr[i]), mergeSort(arr,0,n-1) print ("\n\nSorted array is") for i in range(n): print ("%d" %arr[i]), # This code is contributed by Mohit Kumra
false
b288d4d0bb10fe3fa47c578349f5070afcd1282c
maryb0r/geekbrains-python-hw
/lesson05/example01.py
539
4.34375
4
# Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. # Об окончании ввода данных свидетельствует пустая строка. with open("file01.txt", "w") as f_obj: line = None while line != '': line = input("Type your text >>> ") f_obj.write(f"{line}\n") print() with open("file01.txt", "r") as f_obj: print(f_obj.read())
false
1e94eb4654f5f61e11fbc61a382904a4ab393828
maryb0r/geekbrains-python-hw
/lesson04/example05.py
828
4.125
4
# Реализовать формирование списка, используя функцию range() и возможности генератора. # В список должны войти четные числа от 100 до 1000 (включая границы). # Необходимо получить результат вычисления произведения всех элементов списка. # Подсказка: использовать функцию reduce(). from random import randint from functools import reduce def multi(prev_num, num): return prev_num * num number_list = [] for i in range(0, 10): num = randint(100, 1000) if num % 2 == 0: number_list.append(num) print(f"Original list: {number_list}") print(f"Result: {reduce(multi, number_list)}")
false
ffbd1535e7f9c25e817c10e31e0e6812a7645724
knpatil/learning-python
/src/dictionaries.py
686
4.25
4
# dictionary is collection of key-value pairs # students = { "key1":"value1", "key2": "value2", "key3": "value3" } # color:point alien = {} # empty dictionary alien = {"green":100} alien['red'] = 200 alien['black'] = 90 print(alien) # access the value print(alien['black']) # modify the value alien['red'] = 500 print(alien) # remove the value # del alien['green'] # print(alien) # name: favorite programming lanauge print("__" * 40) # loop through all key/value pairs for key,value in alien.items(): print(key, value) print("__" * 40) for key in sorted(alien.keys()): print(key) print("__" * 40) for value in alien.values(): print(value) print("__" * 40)
true
7b3f5e98d0ec4f94764e65e70a68c542f44ea966
knpatil/learning-python
/src/lists2.py
2,077
4.46875
4
cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) # sort a list by alphabetical order # cars.sort() # print(cars) # # cars.sort(reverse=True) # reverse order sort # print(cars) print(sorted(cars)) # temporarily sort a list print(cars) cars.reverse() print(cars) print(len(cars)) # print(cars[4]) # exceptions # comment for car in cars: print(car.title()) # 4 spaces of indentation for value in range(1, 1): # in operator always works with list print(value) for number in [1, 2, 4, 2]: # print(number) numbers = [11, 232, 44, 0, 2, 5] smallest_number = min(numbers) print(smallest_number) biggest_number = max(numbers) print(biggest_number) print("sum of all numbers:", sum(numbers)) # List comprehensions: allows you to generate a list using some code # list of squares for numbers: 1 - 10 # ** exponent print("--------") for x in range(1, 11): print(x**2) print("--------") squares = [x**2 for x in range(1, 11)] print("squares of 1 - 10: ", squares) cubes = [x**3 for x in range(1, 11)] print("cubes of 1 - 10: ", cubes) # slice of list (part of the list) print("Cubes of first 5 numbers: ", cubes[0:5]) # 0, 1, 2, 3, 4 print("Cubes of numbers from 2 - 4: ", cubes[1:4]) # 0, 1, 2, 3, 4 start = 0 end = 6 print(cubes[:end]) # slice 0 --> 5 end index non-inclusive print(cubes[4:]) # slice 0 --> 5 end index non-inclusive print(cubes[:]) # slice of last 3 numbers in the list print(cubes[-3:]) print(cubes[-3:-1]) # for number in cubes[4:8]: # list slice from 4th to 7th item print(number) squares2 = squares print(squares) squares[0] = 9999 print("squares:", squares) print("squares2:", squares2) squares3 = squares[:] # new slice print(squares3) squares[0] = 1111 print(squares3) squares[5] = 42942940 print(squares) # lists in python are mutable(changeable): that means you can change/modify the values # tuple -- immutable <-- you cannot change values x = (2, 4) # using a round bracket, it is a tuple print(x) print(x[0]) # accessing the value for i in x: print(i) x = (3, 9) # types are dynamic
true
a87bf15fb1e4f742f5f31be7a1af84276ffe6fc2
MaxAttax/maxattax.github.io
/resources/Day1/00 - Python Programming/task4.py
808
4.40625
4
# Task 4: Accept comma-separated input from user and put result into a list and into a tuple # The program waits until the user inputs a String into the console # For this task, the user should write some comma-separated integer values into the console and press "Enter" values = input() # Use for Python 3 # After the user pressed "Enter", the rest of the program from here is executed # The split()-operator splits a given String at the indicated separator (here a comma ",") # The split(",") function is used with the value that carries the user input from above (values) l = values.split(",") # A tuple is a special kind of list that can not be modified or extended. # The tuple() function generates a tuple from a given list. t = tuple(l) # Finally the results are printed out. print(l) print(t)
true
2823dce222d6d18b8e901786b78aa696d53effd4
ek17042/ORS-PA-18-Homework02
/task1.py
872
4.25
4
def can_string_be_float(user_value): allowed_characters = ["0","1","2","3","4","5","6","7","8","9",".","-"] for x in user_value: if x not in allowed_characters: return False nr_of_dots = 0 for x in user_value: if x == ".": nr_of_dots = nr_of_dots + 1 if nr_of_dots > 1: return False nr_of_minuses = 0 for x in user_value: if x == "-": nr_of_minuses = nr_of_minuses + 1 if nr_of_minuses > 1: return False if nr_of_minuses == 1: if user_value[0] != "-": return False return True def main(): user_value = input("Enter string which will be evaluated: ") if can_string_be_float(user_value): print(float(user_value)) else: print("String cannot be onverted to float!") #print(float(user_value)) main()
false
e829a743405b49893446c705272db2f7323bb329
Sharanhiremath02/C-98-File-Functions
/counting_words_from_file.py
281
4.375
4
def count_words_from_file(): fileName=input("Enter the File Name:") file=open(fileName,"r") num_words=0 for line in file: words=line.split() num_words=num_words+len(words) print("number of words:",num_words) count_words_from_file()
true
7c821b9a5102495f8f22fc21e29dd9812c77b3bd
chetanDN/Python
/AlgorithmsAndPrograms/02_RecursionAndBacktracking/01_FactorialOfPositiveInteger.py
222
4.125
4
#calculate the factorial of a positive integer def factorial(n): if n == 0: #base condition return 1 else: return n * factorial(n-1) #cursive condition print(factorial(6))
true
9bbcd87d994a200ebe11bc09ff79995dd74eac0a
GBaileyMcEwan/python
/src/hello.py
1,863
4.5625
5
#!/usr/bin/python3 print("Hello World!\n\n\n"); #print a multi-line string print( ''' My Multi Line String ''' ); #concatinate 2 words print("Pass"+"word"); #print 'Ha' 4 times print("Ha" * 4); #get the index of the letter 'd' in the word 'double' print("double".find('d')); #print a lower-case version of the string print("This Sucks".lower()); #print special characters- double escape if you want to print a backslash print("This rocks\tThis rocks\\t"); #If you want to use double quotes here, you would need to escape them print("Single 'quotes' are fine but \"doubles\" are a problem"); #You can use / * + - as well as // (returns whole numbers only and ** which returns exponents and % which mods print(2/2); #variables are like the below my_string = "My sample string"; my_string += " string2"; my_int = 2+2; print(my_string + " testing "); print(my_int); #this is how you print a list/array my_list = [1,2,"three",True]; print(my_list[1]); #print the length of the list print(len(my_list)); #s is how you print from the index position and how many items in the list you want to printt print(my_list[3:len(my_list)]); #You can add items to the list as per below my_list.append(5); print(my_list[0:]); #you can also remove items from the list: my_list.remove("three"); print(my_list); print("My string is " + str(my_int) + " what"); #hashes or dictionaries are set like this ages = {'kevin': 59, 'alex': 60} print(ages); print(ages['kevin']); ages['kayla']=21; print(ages); ages['kayla']=22; print(ages); del ages['kayla']; print(ages); #use this as a safer way to delete an element from a hash ages.pop('alex'); print(ages); #print only the keys or values in the hash print(ages.keys()); print(ages.values()); print(list(ages.values())); #you can also create a hash/dictionary like this weights = dict(kevin=100, bob=200); print(weights);
true
34ad45e897f4b10154ccf0f0585c29e1e51ad2f8
EwarJames/alx-higher_level_programming
/0x0B-python-input_output/3-to_json_string.py
315
4.125
4
#!/usr/bin/python3 """Define a function that returns a json.""" import json def to_json_string(my_obj): """ Function that convert json to a string. Args: my_obj (str): Object to be converted. Return: JSON representation of an object (string) """ return json.dumps(my_obj)
true
431384abd81af78ff79355d261528645cf9c100b
pi408637535/Algorithm
/com/study/algorithm/daily/diameter-of-binary-tree.py
1,370
4.15625
4
''' 树基本是递归。 递归:四要素 本题思路:left+right=diameter https://www.lintcode.com/problem/diameter-of-binary-tree/description ''' #思路: #Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: a root of binary tree @return: return a integer """ def helper(self, root): if not root: return 0 left_depth = self.helper(root.left) right_depth = self.helper(root.right) depth = max(left_depth, right_depth) + 1 return depth def diameterOfBinaryTree(self, root): # write your code here left_depth = self.helper(root.left) right_depth = self.helper(root.right) return left_depth + right_depth if __name__ == '__main__': TreeNode1 = TreeNode(1) TreeNode2 = TreeNode(2) TreeNode3 = TreeNode(3) TreeNode4 = TreeNode(4) TreeNode5 = TreeNode(5) TreeNode1.left = TreeNode2 TreeNode1.right = TreeNode3 TreeNode2.left = TreeNode4 TreeNode2.right = TreeNode5 # TreeNode1 = TreeNode(1) # TreeNode2 = TreeNode(2) # TreeNode3 = TreeNode(3) # # TreeNode2.left = TreeNode3 # TreeNode3.left = TreeNode1 print(Solution().diameterOfBinaryTree(TreeNode1))
true
8661d933bf731b111cda9345752a0307ff4adca8
rodrigomanhaes/model_mommy
/model_mommy/generators.py
1,794
4.34375
4
# -*- coding:utf-8 -*- __doc__ = """ Generators are callables that return a value used to populate a field. If this callable has a `required` attribute (a list, mostly), for each item in the list, if the item is a string, the field attribute with the same name will be fetched from the field and used as argument for the generator. If it is a callable (which will receive `field` as first argument), it should return a list in the format (key, value) where key is the argument name for generator and value is the value for that argument. """ import sys import string import datetime from decimal import Decimal from random import randint, choice, random MAX_LENGTH = 300 def gen_from_list(L): '''Makes sure all values of the field are generated from the list L Usage: from mommy import Mommy class KidMommy(Mommy): attr_mapping = {'some_field':gen_from_list([A, B, C])} ''' return lambda: choice(L) # -- DEFAULT GENERATORS -- def gen_from_choices(C): choice_list = map(lambda x:x[0], C) return gen_from_list(choice_list) def gen_integer(min_int=-sys.maxint, max_int=sys.maxint): return randint(min_int, max_int) gen_float = lambda:random()*gen_integer() def gen_decimal(max_digits, decimal_places): num_as_str = lambda x: ''.join([str(randint(0,9)) for i in range(x)]) return "%s.%s" % ( num_as_str(max_digits-decimal_places), num_as_str(decimal_places) ) gen_decimal.required = ['max_digits', 'decimal_places'] gen_date = datetime.date.today gen_datetime = datetime.datetime.now def gen_string(max_length): return ''.join(choice(string.printable) for i in range(max_length)) gen_string.required = ['max_length'] gen_text = lambda: gen_string(MAX_LENGTH) gen_boolean = lambda: choice((True, False))
true
6c036ab3ae9e679019d589fbd8de8be45486773f
gbrough/python-projects
/palindrome-checker.py
562
4.375
4
# Ask user for input string # Reverse the string # compare if string is equal # challenge - use functions word = None def wordInput(): word = input("Please type a word you would like to see if it's a palindrome\n").lower() return word def reverseWord(): reversedWord = word[::-1] return reversedWord def palindromeCheck(): if word == reverseWord: print("Yes, you have entered a palindrome") else: print("Sorry, this word is not a palindrome") def main(): print("\nPalindrome Checker") wordInput reverseWord palindromeCheck main()
true
881d9ba1f1dea7860a6fd2f30f62ed0f8246bea3
marcelinoandre/python-logica-para-data-science
/07-listas-pacotes-funcoesexternas/7.10.Atividade3.py
407
4.125
4
from math import sqrt lista = list(range(0,5)) for n in range(0, 5): print("Informe o número da posição ", n+1, " da primeira lista") lista[n] = float(input()) for n in range(0, 5): print("Raiz quadrada: "sqrt(lista[n])) if sqrt(lista[n]) % 1 == 0 : print("Raiz quadrada é um valor inteiro") else: print("Raiz quadrada não é um valor inteiro")
false
5ebe1f88e466c99ba52f3dd43a17e692b30c96b2
chena/aoc-2017
/day12.py
2,625
4.21875
4
""" part 1: Each program has one or more programs with which it can communicate, and they are bidirectional; if 8 says it can communicate with 11, then 11 will say it can communicate with 8. You need to figure out how many programs are in the group that contains program ID 0. For example, suppose you go door-to-door like a travelling salesman and record the following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In this example, the following programs are in the group that contains program ID 0: - Program 0 by definition. - Program 2, directly connected to program 0. - Program 3 via program 2. - Program 4 via program 2. - Program 5 via programs 6, then 4, then 2. - Program 6 via programs 4, then 2. Therefore, a total of 6 programs are in this group; all but program 1, which has a pipe that connects it to itself. How many programs are in the group that contains program ID 0? """ def __check_connections__(program_id, connections, group): for c in connections[program_id]: if c in group: continue group.add(c) __check_connections__(c, connections, group) def __get_connetions__(): with open('input/programs.txt') as f: content = f.readlines() connections = {} programs = [p.strip() for p in content] arrow = '<->' for p in programs: parts = p.split(arrow) program = int(parts[0].strip()) connections[program] = [int(l) for l in parts[1].strip().split(', ')] return connections def digital_plumber_zero_group(): connections = __get_connetions__() # traverse through each program and check its connections # keep track of the programs with a set zero_group = {0} __check_connections__(0, connections, zero_group) return len(zero_group) # print(digital_plumber_zero_group()) """ part 2: A group is a collection of programs that can all communicate via pipes either directly or indirectly. The programs you identified just a moment ago are all part of the same group. Now, they would like you to determine the total number of groups. In the example above, there were 2 groups: one consisting of programs 0,2,3,4,5,6, and the other consisting solely of program 1. How many groups are there in total? """ def digital_plumber_group_count(): connections = __get_connetions__() # traverse through each program mark the group it belongs to groupings = {} for p in connections: if p in groupings: continue group = {p} __check_connections__(p, connections, group) for member in group: groupings[member] = p return len(set(groupings.values())) print(digital_plumber_group_count())
true
6e33fd4e81dcfdce22916bd20d4230e472490dae
chena/aoc-2017
/day05.py
1,882
4.53125
5
""" part 1: The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. (0) 3 0 1 -3 - before we have taken any steps. (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1. 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2. 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind. 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2. 2 5 0 1 -2 - jump 4 steps forward, escaping the maze. In this example, the exit is reached in 5 steps. part 2: After each jump, if the offset was three or more, instead decrease it by 1. Otherwise, increase it by 1 as before. Using this rule with the above example, the process now takes 10 steps, and the offset values after finding the exit are left as 2 3 2 3 -1. How many steps does it now take to reach the exit? """ def __parse_maze_input__(filename): with open(filename) as f: content = f.readlines() return [int(n) for n in content] def maze_of_twisty(maze): steps = 0 index = 0 while (index < len(maze)): move_forward = maze[index] if (move_forward >= 3): maze[index] -= 1 else: maze[index] += 1 index += move_forward steps += 1 return steps print(maze_of_twisty([0, 3, 0, 1, -3])) # print(maze_of_twisty(__parse_maze_input__('input/maze.txt')))
true
d42ecceedf925c992c64ad311cbf801eb3757f84
yasukoe/study_python
/comprehension.py
253
4.375
4
# comprehension 内包表記 # print([i for i in range(10)]) # print([i*3 for i in range(10)]) # print([i*3 for i in range(10) if i % 2 ==0]) print(i*3 for i in range(10) if i % 2 ==0) #Generator print({i*3 for i in range(10) if i % 2 ==0}) #set type
false
164dda3ecb9d27c153dbc9d143ba05437c47f656
luisprooc/data-structures-python
/src/bst.py
1,878
4.1875
4
from binary_tree import Node class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): current = self.root while current: if new_val >= current.value: if not current.right: current.right = Node(new_val) return current = current.right else: if not current.left: current.left = Node(new_val) return current = current.left def search(self, find_val): # If current node is equal to # find_value, return True if self.root.value == find_val: return True else: # If the find_value is bigger to current node and the current # node not is a leaf, scroll right if find_val >= self.root.value and self.root.right: self.root = self.root.right return self.search(find_val) else: # If current node not is a leaf, scroll left if self.root.left: self.root = self.root.right return self.search(find_val) # This means that you reached a leaf and not # find the expected value return False def preorder_print(self, start, traversal): if start: traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print (tree.search(4)) # Should be False print (tree.search(6))
true
757cfb65fc22c1f8f9326a25018defb7aafbad56
2FLing/CSCI-26
/codewar/camel_case.py
531
4.25
4
# Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). # Examples # to_camel_case("the-stealth-warrior") # returns "theStealthWarrior" # to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior" def to_camel_case(s): return s[0]+s.translate(str.maketrans("","","-_"))[1:] print(to_camel_case("I_love-You"))
true
5a5581ad8604d9d61d579ab1661be5c7d70cdcb6
rodrigocamarena/Homeworks
/sess3&4ex4.py
2,915
4.5
4
print("Welcome to the universal pocket calculator.") print("1. Type <+> if you want to compute a sum." "\n2. Type <-> if you want to compute a rest." "\n3. Type <*> if you want to compute a multiplication." "\n4. Type </> if you want to compute a division." "\n5. Type <quit> if you want to exit.") while True: prompt = 'Introduce your answer: ' answer = input(prompt) if answer == "+": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num + num2 print("The result of: ",num,"+",num2," is: ",result) break elif answer == "-": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num - num2 print("The result of: ",num,"-",num2," is: ",result) break elif answer == "*": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num * num2 print("The result of: ",num,"*",num2," is: ",result) break elif answer == "/": while True: try: num = input('Introduce the first number: ') num2 = input('Introduce the second number: ') num = float(num) num2 = float(num2) except ValueError: print("opps, please give me a proper number!") except: print("opps, something unknown occured.") else: result = num / num2 print("The result of: ", num, "/", num2, " is: ", result) break elif answer == "quit": print("Was a pleasure working with you. See you soon!") break else: print("opps, invalid answer. Try again please!")
true
7536d2a8c16cc9bda41d4a4d3894c0a8a0911446
artemis-beta/phys-units
/phys_units/examples/example_2.py
1,160
4.34375
4
############################################################################## ## Playing with Measurements ## ## ## ## In this example the various included units are explored in a fun and ## ## silly way to illustrate how units_database behaves. ## ## ## ############################################################################## #--------------------- Fetch all the units we need --------------------------# from units_database import mile, m, furlong, yd, pc, rod my_distance = 5*mile # By default units_database will use SI units the function 'as_base' treats # the unit as a base unit. print('Today I ran {}.'.format(my_distance.as_base())) print('This is equivalent to {}'.format(my_distance)) print('or (if we want to be silly), this is also {}'.format(my_distance.as_unit(pc))) print('In Imperial units this is also {}'.format(my_distance.as_unit(yd))) print('or (to be unusual) {}'.format(my_distance.as_unit(furlong)))
true
3c419f360e36ed45af7d7935aa2f824bb2dc472a
Cleancode404/ABSP
/Chapter8/input_validation.py
317
4.1875
4
import pyinputplus as pyip while True: print("Enter your age:") age = input() try: age = int(age) except: print("Please use numeric digits.") continue if age < 0: print("Please enter a positive number.") continue break print('Your age is', age)
true
bf005c98b3c7beabc0e2000cfd0cfd404010a9a9
AlexRoosWork/PythonScripts
/delete_txts.py
767
4.15625
4
#!/usr/bin/env python3 # given a directory, go through it and its nested dirs to delete all .txt files import os def main(): print(f"Delete all text files in the given directory\n") path = input("Input the basedir:\n") to_be_deleted = [] for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith(".txt"): string = dirpath + os.sep + filename to_be_deleted.append(string) num_of_files = len(to_be_deleted) if input(f"sure you want to delete {num_of_files} .txt files? (y/n)") == "y": for file in to_be_deleted: os.remove(file) print("Done.") else: print("Abortion.") if __name__ == "__main__": main()
true
8ae3f309e572b41a3ff5205692f0ae4c90f11962
Trenchevski/internship
/python/ex6.py
867
4.21875
4
# Defining x with string value x = "There are %d types of people." % 10 # Binary variable gets string value with same name binary = "binary" # Putting string value to "don't" do_not = "don't" # Defining value of y variable using formatters y = "Those who know %s and those who %s." % (binary, do_not) # Printing value of x print x # Printing value of y print y # Printing value of x using formatters print "I said: %r." % x # Printing value of y using formatters print "I also said: '%s'." % y # Boolean with value False hilarious = False # Variable joke_evaluation gets string value joke_evaluation = "Isn't that joke so funny?! %r" # Printing mod of two previous variables print joke_evaluation % hilarious # Putting string value to w and e variables w = "This is the left side of..." e = "a string with a right side." # Printing them one after another print w + e
true
6cd204d47bb1937a024c1afa0c25527316453468
Soares/natesoares.com
/overviewer/utilities/string.py
633
4.5
4
def truncate(string, length, suffix='...'): """ Truncates a string down to at most @length characters. >>> truncate('hello', 12) 'hello' If the string is longer than @length, it will cut the string and append @suffix to the end, such that the length of the resulting string is @length. >>> truncate('goodbye', 4) 'g...' >>> truncate('goodbye', 6) 'goo...' @suffix defaults to '...'. >>> truncate('hello', 3, '..') 'h..' >>> truncate('hello', 3, '') 'hel' """ if len(string) <= length: return string return string[:length-len(suffix)] + suffix
true
066bcfb00c4f01528d79d8a810a65d2b64e8a8a2
bchaplin1/homework
/week02/03_python_homework_chipotle.py
2,812
4.125
4
''' Python Homework with Chipotle data https://github.com/TheUpshot/chipotle ''' ''' BASIC LEVEL PART 1: Read in the data with csv.reader() and store it in a list of lists called 'data'. Hint: This is a TSV file, and csv.reader() needs to be told how to handle it. https://docs.python.org/2/library/csv.html ''' import csv cd 'c:\ml\dat7\data' with open ('chipotle.tsv','rU') as f: data = [row for row in csv.reader(f,delimiter='\t')] ''' BASIC LEVEL PART 2: Separate the header and data into two different lists. ''' header = data[0] data = data[1:] ''' INTERMEDIATE LEVEL PART 3: Calculate the average price of an order. Hint: Examine the data to see if the 'quantity' column is relevant to this calculation. Hint: Think carefully about the simplest way to do this! ''' sum([float(d[4].replace('$','')) for d in data])/len(set([d[0] for d in data])) ''' INTERMEDIATE LEVEL PART 4: Create a list (or set) of all unique sodas and soft drinks that they sell. Note: Just look for 'Canned Soda' and 'Canned Soft Drink', and ignore other drinks like 'Izze'. ''' drinks = set() for d in data: if d[2] == 'Canned Soda' or d[2] == 'Canned Soft Drink': drinks.add(d[3]) print drinks ''' ADVANCED LEVEL PART 5: Calculate the average number of toppings per burrito. Note: Let's ignore the 'quantity' column to simplify this task. Hint: Think carefully about the easiest way to count the number of toppings! ''' topCt = 0 burritoCt = 0 for d in data: if d[2] == 'Burrito' : topCt += len(d[3].split('[')[-1].split(',')) burritoCt+=1 avgCt = topCt / float(burritoCt) print 'average number of toppings per burrito is ' + str(avgCt) ''' ADVANCED LEVEL PART 6: Create a dictionary in which the keys represent chip orders and the values represent the total number of orders. Expected output: {'Chips and Roasted Chili-Corn Salsa': 18, ... } Note: Please take the 'quantity' column into account! Optional: Learn how to use 'defaultdict' to simplify your code. ''' from collections import defaultdict chips = [d for d in data if d[2].startswith('Chips')] d = defaultdict(int) for order in chips: d[order[2]]+=int(order[1]) print d.items() ''' BONUS: Think of a question about this data that interests you, and then answer it! ''' ''' is there a correlation between meat selection and toppings, like fat content? let's put them in a dictionary and find out ''' chicken = [d for d in data if d[2].startswith('Chicken')] steak = [d for d in data if d[2].startswith('Steak')] orderSum = 0 print 'chicken' + str(sum([float(d[4].replace('$','')) for d in chicken])/len(set([d[0] for d in chicken]))) print 'steak' + str(sum([float(d[4].replace('$','')) for d in steak])/len(set([d[0] for d in steak])))
true
0982d07b0af6e12ee34a1bad96af8d9e7730bc8c
andrericardoweb/curso_python_cursoemvideo
/exercicios/ex008.py
287
4.1875
4
# Exercício Python 008: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. m = eval(input('Uma distância em metros: ')) print('CONVERTENDO MEDIDAS') print(f'{m/1000}km | {m/100}hm | {m/10}dam | {m}m | {m*10}dm | {m*100}cm |{m*1000}mm')
false
81ad7ff791adaf6dfad0b90fbb9f60c56139be6c
MagomedNalgiev/Ozon-New-Skills
/DZ_3-1.py
609
4.375
4
string1 = 'Съешь ещё этих мягких французских булок ДА выпей же чаю' #Преобразуем текст в список string1_list = string1.split() #Выводим четвертое слово в верхнем регистре print(string1_list[3].upper()) #Выводим седьмое слово в нижнем регистре print(string1_list[6].lower()) #Выводим третью букву восьмого слова print(string1_list[7][2]) #Выводим все слова в одном столбце for i in string1_list: print(i)
false
90af163267b8d485c28169c9aeb149df021e3509
hemenez/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
423
4.3125
4
#!/usr/bin/python3 def add_integer(a, b): """Module will add two integers """ total = 0 if type(a) is not int and type(a) is not float: raise TypeError('a must be an integer') if type(b) is not int and type(b) is not float: raise TypeError('b must be an integer') if type(a) is float: a = int(a) if type(b) is float: b = int(b) total = a + b return total
true
dbb83d0461e2f93fb463380da950cf83a61eeee4
28kayak/CheckIO_TestFile
/BooleanAlgebra/boolean_algebra.py
1,299
4.15625
4
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence") def boolean(x, y, operation): return operation(x,y) def conv(x): if x == 1: x = True else: x = False def conjunction(x,y): if x == y and x == 0: #print "T" return 1 elif x == y and x == 1: #print "F x and y are 1" return 0 else: #print "F" return 0 def disjunction(x,y): if x == y and x == 0: #print "F x and y are 0" return 0 else: #print "ture!" return 1 def implication(x,y): if x == 1: x = 0 else: x = 1 return disjunction(x,y) def exclusive(x,y): if disjunction(x,y) == 1: if conjunction(x,y) == 1: return 0 else: return 1 else: return 0 def equivalence(x,y): if x == y: return 1 else: return 0 if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert boolean(1, 0, conjunction) == 0, "and" assert boolean(1, 0, disjunction) == 1, "or" assert boolean(1, 1, implication) == 1, "material" assert boolean(0, 1, exclusive) == 1, "xor" assert boolean(0, 1, equivalence) == 0, "same?" #conjunction(1,0) #conjunction(0,0) #conjunction(0,1) #conjunction(1,1) #disjunction(1,0) #disjunction(0,0) #disjunction(0,1) #disjunction(1,1)
false
ba2c8e1e768b24f7ad7a4c00ee6ed4116d31a21a
kjigoe/Earlier-works
/Early Python/Fibonacci trick.py
866
4.15625
4
dic = {0:0, 1:1} def main(): n = int(input("Input a number")) ## PSSST! If you use 45 for 'n' you get a real phone number! counter = Counter() x = fib(n,counter) print("Fibonacci'd with memoization I'd get",x) print("I had to count",counter,"times!") y = recursivefib(n, counter) print("And with recusion I still get",y) print("But the count changes to",counter) def fib(n,counter): if n in dic: return dic[n] else: counter.increment() if n < 2: dic[n] = n else: dic[n] = fib(n-2,counter) + fib(n-1,counter) return dic[n] def recursivefib(n, counter): if n < 2: return n else: counter.increment() return (recursivefib(n-2,counter) + recursivefib(n-1,counter)) class Counter(object): def __init__(self): self._number = 0 def increment(self): self._number += 1 def __str__(self): return str(self._number) main()
true
e996c9bff605c46d30331d13e44a49c04a2e29be
Kaylotura/-codeguild
/practice/greeting.py
432
4.15625
4
"""Asks for user's name and age, and greets them and tells them how old they'll be next year""" # 1. Setup # N/A # 2. Input name = input ("Hello, my name is Greetbot, what's your name? ") age = input(name + ' is a lovely name! How old are you, ' + name + '? ') # 3. Transform olderage = str(int(age) + 1) # 4. Output print ("You're " + age + "-years old? Wow, I guess that means you're going to be " + olderage + " next year!")
true
922c0d74cf538e3a28a04581b9f57f7cfb7377e4
BstRdi/wof
/wof.py
1,573
4.25
4
from random import choice """A class that can be used to represent a wheel of fortune.""" fields = ('FAIL!', 'FAIL!', 100, 'FAIL!', 'FAIL!', 500, 'FAIL!', 250, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 1000, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!') score = [] class WheelOfFortune: """A simple attempt to represent a wheel of fortune.""" def __init__(self, fields, spins=10): """Initialize attributes to describe a wheel of fortune.""" self.fields = fields self.spins = spins def spin_wheel(self): """Spin the wheel of fortune""" for spin in range(1, self.spins): spin = choice(fields) print(spin) if isinstance(spin, int) == True: score.append(spin) sum_score = sum(score) print(f'{player_name} you got {sum_score} points!') # Spin for player one player_name = input('Player One - Enter your name: ') player_one = WheelOfFortune(fields) player_one.spin_wheel() player_one_score = score[:] player_one_name = player_name del score[:] # Spin for player two player_name = input('Player Two - Enter your name: ') player_two = WheelOfFortune(fields) player_two.spin_wheel() player_two_score = score[:] player_two_name = player_name # Selection of the winner if player_one_score > player_two_score: print(f'{player_one_name} wins!') elif player_two_score > player_one_score: print(f'{player_two_name} wins!') elif player_one_score == player_two_score: print('Draw!')
true
22349e2b8bc3f99956fb293d14463d71420ad45c
gustavocrod/vrp
/util.py
1,619
4.21875
4
from graph import * def cost(route, graph): """ Funcao que computa a soma das demandas dos clientes de uma rota :param route: rota a ser computada :param graph: grafo :return: """ cost = 0 for i in route: edge = graph.findEdge(i) cost += edge.demand return cost def showResult(routes, graph): for route in routes: for i in route: print(str(i) + " ", end="") print() #print("Custo total: " + str(totalCost(routes, graph))) def totalCost(routes, graph): """ Funcao q computa o somatorio das distancias de todas as rotas :param routes: :param graph: :return: """ cost = 0 for route in routes: for i in range(1, len(route)): cost += graph.distances[route[i-1], route[i]] # e.g: cost += graph.distances[0, 1] return cost def insertWarehouse(routes): """ adiciona o deposito nas rotas, inicio e fim :param routes: :return: """ for route in routes: route.insert(0, 0) # inicio route.append(0) # fim def usage(): print("Voce deve executar o programa redirecionando um arquivo para a entrada padrao.") print("e.g $ python VRP < vrpnc1.txt") def distance(distFunction, node1, node2): return distFunction(node1, node2) def euclidean(node1, node2): """ sqrt( (xf - xi)^2 + (yf - yi)^2 ) """ if node1 == node2: return 0.0 return math.sqrt(math.pow(node1.x - node2.x, 2) + math.pow(node1.y - node2.y, 2)) def absolute(node1, node2): return abs(node1.x - node2.x) + abs(node1.y - node2.y)
false
b63879f6a16ae903c1109d3566089e47d0212200
idahopotato1/learn-python
/01-Basics/005-Dictionaries/dictionaries.py
1,260
4.375
4
# Dictionaries # A dictionary is an associative array (also known as hashes). # Any key of the dictionary is associated (or mapped) to a value. # The values of a dictionary can be any Python data type. # So dictionaries are unordered key-value-pairs. # Constructing a Dictionary my_dist = {'key1': 'value1', 'key2': 100, 'key3': 99.99} # Accessing Objects from a dictionary print(my_dist['key2']) # 100 print(my_dist['key1'].upper()) # VALUE1 print(my_dist['key2'] - 2) # 98 print(my_dist['key2']) # 100 my_dist['key2'] = my_dist['key2'] - 2 print(my_dist['key2']) # 98 print(my_dist) # {'key1': 'value1', 'key2': 98, 'key3': 99.99} my_colors = {} my_colors['color1'] = 'red' my_colors['color2'] = 'green' print(my_colors) # {'color1': 'red', 'color2': 'green'} # Nesting dictionary my_dist2 = {'key1': {'subKey': 'value'}, 'key2': 100, 'key3': 99.99} print(my_dist2['key1']['subKey'].upper()) # VALUE # Basic Dictionary Methods my_dist3 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} print(my_dist3.keys()) # dict_keys(['key1', 'key2', 'key3']) print(my_dist3.values()) # dict_values(['value1', 'value2', 'value3']) print(my_dist3.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
true
b5dbb2bc21aca13d23b3d3f87569877ce9951eec
idahopotato1/learn-python
/04-Methods-Functions/001-methods.py
736
4.34375
4
# Methods # The other kind of instance attribute reference is a method. # A method is a function that “belongs to” an object. # (In Python, the term method is not unique to class instances: # other object types can have methods as well. # For example, list objects have methods called append, insert, remove, sort, and so on. print('=============================================') my_list = [1, 2, 3] my_list.append(4) print(my_list) # [1, 2, 3, 4] print('=============================================') print(my_list.count(3)) # 1 print('=============================================') print(help(my_list.append)) # append(...) method of builtins.list instance print('=============================================')
true
abb45102966579d6e8efcc54af764ae78c20bccb
QuickJohn/Python
/test/recursion.py
1,287
4.34375
4
# Author: John Quick # Recursion demonstration def main(): print() print('RECURSION WITH PYTHON') print('Choose option:') print('[1] Find factorial') print('[2] Convert to binary') print('[3] Fibonacci') print() # get choice from user option = int(input('Pick option: \n')) # get number from user n = int(input('\nEnter a number: ')) # determine choice if option < 0 | option > 3: print('Choose an option 1 - 3!') else: if option == 1: print(factorial(n)) elif option == 2: print(n,'in binary is') decimalToBinary(n) elif option == 3: print('Fibonacci sequence: ') for i in range(n): print(fibonacci(i)) #print(fibonacci(n)) # calculate factorial function def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) # convert to binary function def decimalToBinary(num): if num > 1: decimalToBinary(num // 2) print(num % 2, end='') # Fibinocci function def fibonacci(num): if num == 0: return 0 elif num == 1: return 1 else: return fibonacci(num-1) + fibonacci(num-2) # call main function main()
false
4afb88e53ccddb16c631b2af181bb0e607a2b37b
Evakung-github/Others
/381. Insert Delete GetRandom O(1).py
2,170
4.15625
4
''' A hashmap and an array are created. Hashmap tracks the position of value in the array, and we can also use array to track the appearance in the hashmap. The main trick is to swap the last element and the element need to be removed, and then we can delete the last element at O(1) cost. Afterwards, we need to update the position of the original last element in the hashmap to its current position. Therefore, that's why we need to record its space in the value of the hashmap. ref: https://www.youtube.com/watch?v=mRTgft9sBhA ''' import random class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.array = [] self.dict = {} def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ if val not in self.dict: self.dict[val] = [len(self.array)] self.array.append([val,0]) return True else: self.dict[val].append(len(self.array)) self.array.append([val,len(self.dict[val])-1]) def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if val in self.dict: if not self.dict[val]: return False else: n = self.dict[val][-1] self.dict[self.array[-1][0]][self.array[-1][1]] = n n = self.dict[val].pop() self.array[n], self.array[-1] = self.array[-1],self.array[n] self.array.pop() return True def getRandom(self) -> int: """ Get a random element from the collection. """ n = random.randint(0,len(self.array)-1) return self.array[n][0] # Your RandomizedCollection object will be instantiated and called as such: # obj = RandomizedCollection() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
true
c57eab0302c15814a5f51c2cbc0fa104910eef08
hihihien/nrw-intro-to-python
/lecture-06/solutions/exponent.py
261
4.28125
4
base = float(input('What is your base?')) exp = float(input('What is your exponent?')) num = exp result = 1 while num > 0: result = result * base num = num - 1 print(f'{base} raised to the power of {exp} is: {result}. ({base} ** {exp} = {base**exp})')
true
ef2e1747c49dca4e17fe558704d05d50b2a11506
kengbailey/interview-prep
/selectionsort.py
1,507
4.28125
4
# Selection Sort Implementation in Python ''' How does it work? for i = 1:n, k = i for j = i+1:n, if a[j] < a[k], k = j → invariant: a[k] smallest of a[i..n] swap a[i,k] → invariant: a[1..i] in final position end What is selection sort? The selection sort algorithm is a combination of searching and sorting. It sorts an array by repeatedly finding the minimum/maximum element from unsorted part and putting it at the end. In selection sort, the inner loop finds the next smallest (or largest) value and the outer loop places that value into its proper location. Selection sort should never be used. it does not adapt to the data in any way. What is performance of selection sort in Big'O? Worst-case performance О(n2) Best-case performance О(n2) Average performance О(n2) Worst-case space Complexity О(n) total, O(1) auxiliary ''' def selection_sort(unsorted_arr): for x in range(len(unsorted_arr)): # store current position n = x # search for the position of the next smallest value # in the unsorted part for y in range(x+1, len(unsorted_arr)): if unsorted_arr[y] < unsorted_arr[n]: n = y # swap next smallest value into postition swap(x,n,unsorted_arr) print(unsorted_arr) def swap(a, b, array): temp2 = array[a] array[a] = array[b] array[b] = temp2 arr = [10,9,7,8,6,5,4,2,3,1] print("Unsorted: ", arr) selection_sort(arr) print("Sorted: ", arr)
true
0ff6efa124129922594e4e996dd1b2955e6002b8
BethMwangi/python
/rock_paper_scissors.py~
1,165
4.21875
4
#!/usr/bin/python # Rock, paper ,scissors game # The rules apply, i.e , # * Rock beats scissors # * Paper beats rock # * Scissors beats paper import sys print "Let's get started!" player1 =raw_input("Enter your name please:") #prompts the user to input their name player2 = raw_input("Enter your name please:") player1_ans = raw_input ("%s, do you want to choose rock, paper or scissors?" % player1) player2_ans = raw_input ("%s, do you want to choose rock, paper or scissors?" % player2) def compare(a,b): if a == b: return "Oops! it is a tie" elif a == "rock": if b == "scissors": #nested if statement to cover all the outcomes return "Rock wins" else: return "paper wins" elif a == "paper": if b == "scissors": return "scissors wins" else: return "paper wins" elif a == "scissors": if b == "rock": return "rock wins" else: return "scissors win" else: return ("Wrong input, kindly choose either rock, paper or scissors to play") sys.exit() print (compare(player1_ans, player2_ans))
false
6c612b3a3904a9710b3f47c0174edf1e0f15545b
spots1000/Python_Scripts
/Zip File Searcher.py
2,412
4.15625
4
from zipfile import ZipFile import sys import os #Variables textPath = "in.txt" outPath = "out.txt" ## Announcements print("Welcome to the Zip Finder Program!") print("This program will take a supplied zip file and locate within said file any single item matching the strings placed in an accompanying text file.") input("To use this program please place the desired skus or other identifies in a folder called \"" + textPath + "\" and then press Enter to continue.\n") ## Ensure before opening text file that we have a valid file to read. if not (os.path.isfile(textPath)): print("A valid text file was not found, program will now exit.") input("Press any key to exit...") sys.exit() ## Attempt to open our text file and read in the data targetList = [] textFile = open(textPath, encoding="utf8") for line in textFile: strippedLine = line.strip("\n") strippedLine = strippedLine.strip("\t") targetList.append(strippedLine) print("Text File successfully read in with " + str(len(targetList)) + " items.") textFile.close() ## Get the filename fileName = input("Please enter the name of the zip file without any extensions. >>>") fileName = fileName + ".zip" ## Make sure the file exists try: zip = ZipFile(fileName, 'r') except: print("Zip File Was Not Opened Successfully") print("Program will exit") sys.exit() print("Zip file was read successfully, processing will now comence") ## Read the zip file fileData = zip.infolist() errorList = [] ## Loop through the data for the relevant for target in targetList: print("Attemtping to locate " + target) found = "false" for dat in fileData: if (target in dat.filename): print("Located target file") path = zip.extract(dat) found = "true" break; if(found == "false"): print("Target was not found.") errorList.append(target) ## output to the output file outFile = open(outPath, "a") for err in errorList: outFile.write(err + "\n") outFile.close() i = len(targetList) - len(errorList) ##Final output print("All processing completed. " + str(i) + " total folders successfully processed while " + str(len(errorList)) + " folders were not able to be found.") input("Press any key to exit...") sys.exit()
true
77ee96c305f1d7d21ddae8c1029639a50627382b
SamuelHealion/cp1404practicals
/prac_05/practice_and_extension/electricity_bill.py
1,317
4.1875
4
""" CP1404 Practice Week 5 Calculate the electricity bill based on provided cents per kWh, daily use and number of billing days Changed to use dictionaries for the tariffs """ TARIFFS = {11: 0.244618, 31: 0.136928, 45: 0.385294, 91: 0.374825, 33: 0.299485} print("Electricity bill estimator 2.0") print("Which tariff are you on?") for tariff, cost in TARIFFS.items(): print("Tariff {} at {} per kWh".format(tariff, cost)) valid_tariff = False while not valid_tariff: try: which_tariff = int(input(">>> ")) if which_tariff in TARIFFS.keys(): valid_tariff = True else: print("Not a valid tariff") except ValueError: print("Please enter a number") daily_use = float(input("Enter daily use in kWh: ")) number_of_days = float(input("Enter number of billing days: ")) estimated_bill = TARIFFS[which_tariff] * daily_use * number_of_days print("Estimated bill: ${:.2f}".format(estimated_bill)) """ Original version print("Electricity bill estimator") cents_per_kwh = float(input("Enter cents per kWh: ")) daily_use = float(input("Enter daily use in kWh: ")) number_of_days = float(input("Enter number of billing days: ")) estimated_bill = (cents_per_kwh / 100) * daily_use * number_of_days print("Estimated bill: ${:.2f}".format(estimated_bill)) """
true
823282e7460b9d11b4d4127fa68a87352a5543ce
SamuelHealion/cp1404practicals
/prac_02/practice_and_extension/word_generator.py
2,154
4.25
4
""" CP1404/CP5632 - Practical Random word generator - based on format of words Another way to get just consonants would be to use string.ascii_lowercase (all letters) and remove the vowels. """ import random VOWELS = "aeiou" CONSONANTS = "bcdfghjklmnpqrstvwxyz" def first_version(): """Requires c and v only""" print("Please enter the word format: C for Consonants, V for Vowels") word_format = str(input("> ").lower()) word = "" for kind in word_format: if kind == "c": word += random.choice(CONSONANTS) elif kind == "v": word += random.choice(VOWELS) else: print("Invalid input") break print(word) def second_version(): """Uses wild cards but also accepts regular inputs # for vowels, % for consonants and * for either""" print("Random word generator that includes your characters but uses:") print("Enter # for Vowels, % for Consonants or * for either") word_format = str(input("> ")) word = "" for kind in word_format: if kind == "%": word += random.choice(CONSONANTS) elif kind == "#": word += random.choice(VOWELS) elif kind == "*": word += random.choice(CONSONANTS + VOWELS) else: word += kind print(word) def third_version(): """Automatically generates the word_format for a random length between 1 and 20""" word_length = random.randint(0, 20) word_format = '' for i in range(word_length): word_format += random.choice('%' + '#') word = "" for kind in word_format: if kind == "%": word += random.choice(CONSONANTS) elif kind == "#": word += random.choice(VOWELS) print(word) user_input = '' while user_input != 'Q': print("Press Q to quit") print("What version would you like to run? 1, 2 or 3") user_input = str(input(">>> ")).upper() if user_input == '1': first_version() elif user_input == '2': second_version() elif user_input == '3': third_version() else: print("Invalid option")
true
d2539727c20ffae59e81cccadb78648b10797a5d
SamuelHealion/cp1404practicals
/prac_06/guitar.py
730
4.3125
4
""" CP1404 Practical 6 - Classes Define the class Guitar """ VINTAGE_AGE = 50 CURRENT_YEAR = 2021 class Guitar: """Represent a Guitar object.""" def __init__(self, name='', year=0, cost=0): """Initialise a Guitar instance.""" self.name = name self.year = year self.cost = cost def __str__(self): """Return a string representation of a Guitar object.""" return "{} ({}) : ${:,.2f}".format(self.name, self.year, self.cost) def get_age(self): """Return the age of the guitar.""" return CURRENT_YEAR - self.year def is_vintage(self): """Return whether a Guitar is 50 years old or older.""" return self.get_age() >= VINTAGE_AGE
true
7ed8c1c53c80c4740739308c7768e5cb65fe92e5
SamuelHealion/cp1404practicals
/prac_02/practice_and_extension/random_boolean.py
854
4.25
4
""" Three different ways to generate random Boolean """ import random print("Press Q to quit") print("What random function do you want to run: A, B or C? ") user_input = str(input("> ")).upper() while user_input != 'Q': if user_input == 'A': if random.randint(0, 1) == 0: print("False") else: print("True") elif user_input == 'B': number = random.randrange(1, 11) if number % 2 == 0: print("True") else: print("False") elif user_input == 'C': number = random.randint(0, 100) if number > 50: print("True") else: print("False") else: print("Invalid choice") print("Press Q to quit") print("What random function do you want to run: A, B or C? ") user_input = str(input("> ")).upper()
false
6339d40839889e191b3ef8dae558cf3266b08ba8
jamieboyd/neurophoto2018
/code/simple_loop.py
407
4.46875
4
#! /usr/bin/python #-*-coding: utf-8 -*- """ a simple for loop with conditionals % is the modulus operator, giving the remainder of the integer division of the left operand by the right operand. If a number divides by two with no remainder it is even. """ for i in range (0,10,1): if i % 2 == 1: print (str (i) + ' is an odd number.') else: print (str (i) + ' is an even number.')
true
86dec63990bd3ae55a023380af8ce0f38fcdf3e2
CQcodes/MyFirstPythonProgram
/Main.py
341
4.25
4
import Fibonacci import Check # Driver Code print("Program to print Fibonacci series upto 'n'th term.") input = input("Enter value for 'n' : ") if(Check.IsNumber(input)): print("Printing fibonacci series upto '" + input + "' terms.") Fibonacci.Print(int(input)) else: print("Entered value is not a valid integer. Please Retry.")
true
e2f55129c04745dd81793e7d6867af117c988661
rinogen/Struktur-Data
/Perkenalan List.py
1,569
4.25
4
# parctice with list in phyton and falsh back in first alpro 1 colors = ["red", "green" , "blue" , "yellow" ] for i in range (len(colors)) : print (colors[i]) print() for i in range (len(colors) -1 , -1 , -1): # --> (panjangnya , sampai ke berapa , mundurnya berapa) # print (colors[i]) print () print () print () # use reverse for i in reversed(colors) : print (i) print() print () print () # ascending with the first alphabeth place on the top for i in reversed(sorted(colors)) : print (i) print () print () print () # descending number in list --> (panjangnya , sampai ke berapa , mundurnya berapa) for i in range (5,-1,-1) : print (i) print () print () print () #make another print with "kutip" for i in range (len(colors)) : print (i ,"-->" , colors [i] ) print () print () print () for i in range (len(colors)) : print (i ,"-->" , '"' + colors [i] +'"' ) print () print () print () for i in range (len(colors)) : print (i ,"-->" , "\"" + colors [i] +"\"" ) print () print () print () #combine two lis in one print ---> use zip name = ["a" , "b" , "c"] for nama,warna in zip (name, colors) : print (nama , "SUKA" , warna) print () print () print () lebihpendek = min(len(name) , len(colors)) for i in range (lebihpendek) : print (name[i] , "SUKA" , colors[i]) print () print () print () # Tuple is the other way of list that cannot be chnage like add with append etc hari = ("SENIN" , "SELASA" , "RABU" , "KAMIS" , "JUMAT" , "SABTU" , "MINGGU") for day in hari: print (day) print () print () print ()
false
f193bf10635f1b1cc9f4f7aa0ae7a209e5f041db
Yashs744/Python-Programming-Workshop
/if_else Ex-3.py
328
4.34375
4
# Nested if-else name = input('What is your name? ') # There we can provide any name that we want to check with if name.endswith('Sharma'): if name.startswith('Mr.'): print ('Hello,', name) elif name.startswith('Mrs.'): print ('Hello,', name) else: print ('Hello,', name) else: print ('Hello, Stranger')
true
012cc0af4adbfa714a4f311b729d89a9ba446d35
Tagirijus/ledger-expenses
/general/date_helper.py
1,213
4.1875
4
import datetime from dateutil.relativedelta import relativedelta def calculateMonths(period_from, period_to): """Calculate the months from two given dates..""" if period_from is False or period_to is False: return 12 delta = relativedelta(period_to, period_from) return abs((delta.years * 12) + delta.months) def interpreteDate(date): """Interprete given date and return datetime or bool.""" if date is False: return False try: return datetime.datetime.strptime(date, '%Y-%m') except Exception as e: return False def normalizePeriods(months, period_from, period_to): """ Normlize the periods so that teh programm can work with them. Basically it tries to generate the other period with self.months months in difference, if only one period date is given. """ if period_from is False and period_to is False: return (False, False) elif period_from is False and period_to is not False: period_from = period_to - relativedelta(months=months) elif period_from is not False and period_to is False: period_to = period_from + relativedelta(months=months) return (period_from, period_to)
true
b5a66fd0978895aaabb5cb93de5a7cfabd57ad8e
yosef8234/test
/python_simple_ex/ex28.py
477
4.3125
4
# Write a function find_longest_word() that takes a list of words and # returns the length of the longest one. # Use only higher order functions. def find_longest_word(words): ''' words: a list of words returns: the length of the longest one ''' return max(list(map(len, words))) # test print(find_longest_word(["i", "am", "pythoning"])) print(find_longest_word(["hello", "world"])) print(find_longest_word(["ground", "control", "to", "major", "tom"]))
true
b787971db2b58732d63ea00aaac8ef233068b822
yosef8234/test
/python_simple_ex/ex15.py
443
4.25
4
# Write a function find_longest_word() that takes a list of words and # returns the length of the longest one. def find_longest_word(words): longest = "" for word in words: if len(word) >= len(longest): longest = word return longest # test print(find_longest_word(["i", "am", "pythoning"])) print(find_longest_word(["hello", "world"])) print(find_longest_word(["ground", "control", "to", "major", "tom"]))
true
9b22d6e5f777384cd3b88f9d44b7f2711346fc74
yosef8234/test
/pfadsai/07-searching-and-sorting/notes/sequential-search.py
1,522
4.375
4
# Sequential Search # Check out the video lecture for a full breakdown, in this Notebook all we do is implement Sequential Search for an Unordered List and an Ordered List. def seq_search(arr,ele): """ General Sequential Search. Works on Unordered lists. """ # Start at position 0 pos = 0 # Target becomes true if ele is in the list found = False # go until end of list while pos < len(arr) and not found: # If match if arr[pos] == ele: found = True # Else move one down else: pos = pos+1 return found arr = [1,9,2,8,3,4,7,5,6] print seq_search(arr,1) #True print seq_search(arr,10) #False # Ordered List # If we know the list is ordered than, we only have to check until we have found the element or an element greater than it. def ordered_seq_search(arr,ele): """ Sequential search for an Ordered list """ # Start at position 0 pos = 0 # Target becomes true if ele is in the list found = False # Stop marker stopped = False # go until end of list while pos < len(arr) and not found and not stopped: # If match if arr[pos] == ele: found = True else: # Check if element is greater if arr[pos] > ele: stopped = True # Otherwise move on else: pos = pos+1 return found arr.sort() ordered_seq_search(arr,3) #True ordered_seq_search(arr,1.5) #False
true
720f5fa949f49b1fa20d7c0ae08ae397fc6fc225
yosef8234/test
/pfadsai/03-stacks-queues-and-deques/notes/implementation-of-stack.py
1,537
4.21875
4
# Implementation of Stack # Stack Attributes and Methods # Before we implement our own Stack class, let's review the properties and methods of a Stack. # The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below. # Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack. # push(item) adds a new item to the top of the stack. It needs the item and returns nothing. # pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified. # peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. # isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value. # size() returns the number of items on the stack. It needs no parameters and returns an integer. class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) s = Stack() print(s.isEmpty()) s.push(1) s.push('two') s.peek() s.push(True) s.size() s.isEmpty() s.pop() s.size()
true
5d1b9a089f9f4c0e6b8674dafffa486f4698cdb4
yosef8234/test
/toptal/python-interview-questions/4.py
1,150
4.5
4
# Q: # What will be the output of the code below in Python 2? Explain your answer. # Also, how would the answer differ in Python 3 (assuming, of course, that the above print statements were converted to Python 3 syntax)? def div1(x,y): print "%s/%s = %s" % (x, y, x/y) def div2(x,y): print "%s//%s = %s" % (x, y, x//y) div1(5,2) div1(5.,2) div2(5,2) div2(5.,2.) # A: # In Python 2, the output of the above code will be: 5/2 = 2 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0 # By default, Python 2 automatically performs integer arithmetic if both operands are integers. As a result, 5/2 yields 2, while 5./2 yields 2.5. # Note that you can override this behavior in Python 2 by adding the following import: from __future__ import division # Also note that the “double-slash” (//) operator will always perform integer division, regardless of the operand types. That’s why 5.0//2.0 yields 2.0 even in Python 2. # Python 3, however, does not have this behavior; i.e., it does not perform integer arithmetic if both operands are integers. Therefore, in Python 3, the output will be as follows: 5/2 = 2.5 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0
true
3c39888213a9dcc78c1c0a641b9ab70c87680c0a
yosef8234/test
/pfadsai/04-linked-lists/questions/linked-list-reversal.py
2,228
4.46875
4
# Problem # Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return the new head of the list. # You are given the example Linked List Node class: class Node(object): def __init__(self,value): self.value = value self.nextnode = None # Solution # Since we want to do this in place we want to make the funciton operate in O(1) space, meaning we don't want to create a new list, so we will simply use the current nodes! Time wise, we can perform the reversal in O(n) time. # We can reverse the list by changing the next pointer of each node. Each node's next pointer should point to the previous node. # In one pass from head to tail of our input list, we will point each node's next pointer to the previous element. # Make sure to copy current.next_node into next_node before setting current.next_node to previous. Let's see this solution coded out: def reverse(head): # Set up current,previous, and next nodes current = head previous = None nextnode = None # until we have gone through to the end of the list while current: # Make sure to copy the current nodes next node to a variable next_node # Before overwriting as the previous node for reversal nextnode = current.nextnode # Reverse the pointer ot the next_node current.nextnode = previous # Go one forward in the list previous = current current = nextnode return previous # You should be able to easily test your own solution to make sure it works. Given the short list a,b,c,d with values 1,2,3,4. Check the effect of your reverse function and maek sure the results match the logic here below: # Create a list of 4 nodes a = Node(1) b = Node(2) c = Node(3) d = Node(4) # Set up order a,b,c,d with values 1,2,3,4 a.nextnode = b b.nextnode = c c.nextnode = d print(a.nextnode.value) print(b.nextnode.value) print(c.nextnode.value) reverse(a) print(d.nextnode.value) print(c.nextnode.value) print(b.nextnode.value) # Great, now we can see that each of the values points to its previous value (although now that the linked list is reversed we can see the ordering has also reversed)
true
9041e5cb16518965f170e82bdac4929e93ab0273
yosef8234/test
/hackerrank/30-days-of-code/day-24.py
2,826
4.375
4
# # -*- coding: utf-8 -*- # Objective # Check out the Tutorial tab for learning materials and an instructional video! # Task # A Node class is provided for you in the editor. A Node object has an integer data field, datadata, and a Node instance pointer, nextnext, pointing to another node (i.e.: the next node in a list). # A removeDuplicates function is declared in your editor, which takes a pointer to the headhead node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list. # Note: The headhead pointer may be null, indicating that the list is empty. Be sure to reset your nextnext pointer when performing deletions to avoid breaking the list. # Input Format # You do not need to read any input from stdin. The following input is handled by the locked stub code and passed to the removeDuplicates function: # The first line contains an integer, NN, the number of nodes to be inserted. # The NN subsequent lines each contain an integer describing the datadata value of a node being inserted at the list's tail. # Constraints # The data elements of the linked list argument will always be in non-decreasing order. # Output Format # Your removeDuplicates function should return the head of the updated linked list. The locked stub code in your editor will print the returned list to stdout. # Sample Input # 6 # 1 # 2 # 2 # 3 # 3 # 4 # Sample Output # 1 2 3 4 # Explanation # N=6N=6, and our non-decreasing list is {1,2,2,3,3,4}{1,2,2,3,3,4}. The values 22 and 33 both occur twice in the list, so we remove the two duplicate nodes. We then return our updated (ascending) list, which is {1,2,3,4}{1,2,3,4}. class Node: def __init__(self,data): self.data = data self.next = None class Solution: def insert(self,head,data): p = Node(data) if head==None: head=p elif head.next==None: head.next=p else: start=head while(start.next!=None): start=start.next start.next=p return head def display(self,head): current = head while current: print(current.data,end=' ') current = current.next def removeDuplicates(self,head): node = head while node: if node.next: if node.data == node.next.data: node.next = node.next.next else: node = node.next else: node = node.next return head mylist= Solution() T=int(input()) head=None for i in range(T): data=int(input()) head=mylist.insert(head,data) head=mylist.removeDuplicates(head) mylist.display(head)
true
756868b809716f135bb1a27a9c35791e116a902a
yosef8234/test
/pfadsai/04-linked-lists/questions/implement-a-linked-list.py
952
4.46875
4
# Implement a Linked List - SOLUTION # Problem Statement # Implement a Linked List by using a Node class object. Show how you would implement a Singly Linked List and a Doubly Linked List! # Solution # Since this is asking the same thing as the implementation lectures, please refer to those video lectures and notes for a full explanation. The code from those lectures is displayed below: class LinkedListNode(object): def __init__(self,value): self.value = value self.nextnode = None a = LinkedListNode(1) b = LinkedListNode(2) c = LinkedListNode(3) a.nextnode = b b.nextnode = c class DoublyLinkedListNode(object): def __init__(self,value): self.value = value self.next_node = None self.prev_node = None a = DoublyLinkedListNode(1) b = DoublyLinkedListNode(2) c = DoublyLinkedListNode(3) # Setting b after a b.prev_node = a a.next_node = b # Setting c after a b.next_node = c c.prev_node = b
true
6eb333b658f76812126d0fefdb33a39e66f608bf
yosef8234/test
/pfadsai/10-mock-interviews/ride-share-company/on-site-question3.py
2,427
4.3125
4
# On-Site Question 3 - SOLUTION # Problem # Given a binary tree, check whether it’s a binary search tree or not. # Requirements # Use paper/pencil, do not code this in an IDE until you've done it manually # Do not use built-in Python libraries to do this, but do mention them if you know about them # Solution # The first solution that comes to mind is, at every node check whether its value is larger than or equal to its left child and smaller than or equal to its right child (assuming equals can appear at either left or right). However, this approach is erroneous because it doesn’t check whether a node violates any condition with its grandparent or any of its ancestors. # So, we should keep track of the minimum and maximum values a node can take. And at each node we will check whether its value is between the min and max values it’s allowed to take. The root can take any value between negative infinity and positive infinity. At any node, its left child should be smaller than or equal than its own value, and similarly the right child should be larger than or equal to. So during recursion, we send the current value as the new max to our left child and send the min as it is without changing. And to the right child, we send the current value as the new min and send the max without changing. class Node: def __init__(self, val=None): self.left, self.right, self.val = None, None, val INFINITY = float("infinity") NEG_INFINITY = float("-infinity") def isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY): if tree is None: return True if not minVal <= tree.val <= maxVal: return False return isBST(tree.left, minVal, tree.val) and isBST(tree.right, tree.val, maxVal) # There’s an equally good alternative solution. If a tree is a binary search tree, then traversing the tree inorder should lead to sorted order of the values in the tree. So, we can perform an inorder traversal and check whether the node values are sorted or not. def isBST2(tree, lastNode=[NEG_INFINITY]): if tree is None: return True if not isBST2(tree.left, lastNode): return False if tree.val < lastNode[0]: return False lastNode[0]=tree.val return isBST2(tree.right, lastNode) # This is a common interview problem, its relatively simple, but not trivial and shows that someone has a knowledge of binary search trees and tree traversals.
true
0d349d0708bdb56ce5da09f585eaf41d8f9952c3
yosef8234/test
/python_essential_q/q8.py
2,234
4.6875
5
# Question 8 What does this stuff mean: *args, **kwargs? And why would we use it? # Answer # Use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we dont know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise. # Here is a little illustration: def f(*args,**kwargs): print(args, kwargs) l = [1,2,3] t = (4,5,6) d = {'a':7,'b':8,'c':9} f() f(1,2,3) # (1, 2, 3) {} f(1,2,3,"groovy") # (1, 2, 3, 'groovy') {} f(a=1,b=2,c=3) # () {'a': 1, 'c': 3, 'b': 2} f(a=1,b=2,c=3,zzz="hi") # () {'a': 1, 'c': 3, 'b': 2, 'zzz': 'hi'} f(1,2,3,a=1,b=2,c=3) # (1, 2, 3) {'a': 1, 'c': 3, 'b': 2} f(*l,**d) # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8} f(*t,**d) # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8} f(1,2,*t) # (1, 2, 4, 5, 6) {} f(q="winning",**d) # () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} f(1,2,*t,q="winning",**d) # (1, 2, 4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs) f2(1,2,3) # 1 2 (3,) {} f2(1,2,3,"groovy") # 1 2 (3, 'groovy') {} f2(arg1=1,arg2=2,c=3) # 1 2 () {'c': 3} f2(arg1=1,arg2=2,c=3,zzz="hi") # 1 2 () {'c': 3, 'zzz': 'hi'} f2(1,2,3,a=1,b=2,c=3) # 1 2 (3,) {'a': 1, 'c': 3, 'b': 2} f2(*l,**d) # 1 2 (3,) {'a': 7, 'c': 9, 'b': 8} f2(*t,**d) # 4 5 (6,) {'a': 7, 'c': 9, 'b': 8} f2(1,2,*t) # 1 2 (4, 5, 6) {} f2(1,1,q="winning",**d) # 1 1 () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} f2(1,2,*t,q="winning",**d) # 1 2 (4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8} # Why do we care? # Sometimes we will need to pass an unknown number of arguments or keyword arguments into a function. Sometimes we will want to store arguments or keyword arguments for later use. Sometimes it's just a time saver.
true
ec8296cf056afef1f3ad97123c852b66f25d75cb
yosef8234/test
/pfadsai/04-linked-lists/notes/singly-linked-list-implementation.py
1,136
4.46875
4
# Singly Linked List Implementation # In this lecture we will implement a basic Singly Linked List. # Remember, in a singly linked list, we have an ordered list of items as individual Nodes that have pointers to other Nodes. class Node(object): def __init__(self,value): self.value = value self.nextnode = None # Now we can build out Linked List with the collection of nodes: a = Node(1) b = Node(2) c = Node(3) a.nextnode = b b.nextnode = c # In a Linked List the first node is called the head and the last node is called the tail. Let's discuss the pros and cons of Linked Lists: # Pros # Linked Lists have constant-time insertions and deletions in any position, in comparison, arrays require O(n) time to do the same thing. # Linked lists can continue to expand without having to specify their size ahead of time (remember our lectures on Array sizing form the Array Sequence section of the course!) # Cons # To access an element in a linked list, you need to take O(k) time to go from the head of the list to the kth element. In contrast, arrays have constant time operations to access elements in an array.
true
09da1340b227103c7eb1bc9800c714907939bfde
yosef8234/test
/python_ctci/q1.4_permutation_of_palindrom.py
1,097
4.21875
4
# Write a function to check if a string is a permutation of a palindrome. # Permutation it is "abc" == "cba" # Palindrome it is "Madam, I'm Adam' # A palindrome is word or phrase that is the same backwards as it is forwards. (Not limited to dictionary words) # A permutation is a rearrangement of letters. import string def isPermutationOfPalindrome(str): # {'a': False, 'c': False, 'b': False, 'e': False, 'd': False, 'g': False, 'f': False, 'i': False, 'h': False, 'k': False, 'j': False, 'm': False, 'l': False, 'o': False, 'n': False, 'q': False, 'p': False, 's': False, 'r': False, 'u': False, 't': False, 'w': False, 'v': False, 'y': False, 'x': False, 'z': False} d = dict.fromkeys(string.ascii_lowercase, False) count = 0 for char in str: if(ord(char) > 96 and ord(char) < 123): d[char] = not d[char] for key in d: if d[key] is True: count += 1 if count > 1: return False return True print(isPermutationOfPalindrome("abcecba")) # True print(isPermutationOfPalindrome("aa bb cc eee f")) # False
true
c117f5f321a25493ee9c3811a51e6c28d6487392
imjching/playground
/python/practice_python/11_check_primality_functions.py
730
4.21875
4
# http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html """ Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to [Exercise 4](/exercise/2014/02/26/04-divisors.html to help you. Take this opportunity to practice using functions, described below. """ number = int(raw_input("Please enter a number: ")) def is_prime(number): if number < 2: return False for i in range(2, (number / 2) + 1): if number % i == 0: return False return True if is_prime(number): print "This is a prime number!" else: print "This is not a prime number"
true
8f13963a5059a9cbb14790645f86ff0415398108
imjching/playground
/python/practice_python/14_list_remove_duplicates.py
764
4.1875
4
# http://www.practicepython.org/exercise/2014/05/15/14-list-remove-duplicates.html """ Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. """ from sets import Set def unique_elements_loop(_list): new_list = [] for i in _list: if i not in new_list: new_list.append(i) return new_list def unique_elements_sets(_list): return list(Set(_list)) print unique_elements_loop([1, 2, 3, 3, 3, 3]) print unique_elements_sets([1, 2, 3, 3, 3, 3])
true
35c0ab9c2e6bfb4eea6f3750b208495ce1407d03
imjching/playground
/python/practice_python/18_cows_and_bulls.py
1,813
4.21875
4
# http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html """ Create a program that will play the 'cows and bulls' game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a 'cow'. For every digit the user guessed correctly in the wrong place is a 'bull'. Every time the user makes a guess, tell them how many 'cows' and 'bulls' they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull ... Until the user guesses the number. """ from random import randint print "Welcome to the Cows and Bulls Game!" number = "".join(["1234567890"[randint(0, 9)] for i in range(4)]) print number def check(input_, number): cows = 0 bulls = 0 for i in range(len(number)): if input_[i] == number[i]: cows += 1 elif input_[i] in number: # something doesn't seem right bulls += 1 if cows == 4: return "0" else: res = str(cows) + " cow, " if cows <= 1 else str(cows) + " cows, " res += str(bulls) + " bull" if bulls <= 1 else str(bulls) + " bulls" return res trials = 0 while True: trials += 1 input_ = raw_input("Enter a number: ") if len(input_) != 4: print "Please enter a 4 digit number." else: result = check(input_, number) if result == "0": print "You have guessed the number with a total of " + str(trials) + " guesses!" break else: print result
true
53937a32b059e4e9613be47b492f586eff09a06d
bkhuong/LeetCode-Python
/make_itinerary.py
810
4.125
4
class Solution: ''' Given a list of tickets, find itinerary in order using the given list. ''' def find_route(tickets:list) -> str: routes = {} start = [] # create map for ticket in tickets: routes[ticket[0]] = {'to':ticket[1]} try: routes[ticket[1]].update({'from':ticket[0]}) except: routes[ticket[1]] = {'from':ticket[0]} # find starting point for k,v in routes.items(): if 'from' not in v.keys(): departure = k break # walk dictionary for route: while 'to' in routes[departure].keys(): print(f'{departure} -> {routes[departure]["to"]}') departure = routes[departure]['to']
true
70cc3581b224daa3beadfc0150d31b52c30f6284
Gachiman/Python-Course
/python-scripts/hackerrank/Medium/Find Angle MBC.py
603
4.21875
4
import math def input_length_side(val): while True: try: length = int(float(input("Enter the length of side {0} (0 < {0} <= 100): ".format(val)))) if 0 < length <= 100: return length else: raise ValueError except ValueError: print("Please reinsert") def main(): side_ab = input_length_side("AB") side_bc = input_length_side("BC") tg_mbc = side_ab / side_bc angle_mbc = math.degrees(math.atan(tg_mbc)) print(round(angle_mbc), '°', sep='') if __name__ == '__main__': main()
true
a1b6391a773b23a0f5fe8e0b0a4d36bc7e03b9b0
hobsond/Computer-Architecture
/white.py
1,788
4.625
5
# Given the following array of values, print out all the elements in reverse order, with each element on a new line. # For example, given the list # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # Your output should be # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. originalList = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] reverseList = originalList[::-1] for i in reverseList: print(i) # Given a hashmap where the keys are integers, print out all of the values of the hashmap in reverse order, ordered by the keys. # For example, given the following hashmap: # { # 14: "vs code", # 3: "window", # 9: "alloc", # 26: "views", # 4: "bottle", # 15: "inbox", # 79: "widescreen", # 16: "coffee", # 19: "tissue", # } # The expected output is: # widescreen # views # tissue # coffee # inbox # vs code # alloc # bottle # window # since "widescreen" has the largest integer key, "views" has the second largest, etc. # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. # hash map key = { 14: "vs code", 3: "window", 9: "alloc", 26: "views", 4: "bottle", 15: "inbox", 79: "widescreen", 16: "coffee", 19: "tissue", } # loop through key get the key.items() # which im gonna sort by the first value # then loop through and print newList = sorted([i for i in key.items()],reverse=True) # newList.sort(key = lambda e:e[0]) # newList.reverse() for i in newList: print(i[1])
true
2718e25886a29226c5050afe0d83c6459bd6747b
Twest19/prg105
/Ch 10 HW/10-1_person_data.py
1,659
4.71875
5
""" Design a class that holds the following personal data: name, address, age, and phone number. Write appropriate accessor and mutator methods (get and set). Write a program that creates three instances of the class. One instance should hold your information and the other two should hold your friends' or family members' information. Just add information, don't get it from the user. Print the data from each object, make sure to format the output for clarity and ease of reading. """ class Data: # This class takes the data for a person and returns that data def __init__(self, name, address, age, phone='n/a'): self.name = name self.address = address self.age = age self.phone = phone def set_name(self, name): self.name = name def get_name(self): return self.name def set_address(self, address): self.address = address def get_address(self): return self.address def set_age(self, age): self.age = int(age) def get_age(self): return self.age def set_phone(self, phone): self.phone = phone def get_phone(self): return self.phone def __str__(self): return f"Name: {self.name}\nAddress: {self.address}\nAge: {self.age}\nPhone: {self.phone}\n" def main(): my_data = Data('Tim', '119 W South Ave', 21, '815-354-7216') friend_data = Data('Saul', '9800 Montgomery Blvd', 49, '505-503-4455') family_data = Data('Tom', '191 E North Ave', 42) print(my_data) print(friend_data) print(family_data) main()
true
b33b65d4b831bcd41fac9f4cd424a65dc4589d39
Twest19/prg105
/3-3_ticket.py
2,964
4.3125
4
""" You are writing a program to sell tickets to the school play. If the person buying the tickets is a student, their price is $5.00 per ticket. If the person buying the tickets is a veteran, their price is $7.00 per ticket. If the person buying the ticket is a sponsor of the play, the price is $2.00 per ticket. """ # Must initialize price and discount to later assign them a new value price = 0 discount = 0 print(f"{'=' * 6} Play Ticket Types w/ Prices {'=' * 6}" "\n(1) Student - $6.00" "\n(2) Veteran - $7.00" "\n(3) Show Sponsor - $2.00" "\n(4) Retiree - $6.00" "\n(5) General Public - $10.00") print(f"{'=' * 36}") # Ask the buyer which ticket group they fall into # Choose a number 1-5 or it will display an error and prompt them until they provide a proper response while True: prompt = input("\nPlease choose a number for the corresponding ticket type that you fall into: ") if prompt in ('1', '2', '3', '4', '5'): ticket_type = int(prompt) # Assign the ticket to a price for the number chosen by the buyer if ticket_type == 1: price = 6.00 print("\nYou have selected Student.") elif ticket_type == 2: price = 7.00 print("\nYou have selected Veteran.") elif ticket_type == 3: price = 2.00 print("\nYou have selected Show Sponsor.") elif ticket_type == 4: price = 6.00 print("\nYou have selected Retiree.") elif ticket_type == 5: price = 10.00 print("\nYou have selected General Public.") break else: print("\nError please try again") # Let the buyer know that they can receive a discount when they buy more tickets print("\nIf you buy 4 - 8 tickets you get a 10% discount.") print("If you buy 9 - 15 tickets you get a 15% discount.") print("If you buy more than 15 tickets you get a 20% discount.") # Ask buyer how many tickets they would like to purchase ticket_quantity = int(input("\nHow many tickets would you like to buy? ")) # Get the total price before any discounts are applied if there are any ticket_total = price * ticket_quantity # Determine if the buyer has met the requirements for a discount if ticket_quantity > 15: print("\nYou get a 20% discount!") discount = ticket_total * .20 elif ticket_quantity >= 9: print("\nYou get a 15% discount!") discount = ticket_total * .15 elif ticket_quantity >= 4: print("\nYou get a 10% discount") discount = ticket_total * .10 else: print("\nSorry, you do not get a discount.") # Calculate the price by applying the discount discount_applied = ticket_total - discount # Calculate average price paid avg = discount_applied / ticket_quantity # Display the total before and after discount with how much they saved print(f"\nTotal before discount: ${ticket_total:.2f}") print(f"You saved: ${discount:.2f} ") print(f"Your price per ticket is: ${avg:.2f}") print(f"Total after discount: ${discount_applied:.2f}")
true
20a0d53d34ba73884e14d026030289475bb6275e
Twest19/prg105
/chapter_practice/ch_9_exercises.py
2,681
4.4375
4
""" Complete all of the TODO directions The number next to the TODO represents the chapter and section in your textbook that explain the required code Your file should compile error free Submit your completed file """ import pickle # TODO 9.1 Dictionaries print("=" * 10, "Section 9.1 dictionaries", "=" * 10) # 1) Finish creating the following dictionary by adding three more people and birthdays birthdays = {'Meri': 'May 16', 'Kathy': 'July 14'} birthdays['Tim'] = 'Jan 19' birthdays['Jane'] = 'Jun 30' birthdays['Harold'] = 'Oct 19' # 2) Print Meri's Birthday print(birthdays['Meri']) # 3) Create an empty dictionary named registration registration = {} # You will use the following dictionary for many of the remaining exercises" miles_ridden = {'June 1': 25, 'June 2': 20, 'June 3': 38, 'June 4': 12, 'June 5': 30, 'June 7': 25} # 1) Print the keys and the values of miles_ridden using a for loop for k, v in miles_ridden.items(): print(k, v) # 2) Get the value for June 3 and print it, if not found display 'Entry not found', replace the "" value = miles_ridden['June 3'] print(value) # 3) Get the value for June 6 and print it, if not found display 'Entry not found' replace the "" if 'June 6' in miles_ridden: value2 = miles_ridden['June 6'] else: value2 = 'Entry not found' print(value2) # 4) Use the values method to print the miles_ridden dictionary print(miles_ridden.values()) # 5) Use the keys method to print all of the keys in miles_ridden print(miles_ridden.keys()) # 6) Use the pop method to remove June 4 then print the contents of the dictionary miles_ridden.pop('June 4') print(miles_ridden) # 7) Use the items method to print the contents of the miles_ridden dictionary print(miles_ridden.items()) # TODO 9.2 Sets print("=" * 10, "Section 9.2 sets", "=" * 10) # 1) Create an empty set named my_set my_set = set() # 2) Create a set named days that contains the days of the week days = {'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'} # 3) Get the number of elements from the days set and print it print(len(days)) # 4) Remove Saturday and Sunday from the days set days.remove('Sun') days.remove('Sat') print(days) # 5) Determine if 'Mon' is in the days set if 'Mon' in days: print('Mon') # TODO 9.3 Serializing Objects (Pickling) print("=" * 10, "Section 9.3 serializing objects using the pickle library", "=" * 10) # 1) Import the pickle library at the top of this file # 2) Create the output file log and open it for binary writing output = open('log.dat', 'wb') # 3) Pickle the miles_ridden dictionary and output it to the log file pickle.dump(miles_ridden, output) # 4) Close the log file output.close()
true
666efab8a625d46543dab413aadd15936594a5dd
Twest19/prg105
/4-1_sales.py
862
4.5625
5
""" You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop. The program should ask the user for the total amount of sales and include the day in the request. At the end of data entry, tell the user the total sales for the week, and the average sales per day. You must create a list of the days of the week for the user to step through, see the example output. """ days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] weekly_total = 0 print("Sales for the week:") for day in days: sales = float(input(f"What was the total amount of sales on {day}? ")) weekly_total += sales print(f"\nThe total amount of sales for the week was: ${weekly_total:,.2f}") print(F"The average amount of sales per day was: ${weekly_total / 7:,.2f}")
true
a3ace412c840aac7ff86999020c0d765a5062a5d
Twest19/prg105
/5-3_assessment.py
2,467
4.21875
4
""" You are going to write a program that finds the area of a shape for the user. """ # set PI as a constant to be used as a global value PI = 3.14 # create a main function then from the main function call other functions to get the correct calculations def main(): while True: menu() choice = int(input("Enter the number of your selection: ")) num = validate(choice) if num == 1: base = int(input("Enter the base of the rectangle in cm: ")) height = int(input("Enter the height of the rectangle in cm: ")) area = rectangle(base, height) print(f"The area of the rectangle is {area:.2f} square cm.") elif num == 2: base = int(input("Enter the base of the triangle in cm: ")) height = int(input("Enter the height of the triangle in cm: ")) area = triangle(base, height) print(f"The area of the triangle is {area:.2f} square cm.") elif num == 3: side = int(input("Enter the length of one side of the square in cm: ")) area = square(side) print(f"The area of the square is {area:.2f} square cm.") elif num == 4: radius = int(input("Enter the radius of the circle: ")) area = circle(radius) print(f"The area of the circle is {area:.2f} square cm.") # menu function displays the options available to the user def menu(): print("\nThis program will find the area of any of the shapes below.") print("1. Rectangle\n" "2. Triangle\n" "3. Square\n" "4. Circle\n" "5. Quit\n") # The validate function confirms the users input if the users provides a correct response def validate(x): while True: if 1 <= x < 5: return x elif x == 5: print("\nGoodbye!") exit() else: print("\nError, please try again.\n") x = int(input("Enter the number of your selection: ")) continue # Create a function for each of the shapes to calculate the area for the corresponding shape def rectangle(x, y): area = x * y return area def triangle(x, y): area = x * y * 1/2 return area def square(x): area = x**2 return area def circle(r): global PI area = PI * r**2 return area main()
true
52dd577610c57f96e36b41ee06982c873f0d55af
dougiejim/Automate-the-boring-stuff
/commaCode.py
753
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Write a function that takes a list value as an argument and returns #a string with all the items separated by a comma and a space, with #and inserted before the last item. For example, passing the previous #spam list to the function would return 'apples, bananas, tofu, and cats'. #But your function should be able to work with any list value passed to it. """ Created on Sat Jan 20 15:53:15 2018 @author: coledoug """ spam = ['apples', 'bananas', 'tofu', 'cats'] newString = '' def stringReturn(list): newString = '' for i in list: if i != list[-1]: return newString + str(i +', ') else: return newString + str(' and '+ i) stringReturn(spam)
true
732a68dc8a28c98ecc93001de996919759778a2c
sakamoto-michael/Sample-Python
/new/intro_loops.py
727
4.28125
4
# Python Loops and Iterations nums = [1, 2, 3, 4, 5] # Looping through each value in a list for num in nums: print(num) # Finding a value in a list, breaking upon condition for num in nums: if num == 3: print('Found!') break print(num) # Finding a value, the continuing execution for num in nums: if num == 3: print('Found') continue print(num) # Loops within loops for num in nums: for letter in 'abc': print(num, letter) # Iterations - range(starting point, end point) for i in range(1, 11): print(i) # While loop - must include a breaking condition. Can also included manual break within loop upon a different condition x = 0 while x < 10: if x == 5: break print(x) x += 1
true
701ea9976f04c66564962c3bc7f64d89e1314120
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/BinaryTree/NumberOfNonLeafNodes.py
1,524
4.3125
4
# @author # Aakash Verma # Output: # Pre Order Traversal is: 1 2 4 5 3 6 7 # Number Of non-Leaf Nodes: 3 # Creating a structure for the node. # Initializing the node's data upon calling its constructor. class Node: def __init__(self, data): self.data = data self.right = self.left = None # Defining class for the Binary Tree class NumberOfNonLeafNodes: # Assigning root as null initially. So as soon as the object will be created # of this NumberOfNonLeafNodes class, root will be set as null. def __init__(self): self.root = None # Pre Order Traversal def preOrder(self, root): if root is None: return print(root.data, end = " ") self.preOrder(root.left) self.preOrder(root.right) def numNonLeafNodes(self, root): if root is None: return 0 if root.left is None and root.right is None: return 0; return 1 + self.numNonLeafNodes(root.left) + self.numNonLeafNodes(root.right) # main method if __name__ == '__main__': tree = NumberOfNonLeafNodes() tree.root = Node(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) print("Pre Order Traversal is:", end = " ") tree.preOrder(tree.root) print() print("Number Of non-Leaf Nodes:", end = " ") print(tree.numNonLeafNodes(tree.root))
true
8878c006639c546777ff2af254a979033560c15a
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/LinkedList/StartingOfLoop.py
1,519
4.34375
4
# # # # @author # Aakash Verma # # Start of a loop in Linked List # # Output: # 5 # # Below is the structute of a node which is used to create a new node every time. class Node: def __init__(self, data): self.data = data self.next = None # None is nothing but null # Creating a class for implementing the code for Starting Of a loop in a LinkedList class LinkedList: # Whenever I'll create the object of a LinkedList class head will be pointing to null initially def __init__(self): self.head = None # Inserting at the end of a Linked List (append function) def append(self, key): h = self.head if h is None: new_node = Node(key) self.head = new_node else: while h.next != None: h = h.next new_node = Node(key) h.next = new_node # middle of a linked list def startingOfLoop(self): fast = self.head slow = self.head isLoopFound = False if self.head is None: print("The list doesn't exist.") return while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow == fast: isLoopFound = True break if isLoopFound is True: slow = self.head while slow != fast: slow = slow.next fast = fast.next print(slow.data) # Code execution starts here if __name__=='__main__': myList = LinkedList() myList.append(3) myList.append(4) myList.append(5) myList.append(6) myList.append(7) myList.head.next.next.next.next.next = myList.head.next.next myList.startingOfLoop()
true
96ca87b2c6191ffd17b5571581f5dec816529ef2
SgtHouston/python102
/sum the numbers.py
249
4.21875
4
# Make a list of numbers to sum numbers = [1, 2, 3, 4, 5, 6] # set up empty total so we can add to it total = 0 # add current number to total for each number iun the list for number in numbers: total += number # print the total print(total)
true
b318bf9bc8d0760352b2b551697b45f24117dcb3
starsCX/Py103
/chap0/Project/ex12-3.py
557
4.1875
4
#在Python 3.2.3中 input和raw_input 整合了,没有了raw_input age = input("How old are you?") height = input("How tall are you?") weight = input("How much do you weigh?") print ("so you are %r old ,%r tall and %r heavy." %(age,height,weight)) print ("so you are %r old ,%r tall and %r heavy." %(age,height,weight)) #python2.7 的话,print是一个表达式,要写 print i #而在python3 的话,print是一个函数,所以要写 print(i) #而且也影响到了赋值的过程,原本两个并列的括号结构变成包含的括号结构。
false
25ceca21258ebec39c3bb51f308a1e5f136aaca4
urmajesty/learning-python
/ex5.py
581
4.15625
4
name = 'Zed A Shaw' age = 35.0 # not a lie height = 74.0 # inches weight = 180.0 #lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print(f"Let's talk about {name}.") print(f"He's {height} pounds heavy.") print("Actually that's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") #study drill #2 cm = (height * 2.54) print(f"He also is {cm} cm tall.") kg = (weight * .453592) print(f"And He weighs {kg} kg.")
true
74ac90a14c752bbb7f61db09150bb3df3cdb7d94
antoinemadec/test
/python/codewars/middle_permutation/middle_permutation.py
1,069
4.1875
4
#!/usr/bin/env python3 f = {} def factorial(n): if n==0: f[n] = 1 elif n not in f: f[n] = n*factorial(n-1) return f[n] def factoradics(n): for k in range(n+2): if factorial(k) > n: break r = [] for k in range(k-1,-1,-1): d = n//factorial(k) r.append(d) n -= d*factorial(k) return r if r else [0] # https://medium.com/@aiswaryamathur/find-the-n-th-permutation-of-an-ordered-string-using-factorial-number-system-9c81e34ab0c8 def middle_permutation(string): string = sorted(string) i = factorial(len(string))//2 - 1 r = "" for k in factoradics(i): r += string[k] string = string[:k] + string[k+1:] return r+''.join(string) print(middle_permutation("ab"),"ab") print(middle_permutation("abc"),"bac") print(middle_permutation("abcd"),"bdca") print(middle_permutation("abcdx"),"cbxda") print(middle_permutation("abcdxg"),"cxgdba") print(middle_permutation("abcdxgz"),"dczxgba") print(middle_permutation("abcdefghijklmnopqrstuvwxyz"))
false
53c52d5fb29d5f8f28c56ead8f8c31dfd6f06d98
antoinemadec/test
/python/codewars/simplifying/simplifying.py
2,602
4.5
4
#!/usr/bin/env python3 ''' You are given a list/array of example formulas such as: [ "a + a = b", "b - d = c ", "a + b = d" ] Use this information to solve a formula in terms of the remaining symbol such as: "c + a + b" = ? in this example: "c + a + b" = "2a" Notes: Variables names are case sensitive There might be whitespaces between the different characters. Or not... There should be support for parenthesis and their coefficient. Example: a + 3 (6b - c). You might encounter several imbricated levels of parenthesis but you'll never get a variable as coefficient for parenthesis, only constant terms. All equations will be linear See the sample tests for clarification of what exactly the input/ouput formatting should be. Without giving away too many hints, the idea is to substitute the examples into the formula and reduce the resulting equation to one unique term. Look carefully at the example tests: you'll have to identify the pattern used to replace variables in the formula/other equations. Only one solution is possible for each test, using this pattern, so if you keep asking yourself "but what if I do that instead of...", that is you missed the thing. ''' import re def simplify(examples,formula): d,letters = {},[] examples = [re.sub('([0-9]+) *([(a-zA-Z])',r'\1*\2',e) for e in examples] for e in examples: m = re.match('(?P<expr>.*) += +(?P<var>\w+)',e) d[m.group('var')] = m.group('expr') letters.extend([c for c in e if c.isalpha()]) c = [c for c in letters if c not in d][0] d[c] = '1' for _ in range(1000): formula = re.sub('([0-9]+) *([(a-zA-Z])',r'\1*\2',formula) for k in d: formula = formula.replace(k,'(' + d[k] + ')') try: r = eval(formula) except: continue return "%d%c" % (r,c) examples=[["a + a = b", "b - d = c", "a + b = d"], ["a + 3g = k", "-70a = g"], ["-j -j -j + j = b"]] formula=["c + a + b", "-k + a", "-j - b" ] answer=["2a", "210a", "1j" ] for i in range(len(answer)): print('examples:' + str(examples[i])) print('formula:' + str(formula[i])) print('expected answer:'+str(answer[i])) print(simplify(examples[i],formula[i])) examples=['y + 6Y - k - 6 K = f', ' F + k + Y - y = K', 'Y = k', 'y = Y', 'y + Y = F'] formula='k - f + y' print('expected answer:14y') print(simplify(examples,formula)) examples=['x = b', 'b = c', 'c = d', 'd = e'] formula='c' print('expected answer:1x') print(simplify(examples,formula))
true
1d5eba8fd2834bb2375016ec7ed9e8cc686f1991
antoinemadec/test
/python/programming_exercises/q5/q5.py
662
4.21875
4
#!/usr/bin/env python3 print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt Question: Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Answer:""") class String: def __init__(self): self.string = "" def getString(self): self.string = input("Enter string: ") def printString(self): print(self.string.upper()) s = String(); s.getString() s.printString()
true
7f17dd1d0b9acc663a17846d838cbd79998bb79b
antoinemadec/test
/python/programming_exercises/q6/q6.py
840
4.21875
4
#!/usr/bin/env python3 print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Answer:""") C = 50 H = 30 Q = [] for D in input("Enter numbers separated by comma: ").split(','): D = int(D) Q.append(int(((2*C*D)/H) ** 0.5)) print(','.join([str(i) for i in Q]))
true
c1679cb04b4e70b555eaf1c35f5dd7ee8d5927f8
antoinemadec/test
/python/asyncio/coroutines_and_tasks/coroutines.py
1,304
4.40625
4
#!/usr/bin/env python3 import asyncio import time # coroutine async def main(): print('hello') await asyncio.sleep(1) print('world') # coroutine async def say_after(delay, what): await asyncio.sleep(delay) print(what) # coroutine async def main_after(): print(f"started at {time.strftime('%X')}") await say_after(1, 'hello') await say_after(2, 'world') print(f"finished at {time.strftime('%X')}") # coroutine async def main_create_task(): task1 = asyncio.create_task(say_after(1, 'hello')) task2 = asyncio.create_task(say_after(2, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}") # Note that simply calling a coroutine will not schedule it to be executed: # To actually run a coroutine, asyncio provides three main mechanisms: # 1- The asyncio.run() function to run the top-level entry point “main()” function asyncio.run(main()) # 2- Awaiting on a coroutine. The following snippet of code will print “hello” # after waiting for 1 second, and then print “world” after waiting for another # 2 seconds: asyncio.run(main_after()) # 3- The asyncio.create_task() function to run coroutines concurrently as asyncio Tasks. asyncio.run(main_create_task())
false
d057707ccd873e895d2caf5eec45a19e0473da84
antoinemadec/test
/python/codewars/find_the_divisors/find_the_divisors.py
708
4.3125
4
#!/usr/bin/env python3 """ Create a function named divisors/Divisors that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust). Example: divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" You can assume that you will only get positive integers as inputs. """ def divisors(i): r = [x for x in range(2,i) if (i//x)*x == i] if r: return r else: return "%0d is prime" % i print(divisors(12)) print(divisors(13))
true
81cc9b7d03933d990e1a90129929d1eb78ffb108
antoinemadec/test
/python/cs_dojo/find_mult_in_list/find_mult_in_list.py
526
4.1875
4
#!/bin/env python3 def find_multiple(int_list, multiple): sorted_list = sorted(int_list) n = len(sorted_list) for i in range(0,n): for j in range(i+1,n): x = sorted_list[i] y = sorted_list[j] if x*y == multiple: return (x,y) elif x>multiple: return None return None # execution l = [int(x) for x in input("Enter list (white space separated): ").split(" ")] m = int(input("Enter multiple: ")) print(find_multiple(l,m))
true
ce349e0d877be430c57a4a11990ac1cdf6096847
GreatRaksin/Saturday3pm
/1505_functions_p4/01_functional_programming.py
639
4.25
4
'''Функциональный код отличается тем, что у него отсутствуют побочные эффекты. Он не полагается на данные вне функции и не меняет их. ''' a = 0 def increment1(): '''Вот это НЕ функциональный код''' global a a += 1 def increment2(a): '''А это функциональный''' return a + 1 nums = ['0', '1', '2', '3', '4', '5'] int_nums = map(int, nums) for i in int_nums: print(type(i), end='') s = map(lambda x: x * x, [1, 2, 3, 4, 5]) for i in s: print(i, end='⏰')
false
1cbd89b34fc28fdfc949fc7b48b363df817adf71
GreatRaksin/Saturday3pm
/1704_functions_2/02_stars_and_functions.py
844
4.25
4
def multiply(n, n1, n2): print(n * n1 * n2) fruits = ['lemon', 'pear', 'watermelon', 'grape'] # ТАК НЕ НАДО: print(fruits[0], fruits[1], fruits[2], fruits[3]) # НАДО ВОТ ТАК: print(*fruits) def insert_into_list(*numbers): l = [] l.append(numbers) return numbers ''' *args - * позволяет передать функции неопределенное количество аргументов. **kwargs - **keyword arguments - позволяет передать функции неопределенное количество !именованных! аргументов ''' def fun(**kwargs): print(f'Type of argument is {type(kwargs)}') print(kwargs) for key, value in kwargs.items(): print(f'{key} == {value}') fun(name='Colt', surname='Steel', hobby='Programming')
false
d6aabcb1f4476a9d8dbb13844e29227df4db6426
GreatRaksin/Saturday3pm
/task1.py
428
4.4375
4
''' Создать словарь со странами и их столицами Вывести предложение: {столица} is a capital of {страна}. ''' countries = { 'USA': 'Minsk', 'Brazil': 'Brasilia', 'Belarus': 'Washington', 'Italy': 'Rome', 'Spain': 'Madrid' } for country, capital in countries.items(): print(f'{capital} is a Capital of {country}') fr = { 9: 'nine', 10: True }
false
ca298fbbff9313d62c867a6a8b5cc9e3511d7e05
pedroinc/hackerhank
/staircase.py
280
4.15625
4
#!/bin/python3 import sys def staircase(n): for x in range(1, n + 1): if x < n: remain = n - x print(remain * " " + x * "#") else: print(x * "#") if __name__ == "__main__": n = int(input().strip()) staircase(n)
false