blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2c55104e100681e13599c5e033a4750fc3c453d6
gorkemunuvar/Data-Structures
/algorithm_questions/3_find_the_missing_element.py
1,569
4.125
4
# Problem: Consider an array of non-negative integers. A second array is formed by shuffling # the elements of the first array and deleting a random element. Given these two arrays, # find which element is missing in the second array. import collections # O(N) # But this way is not work correctly cause # arrays can have duplicate numbers. def finder1(arr1, arr2): for num in arr1: if num not in arr2: print(f"{num} is missing") return print("No missing element.") # O(N) def finder2(arr1, arr2): # Using defaultdict to avoid missing key errors dict_nums = collections.defaultdict(int) for num in arr2: dict_nums[num] += 1 for num in arr1: if dict_nums[num] == 0: print(f"{num} is missing.") return else: dict_nums[num] -= 1 # O(N) # Using XOR to find missing element. # A XOR A = 0. So when we iterate all the numbers # of arr1 and arr2 we'll find the missing el. def finder3(arr1, arr2): result = 0 for num in arr1 + arr2: result ^= num print(result) # Another solution: Also we could sort arr1 and arr2 and then we # could iterate and compare all the numbers. When a comparing is # false, it is the missing element. But time complexity of sort() # func. is O(nlogn). That's why it's not a good solution. finder3([5, 5, 7, 7], [5, 7, 7]) # 5 is missing finder3([1, 2, 3, 4, 5, 6, 7], [3, 7, 2, 1, 4, 6]) # 5 is missing finder3([9, 8, 7, 6, 5, 4, 3, 2, 1], [9, 8, 7, 5, 4, 3, 2, 1]) # 6 is missing
true
351e79d71059e89664cddd394ac4db110beab3d3
hsyun89/PYTHON_ALGORITHM
/FAST_CAMPUS/링크드리스트.py
746
4.125
4
#파이썬 객체지향 프로그래밍으로 링크드리스트 구현하기 from random import randrange class Node: def __init__(self,data,next=None): self.data = data self.next = next class NodeMgmt: def __init__(self, data): self.head = Node(data) def add(self, data): if self.head =='': self.head = Node(data) else: node = self.head while node.next: node = node.next node.next = Node(data) def desc(self): node = self.head while node: print(node.data) node = node.next #출력 linkedlist1 = NodeMgmt(0) for data in range (1,10): linkedlist1.add(data) linkedlist1.desc()
false
e02442b00cf41f9d3dd1933bee6b63122225e3b6
johnehunt/python-datastructures
/trees/list_based_tree.py
1,441
4.1875
4
# Sample tree constructed using lists test_tree = ['a', # root ['b', # left subtree ['d', [], []], ['e', [], []]], ['c', # right subtree ['f', [], []], []] ] print('tree', test_tree) print('left subtree = ', test_tree[1]) print('root = ', test_tree[0]) print('right subtree = ', test_tree[2]) # Functions to make it easier to work with trees def create_tree(r): return [r, [], []] def insert_left(root, new_branch): t = root.pop(1) if len(t) > 1: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def insert_right(root, new_branch): t = root.pop(2) if len(t) > 1: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) return root def get_root_value(root): return root[0] def set_root_value(root, new_value): root[0] = new_value def get_left_child(root): return root[1] def get_right_child(root): return root[2] # Program to exercise functions defined above list_tree = create_tree(3) insert_left(list_tree, 4) insert_left(list_tree, 5) insert_right(list_tree, 6) insert_right(list_tree, 7) print(list_tree) l = get_left_child(list_tree) print(l) set_root_value(l, 9) print(list_tree) insert_left(l, 11) print(list_tree) print(get_right_child(get_right_child(list_tree)))
true
070be4d1e2e9ebcdbff2f227ec97da5a83c45282
johnehunt/python-datastructures
/abstractdatatypes/queue.py
1,055
4.15625
4
class BasicQueue: """ Queue ADT A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and makes its way toward the front, waiting until that time when it is the next element to be removed. """ def __init__(self): self.data = [] def is_empty(self): return self.data == [] def enqueue(self, item): self.data.insert(0, item) def dequeue(self): return self.data.pop() def size(self): return len(self.data) def clear(self): self.data = [] def __str__(self): return 'Queue' + str(self.data) # Implement the length protocol def __len__(self): return self.size() # Implement the iterable protocol def __iter__(self): temp = self.data.copy() temp.reverse() return iter(temp)
true
ad133e4c54b80abf48ff3028f7c00db37a622ec5
benwardswards/ProjectEuler
/problem038PanDigitMultiple.py
1,853
4.21875
4
"""Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?""" from typing import List def listToNumber(numList: List[int]) -> int: s = "".join([str(i) for i in numList]) return int(s) assert listToNumber([1, 2, 3, 4]) == 1234 def numberToList(number: int) -> List[int]: return [int(digit) for digit in str(number)] assert numberToList(1234) == [1, 2, 3, 4] def concatnumbers(listnumbers: List[int]) -> List[int]: listofdigits = [] for num in listnumbers: for digit in numberToList(num): listofdigits.append(digit) return listofdigits assert concatnumbers([1, 23, 45, 6, 789]) == list(range(1, 10)) def panDigit(start): for max_n in range(2, 11): listofnums: List[int] = [i * start for i in range(1, max_n)] listofdigits: List[int] = concatnumbers(listofnums) # print(listofdigits) if len(listofdigits) > 9: return 0 if len(listofdigits) == 9: if set(listofdigits) == {1, 2, 3, 4, 5, 6, 7, 8, 9}: return listToNumber(listofdigits) return 0 assert panDigit(1) == 123456789 assert panDigit(192) == 192384576 assert panDigit(9) == 918273645 maxes = [panDigit(i) for i in range(1, 10000) if panDigit(i) > 0] print("The Largest pan digit multiple is:", max(maxes))
true
1362ec74ae0c72c10bf26c69151e8d6c8d64105c
hopesfall23/Fizzbuzz
/fizzbuzz.py
530
4.125
4
#William's Fizzbuzz program n = 100 #Hard coded upper line # "fizz" Divisible by 3 # "buzz" #Divisible by 5 #"Fizzbuzz" Divisible by 3 and 5 c = 0 #Current number, Will hold the value in our while loop and be printed for c in range(0,n): #Will run this loop from 0 to 100 then terminate if c <= n: if c%3 == 0 and c%5 == 0 : print("fizzbuzz") elif c%3 == 0: print("fizz") elif c%5 == 0: print("buzz") else: print(c)
true
447850fd37249fc7e61e435c8823d86a73c42512
sprajjwal/CS-2.1-Trees-Sorting
/Code/sorting_iterative.py
2,700
4.25
4
#!python def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) because we iterate through the loop once Memory usage: O(1) because we check in place""" # Check that all adjacent items are in order, return early if so if len(items) < 2: return True for index in range(len(items) - 1): if items[index] > items[index + 1]: return False return True def bubble_sort(items): """Sort given items by swapping adjacent items that are out of order, and repeating until all items are in sorted order. Running time: O(n^2) because we iterate over the whole loop once then iterate over n-i items Memory usage: O(1) because it is in place.""" if len(items) < 2: return # Repeat until all items are in sorted order # Swap adjacent items that are out of order for i in range(len(items)): swapped = false for j in range(len(items) - i - 1): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] # return items def selection_sort(items): """Sort given items by finding minimum item, swapping it with first unsorted item, and repeating until all items are in sorted order. TODO: Running time: O(n^2) TODO: Memory usage: O(1)""" if len(items) < 2: return # Repeat until all items are in sorted order for i in range(len(items) - 1): min = i for j in range(i, len(items)): # Find minimum item in unsorted items if items[min] > items[j]: min = j # Swap it with first unsorted item items[i], items[min] = items[min], items[i] # return items def insertion_sort(items): """Sort given items by taking first unsorted item, inserting it in sorted order in front of items, and repeating until all items are in order. Running time: O(n^2) Memory usage: O(1)""" # TODO: Repeat until all items are in sorted order for i in range(1, len(items)): # Take first unsorted item selected = items[i] # Insert it in sorted order in front of items move_to = i for j in range(i - 1, -1, -1): if items[j] > selected: items[j + 1] = items[j] move_to = j else: break items[move_to] = selected # return items if __name__ == "__main__": assert is_sorted([(3, 5)]) is True assert is_sorted([(3, 'A')]) is True # Single item assert is_sorted([('A', 3)]) is True # Single item assert is_sorted([('A', 'B')]) is True # Single item
true
cf33043df637dff1470547b466ded6b71d4cd434
nightphoenix13/PythonClassProjects
/FinalExamQuestion31.py
1,412
4.125
4
def main(): month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] highs = [0] * 12 lows = [0] * 12 for temps in range(len(month)): highs[temps] = int(input("Enter the highest temperature for " + month[temps] + ": ")) lows[temps] = int(input("Enter the lowest temperature for " + month[temps] + ": ")) #end for highMonth = findHighest(highs) lowMonth = findLowest(lows) print("The hottest month was ", month[highMonth], " at ", highs[highMonth], " degrees") print("The coldest month was ", month[lowMonth], " at ", lows[lowMonth], " degrees") #main method end #findHighest method start def findHighest(highs): highest = 0 highestIndex = 0 for value in range(len(highs)): if highs[value] > highest: highest = highs[value] highestIndex = value #end if #end for return highestIndex #findHighest method end #findLowest method start def findLowest(lows): lowest = 100 lowestIndex = 0 for value in range(len(lows)): if lows[value] < lowest: lowest = lows[value] lowestIndex = value #end if #end for return lowestIndex #findLowest method end #call to main method main()
true
b36b52841f7e33f6a6b849a1ba3d14a6545b31ce
MariDoes/PC-2019-02
/ejercicio3.py
1,056
4.1875
4
3 #Escriba un programa que registre las inscripciones de un curso de natación. #El curso solo acepta 5 personas y se debe preguntar 3 datos: nombre, sexo y edad. #El programa solo debe permitir inscripciones de edades entre 5 y 17 años. # El programa debe terminar cuando se tenga a las 5 personas que cumplan los requisitos y mostrar lo siguiente: #• Lista de inscritos (mostrar todos sus datos). #• Cantidad de hombres y mujeres. #• Promedio de edad. N =[] E =[] SM =[] SF =[] while True: e = int(input("Ingrese su edad: ")) if (e >= 5) and (e <= 17): E.append(e) if E == 6: break else: print("numero invalido, vuelva a ingresar") e = int(input("Ingrese su edad: ")) n = input("Ingrese su nombre: ") s = input("Ingrese su sexo (M/F): ").lower if s == m: SM.append(s) elif s == f: SF.append(s) else: print("Dato invalido, vuelva a ingresar (M/F)") s = input("Ingrese su sexo (M/F): ").lower print(E) print(e) print(n) print(s)
false
f6076d80cbf22a0af11337a6a329fe64df60477e
Allaye/Data-Structure-and-Algorithms
/Linked List/reverse_linked_list.py
615
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from linked_list import LinkedList L = LinkedList(10) def reverse(L): ''' reverse a linked list nodes, this reverse implementation made use of linked list implemented before ''' lenght = L.length() if(lenght == 0): raise IndexError('The list is an empty list, please append to the list and try reversing again') return nodes, cur = [], L.head while(cur.next !=None): cur = cur.next nodes.append(cur) cur = L.head nodes.reverse() for node in nodes: cur = L.next = node return cur
true
edfba19244397e3c444e910b9650de1a855633b3
Allaye/Data-Structure-and-Algorithms
/Stacks/balancedParen.py
2,399
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from Stack import Stack # personal implementation of stack using python list # In[12]: def check_balance(string, opening='('): ''' a function to check if parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the any item there is == to the opening variable: d: push then into the stack, else: e: check if the length is not zero, if it is not pop the stack, else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: ''' s = Stack() if len(string) % 2 == 0: for w in string: if w == opening: s.push(w) else: if s.size() > 0: s.pop() else: return False return s.size() == 0 else: return False # In[2]: def double_balance(string, openings=['[', '{', '(']): ''' a function to check if the 3 types of parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the item matches openings: d: push then into the stack, else: e: check if the top element in the stack and item matches any tuple in our matches and pop the stack else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: return False since the parenthesis can only be balance if the have a corresponding closing one ''' s = Stack() matches = [('{', '}'), ('(', ')'), ('[', ']')] if len(string) % 2 == 0: for w in string: if w in openings: s.push(w) else: if (s.peek(), w) in matches: s.pop() else: return False return s.size() == 0 else: <<<<<<< HEAD return False ======= return False >>>>>>> 34dd19a4c05ecb4cd984fb078a578c1934859c39
true
83ec8968625803240349a9187a081f0fc66ee18d
Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning
/Controle de fluxo/Iterando dicionários com loops for.py
766
4.375
4
# Todo: Quando você iterar um dicionário usando um loop for, # fazer do jeito normal (for n in some_dict) vai apenas dar acesso às chaves do dicionário - que é o que queremos em algumas situações. # Em outros casos, queremos iterar as _chaves_e_valores_ do dicionário. Vamos ver como isso é feito a partir de um exemplo. # Considere este dicionário que usa nomes de atores como chaves e seus personagens como valores. cast = { "Jerry Seinfeld": "Jerry Seinfeld", "Julia Louis-Dreyfus": "Elaine Benes", "Jason Alexander": "George Costanza", "Michael Richards": "Cosmo Kramer" } print("Iterando pelas chaves:") for key in cast: print(key) print("\nIterando pelas chaves e valores:") for key, value in cast.items(): print("Ator: {} Papel: {}".format(key, value))
false
a4ac445dab9a10302d57fe822da0bfad49eabe7e
Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning
/Script/Quiz Lidando com erros.py
2,020
4.125
4
# Todo: Quiz Lidando com a divisão por zero # Neste momento, executar o código abaixo causará um erro durante a segunda recorrência à função create_groups porque ela # se depara com uma exceção ZeroDivisionError. # # Edite a função abaixo para lidar com esta exceção. Se ela se depara com a exceção durante a primeira linha da função, # deve exibir uma mensagem de aviso e retornar uma lista vazia. Caso contrário, ela deve executar o resto do código da função. No final, # a função deve sempre exibir quantos grupos foram devolvidos. #Problema # def create_groups(items, n): # """Splits items into n groups of equal size, although the last one may be shorter.""" # # determine the size each group should be # size = len(items) // n # this line could cause a ZeroDivisionError exception # # # create each group and append to a new list # groups = [] # for i in range(0, len(items), size): # groups.append(items[i:i + size]) # # # print the number of groups and return groups # print("{} groups returned.".format(n)) # return groups # # print("Creating 6 groups...") # for group in create_groups(range(32), 6): # print(list(group)) # # print("\nCreating 0 groups...") # for group in create_groups(range(32), 0): # print(list(group)) # ---------------------------------------------------------------------------- #Solução Udacity def create_groups(items, n): try: size = len(items) // n except ZeroDivisionError: print("AVISO: Retornando lista vazia. Por favor, use um número diferente de zero.") return [] else: groups = [] for i in range(0, len(items), size): groups.append(items[i:i + size]) return groups finally: print("{} grupos retornados.".format(n)) print("Criando 6 grupos ...") for group in create_groups(range(32), 6): print(list(group)) print("\nCriando 0 grupos ...") for group in create_groups(range(32), 0): print(list(group))
false
bedc8089b31c69ba198321d399ebad95f7b60f4b
nansleeper/miptlaby2021
/laba2/t11.py
511
4.15625
4
import turtle import numpy as np def circle(r): for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.left(1) for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.right(1) #для начала работы требуется ввести желаемое количество "крыльев" у бабочки turtle.shape('turtle') turtle.speed(0) n = int(input()) turtle.left(90) for i in range(n): circle(40 + 9*i)
false
f0c37197681932ed66662da67f577689e3f0748c
nansleeper/miptlaby2021
/laba2/t10.py
588
4.28125
4
import turtle import numpy as np def circle(r): for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.left(1) for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.right(1) def flower(r, n): for j in range(3): circle(r) turtle.left(360 / n) # для начала работы программы требуется ввести желаемое количество листков у цветочка turtle.shape('turtle') turtle.speed(0) n = int(input()) flower(50, n)
false
75b5f5b8da4326b00d7de5d7c613039ecd1c4d25
Marcelove/Python-Tarefas-caro
/QUESTÃO 4 LISTA 2.py
897
4.21875
4
#Checando triângulos e dizendo suas propiedads while True: print ('Olá! Vamos ver se você consegue formar um triângulo com 3 valores de retas.') fi = int(input('Digite o valor da primeira reta:\n')) se = int(input('Digite o número da segunda reta:\n')) th = int(input('Digite o número da terceira reta:\n')) if (fi+se) < th or (fi+th) < se or (th+se) < fi: print ('Não é um triângulo') print ('.\n') else: print ('.\n') print ('Sim! Um triângulo.\n') if fi == se == th: print ('Um triângulo equilátero') print ('.\n') elif fi == se or se == th or th == fi: print ('Um triângulo isósceles') print ('.\n') elif fi != se != th: print ('Um triângulo escaleno') print ('.\n')
false
cc6b56b8c951d7aab983940c8f766ed6d24e0359
ermidebebe/Python
/largest odd.py
725
4.28125
4
x=int(input("X=")) y=int(input("y=")) z=int(input("z=")) if(x%2!=0): print("x is Odd") if(y%2!=0): print("y is Odd") if(z%2!=0): print("z is Odd") if(x%2!=0 and y%2!=0 and z%2!=0 ): if(x>y and x>z): print("x is the greatest of all") elif(y>x and y>z): print("y is the greatest") else : print("z is largest") elif(x%2!=0 and y%2!=0): if(x>y): print("x is the greater than y") else : print("y is greater than x") elif(x%2!=0 and z%2!=0): if(x>z): print("x is the greater than z") else : print("z is greater than x") elif(y%2!=0 and z%2!=0): if(y>z): print("y is the greater than z") else : print("z is greater than y")
false
cfcf85b40806e49c8cfaf1a51b78b1aa5c96ca18
bislara/MOS-Simulator
/Initial work/input_type.py
728
4.25
4
name = raw_input("What's your name? ") print("Nice to meet you " + name + "!") age = raw_input("Your age? ") print("So, you are already " + str(age) + " years old, " + name + "!") #The input of the user will be interpreted. If the user e.g. puts in an integer value, the input function returns this integer value. If the user on the other hand inputs a list, the function will return a list. Python takes your name as a variable. So, the error message makes sense! #raw_input does not interpret the input. It always returns the input of the user without changes, i.e. raw. This raw input can be changed into the data type needed for the algorithm. To accomplish this we can use either a casting function or the eval function
true
36906e07dd7a95969fcfbfb24bc566af77d6c290
w0nko/hello_world
/parameters_and_arguments.py
301
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 18 18:20:48 2017 @author: wonko """ def power(base, exponent): # Add your parameters here! result = base ** exponent print ("%d to the power of %d is %d.") % (base, exponent, result) power(37, 4) # Add your arguments here!
true
bb21d460a800def3b50708218376ed4638a0a841
chenqunfeng/python
/demo1_最简单抓包.py
796
4.21875
4
# 关与urllib和urllib2之间的区别 # http://www.hacksparrow.com/python-difference-between-urllib-and-urllib2.html # 在pythob3.x中urllib2被改为urllib.request import urllib.request # urlopen(url, data, timeout) # @param {string} url 操作的url # @param {any} data 访问url时要传送的数据 # @param {number} timeout 超时时间 response = urllib.request.urlopen("http://waimai.meituan.com/restaurant/244362?pos=0") ''' 以上代码等同于 request = urllib.Request("http:www.baidu.com") response = urllib.request.urlopen(request) 两者的运行结果完全一致,只不过在中间多了一个request对象 而这样写有一个好处,就是你可以针对request加入额外的内容 ''' # 在python3.x中 print "hello" => print ("hello") print (response.read())
false
cc157edc908e4cb99ada1f2f4b880fa939d635cb
alojea/PythonDataStructures
/Tuples.py
1,105
4.5
4
#!/usr/bin/python import isCharacterInsideTuple import convertTupleIntoList import addValueInsideTuple alphabetTuple = ('a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') stringTuple = "" for valueTuple in alphabetTuple: stringTuple = stringTuple + valueTuple print("1.Convert the alphabet tuple to a string and print the string.") print(stringTuple) print() print("2. Output the length of the tuple") print(len(alphabetTuple)) print() print("3. Write a program that ask the user to input a character, and will then tell the user whether the character is in the tuple and give its position if it is.") isCharacterInsideTuple.isCharInsideTuple(alphabetTuple) print() print("4. Write a program that will convert the tuple to a list.") print(type(alphabetTuple)," was converted into ",type(convertTupleIntoList.convertTupleIntoList(alphabetTuple))) print() print("5. Write a program that will ask the user for input, and will then add their input to the tuple.") print(addValueInsideTuple.addValue(alphabetTuple))
true
c50d0f924ae516d9d6bab320cb1bb71cfc35d7a6
nishantvyas/python
/unique_sorted.py
1,603
4.15625
4
""" Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world """ def printListString(listObj): """ This function prints the data in list line by line :param listObj: :return: """ print(" ".join(listObj)) def uniqueWords(stringObj): """ This function takes text string as input and returns the string of unique words :param stringObj: :return: """ returnListObj = [] inputListObj = [x for x in stringObj.split()] ##manually removing duplicate words by creating new list """ for i in range(0,len(inputListObj)): if not inputListObj[i] in returnListObj: returnListObj.append(inputListObj[i]) """ ###using set method on list to remove duplicates returnListObj = list(set(inputListObj)) return returnListObj def sortWords(listObj): """ This function takes list of words as input and returns the sorted list :param listObj: :return: """ listObj.sort() return listObj if __name__ == "__main__": """ """ inputList = [] print("Enter text to be sorted on unique words:") while True: stringObj = input() if stringObj: inputList = sortWords(uniqueWords(stringObj)) else: break printListString(inputList)
true
589f077eb0b0080801f5dc3e7b4da8e3a4d1bf35
applicationsbypaul/Module7
/fun_with_collections/basic_list.py
837
4.46875
4
""" Program: basic_list.py Author: Paul Ford Last date modified: 06/21/2020 Purpose: uses inner functions to be able to get a list of numbers from a user """ def make_list(): """ creates a list and checks for valid data. :return: returns a list of 3 integers """ a_list = [] for index in range(3): while True: try: user_input = int(get_input()) except ValueError: print('User must submit a number.') continue a_list.insert(index, user_input) break return a_list def get_input(): """ Ask the user for a number :return: returns a string of the user input """ user_input = input('Please enter a number') return user_input if __name__ == '__main__': print(make_list())
true
726acce695d62e6d438f2abd93b1685daab8f95a
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dict_membership.py
502
4.15625
4
""" Program: dict_membership.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries for the first time """ def in_dict(dictionary, data): """ accept a set and return a boolean value stating if the element is in the dictionary :param dictionary: The given dictionary to search :param data: The data searching in the dictionary :return: A boolean if the data is in the dictionary """ return data in dictionary if __name__ == '__main__': pass
true
d38c77a4b3c2b8448226fa481fc79e177048fa65
applicationsbypaul/Module7
/Module10/class_definitions/student.py
2,597
4.25
4
from datetime import datetime class Student: """Student class""" def __init__(self, lname, fname, major, startdate, gpa=''): """ constructor to create a student :param lname: last name :param fname: first name :param major: Major of student :param gpa: students gpa on a 4.0 scale """ name_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-' '") ''' Checking values for good input ''' if not (name_characters.issuperset(lname)): raise ValueError if not (name_characters.issuperset(fname)): raise ValueError if not (name_characters.issuperset(major)): raise ValueError if not isinstance(gpa, float): raise ValueError if not 0 <= gpa <= 4: raise ValueError ''' Setting constructor values ''' self.last_name = lname self.first_name = fname self.major = major self._start_date = startdate self.gpa = gpa def __str__(self): """ prints student data :return: str of students data """ return self.last_name + ", " + self.first_name + " has major " + self.major + \ "\nStart Date: " + str(self._start_date) + \ '\nGPA: ' + str(self.gpa) def change_major(self, new_major): """ changes the major of the student checks if the new major is valid :param new_major: new major to change. """ name_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!'- ' '") if not (name_characters.issuperset(new_major)): raise ValueError self.major = new_major def update_gpa(self, new_gpa): """ updates the gpa of the student :param new_gpa: new GPA """ if not isinstance(new_gpa, float): raise ValueError if not 0 <= new_gpa <= 4: raise ValueError self.gpa = new_gpa def display(self): """ A better formatted version of student data :return: str of student data """ return "First Name: " + self.first_name + "\nLast Name: " + self.last_name + \ "\nMajor: " + self.major + \ "\nStart Date: " + str(self._start_date) + \ '\nGPA: ' + str(self.gpa) # driver # start_date = datetime(2018, 9, 1) # create a datetime to confirm # student = Student('Ford', 'Paul', 'English', start_date, 4.0) # print(student)
false
8510a11490351504b7bf1707f5ba14318fae7240
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dictionary_update.py
1,563
4.28125
4
""" Program: dictionary_update.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries to gather store and recall info """ def get_test_scores(): """ Gathers test scores for a user and stores them into a dictionary. :return: scores_dict a dictionary of scores """ scores_dict = dict() num_scores = int(input('Please how many test scores are going to be entered: ')) key_values = 'score' # this value will be the key for the dictionary incrementing by 1 for key in range(num_scores): while True: try: # ask the user for new data since the function data was bad score = int(input('Please enter your test score: ')) scores_dict.update({key_values + str(key + 1): score}) if int(score < 0) or int(score > 100): raise ValueError except ValueError: print('Test score has to be between 1 and 100.') continue else: break return scores_dict def average_scores(dictionary): """ Recall the scores from the dictionary adding them to total calculate the average :param dictionary: a dictionary of scores :return: returns the average score. """ total = 0 # local variable to calculate total key_values = 'score' for score in range(len(dictionary)): total += dictionary[key_values + str(score + 1)] return round(total / len(dictionary), 2) if __name__ == '__main__': pass
true
97d812a9b932e9ae3d7db1726be2089627985347
PikeyG25/Python-class
/forloops.py
658
4.15625
4
##word=input("Enter a word") ##print("\nHere's each letter in your word:") ##for letter in word: ## print(letter) ## print(len(word)) ##message = input("Enter a message: ") ##new_message = "" ##VOWELS = "aeiouy" ## ##for letter in message: ## if letter.lower() not in VOWELS: ## new_message+=letter ## print("A new string has been created",new_message) ##print("\nYour message without vowels is:",new_message) print("Counting: ") for i in range( 10): print(i,end="") print("\n\nCounting by fives: ") for i in range( 0, 50, 5): print(i,end="") print("\n\nCounting backwards:") for i in range( 10, 0, -1): print(i,end="")
true
6700dca221f6a0923ef9b5dbbf1ec56ab69b0671
Reetishchand/Leetcode-Problems
/00328_OddEvenLinkedList_Medium.py
1,368
4.21875
4
'''Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Constraints: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ... The length of the linked list is between [0, 10^4].''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: even,odd = ListNode(-1), ListNode(-1) e,o=even,odd c=1 while head!=None: if c%2==0: e.next = head head=head.next e=e.next e.next=None else: o.next=head head=head.next o=o.next o.next=None c+=1 o.next=even.next return odd.next
true
56bb70f89a3b2e9fa203c1ee8d4f6f47ec71daf8
Reetishchand/Leetcode-Problems
/00922_SortArrayByParityII_Easy.py
924
4.125
4
'''Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: Input: nums = [2,3] Output: [2,3] Constraints: 2 <= nums.length <= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 <= nums[i] <= 1000''' class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: odd,even=1,0 while odd<len(A) and even<len(A): if A[odd]%2==0 and A[even]%2!=0: A[odd],A[even]=A[even],A[odd] if A[odd]%2!=0: odd+=2 if A[even]%2==0: even+=2 return A
true
5231912489a4f9b6686e4ffab24f4d4bc13f3a46
Reetishchand/Leetcode-Problems
/00165_CompareVersionNumbers_Medium.py
2,374
4.1875
4
'''Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0. Example 1: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". Example 2: Input: version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: version1 does not specify revision 2, which means it is treated as "0". Example 3: Input: version1 = "0.1", version2 = "1.1" Output: -1 Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. Example 4: Input: version1 = "1.0.1", version2 = "1" Output: 1 Example 5: Input: version1 = "7.5.2.4", version2 = "7.5.3" Output: -1 Constraints: 1 <= version1.length, version2.length <= 500 version1 and version2 only contain digits and '.'. version1 and version2 are valid version numbers. All the given revisions in version1 and version2 can be stored in a 32-bit integer.''' class Solution: def compareVersion(self, v1: str, v2: str) -> int: L,R = v1.split("."), v2.split(".") while len(L)<len(R): L.append("0") while len(L)>len(R): R.append("0") # l1,l2 = len(L),len(R) i,j=0,0 while i<len(L) and j <len(R): if int(L[i])<int(R[j]): return -1 elif int(L[i])>int(R[j]): return 1 i+=1 j+=1 return 0
true
8937e4cc7b216ba837dcbf3a326b2a75fb325cd0
Reetishchand/Leetcode-Problems
/00690_EmployeeImportance_Easy.py
1,800
4.1875
4
'''You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct. Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates. Example 1: Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Output: 11 Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11. Note: One employee has at most one direct leader and may have several subordinates. The maximum number of employees won't exceed 2000.''' """ # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, arr: List['Employee'], id: int) -> int: imp={} sub={} for i in range(len(arr)): emp =arr[i].id im = arr[i].importance su = arr[i].subordinates imp[emp]=im sub[emp]=su st=[id] s=0 while st: x=st.pop() s+=imp[x] for i in sub[x]: st.append(i) return s
true
c0a23174b8c9d3021942781c960a21d2ad0699b5
Reetishchand/Leetcode-Problems
/02402_Searcha2DMatrixII_Medium.py
1,388
4.25
4
'''Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true Example 2: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= 300 -109 <= matix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 109''' class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if len(matrix)==0 or len(matrix[0])==0: return False row = len(matrix)-1 col=0 while row>=0 and col<len(matrix[0]): print(row,col) if target<matrix[row][col]: row-=1 elif target>matrix[row][col]: col+=1 else: return True return False
true
99202f99cbf5b47e4f294c8e0da826f993ac5d3b
Reetishchand/Leetcode-Problems
/00537_ComplexNumberMultiplication_Medium.py
1,240
4.15625
4
'''Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: Input: "1+-1i", "1+-1i" Output: "0+-2i" Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. Note: The input strings will not have extra blank. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.''' class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: n1=a.split("+") n2=b.split("+") print(n1,n2) ans=[0,0] ans[0]=str((int(n1[0])*int(n2[0]))-(int(n1[1].replace("i",""))*int(n2[1].replace("i","")))) ans[1]=str((int(n1[1].replace("i",""))*int(n2[0])) + (int(n2[1].replace("i","")) * int(n1[0])))+"i" print(int(n1[1].replace("i",""))*int(n2[0])) print(int(n2[1].replace("i","")) * int(n2[0])) return '+'.join(ans)
true
68198c760cdb09b8e882088013830389b0b4d19d
Reetishchand/Leetcode-Problems
/00346_MovingAveragefromDataStream_Easy.py
1,289
4.3125
4
'''Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream. Example 1: Input ["MovingAverage", "next", "next", "next", "next"] [[3], [1], [10], [3], [5]] Output [null, 1.0, 5.5, 4.66667, 6.0] Explanation MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 Constraints: 1 <= size <= 1000 -105 <= val <= 105 At most 104 calls will be made to next.''' from collections import deque class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.mov=deque([],maxlen=size) def next(self, val: int) -> float: self.mov.append(val) return sum(self.mov)/len(self.mov) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
true
68f0b89631b89d1098932cd021cf579348d71004
jaipal24/DataStructures
/Linked List/Detect_Loop_in_LinkedList.py
1,388
4.25
4
# Given a linked list, check if the linked list has loop or not. #node class class Node: def __init__(self, data): self.data = data self.next = None # linked list class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node def detect_loop(self): s = set() current = self.head while current: if current in s: return True s.add(current) current = current.next return False def print_list(self): val = [] temp = self.head while temp: val.append(str(temp.data)) temp = temp.next return '->'.join(v for v in val) def __str__(self): return self.print_list() if __name__ == "__main__": L_list = LinkedList() L_list.push(1) L_list.push(3) L_list.push(4) L_list.push(5) L_list.push(2) print("Linked list is:", L_list) # creating a loop in the linked list L_list.head.next.next.next.next = L_list.head if L_list.detect_loop(): print("Loop Detected") else: print("No Loop")
true
87f6078f3f99bd3c33f617e2b7b33143fed70369
BonnieBo/Python
/第二章/2.18.py
412
4.125
4
# 计算时间 import time currentTime = time.time() print(currentTime) totalSeconds = int(currentTime) currentSeconds = totalSeconds % 60 totalMinutes = totalSeconds // 60 currentMinute = totalMinutes % 60 totalHours = totalMinutes // 60 currentHours = totalHours % 24 print("Current time is", currentHours, ":", currentMinute, ":", currentSeconds, "GMT") print(time.asctime(time.localtime(time.time())))
true
83920bc4e32b0dbc42187f9ce0fd8ce8e840a15f
emicalvacho/All-algorithms-and-data-structures-AEDI
/arboles/binary_tree.py
2,433
4.125
4
#TAD de Árbol Binario class BinaryTree(object): """Clase del Binary Tree""" def __init__(self, data): """Constructor del BT: Creo un nodo con el valor que se instancia e inicializo tanto los dos hijos con None.""" self.key = data self.leftChild = None self.rightChild = None def insertLeft(self, newNode): """Inserto por izquierda: si el hijo izquierdo está vacío lo instancio como BT. Sino voy hasta el hijo izquierdo del izquierdo y lo inserto allí.""" if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): """Insertar por derecha: Simétrico a insertar por izquierda.""" if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): """Obtengo el hijo derecho.""" return self.rightChild def getLeftChild(self): """Obtengo el hijo izquierdo.""" return self.leftChild def setRootVal(self, obj): """Configuro la raíz.""" self.key = obj def getRootVal(self): """Obtengo la raíz.""" return self.key def printPreordenTree(self, n): """Recorro el BT: raíz, subárbol izquierdo y subárbol derecho.""" if self.getRootVal() != None: print("Level: "+ str(n) + " : " + str(self.getRootVal())) if self.getLeftChild() != None: self.getLeftChild().printPreordenTree(n+1) if self.getRightChild() != None: self.getRightChild().printPreordenTree(n+1) return n def printInordenTree(self, n): """Recorro el BT: subárbol izquierdo, raíz y subárbol derecho.""" if self.getRootVal() != None: if self.getLeftChild() != None: self.getLeftChild().printInordenTree(n+1) print("Level: "+ str(n) + " : " + str(self.getRootVal())) if self.getRightChild() != None: self.getRightChild().printInordenTree(n+1) return n def printPostordenTree(self, n): """Recorro el BT: subárbol izquierdo, subárbol derecho y raíz.""" if self.getRootVal() != None: if self.getLeftChild() != None: self.getLeftChild().printPostordenTree(n+1) if self.getRightChild() != None: self.getRightChild().printPostordenTree(n+1) print("Level: "+ str(n) + " : " + str(self.getRootVal())) return n
false
7b5b3ff7995758cb199808977015ea635a879309
Farazi-Ahmed/python
/lab-version2-6.py
288
4.125
4
# Question 8 Draw the flowchart of a program that takes a number from user and prints the divisors of that number and then how many divisors there were. a=int(input("Number? ")) c=1 d=0 while c<=a: if a%c==0: d+=1 print(c) c+=1 print("Divisors in total: "+str(d))
true
03074b61771fa4e751fd84c97aac21e3a918fa35
Farazi-Ahmed/python
/problem-solved-9.py
326
4.4375
4
# Question 9 : Draw flowchart of a program to find the largest among three different numbers entered by user. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) if x>y and x>z: print(x) elif y>z and y>x: print(y) else: print(z) MaxValue = max(x,y,z) print(MaxValue)
true
28f739f2ac311a56f42af138f8c3432a4e0620e9
Farazi-Ahmed/python
/problem-solved-7.py
303
4.375
4
# Question 7: Write a flowchart that reads the values for the three sides x, y, and z of a triangle, and then calculates its area. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) s = (x + y + z) / 2 area = ((s * (s-x)*(s-y)*(s-z)) ** 0.5) print(area)
true
3e5006cf9e83f5127beb05765bf276de6efcc3d3
peoolivro/codigos
/Cap5_Exercicios/PEOO_Cap5_ExercicioProposto03.py
509
4.21875
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 05 # Questão.: Exercício Proposto 3 # Autor...: Fábio Procópio # Data....: 15/06/2019 import random RIFA = [] while True: nome = input("Informe um nome: ") RIFA.append(nome) resp = input("Deseja continuar [S|N]? ") if resp.upper() == "N": break random.shuffle(RIFA) # Embaralha a lista sorteado = random.choice(RIFA) # Sorteia aleatoriamente um elemento print(f"{sorteado} foi o(a) sorteado(a)!")
false
39b6f848cd2579bbc0c33cdafa3a73dbf356244d
peoolivro/codigos
/Cap2_Exercicios/PEOO_Cap2_ExercicioProposto05.py
475
4.375
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 02 # Questão.: Exercício Proposto 5 # Autor...: Fábio Procópio # Data....: 18/02/2019 from math import sqrt print("Dados do ponto P1:") x1 = float(input("Digite x1: ")) y1 = float(input("Digite y1: ")) print("Dados do ponto P2:") x2 = float(input("Digite x2: ")) y2 = float(input("Digite y2: ")) d = sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)) print(f"Distância entre P1 e P2 = {d:.2f}")
false
9badcbc5bc0a142e7fea1b8f5057ada50378e713
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto07.py
749
4.3125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 31/05/2019 altura1 = float(input("Digite a estatura da 1ª pessoa (em metros): ")) altura2 = float(input("Digite a estatura da 2ª pessoa (em metros): ")) altura3 = float(input("Digite a estatura da 3ª pessoa (em metros): ")) if altura1 == altura2 or altura1 == altura3 or altura2 == altura3: print("\nHá, pelo menos, 2 números iguais") elif altura1 > altura2 and altura1 > altura3: print(f"A pessoa mais alta tem {altura1}m.") elif altura2 > altura1 and altura2 > altura3: print(f"A pessoa mais alta tem {altura2}m.") else: print(f"A pessoa mais alta tem {altura3}m.")
false
ca22c26a971c31449b679a1e243d835105b0b2a7
peoolivro/codigos
/Cap5_Exercicios/PEOO_Cap5_ExercicioProposto02.py
735
4.125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 05 # Questão.: Exercício Proposto 2 # Autor...: Fábio Procópio # Data....: 15/06/2019 ATLETA = [] TEMPO = [] for x in range(7): nome = input("Informe o nome do nadador: ") tempo = float(input("Informe o tempo do nadador: ")) ATLETA.append(nome) TEMPO.append(tempo) # Recupera o índice em que está o melhor tempo indice_melhor = TEMPO.index(min(TEMPO)) # Recupera o índice em que está o pior tempo indice_pior = TEMPO.index(max(TEMPO)) media_tempos = sum(TEMPO) / len(TEMPO) print(f"{ATLETA[indice_melhor]} tem o melhor tempo.") print(f"{ATLETA[indice_pior]} tem o pior tempo.") print(f"Média dos tempos: {media_tempos:.2f}s.")
false
de9d698079b2f694b6233ebc72eb35e899dd530e
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto01.py
390
4.28125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 1 # Autor...: Fábio Procópio # Data....: 31/05/2019 num = int(input("Digite um número: ")) if num % 2 == 0: quadrado = num ** 2 print(f"{num} é par e o seu quadrado é {quadrado}.") else: cubo = num ** 3 print(f"{num} é ímpar e o seu cubo é {cubo}.")
false
6713ce569d9bd93b9bccdb4e85e9caddb1fc0848
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto02.py
958
4.625
5
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 2 # Autor...: Fábio Procópio # Data....: 31/05/2019 num1 = float(input("Digite um número: ")) num2 = float(input("Digite outro número: ")) print("\n1. Média ponderada, com pesos 2 e 3, respectivamente") print("2. Quadrado da soma dos 2 números") print("3. Cubo do menor número") op = int(input("Escolha uma opção: ")) if op < 1 or op > 3: print("\nOpção inválida.") elif op == 1: media = (num1 * 2 + num2 * 3) / 5 print(f"\nMédia ponderada calculada: {media:.2f}.") elif op == 2: quadrado = (num1 + num2) ** 2 print(f"\nQuadrado da soma dos números: {quadrado:.2f}.") else: if num1 < num2: cubo = num1 ** 3 print(f"\n{num1:.2f} é menor número e o seu cubo é {cubo:.2f}.") else: cubo = num2 ** 3 print(f"\n{num2:.2f} é menor número e o seu cubo é {cubo:.2f}.")
false
58df08bc90edaf08f828285d1ed3701c50f671ae
peoolivro/codigos
/Cap4_Exercicios/PEOO_Cap4_ExercicioProposto07.py
759
4.125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 04 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 04/06/2019 idade = int(input("Idade: ")) '''Como não há nenhuma idade a ser comparada, neste momento, a primeira idade é, ao mesmo tempo, o mais novo e o mais velho''' mais_novo = idade mais_velho = idade while True: idade = int(input("Idade: ")) if idade < 0: #Quando idade negativa, laço será interrompido break if idade < mais_novo: mais_novo = idade elif idade > mais_velho: mais_velho = idade print(f"Menor idade: {mais_novo}") print(f"Maior idade: {mais_velho}") media = (mais_novo + mais_velho) / 2 print(f"Média das duas idades = {media:.2f}")
false
519d04e843b4966f58d0d2ffc1e4a4596ef1ea09
manand2/python_examples
/comprehension.py
2,044
4.40625
4
# list comprehension nums = [1,2,3,4,5,6,7,8,9,10] # I want 'n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n) print my_list #list comprehension instead of for loop my_list = [n for n in nums] print my_list # more complicated example # I want 'n*n' for each 'n' in nums my_list = [n*n for n in nums] print my_list #another way to do this is using maps and lambda # maps pretty much runs through functions #lambda is a function #using map + lambda my_list = map(lambda n: n*n, nums) # you can convert map and lambda to list comprehension as it is more readable #learn map, lambda and filter #I want 'n' for each 'n in nums if 'n' is even my_list = [] for n in nums: if n%2 == 0: my_list.append(n) print my_list # using list comprehension my_list = [n for n in nums if n%2 == 0] print my_list # Using a filter + lambda my_list = filter(lambda n: n%2 == 0, nums) print my_list # more difficult example # I want a letter and number pair for each letter in 'abcd' and each number in '0123' my_list = [(letter,num) for letter in 'abcd' for num in range(4)]] #dictionary and sets comprehension # Dictionary comprehension names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] # using for loop for name in names: for hero in heros: my_dict[name] = hero print my_dict # using dictionary comprehension my_dict = {name:hero for name, hero in zip(names, heros)} print my_dict #if name is not equal to Peter my_dict = {name:hero for name, hero in zip(names, heros) if name != 'Peter'} print my_dict # set comprehension - similar to list but have unique values nums = [1,1,2,2,3,3,4,4,5,5,6,7,8,9,9] my_set = {n for n in nums} # generators expression # generators expressions are like list comprehension def gen_func(nums): for n in nums: yield n*n my_gen = gen_func(nums) for in my_gen: print i # let us change for loop code to comprehension my_gen = (n*n for in in nums) for i in my_gen: print i
true
37498e70f1550bd468c29f5b649075ce4254978d
chrishaining/python_stats_with_numpy
/arrays.py
384
4.15625
4
import numpy as np #create an array array = np.array([1, 2, 3, 4, 5, 6]) print(array) #find the items that meet a boolean criterion (expect 4, 5, 6) over_fives = array[array > 3] print(over_fives) #for each item in the array, checks whether that item meets a boolean criterion (expect an array of True/False, in this case [False, False, False, True, True, True]) print(array > 3)
true
c0585d2d162e48dd8553ccfc823c3e363a2b28c0
samson027/HacktoberFest_2021
/Python/Bubble Sort.py
416
4.125
4
def bubblesort(array): for i in range(len(array)): for j in range(len(array) - 1): nextIndex = j + 1 if array[j] > array[nextIndex]: smallernum = array[nextIndex] largernum = array[j] array[nextIndex] = largernum array[j] = smallernum return array # a test case print(bubblesort([9, 8, 7, 4, 5, 6, 12, 10, 3]))
true
148418a17af55f181ecea8ffd5140ba367d7dc2d
youngdukk/python_stack
/python_activities/oop_activities/bike.py
974
4.25
4
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print("Bike's Price: ${}".format(self.price)) print("Bike's Maximum Speed: {} mph".format(self.max_speed)) print("Total Miles Ridden: {} miles".format(self.miles)) return self def ride(self): self.miles += 10 print("Riding", self.miles) return self def reverse(self): if self.miles < 6: print("Cannot reverse") else: self.miles -= 5 print("Reversing", self.miles) return self instance1 = Bike(200, 25) instance2 = Bike(100, 10) instance3 = Bike(500, 50) print("Bike 1") instance1.ride().ride().ride().reverse().displayInfo() print("Bike 2") instance2.ride().ride().reverse().reverse().displayInfo() print("Bike 3") instance3.reverse().reverse().reverse().displayInfo()
true
1a3113a91f5b6ffe95899f952be3248e8197498b
frankiegu/python_for_arithmetic
/力扣算法练习/day86-实现 Trie (前缀树).py
1,698
4.1875
4
# -*- coding: utf-8 -*- # @Time : 2019/5/28 22:15 # @Author : Xin # @File : day86-实现 Trie (前缀树).py # @Software: PyCharm # 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 # # 示例: # # Trie trie = new Trie(); # # trie.insert("apple"); # trie.search("apple"); // 返回 true # trie.search("app"); // 返回 false # trie.startsWith("app"); // 返回 true # trie.insert("app"); # trie.search("app"); // 返回 true # 说明: # # 你可以假设所有的输入都是由小写字母 a-z 构成的。 # 保证所有输入均为非空字符串。 import collections class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.dict = collections.defaultdict(list) def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: None """ self.dict[word[0]].append(word) def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ if word in self.dict[word[0]]: return True return False def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ length = len(prefix) for i in self.dict[prefix[0]]: if prefix == i[:length]: return True return False # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
false
797d224072c34473343a93e16fbadd7015d5f484
frankiegu/python_for_arithmetic
/力扣算法练习/day39-接雨水.py
1,944
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2019/4/8 21:23 # @Author : Xin # @File : day39-接雨水.py # @Software: PyCharm # 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 # # day39图 # 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。 # # 示例: # # 输入: [0,1,0,2,1,0,1,3,2,1,2,1] # 输出: 6 #解法: # 1.找出最高点 # 2.分别从两边往最高点遍历:如果下一个数比当前数小,说明可以接到水 class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if len(height)<=1: return 0 max_height=0 max_height_index = 0 #找到最高点 # for i in range(len(height)): # h = height[i] # if h > max_height: # max_height=h # max_height_index=i max_height=max(height) max_height_index=height.index(max_height) #初始化面积参数 area = 0 #从左边往最高点遍历 tmp = height[0] for i in range(max_height_index): if height[i]>tmp: tmp=height[i] else: area=area+(tmp-height[i]) #从右边往最高点遍历 tmp = height[-1] # for i in reversed(range(max_height_index+1,len(height))): # if height[i]>tmp: # tmp=height[i] # else: # area=area+(tmp-height[i]) for i in range(len(height)-1,max_height_index,-1): if height[i]>tmp: tmp=height[i] else: area=area+(tmp-height[i]) return area height= [0,1,0,2,1,0,1,3,2,1,2,1] s = Solution() print(s.trap(height))
false
52d35b2a21c30e5f35b1193b123f0b59a795fa17
prefrontal/leetcode
/answers-python/0021-MergeSortedLists.py
1,695
4.21875
4
# LeetCode 21 - Merge Sorted Lists # # Merge two sorted linked lists and return it as a new sorted list. The new list should be # made by splicing together the nodes of the first two lists. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 # Determine where we are going to start regarding the output output = None if l1.val < l2.val: output = l1 l1 = l1.next else: output = l2 l2 = l2.next # Now we can start assembling the rest of the output previous_node = output while l1 or l2: # Handle the cases where we have values in one list but not the other if not l1 and l2: previous_node.next = l2 previous_node = l2 l2 = l2.next continue if l1 and not l2: previous_node.next = l1 previous_node = l1 l1 = l1.next continue # Handle the case where we have values in both lists if l1.val < l2.val or l1.val == l2.val: previous_node.next = l1 previous_node = l1 l1 = l1.next else: previous_node.next = l2 previous_node = l2 l2 = l2.next return output # Tests c = ListNode(4, None) b = ListNode(2, c) a = ListNode(1, b) z = ListNode(4, None) y = ListNode(3, z) x = ListNode(1, y) sortedNode = mergeTwoLists(a, x) # Expected output is 1->1->2->3->4->4 while sortedNode: print(sortedNode.val) sortedNode = sortedNode.next
true
b1ff4822be75f8fffb11b8c2af5c64029a27a874
prefrontal/leetcode
/answers-python/0023-MergeKSortedLists.py
2,349
4.125
4
# LeetCode 23 - Merge k sorted lists # # Given an array of linked-lists lists, each linked list is sorted in ascending order. # Merge all the linked-lists into one sort linked-list and return it. # # Constraints: # k == lists.length # 0 <= k <= 10^4 # 0 <= lists[i].length <= 500 # -10^4 <= lists[i][j] <= 10^4 # lists[i] is sorted in ascending order. # The sum of lists[i].length won't exceed 10^4. from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Pulled from answer 21, Merge Sorted Lists def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 # Determine where we are going to start regarding the output output = None if l1.val < l2.val: output = l1 l1 = l1.next else: output = l2 l2 = l2.next # Now we can start assembling the rest of the output previous_node = output while l1 or l2: # Handle the cases where we have values in one list but not the other if not l1 and l2: previous_node.next = l2 previous_node = l2 l2 = l2.next continue if l1 and not l2: previous_node.next = l1 previous_node = l1 l1 = l1.next continue # Handle the case where we have values in both lists if l1.val < l2.val or l1.val == l2.val: previous_node.next = l1 previous_node = l1 l1 = l1.next else: previous_node.next = l2 previous_node = l2 l2 = l2.next return output def mergeKLists(lists: List[ListNode]) -> ListNode: if not lists: return None if len(lists) == 1: return lists[0] output = lists[0] for index, node in enumerate(lists): if index == 0: continue output = mergeTwoLists(output, node) return output # Tests c1 = ListNode(5, None) b1 = ListNode(4, c1) a1 = ListNode(1, b1) c2 = ListNode(4, None) b2 = ListNode(3, c2) a2 = ListNode(1, b2) b3 = ListNode(6, None) a3 = ListNode(2, b3) sortedNode = mergeKLists([a1, a2, a3]) # Expected output is 1,1,2,3,4,4,5,6 while sortedNode: print(sortedNode.val) sortedNode = sortedNode.next
true
9348abc87c6ec5318606464dac6e792960a0bc0f
NNHSComputerScience/cp1ForLoopsStringsTuples
/notes/ch4_for_loops_&_sequences_starter.py
1,795
4.78125
5
# For Loops and Sequences Notes # for_loops_&_sequences_starter.py # SEQUENCE = # For example: range(5) is an ordered list of numbers: 0,1,2,3,4 # ELEMENT = # So far we have used range() to make sequences. # Another type of sequence is a _________, # which is a specific order of letters in a sequence. # For example: # ITEREATE = # FOR LOOP = # So, we can iterate through a string using a for loop just like a range: # CHALLENGE #1: Secret Message - Ask the user for a message and then display # the message with each letter displayed twice. # Ex) message = "great" output = "ggrreeaatt" # Quick Question: What would display? # ANSWER: # The len() function: # Used to count the number of elements in a sequence. # Practice: Save your first name to the variable 'name', and then display # how many letters are in your first name. # Practice 2: Now do the same thing for your first and last name. # Be sure to put your first and last in the SAME string. # What did you learn about the len() function? # ANSWER: # CHALLENGE #2: Ask the user for their last name. # Tell the user the number of letters in their last name. # Then, determine if the user's name includes the letter "A" or not. # If they do, display "Awesome, you have an A!" # CHALLENGE #3: Password # Ask the user for a password. It must be at least 6 characters long, # and it must contain a '!' or a '$' sign. If they give a valid password # display "Valid Password", otherwise display "Invalid Password". # Adv. CHALLENGE: Can you use a while loop to keep asking for the password # until the user enters it in the correct format? input("\nPress enter to exit.")
true
f6ccf4fa74bc616ae4ef5e5baefa86a979dd2052
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex73.py
921
4.25
4
'''Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense.''' times = ('PALMEIRAS', 'FLAMENGO', 'INTERNACIONAL', 'GRÊMIO', 'SÃO PAULO', 'ATLÉTICO-MG', 'ATLÉTICO-PR', 'CRUZEIRO', 'BOTAFOGO', 'SANTOS', 'BAHIA', 'FLUMINENSE', 'CORINTHIANS', 'CHAPECOENSE', 'CEARÁ SC', 'VASCO DA GAMA', 'SPORT RECIFE', 'AMÉRIICA-MG', 'EC VITÓRIA', 'PARANÁ') print('Os primeiros colocados foram:') for c in range(0, 5): print(times[c]) print('Os últimos colocados foram: ') for x in range(16, 20): print(times[x]) print('Os times em ordem alfabética') print(sorted(times)) print('A chapecoense ficou em {}º lugar'.format(times.index('CHAPECOENSE')+1))
false
60a90abddad95055618302d95db8b21cb33d907f
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex93.py
1,037
4.25
4
'''Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.''' jogador = dict() soma = 0 jogador['nome'] = str(input('Digite o nome do jogador: ')) jogador['npartidas'] = int(input('Quantas partidas ele jogou? ')) partidas = list() for c in range (0 , jogador['npartidas']): jogador['gols'] = int(input(f'Quantos gols ele marcou na {c+1}° partida ? ')) soma += jogador['gols'] partidas.append(jogador['gols']) print(f'O jogador {jogador["nome"]}') print(f'Jogou {jogador["npartidas"]} partidas') print('-='*30) for g in enumerate(partidas): print(f'Jogo {g[0]+1} ----- {partidas[g[0]]} gols marcados') print('-'*20) print('-='*30) print('No total foram {} gols em um total de {} jogos'.format(soma, jogador['npartidas'])) print('-='*30)
false
a73e0adf7527348b492741b5bd782081775d9113
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex72.py
653
4.25
4
'''Exercício Python 72: Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.''' numeros = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Catorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte ') x = 0 while True: x = int(input('Escolha um número entre 1 e 20 ')) if x > 20 : break print(numeros[x]) print('Caso queira encerrar o programa digite algum número maior que 20 ')
false
f3fdc60439a3a4219e11a6b285eaa0db756244eb
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex105.py
944
4.15625
4
'''Exercício Python 105: Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: – Quantidade de notas – A maior nota – A menor nota – A média da turma – A situação (opcional) ''' def notas(*num, sit = False): """ :param num: Uma ou mais notas dos alunos :param sit: Escplha se quer ou não checar a situação dos alunos :return: Um dicionário com várias informações sobre a turma """ r = dict() r['total'] = len(num) r['maior'] = max(num) r['menor'] = min(num) r['média'] = sum(num)/len(num) if sit: if r['média'] >= 7: r['situação'] = 'BOA' elif r['média'] >= 5: r['situação'] = 'ACEITÁVEL' else: r['situação'] = 'RUIM' return r #main resp = notas(9, 3, 4, 5, 6, sit=True) print(resp) #help(notas)
false
7cb2c3e5720f6f5fb26c1572b02c2b233ff631e7
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex68.py
1,289
4.15625
4
'''Exercício Python 68: Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. ''' import random jogador = '' computador = '' c = 0 n = 0 s = 0 cont = 0 while True: jogador = input('Escolha entre par ou ímpar ').upper() while jogador != ('PAR') and jogador != ('ÍMPAR'): print('Opção inválida tente novamente') jogador = input('Escolha enter par ou ímpar ').upper() if jogador == 'PAR': computador ='ÍMPAR' elif jogador == 'ÍMPAR': computador = 'PAR' c = random.randint(0, 10) n = int(input('O computador escolheu um número tente vecer ele no jogo do ímpar ou par escolhendo um númreo inteiro ')) print(f'O computador escolheu {c} e você escolheu {n}') s = c+n if s % 2 == 0: if jogador == 'PAR': cont += 1 print('Você venceu') else: print('O computador venceu') break else: if jogador == 'ÍMPAR': cont += 1 print('Você venceu') else: print('O computador venceu') break print(f'O número de vezes que você venceu foi {cont}')
false
5640294cdf3d30f67af661fc674b2c35ac60738a
Iftakharpy/Data-Structures-Algorithms
/section 6 reverse_string.py
256
4.15625
4
usr_input = input('Write something : ') reversed_str = '' #custom implementation #O(n) time #O(n) space for i in range(len(usr_input)-1,-1,-1): reversed_str+=usr_input[i] print(reversed_str) #built in function print(input('Write something : ')[::-1])
false
f0499de132924504b7d808d467e88af636eb5d27
KindaExists/daily-programmer
/easy/3/3-easy.py
1,057
4.21875
4
""" [easy] challenge #3 Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/ """ # This can most likely be done in less than 2 lines # However still haven't figured a way to stop asking "shift" input def encrypt(string, shift): return ''.join([chr((((ord(char) - 97) + shift) % 26) + 97) if char.isalpha() else char for char in string]) # Actually only the encrypt function is technically needed, as it can both do encrypt(+shift) and decrypt(-shift) # However for the sake of simplicity and formality I just seperated the functionalities def decrypt(string, unshift): return ''.join([chr((((ord(char) - 97) - unshift) % 26) + 97) if char.isalpha() else char for char in string]) if __name__ == '__main__': method = input('(e)ncrypt / (d)ecrypt?: ') text_in = input('String to encrypt: ') shift = int(input('Shift by: ')) if method == 'e': print(f'> output: {encrypt(text_in, shift)}') elif method == 'd': print(f'> output: {decrypt(text_in, shift)}')
true
d84ec922db8eeb84c633c868b5c440b5de7f9445
gaogep/LeetCode
/剑指offer/28.二叉树的镜像.py
1,116
4.125
4
# 请完成一个函数,输入一棵二叉树,改函数输出它的镜像 class treeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right root = treeNode(1) root.left = treeNode(2) root.right = treeNode(3) root.left.left = treeNode(4) root.right.right = treeNode(5) def showMirror(root): if not root: return if not root.left and not root.right: return root.left, root.right = root.right, root.left if root.left: showMirror(root.left) if root.right: showMirror(root.right) return root def showMirrorLoop(root): if not root: return queue = [root] while queue: node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) node.left, node.right = node.right, node.left return root showMirrorLoop(root) print(root.value) print(root.left.value, " ", end="") print(root.right.value) print(root.left.left.value, " ", end="") print(root.right.right.value)
true
90233e801ae204d17c260c32f126d52529858083
gaogep/LeetCode
/剑指offer/25.反转链表.py
771
4.15625
4
# 定义一个函数,输入一个链表的头结点 # 反转该链表并输出反转后链表的头结点 class listNode: def __init__(self, Value, Next=None): self.Value = Value self.Next = Next def insert(self, Value): next_node = listNode(Value) while self.Next: self = self.Next self.Next = next_node head = listNode(1) for val in range(2, 6): head.insert(val) def reverseList(head): # 处理头结点为空或者只包含头结点的情况 if not (head and head.Next): return head pre = None cur = head while cur: rear = cur.Next cur.Next = pre pre = cur cur = rear return pre head = reverseList(listNode(1)) print(head.Value)
false
3f508261b762fb7d2e66aae50828e31612af7261
jemper12/ITEA_lesson_igor_gaevuy
/lessons_2/1_task.py
2,003
4.3125
4
""" Создать класс автомобиля. Описать общие аттрибуты. Создать классы легкового автомобиля и грузового. Описать в основном классе базовые аттрибуты для автомобилей. Будет плюсом если в классах наследниках переопределите методы базового класса. """ from random import randrange as rand class Car: engine = 'Gasoline' drive = "front" def __init__(self, color, transmission): self._color = color self._transmission = transmission class PassengerCar(Car): weight = rand(0, 4) speed = rand(70, 240) type_car = 'passenger' def __init__(self, color, transmission, driver): super().__init__(color, transmission) self._driver = driver def get_driver(self): return self._driver def set_driver(self, to): if type(to) is str: self._driver = to else: print('error, not correct type variable') def get_detaly(self): data = f'car type = {self.type_car}\ncolor car = {self._color}\ndriver = {self._driver}\n' return data class Cargo(Car): weight = rand(5, 10) speed = rand(30, 90) type_car = 'cargo' def __init__(self, color, transmission, driver): super().__init__(color, transmission) self._driver = driver def get_driver(self): return self._driver def set_driver(self, to): if type(to) is str: self._driver = to else: print('error, not correct type variable') def get_detaly(self): data = f'car type = {self.type_car}\ncolor car = {self._color}\ndriver = {self._driver}\n' return data car1 = PassengerCar('red', 'auto', 'Ivan') car1.set_driver('Andrey') car2 = Cargo('white', 'mechanical', 'Igor') print(car1.get_detaly()) print(car2.get_detaly())
false
1e18b7a08b74e804774882603eabc30829622571
pchandraprakash/python_practice
/mit_pyt_ex_1.5_user_input.py
686
4.1875
4
""" In this exercise, we will ask the user for his/her first and last name, and date of birth, and print them out formatted. Output: Enter your first name: Chuck Enter your last name: Norris Enter your date of birth: Month? March Day? 10 Year? 1940 Chuck Norris was born on March 10, 1940. """ def userinput(): fn = input("Please enter your first name: ") ln = input("Please enter your last name: ") print("Please enter your date of birth details") month = input("Month?: ") day = input("Day?: ") year = input("Year?: ") print("----------------") print(fn, ln, 'was born on', month, day + ',', year) exit() userinput()
true
b3cccd80b43cda1068d0990b8823395e7ca570b9
marcin-bakowski-intive/python3-training
/code_examples/builtin_types/tuples.py
1,220
4.25
4
#!/usr/bin/env python3 # https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range animals = ("dog", "cat") lookup = ("dog", "horse", "cat") for lookup_value in lookup: if lookup_value in animals: print("'%s' found in animals tuple" % lookup_value) else: print("'%s' not found in animals tuple" % lookup_value) fruits = ('orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana') print("apple count: %s" % fruits.count('apple')) print("tangerine count: %s" % fruits.count('tangerine')) print("banana count: %s" % fruits.count('banana')) print("banana index: %s" % fruits.index('banana')) print("2nd banana index: %s" % fruits.index('banana', 4)) for fruit in fruits: print("This is a %s" % fruit) print("There are %d fruits" % len(fruits)) fruits = ('orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana') print("First fruit: %s" % fruits[0]) print("Last fruit: %s" % fruits[-1]) print("There are %d fruits" % len(fruits)) print("Let's take first 2 fruits: %s" % (fruits[:2],)) print("Let's take last 3 fruits: %s" % (fruits[-3:],)) print("Let's take every second fruit: %s" % (fruits[::2],)) print("is plum in fruits: %s" % ("plum" in fruits))
false
f1501d4453bfbe8b9ac668d0347efd61be61d382
habibi05/ddp-lab-4
/main.py
1,175
4.125
4
# DDP LAB-4 # Nama: Habibi # NIM: 0110220247 # SOAL 1 - Mencetak nama # Tuliskan program untuk Soal 1 di bawah ini # Simpan masukan nama kedalam variabel nama nama = input("Masukkan nama: ") # Simpan panjang nama kedalam variabel lenNama lenNama = len(nama) # Deklarasi variabel iNama dengan nilai 1 untuk kebutuhan perulangan iNama = 1 # Lakukan perulangan sebanyak nilai yang ada di variabel lenNama while iNama <= lenNama: # print nama dengan String Slicing sesuai urutan perulangan print(nama[0:iNama]) # tambahkan nilai iNama dengan 1 iNama = iNama + 1 # SOAL 2 - Validasi teks # Tuliskan program untuk Soal 2 di bawah ini # Simpan masukan text kedalam variabel text text = input("\nMasukkan text: ") # Program melakukan pengecekan apakah panjang text lebih atau sama dengan 8, terdapat kata nf, terdapat YYY atau yyy, dan terdapat angka di dalam text tersebut if len(text) >= 8 and ( 'nf' in text.lower()) and (text.endswith('YYY') or text.endswith('yyy')) and any(char.isdigit() for char in text): # jika memenuhi syarat maka print print("Teks valid. Program berhenti.") else: # jika tidak memenuhi syarat maka print print("Teks tidak valid.")
false
b82739886b7bd5e7d35d91b79b87fd0649cd3086
J-pcy/Jffery_Leetcode_Python
/Medium/247_StrobogrammaticNumberII.py
1,342
4.28125
4
""" A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"] """ class Solution: def findStrobogrammatic(self, n): """ :type n: int :rtype: List[str] """ """ return self.helper(n, n) def helper(self, m, n): if m == 0: return [''] if m == 1: return ['0', '1', '8'] tmp = self.helper(m - 2, n) res = [] for t in tmp: if m != n: res.append('0' + t + '0') res.append('1' + t + '1') res.append('6' + t + '9') res.append('8' + t + '8') res.append('9' + t + '6') return res """ t0 = [''] t1 = ['0', '1', '8'] res = t0 if n % 2 == 1: res = t1 for i in range(n % 2 + 2, n + 1, 2): tmp = [] for r in res: if i != n: tmp.append('0' + r + '0') tmp.append('1' + r + '1') tmp.append('6' + r + '9') tmp.append('8' + r + '8') tmp.append('9' + r + '6') res = tmp return res
false
1e10d7f86e975ef682821785ebe59bc5e499d219
J-pcy/Jffery_Leetcode_Python
/Medium/418_SentenceScreenFitting.py
2,233
4.28125
4
""" Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must remain unchanged. Two consecutive words in a line must be separated by a single space. Total words in the sentence won't exceed 100. Length of each word is greater than 0 and won't exceed 10. 1 ≤ rows, cols ≤ 20,000. Example 1: Input: rows = 2, cols = 8, sentence = ["hello", "world"] Output: 1 Explanation: hello--- world--- The character '-' signifies an empty space on the screen. Example 2: Input: rows = 3, cols = 6, sentence = ["a", "bcd", "e"] Output: 2 Explanation: a-bcd- e-a--- bcd-e- The character '-' signifies an empty space on the screen. Example 3: Input: rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] Output: 1 Explanation: I-had apple pie-I had-- The character '-' signifies an empty space on the screen. """ class Solution: def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ se = ' '.join(sentence) + ' ' length = len(se) res = 0 for i in range(rows): res += cols if se[res % length] == ' ': res += 1 else: while res > 0 and se[(res - 1) % length] != ' ': res -= 1 return res // length """ #Time Limit Exceeded se = ' '.join(sentence) + ' ' length = len(se) n = len(sentence) res, idx = 0, 0 for i in range(rows): restCols = cols while restCols > 0: if restCols >= len(sentence[idx]): restCols -= len(sentence[idx]) if restCols > 0: restCols -= 1 idx += 1 if idx >= n: res += 1 + restCols // length restCols %= length idx = 0 else: break return res """
true
c75df56aed95a3e74e0436c54ea4e22e669c395f
J-pcy/Jffery_Leetcode_Python
/Medium/75_SortColors.py
2,518
4.25
4
""" Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with a one-pass algorithm using only constant space? """ class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ """ red = white = blue = 0 for i in range(len(nums)): if nums[i] == 0: red += 1 if nums[i] == 1: white += 1 if nums[i] == 2: blue += 1 for i in range(red): nums[i] = 0 for i in range(red, red + white): nums[i] = 1 for i in range(red + white, red + white + blue): nums[i] = 2 """ """ cnt = [0] * 3 for i in range(len(nums)): cnt[nums[i]] += 1 index = 0 for i in range(3): for j in range(cnt[i]): nums[index] = i index += 1 """ """ red, blue = 0, len(nums) - 1 index = 0 while index <= blue: if nums[index] == 0: nums[red], nums[index] = nums[index], nums[red] red += 1 elif nums[index] == 2: nums[blue], nums[index] = nums[index], nums[blue] index -= 1 blue -= 1 index += 1 """ red = white = blue = -1 for i in range(len(nums)): if nums[i] == 0: red += 1 white += 1 blue += 1 nums[blue] = 2 nums[white] = 1 nums[red] = 0 elif nums[i] == 1: white += 1 blue += 1 nums[blue] = 2 nums[white] = 1 else: blue += 1 nums[blue] = 2
true
b2c6dc8fdd2f25b0e7ed668f2af2237120e33184
Daneidy1807/CreditosIII
/07/ejercicio4.py
449
4.34375
4
""" Ejercicio 4. Pedir dos numeros al usuario y hacer todas las operaciones básicas de una calculadora y mostrarlo por pantalla. """ numero1 = int(input("Introduce un primer número: ")) numero2 = int(input("Introduce el segundo número: ")) print("#### CALCULADORA ####") print("Suma: " + str(numero1+numero2)) print("Resta: " + str(numero1-numero2)) print("Multiplicación: " + str(numero1*numero2)) print("División: " + str(numero1/numero2))
false
bb7b31b34fc66a0d41b29659eb34187969f05b8f
flavio-brusamolin/py-scripts
/list02/ex02.py
363
4.125
4
numbers = list() option = 'Y' while option == 'Y': numbers.append(int(input('Enter a number: '))) option = input('Keep inserting? Y/N ') even = list(filter(lambda number: number % 2 == 0, numbers)) odd = list(filter(lambda number: number % 2 != 0, numbers)) print(f'All numbers: {numbers}') print(f'Even numbers: {even}') print(f'Odd numbers: {odd}')
false
2d8491624e72ef82b1a1b7179dbc13bbbacb8ebb
juan-g-bonilla/Data-Structures-Project
/problem_2.py
1,293
4.125
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if None in (suffix, path) or "" in (suffix, path): return None sol = [] for fil in os.listdir(path): if os.path.isfile(path + "/" + fil): if fil.endswith(suffix): sol.append(path + "/" + fil) else: sol = sol + find_files(suffix, path + "/" + fil) return sol def test_find_files(): assert(find_files(".c", "./testdir_p_2") == ['./testdir_p_2/subdir1/a.c', './testdir_p_2/subdir3/subsubdir1/b.c', './testdir_p_2/subdir5/a.c', './testdir_p_2/t1.c']) assert(find_files(".gitkeep", "./testdir_p_2") == ['./testdir_p_2/subdir2/.gitkeep', './testdir_p_2/subdir4/.gitkeep']) assert(find_files("", "./testdir_p_2") == None) assert(find_files(".c", "") == None) assert(find_files(None, "") == None) if __name__ == "__main__": test_find_files()
true
31b93a072533214b5f1e592442d6072e1a83c01c
texrer/Python
/CIS007/Lab2/BMICalc.py
658
4.40625
4
#Richard Rogers #Python Programming CIS 007 #Lab 2 #Question 4 #Body mass index (BMI) is a measure of health based on weight. #It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. #Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. #Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. weight_lbs = eval(input("Enter weight in pounds:")) height_inches = eval(input("Enter height in inches:")) weight_kgs = weight_lbs*0.45359237 height_meters = height_inches*0.0254 print("BMI is:", round(weight_kgs/height_meters**2, 4))
true
ffbff41905680bde74a7d42f06d0aa90f55fca25
yingwei1025/credit-card-checksum-validate
/credit.py
1,333
4.125
4
def main(): card = card_input() check = checksum(card) validate(card, check) def card_input(): while True: card_number = input("Card Number: ") if card_number.isnumeric(): break return card_number def checksum(card_number): even_sum = 0 odd_sum = 0 card_number = reversed([int(digit) for digit in card_number]) for i, digit in enumerate(card_number): if (i + 1) % 2 == 0: odd_digit = digit * 2 if odd_digit > 9: odd_sum += int(odd_digit / 10) + odd_digit % 10 else: odd_sum += odd_digit else: even_sum += digit result = even_sum + odd_sum return result def validate(card_number, checksum): # get the first 2 digit card_prefix = int(card_number[0:2]) # get the length of card length = len(card_number) # check the last digit by % 10 last_digit = checksum % 10 if last_digit == 0: if card_prefix in [34, 37] and length == 15: print("AMEX") elif (card_prefix in range(51, 56)) and length == 16: print("MASTERCARD") elif (int(card_number[0]) == 4) and length in [13, 16]: print("VISA") else: print("INVALID") else: print("INVALID") main()
true
66f0ccab7057084061766ca23e21d790e829922b
irmowan/LeetCode
/Python/Binary-Tree-Maximum-Path-Sum.py
1,307
4.15625
4
# Time: O(n) # Space: O(n) # Given a binary tree, find the maximum path sum. # # For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. # # For example: # Given the below binary tree, # # 1 # / \ # 2 3 # Return 6. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ return self.maxPathSumRecu(root)[0] def maxPathSumRecu(self, root): if root is None: return float("-inf"), float("-inf") left_inner, left_link = self.maxPathSumRecu(root.left) right_inner, right_link = self.maxPathSumRecu(root.right) link = max(left_link, right_link, 0) + root.val inner = max(left_link + root.val + right_link, link, left_inner, right_inner) return inner, link if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) result = Solution().maxPathSum(root) print result
true
9fe261707283f616194ebe30757a6381d500d534
irmowan/LeetCode
/Python/Palindrome-Number.py
1,065
4.125
4
# Time: O(n) # Space: O(1) # # Determine whether an integer is a palindrome. Do this without extra space. # # click to show spoilers. # # Some hints: # Could negative integers be palindromes? (ie, -1) # # If you are thinking of converting the integer to string, note the restriction of using extra space. # # You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? # # There is a more generic way of solving this problem. class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False temp = x y = 0 while (temp > 0): y = y * 10 + temp % 10 temp = temp / 10 if x == y : return True else: return False if __name__ == "__main__": print(Solution().isPalindrome(-13)) print(Solution().isPalindrome(919)) print(Solution().isPalindrome(120))
true
5f8c9db073643da16d88ef03512b4ca6e97d28ca
LinuxUser255/Python_Penetration_Testing
/Python_Review/dmv.py
308
4.125
4
#!/usr/bin/env python3 #If-else using user defined input: print("""Legal driving age. """) age = int(input("What is your age? ")) if age < 16: print("No.") else: if age in range(16, 67): print("Yes, you are eligible.") if age > 66: print("Yes, but with special requirements.")
true
6361f4914c5a1570c9113a55222c139a9844efb2
mihirbhaskar/save-the-pandas-intpython
/filterNearby.py
973
4.125
4
""" File: filterNearby Description: Function to filter the dataframe with matches within a certain distance Next steps: - This function can be generalised, but for now assuming data is in a DF with lat/long columns named 'latitude' and 'longitude' """ import pandas as pd from geopy.distance import distance def filterNearby(point, data, max_dist = 5): # Combing lat and long columns into one column with tuples data['place_coords'] = data[['LATITUDE', 'LONGITUDE']].apply(tuple, axis=1) ## Alternative code for the above - could be faster? ## data['place_coords'] = list(zip(data.latitude, data.longitude)) # Applying the distance function to each row to create new column with distances data['DISTANCE IN MILES'] = data.apply(lambda x: distance(point, x['place_coords']).miles, axis=1) # Return data frame filtered with rows <= the maximum distance return data[data['DISTANCE IN MILES'] <= max_dist]
true
2096aed0b726883d89aae8c3d886ae5ef3b11518
simplex06/HackerRankSolutions
/Lists.py
1,683
4.3125
4
# HackerRank - "Lists" Solution #Consider a list (list = []). You can perform the following commands: # #insert i e: Insert integer at position . #print: Print the list. #remove e: Delete the first occurrence of integer . #append e: Insert integer at the end of the list. #sort: Sort the list. #pop: Pop the last element from the list. #reverse: Reverse the list. #Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. # # #Input Format # #The first line contains an integer, , denoting the number of commands. #Each line of the subsequent lines contains one of the commands described above. # #Constraints # #The elements added to the list must be integers. #Output Format # #For each command of type print, print the list on a new line. # #Sample Input 0 # #12 #insert 0 5 #insert 1 10 #insert 0 6 #print #remove 6 #append 9 #append 1 #sort #print #pop #reverse #print #Sample Output 0 # #[6, 5, 10] #[1, 5, 9, 10] #[9, 5, 1] if __name__ == '__main__': L = [] N = int(input()) for i in range(0, N): tokens = input().split() if tokens[0] == 'insert': L.insert(int(tokens[1]), int(tokens[2])) elif tokens[0] == 'print': print(L) elif tokens[0] == 'remove': L.remove(int(tokens[1])) elif tokens[0] == 'append': L.append(int(tokens[1])) elif tokens[0] == 'sort': L.sort() elif tokens[0] == 'pop': L.pop() elif tokens[0] == 'reverse': L.reverse()
true
492689343e28be7cdbb2d807514881925534a010
SynTentional/CS-1.2
/Coursework/Frequency-Counting/Frequency-Counter-Starter-Code/HashTable.py
2,156
4.3125
4
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) # 1️⃣ TODO: Complete the create_arr method. # Each element of the hash table (arr) is a linked list. # This method creates an array (list) of a given size and populates each of its elements with a LinkedList object. def create_arr(self, size): #instantiation of array arr = [] #uses the size parameter to append one Linked List function call to each index within range for i in range(size): new_ll = LinkedList() arr.append(new_ll) return arr # 2️⃣ TODO: Create your own hash function. # Hash functions are a function that turns each of these keys into an index value that we can use to decide where in our list each key:value pair should be stored. def hash_func(self, key): return (ord(key[0]) - ord('s')) % self.size # 3️⃣ TODO: Complete the insert method. # Should insert a key value pair into the hash table, where the key is the word and the value is a counter for the number of times the word appeared. When inserting a new word in the hash table, be sure to check if there is a Node with the same key in the table already. def insert(self, key, value): #Find the index where the key value should be placed key_index = self.hash_func(key) # range of index value to tell if key is found within array found = self.arr[key_index].find(key) # if key is within array, take the value associated with it and increment it according to frequency of occurance if found == -1: toople = (key, value) self.arr[key_index].append(toople) # inserting the associated tuple into the Linked List # 4️⃣ TODO: Complete the print_key_values method. # Traverse through the every Linked List in the table and print the key value pairs. # For example: # a: 1 # again: 1 # and: 1 # blooms: 1 # erase: 2 def print_key_values(self): if self.size == None: print("empty") return -1 else: for i in self.arr: i.print_nodes()
true
1a9ba4cfe848b8529b0aa9eaddd09882f9bcd5bf
khankatan/CP3-Chetsarit-Mesathanon
/assignments/Exercise5_1_Chetsarit_M.py
269
4.15625
4
print("--------- CALCULATOR ---------- ") x = int(input("num1 : ")) y = int(input("num2 : ")) print("=============================== ") print(x,"+",y,"=",x+y) print(x,"-",y,"=",x-y) print(x,"x",y,"=",x*y) print(x,"/",y,"=",x/y) print("=============================== ")
false
aa29cde7070d9c68e6572d9a362fed336488f4a1
SeilaAM/BasicProgramPython
/ModulePractice/CustomerSystemMoveTest/Modules/Asset/BasicData.py
1,767
4.21875
4
# ----------------- 客戶的基本資料 ----------------- # class BasicData: def __init__(self, name, age, gender, phone, email): self.__name = name self.__age = age self.__gender = gender self.__phone = phone self.__email = email def get_name(self): return self.__name def get_age(self): return self.__age def get_gender(self): return self.__gender def get_phone(self): return self.__phone def get_email(self): return self.__email def set_name(self, name): self.__name = name def set_age(self, age): self.__age = age def set_gender(self, gender): self.__gender = gender def set_phone(self, phone): self.__phone = phone def set_email(self, email): self.__email = email if __name__ == '__main__': print('\n') # ---------- 測試 BasicData 類別運作正常 ---------- # basic_data = BasicData('John', '32', 'man', '0900123456', 'john@xmail.com') print('[Original Basic Data]') print('Name = ' + basic_data.get_name()) print('Age = ' + basic_data.get_age()) print('Gender = ' + basic_data.get_gender()) print('Phone = ' + basic_data.get_phone()) print('Email = ' + basic_data.get_email()) print('\n') basic_data.set_name('John Smith') basic_data.set_age('99') basic_data.set_gender('mana') basic_data.set_phone('0988765432') basic_data.set_email('john_smith@xmail.com.tw') print('[Modified Basic Data]') print('Name = ' + basic_data.get_name()) print('Age = ' + basic_data.get_age()) print('Gender = ' + basic_data.get_gender()) print('Phone = ' + basic_data.get_phone()) print('Email = ' + basic_data.get_email()) print('\n')
false
7f7c20e3c655b59fb28d90a5b7fec803d3b65170
MrSmilez2/z25
/lesson3/4.py
272
4.125
4
items = [] max_element = None while True: number = input('> ') if not number: break number = float(number) items.append(number) if not max_element or number >= max_element: max_element = number print(items) print('MAX', max_element)
true
a2ab21a48d07c3fe753681babeb8cfeea023038c
floryken/Ch.05_Looping
/5.2_Roshambo.py
1,632
4.8125
5
''' ROSHAMBO PROGRAM ---------------- Create a program that randomly prints 1, 2, or 3. Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list. Add to the program so it first asks the user their choice as well as if they want to quit. (It will be easier if you have them enter 1 for rock, 2 for paper, and 3 for scissors.) Add conditional statements to figure out who wins and keep the records When the user quits print a win/loss record ''' import random print("Welcoome to my ROSHAMBO program") user_win=0 computer=0 ties=0 done=False while done==False: user=int(input("What is your choice?(Type in #)\n 1. Rock\n 2. Paper\n 3. Scissors\n 4. Quit")) if user==1: print("You chose Rock") elif user==2: print("You chose Paper") elif user==3: print("You chose Scissors") elif user==4: done==True else: print("Not an answer") number=random.randrange(1,4) if number==user: print("It's a tie!") ties+=1 elif number==1 and user==2: print("User Won!") user_win+=1 elif number==1 and user==3: print("Computer Won!") computer+=1 elif number==2 and user==1: print("Computer Won!") computer += 1 elif number==2 and user==3: print("User Won!") user_win += 1 elif number==3 and user==2: print("Computer Won!") computer += 1 elif number==3 and user==1: print("User Won!") user_win+=1 print("BYE!") print("Your Win/Loss/Tie record was\n",user_win,"/",computer,"/",ties)
true
f95a79a3a2d6c1718efb817cba7c8cb7072ce57f
goateater/SoloLearn-Notes
/SL-Python/Data Types/Dictionaries.py
2,870
4.71875
5
# Dictionaries # Dictionaries are data structures used to map arbitrary keys to values. # Lists can be thought of as dictionaries with integer keys within a certain range. # Dictionaries can be indexed in the same way as lists, using square brackets containing keys. # Each element in a dictionary is represented by a key:value pair. # Example: ages = {"Dave": 24, "Mary": 42, "John": 58} print(ages["Dave"]) print(ages["Mary"]) print() # Trying to index a key that isn't part of the dictionary returns a KeyError. primary = { "red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255], } print("Red is" , type(primary["red"])) print() # print(primary["yellow"]) # As you can see, a dictionary can store any types of data as values. # An empty dictionary is defined as {}. # test = { } # print(test[0]) # Only immutable objects can be used as keys to dictionaries. # Immutable objects are those that can't be changed. # So far, the only mutable objects you've come across are lists and dictionaries. # Trying to use a mutable object as a dictionary key causes a TypeError. # This will work good_dict = { 1: "one two three", } print(good_dict[1]) print() # This will not #bad_dict = { # [1, 2, 3]: "one two three", #} #print(bad_dict[1,2,3]) # Dictionary Functions # Just like lists, dictionary keys can be assigned to different values. # However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist. squares = {1: 1, 2: 4, 3: "error", 4: 16,} print(squares) squares[8] = 64 squares[3] = 9 print(squares) print() # Something a little tricky # What you've here is hierarchical nested Key-Value mapping passed on to the print function as an argument. #So, you'd start start out first by solving the inner embedded Dictionary mapping call, primes[4], which maps to the value 7. # And then, this 7 is rather a key to the outer Dictionary call, and thus, primes[7] would map to 17. primes = {1: 2, 2: 3, 4: 7, 7:17} print(primes[primes[4]]) print() # To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. # Example: nums = { 1: "one", 2: "two", 3: "three", } print(1 in nums) print("three" in nums) print(4 not in nums) print() # A useful dictionary method is get. # It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead ('None', by default). pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(True)) print(pairs.get(12345, "not in dictionary")) # returns an alternate value instead of the default None, if they key does not exist. print(pairs.get(None)) print() # What is the result of the code below? fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(4, 0) + fib.get(7, 5))
true
333d2fae7916937db479ee1778ed237c59e6e57d
goateater/SoloLearn-Notes
/SL-Python/Opening Files/writing_files.py
2,703
4.5625
5
# Writing Files # To write to files you use the write method, which writes a string to the file. # For Example: file = open("newfile.txt", "w") file.write("This has been written to a file") file.close() file = open("newfile.txt", "r") print(file.read()) file.close() print() # When a file is opened in write mode, the file's existing content is deleted. file = open("newfile.txt", "r") print("Reading initial contents") print(file.read()) print("Finished") file.close() print() file = open("newfile.txt", "w") file.write("Some new text") file.close() print() file = open("newfile.txt", "r") print("Reading new contents") print(file.read()) print("Finished") file.close() # Try It Yourself # Result: # >>> # Reading initial contents # some initial text # Finished # Reading new contents # Some new text # Finished # >>> print() # The write method returns the number of bytes written to a file, if successful. msg = "Hello world!" file = open("newfile.txt", "w") print(msg) amount_written = file.write(msg) print(type(amount_written)) print(amount_written) file.close() print() file = open("newfile.txt", "r") print(file.read()) file.close() print() # Working with Files # It is good practice to avoid wasting resources by making sure that files are always closed after they have been used. # One way of doing this is to use try and finally. # This ensures that the file is always closed, even if an error occurs. try: f = open("newfile.txt") print(f.read()) finally: f.close() print() # Finally block won't work properly if FileNotFoundError occurred. So... we can make another try~except block in finally: try: f = open("filename.txt") print(f.read()) except FileNotFoundError: f = open("filename.txt", "w") f.write("The file has now been created") f.close() f = open("filename.txt", "r") print(f.read()) f.close() # print("No such file or directory") finally: try: f.close() except: print("Can't close file") # Or we can force our program to open our py file. Like this: try: f = open("filename.txt") print(f.read()) except FileNotFoundError: print("No such file or directory") f = open(__file__, "r") # open itself finally: f.close() # In other cases when we catch FileNotFoundError f.close() makes error too (and program will stop). # An alternative way of doing this is using "with" statements. # This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement. with open("filename.txt") as f: print(f.read()) # The file is automatically closed at the end of the with statement, even if exceptions occur within it.
true
e7c9ff96bfd41f28f35486d8635a44bbcdb47126
benilak/Everything
/CS241_Miscellaneous/scratch_2.py
2,743
4.28125
4
'''class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self._hours = hours self._minutes = minutes self._seconds = seconds def get_hours(self): return self._hours def set_hours(self, hours): if hours < 0: self._hours = 0 elif hours > 23: self._hours = 23 else: self._hours = hours def get_minutes(self): return self._minutes def set_minutes(self, minutes): if minutes < 0: self._minutes = 0 elif minutes > 59: self._minutes = 59 else: self._minutes = minutes def get_seconds(self): return self._seconds def set_seconds(self, seconds): if seconds < 0: self._seconds = 0 elif seconds > 59: self._seconds = 59 else: self._seconds = seconds def main1(): time = Time() hours = int(input("Please enter hours: ")) minutes = int(input("Please enter minutes: ")) seconds = int(input("Please enter seconds: ")) time.set_hours(hours) print(time.get_hours()) time.set_minutes(minutes) print(time.get_minutes()) time.set_seconds(seconds) print(time.get_seconds()) if __name__ == "__main__": main() ''' class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self.__hours = 0 self.__minutes = 0 self.__seconds = 0 def get_hours(self): return self.__hours def set_hours(self, hours): if hours < 0: self.__hours = 0 elif hours > 23: self.__hours = 23 else: self.__hours = hours hours = property(get_hours, set_hours) def get_minutes(self): return self.__minutes def set_minutes(self, minutes): if minutes < 0: self.__minutes = 0 elif minutes > 59: self.__minutes = 59 else: self.__minutes = minutes minutes = property(get_minutes, set_minutes) def get_seconds(self): return self.__seconds def set_seconds(self, seconds): if seconds < 0: self.__seconds = 0 elif seconds > 59: self.__seconds = 59 else: self.__seconds = seconds seconds = property(get_seconds, set_seconds) def main(): time = Time() hours = int(input("Please enter hours: ")) minutes = int(input("Please enter minutes: ")) seconds = int(input("Please enter seconds: ")) time.hours = hours print(time.hours) time.minutes = minutes print(time.minutes) time.seconds = seconds print(time.seconds) if __name__ == "__main__": main()
false
cb63ddf5d873dc45e0f46f0c048b06cf17864c53
virenparmar/TechPyWeek
/core_python/Function/factorial using recursion.py
499
4.28125
4
# Python program to find the factorial of a number using recursion def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n==1: return n else: return n*recur_factorial(n-1) #take input from the user num=int(input("Enter a number=")) #check is the number is negative if num<0: print("Sorry,factorial does not exist for negative numbers") elif num==0: print("The factorial of 0 is 1") else: print("The factorial of",num,"is",recur_factorial(num))
true
830bf963c902c0382c08fca73c71d2fa2f7d1522
virenparmar/TechPyWeek
/core_python/fibonacci sequence.py
479
4.40625
4
#Python program to display the fibonacci sequence up to n-th term where n is provided #take in input from the user num=int(input("How many term?")) no1=0 no2=1 count=2 # check if the number of terms is valid if num<=0: print("please enter a positive integer") elif num == 1: print("fibonacci sequence") print(no1) else: print("fibonacci sequence") print(no1,",",no2,",") while count<num: nth=no1+no2 print(nth,",") #update values no1=no2 no2=nth count+=1
true
4ae8ad04f48d102055e470f4ca953940a8ca1f25
virenparmar/TechPyWeek
/core_python/Function/anonymous(lambda) function.py
299
4.46875
4
#Python Program to display the power of 2 using anonymous function #take number of terms from user terms=int(input("How many terms?")) #use anonymous function result=list(map(lambda x:2 ** x, range(terms))) #display the result for i in range(terms): print "2 raised to power",i,"is",result[i]
true
01ab8ec47c8154a5d90d5ee4bd207f143a0051b3
virenparmar/TechPyWeek
/core_python/Function/display calandar.py
242
4.40625
4
# Python Program to display calender of given month of the year #import module import calendar #assk of month and year yy=int(input("Enter the year=")) mm=int(input("Enter the month=")) #display the calender print(calendar.month(yy,mm))
true
17af5750832fde25c0a10ec49865f478fae390d9
jonathansantilli/SMSSpamFilter
/spamdetector/file_helper.py
973
4.1875
4
from os import path class FileHelper: def exist_path(self, path_to_check:str) -> bool: """ Verify if a path exist on the machine, returns a True in case it exist, otherwise False :param path_to_check: :return: boolean """ return path.exists(path_to_check) def read_pattern_separated_file(self, file_path:str, pattern:str) -> list: """ Read each of a text file and split them using the provided pattern :param file_path: File path to read :param pattern: The pattern used to split each line :return Array: The array that contain the splitted lines """ pattern_separated_lines = [] if file_path and self.exist_path(file_path): with open(file_path, encoding='UTF-8') as f: lines = f.readlines() pattern_separated_lines = [line.strip().split(pattern) for line in lines] return pattern_separated_lines
true
bd4daf1ee0c3fc74486bc4680a1b3355337eab62
Pythonmaomao/String
/3-52.py
990
4.34375
4
class Human: ''' this is the Human class!!! ''' name = 'ren' __money = 100 def __init__(self,name,age):#对象实例化后init函数自动执行 print('#'*50) self.name = name#只是赋值,没有输出打印;传入实例的属性 self.age = age print('#'*50) #@classmethod#类方法 @property def say(self):#公有方法,有self参数 print("my name is %s i have %s"%(self.name,self.__money)) return self.name @staticmethod#静态类方法,装饰器 def bye():#公有方法,不用self参数 print("GAME OVER") #Human.bye()#通过类直接访问,不用加装饰器也能调用 #tom = Human('name',20) #tom.bye()#有了装饰器通过对象访问 #Human.say()#通过类直接访问 #tom = Human('name',20) #tom.say()#有了装饰器通过对象访问 #x = Human.say() #print(x) tom = Human('tom',20) print(tom.say)#property方法变属性 #print(Human.say)#property方法变属性
false
cf5b64089024a35ddd119fc90ae09cc8e404129e
mani-barathi/Python_MiniProjects
/Beginner_Projects/Number_guessing_game/game.py
926
4.25
4
from random import randint def generateRandomNumber(): no = randint(1,21) return no print('Number Guessing Game!') print("1. Computer will generate a number from 1 to 20") print("2. You have to guess it with in 3 guess") choice = input("Do you want to play?(yes/no): ") if choice.lower() == 'yes': while True: number = generateRandomNumber() chances = 3 found = False while chances>=1: guess = int(input("\nMake a guess: ")) if guess == number: print(f'Yes your guess was correct, it was {guess}') found = True break elif number > guess: print("It's bigger than your guess!") else: print("It's smaller than your guess") chances -=1 if found == False: print(f"\nYour chances got over, the number was {number}") choice = input("\nDo you want to continue playing?(yes/no): ") if choice.lower() == 'no': break print("Thank you...Bye") else: print("Thank you")
true
3d78394ffe2709a01d1e6a34df7dfcb7ba407a76
mani-barathi/Python_MiniProjects
/Beginner_Projects/DataStructures/Stack.py
948
4.1875
4
class Stack: def __init__(self): self.stack=[] # emty list self.top=-1 def isEmpty(self): if len(self.stack)==0: return True else : return False def push(self): self.top+=1 element = input("Enter the Element: ") self.stack.insert(self.top,element) print(f" {element} is pushed") def pop(self): if self.isEmpty(): print("Stack is empty!") else: self.top-=1 print(f"Element poped: {self.stack.pop()}") def printStack(self): if self.isEmpty(): print("stack is Empty") else: print(self.stack) # print(" iniside main.py: ",__name__) if __name__=='__main__': s= Stack() # creating a object of stack print("1. push\n2. pop\n3. printStack") while True: choice= input("Enter your choice: ") if choice=='1': Stack.push(s) elif choice=='2': s.pop() elif choice=='3': s.printStack() else: break
false
c3f3c6409e68ceae0d46054bf50c22b7ff56f37b
rsp-esl/python_examples_learning
/example_set-2/script_ex-2_5.py
939
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher ## Data structures, Lists, List manipulation def rotate_right( _list ): # define a function _list.insert( 0, _list.pop() ) return _list # create a list: [10, 20, 30] list1 = [ 10*(e+1) for e in xrange(3) ] for i, e in enumerate( list1 ): print (i, '->', e) # output: # 0 -> 10 # 1 -> 20 # 2 -> 30 list2 = rotate_right( list1 ) print ('list1 =', list1) print ('list2 =', list2) # output: # list1 = [30, 10, 20] # list2 = [30, 10, 20] ##############################################################################
false
fc67206793cd483acdbb305f621ab33b8ad63083
rsp-esl/python_examples_learning
/example_set-1/script_ex-1_27.py
1,088
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher ## Data structures, Lists numbers = [0,-1,2,-2,1,-3,3] # create a list of int numbers = sorted( numbers ) # sort the list print (numbers) # show the numbers in the (sorted) list # output: [-3, -2, -1, 0, 1, 2, 3] # create a list of positive numbers from a list positives = [ n for n in numbers if (n > 0) ] print (positives) # output: [1, 2, 3] # create a list of negative numbers from a list negatives = [ n for n in numbers if (n < 0) ] print (negatives) # output: [-3, -2, -1] squares = [ i*i for i in numbers ] print (squares) print (sum(squares)) # output: [9, 4, 1, 0, 1, 4, 9] # output: 28 ##############################################################################
true