blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
47934eccdc1e2a12909d36338bf1ae54cba8d9d6
RobertMisch/Data-Structures
/stack/stack.py
2,224
4.375
4
import singly_linked_list """ A stack is a data structure whose primary purpose is to store and return elements in Last In First Out order. 1. Implement the Stack class using an array as the underlying storage structure. Make sure the Stack tests pass. 2. Re-implement the Stack class, this time using the linked list implementation as the underlying storage structure. Make sure the Stack tests pass. 3. What is the difference between using an array vs. a linked list when implementing a Stack? """ # class Stack: # def __init__(self): # self.size = 0 # self.storage = [] # def __len__(self): # self.size = len(self.storage) # return self.size # def push(self, value): # # if(self.storage == None): # # self.storage=[] # self.storage.append(value) # self.size = len(self.storage) # return self.storage # def pop(self): # data=None # if(len(self.storage)>=1): # data = self.storage.pop() # self.size = len(self.storage) # return data #here if we need to impliment a linked list ourselves withing the stack class # class Node: # def __init__(self, value, next=None): # self.value = value # self.next_node = next # ​ # def get_value(self): # # returns the node's data # return self.value # ​ # def get_next(self): # # returns the thing pointed at by this node's `next` reference # return self.next_node # ​ # def set_next(self, new_next): # # sets this node's `next` reference to `new_next` # self.next_node = new_next class Stack: def __init__(self): self.size = 0 self.storage=singly_linked_list.LinkedList() def __len__(self): return self.size def push(self, value): #here I don't have to make a new node since our list does it for me self.storage.add_to_tail(value) self.size= self.size + 1 return self.storage.tail.value def pop(self): data = self.storage.remove_tail() if self.size != 0: self.size= self.size - 1 # print(self.size) return data
true
37c12bdb79815bdc4b5b55e84fa2b3ef268e1390
AqilAhamed/PersonalProjects
/Guess the Secret Number Game/GuessTheSecretNumberGame.py
982
4.15625
4
from random import randint print("Welcome to Guess The Secret Number Game!") print("Rules of the game are to correctly predict a secret number from the range 1 to the maximum number of your choice.") print("Have Fun!") print() def choice(): user_choice = input("Would you like to play again? (y/n): ") if user_choice == 'y': print() game() elif user_choice == 'n': print("Thanks for playing! See you again later :)") else: choice() def game(): n = int(input("Choose maximum range number: ")) sec_num = randint(1, n) while True: user_input = int(input("Input your guess: ")) if user_input > sec_num: print("Your number is too high. Try again.") elif user_input < sec_num: print("Your number is too low. Try again.") else: print("Congratulations! You guessed correctly!") break choice() game()
true
3f2c92f077e7a3365a23b358f12e310c8d8f8cf5
JiapengWu/COMP-206
/Text Mining & Chat Bot-Python/q1_word_count.py
1,210
4.25
4
#!/usr/bin/python import sys import re def countFrequency(): regex = re.compile('[^a-zA-Z]'); if len(sys.argv) <= 1: print "Please enter correct arguement." sys.exit() filename=sys.argv[1] try: fhand=open(filename,"r") except: print "Please input a valid file name." sys.exit() text = fhand.read().lower() words=text.split() #words are the collection of words splited by " " newWords=list(); for word in words: for splitted in word.split("-")[0:]: newWords.append(splitted) #get rid of the words which contains no hyphen in "words final=list() for word in newWords: word=regex.sub('',word) if word is not '': final.append(word) #strip the words containing non-alphabetic charaters count=dict() length=float(len(final)) for word in final: count[word]=count.get(word,0)+1 #count word #for key in count.keys(): #count[key]/=len(count) #calculate ratio sorted_count = sorted([(v,k) for (k,v) in count.items()],reverse = True) #sort the list for (v,k) in sorted_count[:]: print k,":",v countFrequency()
true
7e491cc9caac4bbae13e18a40b52b9bc076bd960
matildak/think-python
/variablesExpressionsStatements.py
1,112
4.25
4
# VALUES AND TYPES: # to get what type: type('Hello, World!') # type(44) #str, int and float (3.4) print(1,000,000) # = 1 0 0 # VARIABLES: a name that refers to a value #assignment statement: message = 'And now for something different' n = 17 pi = 3.14159265 messageType = type(message) nType = type(n) piType = type(pi) print(messageType) print(nType) print(piType) #keywords: #Python 2 has 31 keywords: #and del from not while as elif global or with assert else if pass yield #break except import print class exec in raise continue finally is return #def for lambda try #In Python 3, exec is no longer a keyword, but nonlocal is. #OPERATORS AND OPERANDS # +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation minute = 59 print (minute/60) # = 0.9833333333333333 print (minute//60) # = 0 #EXPRESSIONS AND STATEMMENTS #An expression is a combination of values, variables, and operators. #A statement is a unit of code that the Python interpreter can execute #an --expression-- has a value; a --statement-- does not.
true
6c21ce4834f59c5be63becf787b8b9d6fc8cb0c2
ninad1704/coursera
/Deep-Learning-Specialization/2-Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week1/for_prop_gradcheck.py
1,417
4.1875
4
def forward_propagation_n(X, Y, parameters): """ Implements the forward propagation (and computes the cost) presented in Figure 3. Arguments: X -- training set for m examples Y -- labels for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": W1 -- weight matrix of shape (5, 4) b1 -- bias vector of shape (5, 1) W2 -- weight matrix of shape (3, 5) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector of shape (1, 1) Returns: cost -- the cost function (logistic cost for one example) """ import numpy as np from misc_3 import relu, sigmoid # retrieve parameters m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) # Cost logprobs = np.multiply(-np.log(A3), Y) + np.multiply(-np.log(1 - A3), 1 - Y) cost = 1. / m * np.sum(logprobs) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) return cost, cache
true
fe8a5ed2ceabd8aea4971e90fa635435ed9dd04b
codexpage/Code_training
/lc206.py
1,166
4.1875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None #in the recursion return back, it's a backwards traverse, so will can make use of this point #the point is cancel and switch pointers backwards is much easier than forward class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return None if head.next == None: return head return self.reverse_next(head) def reverse_next(self, cur): if cur.next.next == None: cur.next.next = cur # print(cur.val,"<-",cur.next.val) ret = cur.next cur.next = None return ret else: new_head = self.reverse_next(cur.next) cur.next.next = cur # print(cur.val,"<-",cur.next.val) cur.next = None return new_head
true
8b57655b9b95b7ce4ecc713dd6815559b159a23e
ani03sha/Python-Language
/02_datatypes/04_find_the_percentage.py
915
4.375
4
# You have a record of N students. Each record contains the student's name, and their percent marks in Maths, # Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and # marks for N students. You are required to save the record in a dictionary data type. The user then enters a student's # name. Output the average percentage marks obtained by that student, correct to two decimal places. if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() # Getting the list of marks of the student score = student_marks[query_name] # Calculating the average average = sum(score) / 3 # Printing the result upto two decimal places print("{:.2f}".format(average))
true
266a28e3551937a03b4176cd3445dfe68068af2e
ani03sha/Python-Language
/07_collections/07_company_logo.py
1,089
4.375
4
# A newly opened multinational brand has decided to base their company logo on the three most common characters in # the company name. They are now trying out various combinations of company names and logos based on this condition. # Given a string s, which is the company name in lowercase letters, your task is to find the top three most common # characters in the string. # # Print the three most common characters along with their occurrence count. # Sort in descending order of occurrence count. # If the occurrence count is the same, sort the characters in alphabetical order. # For example, according to the conditions described above, # # GOOGLE would have it's logo with the letters G, O, E. # # Print the three most common characters along with their occurrence count each on a separate line. # Sort output in descending order of occurrence count. # If the occurrence count is the same, sort the characters in alphabetical order. from collections import Counter items = Counter(input()).items() for items, x in sorted(items, key=lambda i: (-i[1], i[0]))[:3]: print(items, x)
true
d6277a77f452859f24ae8a8c28bcda679252ca69
wangxd100/myFirstPython2
/class-__str__.py
1,029
4.25
4
##### # It provides human readable version of output # rather "Object": Example: ##### class Pet(): # class attributes pet_address = "627 ..." def __init__(self, name, species): self.name = name self.species = species def getName(self): return self.name def getSpecies(self): return self.species def Norm(self): return "%s is a %s" % (self.name, self.species) if __name__=='__main__': a = Pet("jax", "human") print(a) # print Class Attributes - Static Attributes print(Pet.pet_address) ##### # It provides human readable version of output # rather "Object": Example: # __str__ ##### class Pet(): def __init__(self, name, species): self.name = name self.species = species def getName(self): return self.name def getSpecies(self): return self.species def __str__(self): return "%s is a %s" % (self.name, self.species) if __name__=='__main__': a = Pet("jax", "human") print(a)
true
9f8c8559b43f053c1b9c3bcb47c7a8142a0ba3f8
javaDeveloperBook/python-learn
/base/0016_python_map_reduce.py
515
4.15625
4
# map() 函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 from functools import reduce def power(x): return x * x print(list(map(power, [1, 2, 3, 4, 5]))) print(list(map(str, [1, 2, 3, 4, 5]))) # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算 reduce(power, [1, 2, 3])
false
80c2434fb9f153b24d900e19520b6e9d1985457f
LaRenaiocco/job-practice
/domain.py
1,401
4.15625
4
# Write a function that when given a URL as a string, # parses out just the domain name and returns it as a string. def domain_name(url): """ >>> domain_name("http://github.com/carbonfive/raygun") 'github' >>> domain_name("http://www.zombie-bites.com") 'zombie-bites' >>> domain_name("https://www.cnet.com") 'cnet' >>> domain_name("www.xakep.ru") 'xakep' >>> domain_name("buffy.com") 'buffy' """ if url.startswith('http'): url_list = url.split('//') if url_list[1].startswith('www'): one_list = url_list[1].split('.') return one_list[1] else: one_list = url_list[1].split('.') return one_list[0] elif url.startswith('www'): url_list = url.split('.') return url_list[1] else: url_list = url.split('.') return url_list[0] # Much more eloquent version!!! # return url.split("//")[-1].split("www.")[-1].split(".")[0] # pseudocode: # possible starts of input == http and www # if start with http: # split on '//' # look at index 1 # if starts with www, split on . # return index 1 # if starts with a www # split on . # return index 1 # else # split on . # return index 0 if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print('\n✨ ALL TESTS PASSED!\n')
true
71c756e51118e49d6aa0e9068cc961c166aea7af
LaRenaiocco/job-practice
/non-decreasing-array.py
1,090
4.3125
4
# Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. # We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). # Example 1: # Input: nums = [4,2,3] # Output: true # Explanation: You could modify the first 4 to 1 to get a non-decreasing array. # Example 2: # Input: nums = [4,2,1] # Output: false # Explanation: You can't get a non-decreasing array by modify at most one element. # Example 3: # Input: [3,4,2,3] # Output: false def non_decreasing_array(nums): """ >>> non_decreasing_array([4,2,3]) True >>> non_decreasing_array([4,2,1]) False >>> non_decreasing_array([3,4,2,3]) False """ count = 0 for i in range(0, len(nums) -1): print(i) if nums[i] > nums[i +1]: count += 1 if count > 1: return False else: return True if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print('\n✨ ALL TESTS PASSED!\n')
true
9d5b6097d69d1adcf067bb51fa1a90f244502ff2
2ykwang/learn-algorithm
/leetcode/6. ZigZag Conversion/zigzag-conversion.py
864
4.3125
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: """ class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s rows = [[] for _ in range(numRows)] down = True seq = 0 for chr in s: rows[seq].append(chr) seq += 1 if down else -1 if seq == 0 or seq == numRows-1: # flip down = not down return ''.join([''.join(r) for r in rows]) s = Solution() result = s.convert("AB",1) print(result)
true
9e79479d6ead1f2ef4ca1fecd8af6e04f77ff04a
kuasimikua/CP2015
/P02/q05_find_month_days.py
774
4.125
4
def is_leap(n): if (int(year)%4==0) and (int(year)%100!=0): return True else: return False month=input("Please enter a month (mm): ") if int(month)>12 or int(month)<0: print("That is not a valid month") exit() year=input("Please enter a year (yyyy): ") if int(year)<0: print("That is not a valid year") exit() if int(month) in [1,3,5,7,8,10,12]: days=31 elif int(month) in [4,6,9,11]: days=30 else: if is_leap(int(year)): days=29 else: days=28 month_names={1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:"December"} print("There are "+ str(days) + " days in " +(month_names[int(month)]) + ", year " + year)
false
a61b90c9c26d3cd130a8bd66343dd3b937d9a026
lacerda92/exercicios-python
/ex006 dobro, triplo, raiz quadrada.py
883
4.46875
4
#crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada """numero =int(input('Digite um número: ')) print('O dobro do número {} é:'.format(numero),numero*2,'o triplo do número {} é:'.format(numero),numero*3,'e a raiz quadrada ' 'do número {} é:'.format(numero),numero**(1/2))""" #outra maneira de realizar essa tarefa numero =int(input('Digite um número: ')) dobro = numero*2 triplo = numero*3 raiz2 = numero**(1/2) print("O dobro é igual {}, \nO triplo é igual {} \nE a raiz quadrada é igual a {:.2f}".format(dobro,triplo,raiz2)) #o codigo .2f serve para indicar duas casas após a vírgula, é um comando float # \n serve para pular uma linha! # a raíz quadrada também pode ser calculada com a função pow #exemplo usand pow print('A raíz cubida do numero {} é igual a: {:.2f}. '.format(numero,pow(numero,1.3)))
false
c0e767dbe4dabed49825837b566aca5163cb1f31
lacerda92/exercicios-python
/ex008 conversor de medidas.py
595
4.25
4
#escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros """metros = int(input('Digite a distância em metros: ')) centimetros = metros*100 milimetros = metros*1000 print('A distância é de: {} centimetros. A distância é de: {} milimetros'.format(centimetros, milimetros))""" #outra forma de realização a atividade metros = float(input('Digite a distância em metros: ')) centimetros = metros*100 milimetros = metros*1000 print('A distância é de: {} centimetros. \nA distância é de: {} milimetros.'.format(centimetros,milimetros))
false
345c9420ffc96da1bbee2fc3dd388706dd67084c
Clevercav/Python-Projects
/Text/Palindrome/main.py
406
4.28125
4
def main(): print() print("Is your input a palindrome? Let's find out") while(True): value = input("Enter your word: ") palindrome(value.lower()) def palindrome(value): if(value == reverse_string(value)): print("It is!") return print("Unfortunatly not...") return def reverse_string(x): return x[::-1] if __name__ == '__main__': main()
true
5af80574c937760d8f23153225ce9f527b638740
dskripka/test_repo
/src/HW12/task_12_02.py
866
4.25
4
#Создать класс MyTime. Атрибуты: hours, minutes, seconds. # Методы: переопределить магические методы сравнения, # сложения, вычитания, умножения на число, вывод на экран. # Перегрузить конструктор на обработку входных параметров # вида: одна строка, три числа, другой объект класса # MyTime, и отсутствие входных параметров. from datetime import datetime, date, time, timedelta def main(): class MyTime: def __init__(self, hours, minutes, seconds): self.hours = hours self.minutes = minutes self.seconds = seconds my_time = MyTime(10, 20, 55) if __name__ == '__main__': main()
false
ae7fef963475f5088af4c737015610cd83b1ec76
dskripka/test_repo
/src/HW09/task_9_2.py
553
4.125
4
#Создать lambda функцию, которая принимает на вход #неопределенное количество именных аргументов и выводит #словарь с ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} def my_func(**kwargs): old_dict = kwargs for key, value in old_dict.items(): new_dict = {key * 2: value for key, value in old_dict.items()} print(new_dict) my_func(abc = 1, defgh = 2, ijkl = 3, mno = 4, pqrs = 5, tu = 6, xy = 7, z = 8)
false
3e97e9ef419a4a43d9a3df807915e70aba95e524
arnoldvaz27/PythonInterviewQuestions
/Programs/armstrongnumber.py
263
4.25
4
def armstrongNumber(arm): number = 0 for x in arm: number = number + (int(x) ** 3) print("The given number is armstrong" if number == int(arm) else "The given number is not armstrong") arms = input("Enter a number: ") armstrongNumber(arms)
true
b7befc3ab7571c2e821b9fffad0b879ec22211c8
ChloeL19/CNN-pset
/Staff_Code/less_comfy/CIFAR_preprocessing_staff.py
1,732
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 24 11:56:47 2018 @author: chloeloughridge """ # FOR STAFF # first, let's import keras import keras # for visualizing data we need this: import matplotlib.pyplot as plt # for working with matrices of numbers import numpy as np # Keras has the cifar10 dataset preloaded. Yay for us! from keras.datasets import cifar10 # a function for preprocessing the cifar10 dataset def preprocess_cifar(verbose=True): # import cifar10 data from keras (X_train, Y_train), (X_test, Y_test) = cifar10.load_data() if verbose == True: # visualize an image print("The shape of each image: {}".format(X_train[0].shape)) print("An example training image:") plt.imshow(X_train[0]) plt.show() # we need to normalize the X data before feeding into our model X_train = X_train/255 # divide by max value of pixel values to put in range 0 to 1 X_test = X_test/255 # we also need to convert the Y data into one-hot vectors num_classes = 10 Y_train = keras.utils.to_categorical(Y_train, num_classes) # may want to explain this more clearly [background] Y_test = keras.utils.to_categorical(Y_test, num_classes) # for interpretation purposes, create a dictionary mapping the label numbers # to image labels num_to_img = { 0:"airplane", 1:"automobile", 2:"bird", 3:"cat", 4:"deer", 5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck" } if verbose == True: print("Label: {}".format(num_to_img[np.argmax(Y_train[0])])) return (X_train, Y_train), (X_test, Y_test), num_to_img
true
e8779407b71f6508958f362b0dbe15b2bae30798
its-Kumar/Python.py
/3_Strings/string_rotations.py
651
4.3125
4
def rotate(string): """ Rotate the given string 'str' INPUT : "Hello" OUTPUT : "elloH" """ string = list(string) temp = string.pop(0) string.append(temp) return "".join(string) def string_rotations(string): """ INPUT : "Hello" <String> OUTPUT: ['elloH', 'lloHe', 'loHel', 'oHell', 'Hello'] """ lst = [] for i in range(len(string)): string = rotate(string) lst.append(string) return lst s = input("Enter any string : ") print("You have entered : ", s) rotations = string_rotations(s) print("\nThe rotations are : ") print(rotations)
true
8646a7fee0daa6f8f303f3beb272dbad2a05fe21
its-Kumar/Python.py
/1_Numbers/Strange_root.py
489
4.25
4
""" A strange root is a number whose squar and squar root share any digit. INPUT : 11 OUTPUT : True """ def is_strange_root(n: int) -> bool: sqrt = n ** 0.5 sqrt = str(sqrt).split(".")[1] sqr = n ** 2 sqr = str(sqr).split(".")[0] print(sqr, sqrt) for d in sqr: if d in sqrt: return True return False if __name__ == "__main__": num = int(input("Enter any number : ")) print(is_strange_root(num))
false
0ca039633fd5479dfcef6fe2a85e14d5d5992e82
lancezlin/Python-Program
/calSpam.py
1,104
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 22:40:33 2015 Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475 When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating point number on the line. Count these lines and the compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence. @author: Lance """ fileName = raw_input('Please type a file name here: \n') try: openFile = open(fileName) count = 0 total = 0 avgSpam = None for line in openFile: line.rstrip().lstrip() if line.startswith('X-DSPAM-Confidence:'): startPoint = line.find(':') endPoint = len(line) spams = line[startPoint+2:endPoint] count = count + 1 total = total + float(spams) avgSpam = total/count else: continue print count, total, avgSpam except: print 'Cannot open the file'
true
3327595f90d158ae1601b8a8d54bf8ceb34a30ae
lancezlin/Python-Program
/piglatin.py
1,737
4.125
4
#Pig Latin #Pig Latin is a game of alterations played on the English language game. #To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed #(Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. #For words that begin with vowel sounds or silent letter, you just add "way" (or "wa") to the end. #isalpha def pigLatin (original): #original = raw_input("please input:") word = original.lower() vowel = "way" consonant = "ay" first = word[0] if len(word) > 0: if first.isalpha() == True: if first in "aeiou": #newWordVowel = str(word) + str(vowel) newWordVowel = word + vowel print newWordVowel else: #newWordConsonant = str(word[1:]) + str(first) + str(consonant) newWordConsonant = word[1:] + first + consonant print newWordConsonant else: print "character only" else: print "Empty" original = raw_input("please input:") pigLatin (original) """ if len(word) > 0 and first.isalpha() == TRUE: if first in "aeiou": #newWordVowel = str(word) + str(vowel) newWordVowel = word + vowel print newWordVowel else: #newWordConsonant = str(word[1:]) + str(first) + str(consonant) newWordConsonant = word[1:] + first + consonant print newWordConsonant elseif len(word) > 0 and first.isalpha() == FALSE: print "character only" else: print "Empty" # not alpha """
true
0ffbbe8c8f7d597803f4e3421fe64a3860dd5fa9
lancezlin/Python-Program
/readFile.py
388
4.28125
4
# -*- coding: utf-8 -*- """ Write a program to read through a file and print the contents of the file (line by line) all in upper case. @author: lancezlin """ fname = raw_input('Type a file name to read: \n') try: openFile = open(fname) for line in openFile: line = line.upper().rstrip().lstrip() print line except: print 'File cannot be opened!' exit()
true
6182cfbce62af7c4a399a5fab835340437ba4dcc
mateusz-buczek/search_algorithms
/linear_search.py
1,071
4.15625
4
from random import randrange, randint, choice # generating up to 20 random numbers(0-1000) so there's something to sort data = [randint(0, 1000) for item in range(randrange(20))] print(f'Generated {len(data)} random numbers: {data}') """ Wanting to see both cases work without rerunning program ad infinitum uncomment target based on choice function and comment out the randint one """ target = randint(0, 1000) # target = choice(data) def linear_sort(data, target): # take data in form of list, and wanted number as arguments result = [] # create list collecting indices of searched number for index in range(len(data)): # iterate through input data indices if data[index] == target: # check if it matches searched number, add its index to list if it does result.append(index) if result: # return created list, or "not found" if empty return print(f"{target} found in following indices: {result}.") else: return print(f"{target} not found in {data}.") linear_sort(data, target)
true
dc9c1e5314398b69b6a2840cb193b874f461f150
SiTh08/gaming_list
/userinterface.py
2,637
4.1875
4
from run import * print('Welcome to games listing! What would you like to do?') while True: print('Option 1: Add a game to the listing.') print('Option 2: View all games.') print('Option 3: View one game.') print ('Exit.') userinput = input('Which option would you like to choose? ').strip().lower() if userinput == 'option 1': gamename = input('What is your game called?').strip() genre = input('What is the genre of the game?').strip() platform = input('How can you play the game?').strip() price = input('How much does the game cost?').strip() phone = input('What is your phone number?').strip() location = input('What is your postcode?').strip() edprice = float(price) games.create("'{}'".format(gamename), "'{}'".format(genre), "'{}'".format(platform), "'{}'".format(edprice), "'{}'".format(phone), "'{}'".format(location)) games.updatelongnlat2("'{}'".format(gamename)) print(f'{gamename} has been added.') more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break else: print('Please annswer with yes or no.') more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break elif userinput == 'option 2': games.readall() more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break else: print('Please annswer with yes or no.') more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break elif userinput == 'option 3': pickID = input('What is the ID of the game you would like to view? ') games.readone(pickID) more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break else: print('Please annswer with yes or no.') more = input('Would you like to do anything else? ').strip().lower() if more == 'yes': continue elif more == 'no': break elif userinput == "exit": break else: print('Please answer with option 1 or option 2 or option 3.') continue
true
d7751041b6babab85ef9ae6f495af569d5200e24
JHS1790/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,308
4.53125
5
#!/usr/bin/python3 """File for class Square""" class Square: """class to build a square Attributes: size (int): size of the square position (tuple): position of the square down and right """ def __init__(self, size=0): """__init__ function for the Square class Args: size (int): size of the square, attribute assignment position (tuple): position of the square, attribute assignment """ self.size = size @property def size(self): """int: size of the square""" return self.__size @size.setter def size(self, value): """ Raises: TypeError: if value is not an int ValueError: if value is less than zero """ if not isinstance(value, int): raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value def area(self): """method to find area of square""" return self.size * self.size def my_print(self): """method to print square""" for x in range(self.size): for y in range(self.size): print("#", end="") print() if self.size == 0: print()
true
cfb17051b5d058147650f2f760d5399e21fe69ef
lucas-silvs/Curso-Guanabara
/Mundo - 2/Ex 37 - base numerica.py
441
4.28125
4
num= int(input('Digite um número:\n')) choice = int(input("Escolha uma base de conversão\n1-binário\n2-octal\n3-hexadecimal:\n")) if(choice==1): b=bin(num)[2:] print(f'O Número {num} convertido para binário ficara: {b}') elif(choice==2): print(f'O Número {num} convertido para binário ficara: {oct(num)[2:]}') elif (choice == 3): print(f'O Número {num} convertido para binário ficara: {hex(num)[2:]}')
false
24a6115cc43f0951fdf1c75584cc4a950830f780
sonzza/lessons
/pythonlessons/Lesson_4_part_2.py
378
4.28125
4
# Создайте функцию, принимающую на вход 3 числа и возвращающую наибольшее из них. def max_func(): numbers = [] for i in range(3): number = int(input("Введите число: ")) numbers.append(number) return max(numbers) print('Максимальное число', max_func())
false
96f3239a075b5b3092e0e9ba06a9bd9aed971aa0
okdarnoc/Python_Regex_Tool
/regex.py
1,661
4.71875
5
# The line import re, re is a python library which allow python to carry out regular expression operations. import re # Tin is a customize name, we use tin to be a variable to open 'input.txt', input.txt must be located with the same folder as the script. # The reason of doing this is simple, if we don't open a file, we cannot read or write. tin=open('input.txt',"r",encoding="utf-8") # Tout is a customize name, we use tin to be a variable to open 'output.txt', input.txt must be located with the same folder as the script. # The reason of doing this is simple, if we don't open a file, we cannot read or write. tout=open('output.txt',"w",encoding="utf-8") # tintext is a customize name, we use tintext to be a variable to read tin (The read() method returns the specified number of bytes from the file). tintext=tin.read() # x is a customize name, we use x to store the results of re.sub manipulation of the data in tintext. # There are 3 input in re.sub # 1. Pattern [Recognized Pattern] # 2. Replacement Patter [Replacement Patter, repl] # 3. The input [String] # In our function x, we are telling them we want to look for a pattern r"\[(.*)\]\n(.*)" in tintext and replace it with pattern r"\1 \2" x= re.sub(r"\[(.*)\]\n(.*)", r"\1 \2", tintext) # Once we have finished all the operation, its store in the computer's ram, we have to ask the computer to store it into the file we want. # Threfore we have to use the function write. # This line basically means in tout we erase whats on there and write x to it. X is the result of re.sub manipulation of the data in tintext. tout.write(x) # Here we close our files. tin.close() tout.close()
true
86cd748e9cdcbc929de15cc1307afcf7bc25c8ac
Fleid/LearnPythonTheHardWay
/Exercise01-26/Exercise05 - More Variables/ex5.py
765
4.3125
4
# cd ~/Documents/GitHub/LearnPythonTheHardWay/Exercise05\ -\ More\ Variables/ # -*- coding: utf-8 -*- my_name = 'Florian Eiden' my_age = 35 my_height = 193.5 #cms my_weight = 110 #kgs my_eyes = 'Brown' my_hair = 'Brown' print "Let's talk about %s." % my_name print "He's %s cms tall USING S." % my_height # Will cast the float in string print "He's %d cms tall USING D." % my_height # Will cast the float in int print "He's %r cms tall USING R." % my_height # Will show the float anyway print "He's %f cms tall USING F." % my_height # Will show the float in full print "He's %d kgs heavy." % my_weight print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
true
00960ad4c347e07f01be82e8423be40daf3d14e6
JackSnowdon/word_sorter
/run.py
2,416
4.34375
4
wordarray = ['Hello World', 'Goodbye World', 'World Gossip', 'Doll Loop Hell Teeth'] def sort_words(array): """ Takes Array of strings Reverses the order Then checks each word in string, any repeated letters are both replaced with '*' by turning the word into a list, replacing letters and using join() Returns Sorted Array of Strs """ sortedwords = [] for word in wordarray: rev_w = ' '.join(reversed(word.split(' '))) last_letter = '' for i, l in enumerate(rev_w): if l == last_letter: listed_word = list(rev_w) listed_word[i-1] = '*' listed_word[i] = '*' rev_w = ''.join(listed_word) last_letter = l sortedwords.append(rev_w) return sortedwords def add_word(): word = input("Type word to add to array: ") if word.isdigit(): print("Input needs to be string!") add_word() print(f"Added '{word}'") wordarray.append(word) check() def remove_word(): for i, word in enumerate(wordarray): print (f"{i+1}: {word}") choice = input("Type number to delete or 'b' to go back: " ) if choice.isdigit(): try: to_delete = wordarray[int(choice) - 1] print(f"Revmoed {to_delete} from Array") wordarray.remove(to_delete) check() except: print("Not a valid selection") remove_word() elif choice == 'b': check() else: print("Not an int selection") remove_word() def check(): print(f"Current Words: {wordarray}") cmd = input("Type 'add' or 'remove' to work with array, or 'run' to start task ('q' to quit): ") if cmd == 'run': result = sort_words(wordarray) print(f"Returned Words: {result}") again = input("Run Again y/n: ") if again == 'y': check() else: print("Thanks for using the word checker!") elif cmd == 'add': add_word() elif cmd == 'remove': remove_word() elif cmd == 'q': print("Thanks for using the word checker!") else: print(f"'{cmd}' not valid entry") check() check() """ This task was more suited to my python skills, resulting in neater code. To refactor I would look at quicker way to replace the letters without creating a new list. """
true
4112aba3cb813a8b88fa0c69641f0b74c75f4d69
AlvaroArratia/curso-python
/manejo de errores/excepciones.py
1,596
4.40625
4
# Manejo de excepciones """ try: # Para el control de errores de un codigo susceptible a ellos nombre = input("Ingresa tu nombre: ") if nombre == "asd": nombre_usuario = nombre print(nombre_usuario) except: # Si es que ocurre un error print("Ha ocurrido un error al obtener el nombre.") else: # Si es que no ocurre un error print("Todo ha funcionado correctamente.") finally: # Cuando termina la instruccion completa print("Fin del bloque de codigo.") """ # Multiples excepciones """ try: numero = int(input("Ingrese un numero para elevarlo al cuadrado: ")) print("El cuadrado es: " + str(numero**2)) except TypeError: # Para mostrar una respuesta al error de tipo TypeError print("Debes convertir cadenas de texto a entero.") except ValueError: # Para mostrar una respuesta al error de tipo ValueError print("Debes ingresar solo numeros.") except Exception as err: # Para obtener el error en especifico print("Ha ocurrido un error: ", type(err).__name__) # Para obtener el nombre del tipo de error else: print("Todo ha funcionado correctamente.") finally: print("Fin del bloque de codigo.") """ # Excepciones personalizadas o lanzar excepcion try: nombre = input("Ingresa tu nombre: ") edad = int(input("Ingresa tu edad: ")) if edad < 5 or edad > 110: raise ValueError("La edad introducida no es real.") elif len(nombre) <= 1: raise ValueError("El nombre no esta completo.") else: print(f"Bienvenido {nombre}!!") except ValueError: print("Introduce los datos correctamente.")
false
900424c69af17fb1364e9fb21a40db3cb8c99d35
mskyberg/Module6
/more_functions/inner_functions_assignment.py
1,140
4.5625
5
""" Program: inner_functions_assignment.py Author: Michael Skyberg, mskyberg@dmacc.edu Last date modified: June 2020 Purpose: demonstrate the use of inner functions """ def measurements(m_list): """ calculate the area and perimeter of a rectangle or square :param m_list: list of length and width values :returns: string of calculated perimeter and area """ def area(a_list): """ calculate thea area :param a_list: list of length and width values :returns: calculated perimeter float """ if len(a_list) == 2: return a_list[0] * a_list[1] else: return a_list[0] * a_list[0] def perimeter(p_list): """ calculate the perimeter :param p_list: list of length and width values :returns: calculated perimeter float """ if len(p_list) == 2: return 2 * (p_list[0] + p_list[1]) else: return 4 * (p_list[0]) return f'Perimeter = {perimeter(m_list)} Area = {area(m_list)}' if __name__ == '__main__': print(measurements([20.1, 30.4])) print(measurements([108.89]))
true
b834c14861457187b272ca8b02bce828a0c51f03
patdriscoll61/Practicals
/Practical01/Workshop02/taskThree.py
368
4.125
4
# Discount Calculator DISCOUNT_PERCENT = .20 # .2 is 20% def main(): full_price = float(input("Enter Full Price: ")) discounted_price = calculate_discount(full_price) print("Discounted Price: ", discounted_price) def calculate_discount(full_price): discounted_price = full_price - full_price * DISCOUNT_PERCENT return discounted_price main()
true
5d5a02ff6ce4f8dfeb71403791a2cade54ab4a3f
patdriscoll61/Practicals
/Practical01/Practical07Ext/drivingSimulator.py
1,603
4.21875
4
""" Driving Simulator as per Extension WorkPrac 07 """ from Practical07.car import Car def main(): print("Let's drive!") # name = "The bomb" name = input("Enter your car name: ") fuel = 100 car = Car(fuel, name) choice = "" while choice != "Q": print("{}, fuel={}, odo={}".format(car.name, car.fuel, car.odometer, )) showmenu() choice = input("Enter your choice: ").upper() if choice == "D": ran_out_of_fuel = False km = int(input('How many km do you want to drive? ')) while km < 0: print("Distance must be >= 0") km = int(input('How many km do you want to drive? ')) if km > car.fuel: km = car.fuel ran_out_of_fuel = True car.drive(km) print("The car drove {}km {}.".format(km,"and ran out of fuel" if ran_out_of_fuel else "")) elif choice == "R": fuel_to_add = int(input("How many units of fuel do you want to add to the car? ")) while fuel_to_add < 0: print("Fuel amount must be >= 0") fuel_to_add = int(input("How many units of fuel do you want to add to the car? ")) car.add_fuel(fuel_to_add) print("Added {} units of fuel.".format(fuel_to_add)) else: if choice != "Q" print("Invalid choice") print("") print("Good bye {}'s driver.".format(car.name)) def showmenu(): print("Menu:") print("d) drive") print("r) refuel") print("q) quit") main()
true
aece4d487cbd2b68666d058f119fccebb1df9f61
zendfly/DailyCode_python
/python3_grammar/静态属性.py
1,202
4.3125
4
""" 静态属性 @property,将class中方法变成数据属性。隐藏中间的处理过程 当类调用方法时(不创建实例时,调用类中的方法) @classmethod,变成类使用的方法,自动传递参数 @staticmethod,静态方法只是名义上归属类管理,不能使用变量和实例变量,是类的工具包 """ class Student(): targ = 'targe' def __init__(self,a,b,c): self.a = a self.b = b self.c = c @property #变成数据属性 def add_a(self): return self.a + self.b @classmethod #将方法变成类方法,自动传递参数 def teat_a(cls): print(cls) print(cls.targ) @staticmethod #静态方法, def wash_baby(): print('test') if __name__ == '__main__': """ 将方法变成类的数据属性,可以直接调用 """ s = Student(1,2,3) print(s.add_a) #经过property装饰器后,和调用class的数据属性一样 print(s.a) print(s.b) """ 将方法变成类方法 """ Student.teat_a() #使用classmethood后,可以不用将class实例化(创建实例)后进行直接调用
false
d0b3fa6666cff67adbfc1fd02099f1188c09e266
zendfly/DailyCode_python
/cookbook/iterator_types.py
1,674
4.1875
4
# encoding:utf-8 """ @time:2021/9/121:08 @desc: 迭代器 """ # list、tuple、dict、set都是可迭代的对象,可以从他们中获取迭代器(iterator), # 即:可以使用iter()方法来获取迭代器: 使用 iter() list_a = iter([1, 2, 3, 4, 5]) tuple_a = iter((1, 2, 3, 4, 5)) dict_a = iter({1: 1, 2: 2, 3: 3, 4: 4, 5: 5}) set_a = iter({1, 2, 3, 4, 5}) for i in range(5): print(next(list_a)) print(next(tuple_a)) print(next(dict_a)) print(next(set_a)) # 同样的字符串也能使用iter()方法获取迭代器 string_a = iter('abcdef') for i in range(5): print(next(string_a)) """ 创建迭代器 必须包含__iter__()、__next__()两个方法,他们两个共同组成迭代器协议,具体作用: __iter__():返回迭代器对象本身; __next__():从容器中返回下一项,如果已经没有任何返回,则会引发StopIteration异常。 """ # 创建一个返回数字的迭代器,从1开始,然后每个序列加1(例如:1,2,3,4,5...) class Itera_pratice(): def __init__(self): pass def __iter__(self): self.a = 1 return self # 返回本身 def __next__(self): if self.a < 20: x = self.a self.a += 1 return x else: # 在迭代的停止条件满足时,使用StopIteration,即:可以使用StopIteration语句来表明迭代完成 raise StopIteration itera_p = iter(Itera_pratice()) # 同样的需要使用iter()方法 for i in range(6): print(f"迭代器练习:{next(itera_p)}")
false
4137b0cc74c77ebdd270ab37e1de5f7769a927ef
caiopg/random-text-generator
/randomtextgenerator.py
519
4.25
4
import wordgenerator NUMBER_OF_WORDS = int(input("How many random words do you want? ")) NUMBER_OF_LETTERS = int(input("How many letters do you want the random words to have? ")) user_options = list() for i in range(0 , NUMBER_OF_LETTERS): user_choice = input("What letter " + str(i + 1) + " do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ") user_options.append(user_choice) for i in range(0, NUMBER_OF_WORDS): word = wordgenerator.assemble_word(user_options) print(word)
true
799ba73ef12c889bbb2bc95d6e587dbd8739e701
KingShark1/APP_CLASS
/Assignment_2/ques_1.py
249
4.125
4
given_tuple = (('Red','White','Blue'),('Green','Pink','Purple'),('Orange','Yellow','Lime')) #to find a tuple in list of tuple find_tuple = 'White' for i in range(len(given_tuple)): if find_tuple in given_tuple[i]: print("tuple exists")
true
00ccfd028b6a61e6f889af9eb12cba3a5de69cfa
Beautyi/PythonPractice
/Chapter5-Practice/ex_5_9.py
317
4.1875
4
#处理没有用户的情形 names = [] if names: for name in names: if name == 'admin': print("Hello,admin,would you like to see a statues report?") else: print("Hello " + name + "," + "thank you for logging in again.") else: print("We need to find some uesers!")
true
fa5a3f118e77ea9b4b21f0da2c48967b3eb766c8
Beautyi/PythonPractice
/Chapter3-Practice/ex_3_8.py
345
4.125
4
cities = ['dali', 'hangzhou', 'xian', 'guilin', 'chengdu'] print(cities) print(sorted(cities)) print(cities) print(sorted(cities,reverse=True)) print(cities) cities.reverse()#反向打印 print(cities) cities.reverse()#恢复 print(cities) cities.sort()#按字母排序 print(cities) cities.sort(reverse=True)#按反向字母排序 print(cities)
false
55493cf972ef09b5696acee8a5d943bf301e44eb
Beautyi/PythonPractice
/Chapter7-Practice/test_7.1.3.py
350
4.40625
4
#求模运算符,%返回余数 print(4 % 3) print(5 % 3) print(6 % 3) print(7 % 3) #求一个数是奇数还是偶数 number = input("Entre a number, and I will tell you it is even or odd: ") int_number = int(number) if int_number % 2 == 0: print("\nThe number " + number + " is even." ) else: print("\nThe number " + number + " is odd.")
false
93ee89f3b1f831ec99658f453c29c4b3d424a961
Beautyi/PythonPractice
/Chapter4-Practice/test_4.4.2.py
247
4.34375
4
names = ['Jack', 'Jobs', 'Tom', 'Martin', 'Ava', 'Zoe', 'Rose'] print("Here are the first three players on my team:") for name in names[:3]:#遍历切片 print(name.title()) # Here are the first three players on my team: # Jack # Jobs # Tom
false
93f13c3f9d0a9a3f55156dab9f96e009d02f05a6
y0g1bear/Character-Distribution
/distribution.py
1,749
4.28125
4
""" distribution.py Author: John Warhold Credit: dan, andy Assignment: Write and submit a Python program (distribution.py) that computes and displays the distribution of characters in a given sample of text. Output of your program should look like this: Please enter a string of text (the bigger the better): The rain in Spain stays mainly in the plain. The distribution of characters in "The rain in Spain stays mainly in the plain." is: iiiiii nnnnnn aaaaa sss ttt ee hh ll pp yy m r Notice about this example: * The text: 'The rain ... plain' is provided by the user as input to your program. * Uppercase characters are converted to lowercase * Spaces and punctuation marks are ignored completely. * Characters that are more common appear first in the list. * Where the same number of characters occur, the lines are ordered alphabetically. For example, in the printout above, the letters e, h, l, p and y both occur twice in the text and they are listed in the output in alphabetical order. * Letters that do not occur in the text are not listed in the output at all. """ we = input("Please enter a string of text (the bigger the better): ") harambe = ('The distribution of characters in "' + we + '" is:') print(harambe) we = we.lower() letters = [] alph = ('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') for e in alph: school = we.count(e) if not school == 0: letters.append(e*school) for l in range(26): jum = 0 while jum < len(letters)-1: if len(letters[jum]) < len(letters[jum+1]): wax = letters[jum] letters[jum]= letters[jum+1] letters[jum+1] = wax jum +=1 for g in letters: print(g)
true
5384341b99c9da044a9e96cedfc22417d1f12d66
salma1415/Project-Euler
/022 Names scores/022.py
2,038
4.21875
4
''' Names scores ================================================== Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? ''' import string alphabet_list = list(string.ascii_uppercase) def extract_names_from(file_path): """ الدالة تقوم باستخراج الاسماء من الملف المعطى """ names = None with open(file_path) as file: # name[1:-1] حتى لا ندرج علامات التنصيص فى الاسم names = [name[1:-1] for name in file.read().split(',')] # ترتيب الاسماء ابجديا دون الحاجة لانشاء مجموعة جديدة names.sort() return names def calc_names_in_file(path): """ الدالة تقوم بارجاع مجموع الارقام الموافقة لكل اسم فى الملف المعطى """ names_list = extract_names_from(path) sum_file = 0 for rank, name in enumerate(names_list): # مجموع ترتيب حروف الاسم name_total = 0 for letter in name: # اضف واحد لان الترتيب يبدا من رقم صفر # بينما الترتيب فى السئال يبدأ من رقم 1 name_total += (alphabet_list.index(letter) + 1) # اضف واحد لان الترتيب يبدا من رقم صفر # بينما الترتيب فى السئال يبدأ من رقم 1 sum_file += name_total * (rank + 1) print(sum_file) calc_names_in_file('./names.txt')
false
eb21eb25178dcc6ea7fa88e493686dbd25a846e1
BenDeb/LearnPython
/python-fonctions/parametres_defaut.py
646
4.15625
4
#!/usr/bin/python3 # Il est possible de définir des paramètres par défaut dans une fonction. ces derniers sont utilisés si l'utilisateur ne rentre aucun paramètre. Cela n'empêche pas l'utilisateur d'entrer des paramètres différents des paramètres par défaut. def fonction_defaut(a=5, b=10): print(a, " + ", b, " = ", a + b) #fonction_defaut() #5 + 10 = 15 #fonction_defaut(10,20) #10 + 20 = 30 fonction_defaut(7,8) #7 + 8 = 15 #En définissant une fonction du meme nom, on écrase la fonction précédente : def fonction_defaut(a=5, b=10): print(a, " * ", b, " = ", a * b) fonction_defaut(7,8) #7 * 8 = 56
false
42de7a41adb2076473582dc41813f7118c2d5d08
dmaynard24/hackerrank
/python/algorithms/implementation/between_two_sets/get_total_x.py
2,186
4.25
4
# Between Two Sets # You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions: # The elements of the first array are all factors of the integer being considered # The integer being considered is a factor of all elements of the second array # These numbers are referred to as being between the two arrays. You must determine how many such numbers exist. # For example, given the arrays a = [2, 6] and b = [24, 36], there are two numbers between them: 6 and 12. 6 % 2 = 0, 6 % 6 = 0, 24 % 6 = 0 and 36 % 6 = 0 for the first value. Similarly, 12 % 2 = 0, 12 % 6 = 0 and 24 % 12 = 0, 36 % 12 = 0. # Function Description # Complete the get_total_x function in the editor below. It should return the number of integers that are betwen the sets. # get_total_x has the following parameter(s): # a: an array of integers # b: an array of integers # Input Format # The first line contains two space-separated integers, n and m, the number of elements in array a and the number of elements in array b. # The second line contains n distinct space-separated integers describing a[i] where 0 <= i < n. # The third line contains m distinct space-separated integers describing b[i] where 0 <= j < m. # Constraints # 1 <= n, m <= 10 # 1 <= a[i] <= 100 # 1 <= b[j] <= 100 # Output Format # Print the number of integers that are considered to be between a and b. # Sample Input # 2 3 # 2 4 # 16 32 96 # Sample Output # 3 # Explanation # 2 and 4 divide evenly into 4, 8, 12 and 16. # 4, 8 and 16 divide evenly into 16, 32, 96. # 4, 8 and 16 are the only three numbers for which each element of a is a factor and each is a factor of all elements of b. def get_total_x(a, b): factor_count = 0 potential_factor = a[-1] while potential_factor <= b[0]: is_multiple = True is_factor = True for i in range(len(a) - 1): if potential_factor % a[i] != 0: is_multiple = False break for i in range(len(b)): if b[i] % potential_factor != 0: is_factor = False break if is_multiple and is_factor: factor_count += 1 potential_factor += a[-1] return factor_count
true
b11b165df5fc4b5ae9fd39145584c20e034b939f
dmaynard24/hackerrank
/python/algorithms/implementation/migratory_birds/migratory_birds.py
2,510
4.5
4
# Migratory Birds # You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings. Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number. # For example, assume your bird sightings are of types arr = [1, 1, 2, 2, 3]. There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1. # Function Description # Complete the migratory_birds function in the editor below. It should return the lowest type number of the most frequently sighted bird. # migratory_birds has the following parameter(s): # arr: an array of integers representing types of birds sighted # Input Format # The first line contains an integer denoting n, the number of birds sighted and reported in the array arr. # The second line describes arr as n space-separated integers representing the type numbers of each bird sighted. # Constraints # 5 <= n <= 2 x 10^5 # It is guaranteed that each type is 1, 2, 3, 4, or 5. # Output Format # Print the type number of the most common bird; if two or more types of birds are equally common, choose the type with the smallest ID number. # Sample Input 0 # 6 # 1 4 4 4 5 3 # Sample Output 0 # 4 # Explanation 0 # The different types of birds occur in the following frequencies: # Type 1: 1 bird # Type 2: 0 birds # Type 3: 1 bird # Type 4: 3 birds # Type 5: 1 bird # The type number that occurs at the highest frequency is type 4, so we print 4 as our answer. # Sample Input 1 # 11 # 1 2 3 4 5 4 3 2 1 3 4 # Sample Output 1 # 3 # Explanation 1 # The different types of birds occur in the following frequencies: # Type 1: 2 # Type 2: 2 # Type 3: 3 # Type 4: 3 # Type 5: 1 # Two types have a frequency of 3, and the lower of those is type 3. def migratory_birds(arr): bird_counts = {} largest_count = 0 largest_id = None for bird in arr: bird_counts[bird] = bird_counts.get(bird, 0) + 1 if bird_counts[bird] > largest_count or (bird_counts[bird] == largest_count and bird < largest_id): largest_count = bird_counts[bird] largest_id = bird return largest_id
true
59a88a3409293d467bcbc7c6af87011df8066b32
dmaynard24/hackerrank
/python/algorithms/warmup/birthday_cake_candles/birthday_cake_candles.py
1,617
4.375
4
# Birthday Cake Candles # You are in charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out. # For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are 2 such candles. # Function Description # Complete the function birthday_cake_candles in the editor below. It must return an integer representing the number of candles she can blow out. # birthday_cake_candles has the following parameter(s): # ar: an array of integers representing candle heights # Input Format # The first line contains a single integer, n, denoting the number of candles on the cake. # The second line contains n space-separated integers, where each integer i describes the height of candle i. # Constraints # 1 <= n <= 10^5 # 1 <= ar[i] <= 10^7 # Output Format # Return the number of candles that can be blown out. # Sample Input 0 # 4 # 3 2 1 3 # Sample Output 0 # 2 # Explanation 0 # We have one candle of height 1, one candle of height 2, and two candles of height 3. Your niece only blows out the tallest candles, meaning the candles where height = 3. Because there are 2 such candles, we return 2. def birthday_cake_candles(ar): ar.sort(reverse=True) count = 1 while count < len(ar) and ar[count] == ar[0]: count += 1 return count
true
89bda00f9c9dd079f7cd1ae1a391609b1be7bd07
dmaynard24/hackerrank
/python/algorithms/warmup/mini_max_sum/mini_max_sum.py
1,768
4.25
4
# Mini-Max Sum # Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then return the respective minimum and maximum values as a single line of two space-separated long integers. # For example, arr = [1, 3, 5, 7, 9]. Our minimum sum is 1 + 3 + 5 + 7 = 16 and our maximum sum is 3 + 5 + 7 + 9 = 24. We would return # 16 24 # Function Description # Complete the mini_max_sum function in the editor below. It should return two space-separated integers on one line: the minimum sum and the maximum sum of 4 of 5 elements. # mini_max_sum has the following parameter(s): # arr: an array of 5 integers # Input Format # A single line of five space-separated integers. # Constraints # 1 <= arr[i] <= 10^9 # Output Format # Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.) # Sample Input # 1 2 3 4 5 # Sample Output # 10 14 # Explanation # Our initial numbers are 1, 2, 3, 4, and 5. We can calculate the following sums using four of the five integers: # If we sum everything except 1, our sum is 2 + 3 + 4 + 5 = 14. # If we sum everything except 2, our sum is 1 + 3 + 4 + 5 = 13. # If we sum everything except 3, our sum is 1 + 2 + 4 + 5 = 12. # If we sum everything except 4, our sum is 1 + 2 + 3 + 5 = 11. # If we sum everything except 5, our sum is 1 + 2 + 3 + 4 = 10. # Hints: Beware of integer overflow! Use 64-bit Integer. def mini_max_sum(arr): arr.sort() min_sum = 0 max_sum = 0 i = 0 for i in range(len(arr) - 1): min_sum += arr[i] max_sum += arr[-(i + 1)] return f'{min_sum} {max_sum}'
true
e0c41bb0ab12354257ac26ff0f53ccfa31a8039f
dmaynard24/hackerrank
/python/algorithms/warmup/simple_array_sum/simple_array_sum.py
867
4.4375
4
# Simple Array Sum # Given an array of integers, find the sum of its elements. # For example, if the array ar = [1, 2, 3], 1 + 2 + 3 = 6, so return 6. # Function Description # Complete the simple_array_sum function in the editor below. It must return the sum of the array elements as an integer. # simple_array_sum has the following parameter(s): # ar: an array of integers # Input Format # The first line contains an integer, n, denoting the size of the array. # The second line contains n space-separated integers representing the array's elements. # Constraints # 0 < n, ar[i] <= 1_000 # Output Format # Print the sum of the array's elements as a single integer. # Sample Input # 6 # 1 2 3 4 10 11 # Sample Output # 31 # Explanation # We print the sum of the array's elements: 1 + 2 + 3 + 4 + 10 + 11 = 31. def simple_array_sum(ar): return sum(ar)
true
ce7c5a0dc9b81f7e7834727570aa420eb6db3c1a
dmaynard24/hackerrank
/python/algorithms/implementation/divisible_sum_pairs/divisible_sum_pairs.py
1,526
4.15625
4
# Divisible Sum Pairs # You are given an array of n integers, ar = [ar[0], ar[1], ..., ar[n - 1]], and a positive integer, k. Find and print the number of (i, j) pairs where i < j and ar[i] + ar[j] is divisible by k. # For example, ar = [1, 2, 3, 4, 5, 6] and k = 5. Our three pairs meeting the criteria are [1, 4], [2, 3] and [4, 6]. # Function Description # Complete the divisible_sum_pairs function in the editor below. It should return the integer count of pairs meeting the criteria. # divisible_sum_pairs has the following parameter(s): # n: the integer length of array ar # ar: an array of integers # k: the integer to divide the pair sum by # Input Format # The first line contains 2 space-separated integers, n and k. # The second line contains n space-separated integers describing the values of ar = [ar[0], ar[1], ..., ar[n - 1]]. # Constraints # 2 <= n <= 100 # 1 <= k <= 100 # 1 <= ar[i] <= 100 # Output Format # Print the number of (i, j) pairs where i < j and ar[i] + ar[j] is evenly divisible by k. # Sample Input # 6 3 # 1 3 2 6 1 2 # Sample Output # 5 # Explanation # Here are the 5 valid pairs when k = 3: # (0, 2) -> ar[0] + ar[2] = 1 + 2 = 3 # (0, 5) -> ar[0] + ar[5] = 1 + 2 = 3 # (1, 3) -> ar[1] + ar[3] = 3 + 6 = 9 # (2, 4) -> ar[2] + ar[4] = 2 + 1 = 3 # (4, 5) -> ar[4] + ar[5] = 1 + 2 = 3 def divisible_sum_pairs(n, k, ar): pair_count = 0 for i in range(len(ar)): for j in range(i + 1, len(ar)): if (ar[i] + ar[j]) % k == 0: pair_count += 1 return pair_count
true
a208f1b93d09e29a7f2fb390e8e623c43e5bc66b
fsxchen/Algorithms_Python
/base.py
974
4.25
4
""" 基础的概念 """ """ 异或问题? 一个数组中,有一种数出现了奇数次,其他数出现了偶数次,怎么找到 """ def find_odd_num(A): res = 0 for i in A: res ^= i return res """ 把一个整型的数据右侧的1提取出来。 """ """ 一个数组中,有2种数出现了奇数次,其他数出现了偶数次,怎么找到 """ def find_odd_num2(A): n = len(A) res = 0 for i in A: res ^= i right_one = res & (~res + 1) only_one: int = 0 for i in range(n): if (i & right_one != 0): only_one ^= i return only_one, only_one^res """ 计算一个二进制数中,1的个数 """ def count1(num: list): count = 0 while num != 0: right_one = num & (~num + 1) num ^= right_one count += 1 return count if __name__ == "__main__": A = [1, 1, 1, 1, 2, 2, 2, 3, 3, 5, 6, 6] print(find_odd_num2(A)) print(count1(9))
false
5a3ea8b3c2fd861bc2b84b1310cfd3dece891fde
mauriciopssantos/PythonClassExercises
/w3resources/exercise12.py
433
4.34375
4
#12. Write a Python class named Student with two instances student1, student2 and assign given values to the said instances attributes. # Print all the attributes of student1, student2 instances with their values in the given format class Student: student_id = 29 student_name = "Mauricio" student1 = Student() student2 = Student() student2.student_name = "Diogo" print(student1.student_name) print(student2.student_name)
true
f08fb7c0986f8f6a3eace59b2a0c15cc82b97281
mauriciopssantos/PythonClassExercises
/w3resources/exercise23.py
608
4.21875
4
import numpy as np #11. Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle# class Circle: def __init__(self,r): self.r = r def areaCircle(self): self.area = np.pi * (self.r**2) return self.area def perimeterCircle(self): self.perimeter = 2*np.pi*self.r return self.perimeter c = Circle(5) c.areaCircle() c.perimeterCircle() print("The radius of your circle is {}\nThe area of your circle is {}\nThe perimeter of your circle is {}".format(c.r,c.area,c.perimeter))
true
bdde586ac65273209d9a8a76a45489e52a89d1c3
studyfree20/Mydictionary
/dictionary.py
1,970
4.1875
4
#collection that is unordered changeable and indexed #code begings here #For nested use nested_dict = { 'dictA': {'key_1': 'value_1'},'dictB': {'key_2': 'value_2'}} president={ "Name":"Hillary Clinton", "Age":30, "Residence":"Washington DC", "Position":"President", "Email":"hillary@statehouse.go.ke", "Phone no":+130657019935, } print (president) #code ends here:for integers dont add quotes #Accesing the dictionary x=president["Email"] print(x) #Also it can be print(president["Name"]) #Also it can be accessed using get() y=president.get("Phone no") print(y) w=president.get("Residence") print(w) a=president.get("Position") print(a) #changing values eg Position president["Position"]="Opposition Leader" print(president) #print(president["Julius Kirimi"]) #looping in a dictionary for presidents in president: print(president) for value in president.values(): print(value) #printing items with fields for m,n in president.items(): print (m,n) #cheking if a value exist if "Age"in president: print('Age is an available field in your dictionary' ) if "Phone no" in president: print('Phone is an available field in your dictionary' ) if "position" in president: print('Position is an available field in your dictionary' ) if "salary amount" not in president: print ('Salary field not found') else: print('Salary is found') #adding an item to dictionary eg ambassador president['ambassador']="Texas USA and California" print(president) president['Popularity']="77 percent" print(president) #remove item using pop() president.pop("Age") print (president) #5 more methods #copying dictionary g=president.copy() print(g) #length of dictionary print("len() method :", len(president)) # Finding a null item h=president.get("Last election number") print(h) # setting a default value r = president.setdefault("Kirimi") print(r) #getting a value print(president.get("Position")) #clearing a dictionary president.clear() print(president) #end
true
631ba283f5d55c27b5d6190ff0af57948ff0c3d1
dbaile6/leet.py
/phonebook.py
424
4.15625
4
phonebook_dict = { 'Alice': '703-493-1834', 'Bob': '857-384-1234', 'Elizabeth': '484-584-2923' } def phone_menu(): print "Electronic Phone Book" print "=" * 10 print "1. Look up an entry" print "2. Set an entry" print "3. Delete an entry" print "4. List all entries" print "5. quit" menu_choice = raw_input ("What do you want to do? 1-5") while menu_choice!= 5 print phone_menu()
true
17935326b8dc12c834e180cdad62e1d127b68796
Anjalibhardwaj1/Rock_Paper_Scissors
/RPC.py
1,425
4.46875
4
#Simple Rock, Paper, Scissors #January 7 2021 #Anjali Bhardwaj import random #Welcome meassage print('\nWelcome to Rock, Paper, Scissors!') #Play function def play(): #dictionaty for keys of rock, paper, scissors keys_ = {'r': 'rock', 'p': 'paper', 's': 'scissors'} #user input user = input("\nEnter 'r' for rock, 'p' for paper, 's' for scissors: ") #randomly generate computer choice computer = random.choice(['r', 'p', 's']) #if the user and computer choices are the same return tie if user == computer: return 'Computer guess the same thing. It is a tie.' #if the user wins, return "You Win!" if win(user, computer): print(f'The computer had chosen "{keys_[computer]}"...') return 'You Win!' #if the computer wins, return "You Lose!" print(f'The computer had chosen "{keys_[computer]}"...') return 'You lose...' #Function to check if computer wins def win(player, opponent): #return true if the player wins if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \ or (player == 'p' and opponent == 'r'): return True #Play until user does not want to anymore play_ = 'y' while play_.lower() == 'y': print(play()) play_ = input("Would you like to play again? (Y/N)") else: exit()
true
246ca323e3da183a639f7d2476a0e4f8155893f3
Gitprincesskerry/IS211_Assignment2
/IS211_Assignment2.py
2,098
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # This is Kerry Rainford's Week 2 Assignment import argparse parser = argparse.ArgumentParser() parser.add_argument("url", help = "url to obtain data from amazon", type=str) args = parser.parse_args() import logging logging.basicConfig(filename = "error.log", level = logging.ERROR, filemode = 'w') assignment2 = logging.getLogger() def downloadData(url=str): """This function downloads the contents located at the url and returns it to a caller""" import urllib2 response = urllib2.urlopen(url) html = response.read() return html from datetime import date import time def processData(html): """Takes the contents of the file as the first parameter, process the file line by line, and returns a dictionary. The dictionary maps a person's ID to a tuple (name, birthday)""" kerrylinebyline = html.split("\n") kerrydict = {} for x in range(1, len(kerrylinebyline)-1): ktempsplit = kerrylinebyline[x].split(',') ktempdate = ktempsplit[2].split("/") try: kerrydict[int(ktempsplit[0])] = (ktempsplit[1], date(int(ktempdate[2]), int(ktempdate[1]), int(ktempdate[0]))) except: assignment2.error("Error processing line# %d for ID# %s" %(x,ktempsplit[0])) return kerrydict def displayPerson(id=int, personData={}): """This function prints the name and birthday of a given user identified by the input ID""" dateStr = ("%d-%d-%d" %(personData[id][1].year,personData[id][1].month,personData[id][1].day)) print("Person #%d is %s with a birthday of %s" %(id,personData[id][0],dateStr)) def main(): try: csvData = downloadData(args.url) except: assignment2.error("There is a problem with the URL") personData = processData(csvData) search_for_id = raw_input("Please enter the Lookup ID:") while int(search_for_id) >0: displayPerson(int(search_for_id), personData) search_for_id = raw_input("Please enter the Lookup ID:") if __name__ == "__main__": main()
true
4c726c4aea381ad068f6b02e0713cb94b8b8f212
ylc0006/GTx-CS1301x-Introduction-to-Computing-using-Python
/5.2.3 Coding Exercise 2.py
1,243
4.375
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 18 14:17:00 2017 @author: yan.yl.chen """ #We've started a recursive function below called #exponentCalc(). It takes in two integer parameters, base #and expo. It should return the mathematical answer to #base^expo. For example, exponentCalc(5, 3) should return #125: 5^3 = 124. # #The code is almost done - we have our base case written. #We know to stop recursing when we've reached the simplest #form. When the exponent is 0, we return 1, because anything #to the 0 power is 1. But we are missing our recursive call! # #Fill in the marked line with the recursive call necessary #to complete the function. Do not use the double-asterisk #operator for exponentiation. Do not use any loops. # #Hint: Notice the similarity between exponentiation and #factorial: # 4! = 4! = 4 * 3!, 3! = 3 * 2!, 2! = 2 * 1 # 2^4 = 2 * 2^3, 2^3 = 2 * 2^2, 2^2 = 2 * 2^1, 2^1 = 2 * 2^0 def exponentCalc(base, expo): if expo == 0: return 1 else: return base * exponentCalc(base, expo-1) #The code below will test your function. It isn't used for #grading, so feel free to modify it. As originally written, #it should print 125. print(exponentCalc(5, 3))
true
e0dedd2026050375813299e86d140e6dd120c293
dipty-survase-automatonai/Python-Basic
/mul.py
249
4.21875
4
#!/usr/bin/python def multiplication(a,b,c=1,d=1): return a*b*c*d if __name__=='__main__': a=eval(input("enter a:")) b=eval(input("enter b:")) c=eval(input("enter c:")) d=eval(input("enter d:")) print("multiplication",multiplication(a,b,c,d))
false
132cfae921bd2017c698ee45649a407f6b72b27b
futureironman/Git-ironman
/oops5.py
1,067
4.15625
4
#==================classmethods can wen used as alternative constructor========= class Employee: no_of_leaves=8 def __init__(self,aname,asalary,arole): self.name=aname self.salary=asalary self.role=arole def printdetails(self):#here self is that instance on which the function is implemented return f"Name is {self.name}.Salary is {self.salary} and role is {self.role}" @classmethod#function can only recieve the class instance variable and change class variable def change_leaves(cls,newleaves): cls.no_of_leaves= newleaves @classmethod def from_dash(cls,string): return cls(*string.split("-")) #params=string.split("-")#it will split the string from dash #print(params) #return cls(params[0],params[1],params[2]) sourav=Employee("sourav",675,"Instructor") harry=Employee("harry",455,"student")#if we give any argument to class then it will taken by init function karan=Employee.from_dash("Karan-464-student") harry.change_leaves(34) print(karan.salary)
true
b81914204958a8861785500509f8dafdee3ffe01
skyrockprojects/draft-python-course
/0-introduction/2-functions.py
882
4.15625
4
# write your own function that takes two numbers and subtracs them # WRITE YOUR SUBTRACTION FUNCTION HERE (call it subtract) # also write a function that prints out it's input twice # WRITE YOUR FUNTION THAT PRINTS TWICE HERE (call it printTwice) #you can also put a function as one of the inputs, try putting values into the subtract function and use it as an input for printTwice # These are test cases we will learn about them next lesson #DO NOT EDIT THIS def checkOutput(index, value): if(output[index] == value): return "CORRECT!" return "WRONG, try again" firstInput = [1,2,3,4,5] secondInput = [-1,0,14,22,3] output = [2,2,-11,-18,2] for i in range(5): print(firstInput[i]," + ",secondInput[i]," = ",subtract(firstInput[i],secondInput[i])," ",checkOutput(i,subtract(firstInput[i],secondInput[i]))) for i in firstInput: printTwice(i)
true
12eb7c59a60890e70cecfe2c2ceda4afcc455310
ninnzz/python-sample
/exercises/first_python_code.py
507
4.53125
5
# Basic example on how to print # text using different approach in # Python. organization = 'WomanWhoCode!' # You can print it right away! print('Hello WomanWhoCode!') # Example of string concatenation print('Hello ' + organization) # Using .format() function to attach a string print('Hello {}'.format(organization)) # First, replace the following text with your name your_name = '<place your name here>' # Then, uncomment the next line by removing the "#" sign #print('Hello {}!'.format(your_name))
true
2fcc046a981d9da8227ad18711ed57df68bde285
ProCodeMundo/practicingPython
/madlibs.py
996
4.21875
4
""" Creating a MadLibs Game Mad Libs is a phrasal template word game which consists of one player prompting others for a list of words to substitute for blanks in a story before reading aloud. The game is frequently played as a party game or as a pastime https://www.youtube.com/watch?v=8ext9G7xspg """ # string concatenation (putting strings together) # suppose that we need to create a string that syas "subcribe to ___" youtube = "Ruben" # some string value # possible ways to do it. print("Subscribe to " + youtube) print("Subscribe to {}".format(youtube)) print(f"Subscribe to {youtube}") adj = input("Type an Adjective: ") verb = input("Type an Verb: ") verb2 = input("Type another Verb: ") famous_person = input("Type a famous person: ") madlib = f"Computer programming is as {adj} as playing video game! It is a new ways of doing things and I like it because \ it make sound {verb}. Stay fresh and {verb2}, like your are {famous_person} " print(madlib)
true
28e5b672ba47118b4eec9954f69452f19e0fb63c
dmaterialized/agility
/tests.py
1,300
4.1875
4
#list creation # # list = [] # # def addAnItem(): # theItem = input('what is the item?') # list.append(theItem) # # addAnItem() # print(list) # # # # let's talk return types # def add(a, b): # print ("Adding %d + %d" % (a, b)) # return a+b # # def subtract(a, b): # print ("Subtracting %d - %d" % (a,b)) # return a-b # # def multiply(a, b): # print("Multiplying %d * %d" % (a,b)) # return a * b # # def divide(a, b): # print("Dividing %d by %d" % (a,b)) # return a / b # # # print("let\'s do some functional math using functions only") # # age = add(30, 5) # height = subtract(78, 4) # weight = multiply(90, 2) # iq = divide(100, 2) # # print("Age: %d. Height: %d. Weight: %d. IQ: %d." % (age, height, weight, iq)) # # # here's a weird ass puzzle # print ("here is a puzzle") # what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) # print ("that becomes: ", what, "Can you do it by hand?") # # # def doTheThing(thing1, thing2): # print("making thing1 and thing2 switch places") # print("thing1 is currently %d" % thing1) # print("thing2 is currently %d" % thing2) # temp_thing1 = thing1 # temp_thing2 = thing2 # print('temp thing1 is: %d' % (thing1)) # thing1==thing2 # print(thing1) # # doTheThing(50,100) # #
true
4dc2ba3ef91b18e7cf282b7a006ec053577b3882
shivam9ronaldo7/python-practice-programs
/dunder_methods.py
919
4.4375
4
""" Dunder methods are also known as magic methods """ class Club: def __init__(self, name): self.name = name self.players = [] def __getitem__(self, i): return self.players[i] def __len__(self): return len(self.players) def __repr__(self): return f'Club {self.name}: {self.players}' def __str__(self): return f'Club {self.name} with {len(self)} players' some_club = Club('Arsenal') some_club.players.append('Ozil') some_club.players.append('Cech') some_club.players.append('Aubmayang') some_club.players.append('Lacazette') some_club.players.append('Bellarin') print(len(some_club)) print(some_club[1]) # To use for loop we must implement __getitem__ methods must you define in order to # be able to use a for loop in your class for player in some_club: print(player) print(some_club) print(str(some_club)) print(repr(some_club))
false
415090463aba37f362b484a454537dda2845c09a
viditpathak11/Basic-Projects
/alarm.py
1,116
4.125
4
#This is a program to make a simple alarm #The python time library is used #We are going to open a youtube page to act as an alarm import time #Import time module import webbrowser #import webbrowesr module d=input("Whether time will bw entered in Hours, Minutes or Seconds") #Prompt the user if d=="Hours": temp=int(input("Enter the no of hours")) t=temp*3600 #convert hours to seconds for the time module time.sleep(t) #sleep function to halt the program elif d=="Minutes": temp=int(input("Enter no of minutes")) t=temp*60 #convert to seconds time.sleep(t) elif d=="Seconds": temp=int(input("Enter the no of seconds")) t=temp time.sleep(t) url="https://www.youtube.com/watch?v=9SKFwtgUJHs" #Enter the url as a variable webbrowser.open(url,new=2) #the open function to open the default browser # the 'new=2' will open the video in a new tab
true
30268f80fa9774ea02a78c9a5948db544937d8d8
andryuha77/Emerging-Technologies-problem-Sheet1
/MergeLists.py
545
4.1875
4
list1 = [] list2 = [] listNew = [] print("Please enter 3 numbers for each list.") print("List 1") for i in range (0,3): listItem = float(input(str(i + 1) + ": ")) list1.append(listItem) print("List 2") for i in range (0,3): listItem = float(input(str(i + 1) + ": ")) list2.append(listItem) listNew = list1 + list2 print() print("List 1: " + str(list1)) print("List 2: " + str(list2)) print("New List: " + str(listNew)) # Adapted from https://docs.python.org/3/howto/sorting.html print("Sorted List: " + str(sorted(listNew)))
false
2af82d3436aee4ba1e0656daf2c547cf3557a5b2
andryuha77/Emerging-Technologies-problem-Sheet1
/Palindrome.py
625
4.21875
4
print("Palindrome Test") run = True while run == True: word = input("Enter a word: ") print("Original: " + str(word)) print("Reversed: " + str(word)[::-1]) #https://stackoverflow.com/questions/931092/reverse-a-string-in-python if str(word) == str(word)[::-1]: print("This is word is a palindrome.") print() else: print("This is word is not a palindrome.") print() again = input("Test another word? Y/N: ") if again.lower() == "y": run = True elif again.lower() == "n": run = False else: again = input("Please enter Y/N: ")
true
849ba1aa3e1ba35b42892726cf0c42bed1379e28
nikhil8856/Students-Marks-prediction
/Students-Marks-prediction.py
2,781
4.34375
4
#!/usr/bin/env python # coding: utf-8 # # Nikhil Madane # Task-1 # Linear Regression with Python Scikit Learn # In this section we will see how the Python Scikit-Learn library for machine learning can be used to implement regression functions. # We will start with simple linear regression involving two variables. # # Simple Linear Regression # In this regression task we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. # This is a simple linear regression task as it involves just two variables. # In[6]: import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[18]: data=pd.read_csv("Student_Scores_Dataset.csv") # data.head() # In[20]: data.shape # In[21]: X = data.iloc[:, :-1].values y = data.iloc[:, 1].values # In[22]: # Plotting the distribution of scores plt.scatter(data['Hours'], data['Scores'],color='r') plt.title('Hours vs Score') plt.xlabel('Hours Studied') plt.ylabel('Percentage Score') plt.show() # In[23]: from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3) # In[24]: from sklearn.linear_model import LinearRegression model = LinearRegression() # In[26]: model.fit(X_train,y_train) print("Training complete") # In[27]: # Plotting the regression line line = model.coef_*X+model.intercept_ # Plotting for the test data plt.scatter(X, y,color='g') plt.plot(X, line,color='r'); plt.show() # In[ ]: #Now that we have trained our algorithm, it's time to make some predictions. # In[28]: print(X_test) # Testing data - In Hours y_pred = model.predict(X_test) # Predicting the scores # In[29]: y_test # In[30]: df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) df # In[31]: # You can also test with your own data hours = [[9.25]] own_pred = model.predict(hours) print("No of Hours = {}".format(hours)) print("Predicted Score = {}".format(own_pred[0])) # In[32]: pred = model.predict(data[['Hours']]) pred # In[33]: from sklearn.metrics import r2_score r2_score(data.Scores,pred) # In[ ]: #Evaluating the model #The final step is to evaluate the performance of algorithm. #This step is particularly important to compare how well different algorithms perform on a particular dataset. #For simplicity here, we have chosen the mean square error. There are many such metrics. # In[34]: from sklearn.metrics import r2_score accuracy_score = r2_score(y_test,y_pred) print("The model has accuracy of {}%".format(accuracy_score*100)) # In[35]: from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred)) # In[ ]:
true
46adb91cb811e70023b009ed07682de21201a099
poloman2308/Python-Crash-Course-Lists
/motorcycles.py
1,339
4.1875
4
{ "cmd": ["/usr/local/bin/python3", "-u", "$file"], } # Modifying elements in a list motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles[-1] = 'honda' print(motorcycles) motorcycles.append('suzuki') print(motorcycles) motorcycles.append('harley') print(motorcycles) # Adding elements to a list bikes = [] bikes.append('honda') bikes.append('yamaha') bikes.append('suzuki') bikes.append('ducati') bikes.append('harley') bikes.append('bmw') print(bikes) # Insert items in a list bikes.insert(0, 'mophead') print(bikes) #remove elements del bikes[0] print(bikes) del bikes[-1] print(bikes) #pop items print(motorcycles) popped_motorcycles = motorcycles.pop() print(motorcycles) print(popped_motorcycles) last_owned = motorcycles.pop() print("The last motorcycle I owned was a " + last_owned.title() + ".") first_owned = motorcycles.pop(0) print("The first motorcycle I owned was a " + first_owned.title() + ".") print(motorcycles) motorcycles.insert(2, 'ducati') motorcycles.insert(3, 'suzuki') print(motorcycles) motorcycles.remove('ducati') print(motorcycles) motorcycles.insert(3, 'ducati') print(motorcycles) too_expensive = 'ducati' motorcycles.remove(too_expensive) print(motorcycles) print("\nA " + too_expensive.title() + " is too expensive for me.")
false
9cf2535cfa2b1de48a5eda5f8b4b925254c330c4
CodingDojoTulsaMay2018/claire_elliott
/python-stack/python-fun/for_loop_basics1.py
1,136
4.125
4
# # Basic - Print all the numbers/integers from 0 to 150. for i in range(0,151): print(i) # Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000. for i in range(5,1000000,5): print(i) # Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If by 10, also print " Dojo". for i in range(1,101): if i % 10 == 0 and i % 5 == 0: print("Dojo") elif i % 5 == 0: print("Coding") else: print(i) # Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum. sum = 0 for i in range(0,500000): if i % 2 != 0: sum += i print(sum) # Countdown by Fours - Print positive numbers starting at 2018, counting down by fours (exclude 0). for i in range(2018,0,-4): print(i) # Flexible Countdown - Based on earlier "Countdown by Fours", given lowNum, highNum, mult, print multiples of mult from lowNum to highNum, using a FOR loop. For (2,9,3), print 3 6 9 (on successive lines) def flex_countdown(lowNum,highNum,mult): for i in range(lowNum,highNum,mult): print(i) flex_countdown(2,9,3)
true
da37177ced3afc65526773cd89f9c4d4cc5e57d9
CoonArmy/enot2
/hw3.py
667
4.34375
4
# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. # узнаем число num = int(input("Введите число ")) # mak - максиммальное число и введенном + исклчаем остаток от деления и ставим деление целого числа mak = num % 10 num = num // 10 # цикл проверки while num > 0: if num % 10 > mak: mak = num % 10 num = num // 10 print(mak)
false
051879d160f7c98b895244d022c36faced049e0f
tanucdi/dailycodingproblem
/PYTHON/EDYODA/2_Inheritance.py
397
4.28125
4
#inheritance #creating a class car which inherits the class vehicle class Vehicle: def __init__(self,brand): self.brand=brand class Car(Vehicle): def __init__(self,brand,name): self.name=name #super used to call the parent class attribute super().__init__(brand) def printa(self): print(self.brand,self.name) a = Car('BMW','X5') a.printa()
true
8540159af2fcd49eb10f53fb6478db9105393d15
tanucdi/dailycodingproblem
/DataStructures/LinkedList/07_ReverseLLByRecursion.py
1,758
4.375
4
#create a class node # node consists of two things - data and next pointer class Node: def __init__(self,data): self.data = data self.next = None #create a class for LINKED LIST #which contains Head pointer class LinkedList: def __init__(self): self.head = None #create an function to add node to linked list def insert(self,newdata): #create a new node by giving new data newnode = Node(newdata) #check if head pointer is NONE or It is pointing to someone #if it is none - assign the newnode to head if self.head == None: self.head = newnode else: #if head is already pointing to someone then traverse and find the last node and last.next = none #put the newnode to the last node. last = self.head while (last.next): last = last.next last.next = newnode #create a function to print our linked list #traverse through linked list and print data def PrintLinkedList(self): current = self.head while current: print(current.data) current=current.next def helperFunc(myll,current,previous): if current.next is None: myll.head=current current.next = previous return next = current.next current.next = previous helperFunc(myll,next,current) def Reversefunc(myll): if myll.head == None: return helperFunc(myll,myll.head,None) #create an object of linked list linkedlist = LinkedList() linkedlist.insert(1) linkedlist.insert(2) linkedlist.insert(3) linkedlist.insert(4) linkedlist.insert(5) Reversefunc(linkedlist) linkedlist.PrintLinkedList()
true
6053e3d1542d5976163565707a4159b499bb75e7
nrohit10/learning-python
/chapter2/variables.py
360
4.125
4
# # Variables Practice # # Declare a variable and initialize it f = 0 print(f) # re-declaring the variable f = "abc" print(f) # Error: variables of different types cannot be combined print("this is a string " + str(123)) # Global vs Local variables in functions def fun1(): global f f = "definition of function fun1" print(f) fun1() print(f)
true
54dc7add3e5f1a190379296f8579e34c7c9fa62c
Roshanbagla/Linkedlist
/linkedlist.py
1,396
4.40625
4
"""Creating LinkedList.""" # create a node # create a LinkedList # insert node to LinkedList # print LinkedList class Node: """Created a Node.""" def __init__(self, data): # a node will have data and next field """Constructer function.""" self.data = data self.next = None class LinkedList: """Creaing a LinkedList.""" def __init__(self): self.head = None def insert(self, newNode): """Inserting a new node to linkedlist.""" if self.head is None: # head -> John--> None self.head = newNode else: lastNode = self.head while True: if lastNode.next is None: break else: lastNode = lastNode.next lastNode.next = newNode def printList(self): """Printing the LinkedList.""" first_node = self.head while True: if first_node is None: break else: print(first_node.data) first_node = first_node.next first_node = Node("John") # creating a node object linkedlist = LinkedList() # created a linkedlist linkedlist.insert(first_node) second_node = Node("Ben") linkedlist.insert(second_node) third_node = Node("Rosh") linkedlist.insert(third_node) linkedlist.printList()
true
b27a8f19cf27e16312ef16c425fbd43620148733
IsratJahan2/-Python-Assignment-
/Jahan5.py
284
4.34375
4
#Jahan5.py #A program that calculates the circumference #By:Israt Jahan import math def main(): diameter=input("Enter the diameter of a circular table\n") diameter=float(diameter) circumference=math.pi*diameter print("The circumference is", circumference) main()
true
da085ab48116f9f5946a78a7986b64a6a78add79
CichoszKacper/PythonLessons
/Pandolime.py
230
4.40625
4
user_string = input("Please enter some word to check if it is pandolime: ") user_string = user_string.lower() if user_string[::] == user_string[::-1]: print("Your word is pandolime") else: print("its not pandolime")
true
93905fd7f5ef85d0a2493a11336da51f803f016e
Moreys/Study
/python/list.py
329
4.1875
4
#!/usr/bin/env python # coding=utf-8 ''' #普通函数调用 #def reverseWords(input) inputWords = input.split("") inputWords = inputWords[-1::-1] output = ' '.join(inputWords) return output #相当于man函数 if __name__ == "__man__": input = "I like morey" rw = reverseWords(input) print(rw) '''
false
183ba67a6249a574d0d4102948bde0544560f86d
shijietopkek/cpy5p2
/q02_triangle.py
447
4.15625
4
#q02_triangle.py #get input sides = [int(input("Enter side 1:")), int(input("Enter side 2:")), int(input("Enter side 3:"))] sides.sort() #calculation perimeter = sides[0] + sides[1] + sides[2] #generate output if sides[2] > (sides[0] + sides[1]): print("Invalid triangle!") else: print("perimeter = {0}".format(perimeter))
true
cda7529a53bdbc6759500db2fb6b9803499f9945
ziGFriedman/A_byte_of_Python
/Func_doc.py
569
4.375
4
'''Строки документации''' def printMax(x, y): '''Выводит максимальное из 2-х чисел. Оба значения должны быть целыми числами.''' # документация x = int(x) #конвертируем в целые, если возможно y = int(y) if x > y: print(x,'наибольшее') else: print(y,'наибольшее') printMax(3, 5) print(printMax.__doc__) #выводит документацию из функции (и не только)
false
467fa0f2e081deae63a68b27bc4f626581f71fd7
dipsdeepak11/Practice-
/02-08/program.py
872
4.15625
4
#program to find all palindrome numbers in a input list def find_palindrome_in_list(input_list): counter=0 palin_list=[] for item in input_list: #finding reverse of the current item temp=item reverse=0 while temp > 0: reverse = reverse * 10 + temp %10 temp=temp / 10 #comparing reverse with the actual number if reverse == item: palin_list.append(item) counter = counter+1 print("the count now is %D" ,counter) return palin_list,counter def print_palindrome_list(palindrom_list): for item in palindrom_list: print("%d" , item) #main program list_first=[11,2321,12321,121,221,252] palindrom_list,count = find_palindrome_in_list(list_first) print_palindrome_list(palindrom_list) print("total count in list first is ",count)
true
b243b492790509d227793c086826c4c6c1bff8ae
yordan-marinov/advanced_python
/functions/even_numbers.py
768
4.125
4
# def even_only(num): # return num % 2 == 0 # # # def even_numbers(): # return list(filter(even_only, map(int, input().split()))) # # # print(even_numbers()) def even_numbers_only(func): def is_even_number(n): return n % 2 == 0 def inner(numbers): return [n for n in func(numbers) if is_even_number(n)] return inner @even_numbers_only def input_numbers(numbers): return numbers numbers = [int(n) for n in input().split()] print(input_numbers(numbers)) # Recursively solved! numbers = [int(n) for n in input().split()] def even_numbers(nums): if not nums: return [] if nums[0] % 2 == 0: return [nums[0]] + even_numbers(nums[1:]) return even_numbers(nums[1:]) print(even_numbers(numbers))
false
e5e7ba9dbac47305da68c6277effb0b9ad682c6a
yordan-marinov/advanced_python
/functions/even_or_odd.py
534
4.1875
4
def odd_numbers(numbers: list) -> [int]: def is_odd(n): return n % 2 != 0 return [n for n in numbers if is_odd(n)] def even_numbers(numbers: list) -> [int]: def is_even(n): return n % 2 == 0 return [n for n in numbers if is_even(n)] def even_odd(*args): command = args[-1] commands = { "even": even_numbers, "odd": odd_numbers, } return commands[command](args[:-1]) print(even_odd(1, 2, 3, 4, 5, 6, "even")) print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
false
7487ee853eeeae1585504cd4fe3d5f86328ed455
yordan-marinov/advanced_python
/decorators/vowel_filter.py
369
4.125
4
def vowel_filter(function): def is_vowel(letter): vowels = {"a", "e", "o", "i", "u", "y"} return letter.lower() in vowels def wrapper(): result = function() return [r for r in result if is_vowel(r)] return wrapper @vowel_filter def get_letters(): return ["a", "b", "c", "d", "e"] print(get_letters()) # ["a", "e"]
false
2869f6922d34009587ae373c3c135e23b812922d
devclassio/200-interview-algorithm-questions
/strings/letter-combinations-of-a-phone-number.py
2,080
4.125
4
''' Full solution at https://devclass.io/letter-combinations-of-a-phone-number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Here is the mapping as a visial mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } ''' class RecursiveSolution: def letterCombinations(self, digits): mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } if len(digits) == 0: return [] if len(digits) == 1: return list(mapping[digits[0]]) all_but_last = self.letterCombinations( digits[:-1]) # all elements except last last = list(mapping[digits[-1]]) # "abc" -> ['a', 'b', 'c'] res = [] for char in last: for expression in all_but_last: res.append(expression + char) return res class BacktrackingSolution: def letterCombinations(self, digits): map_ = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } res = [] def make_combinations(i, accumalated): if i == len(digits): if len(accumalated) > 0: res.append(''.join(accumalated)) return for char in map_[digits[i]]: accumalated.append(char) make_combinations(i+1, cur) accumalated.pop() make_combinations(0, []) return res
true
6c713b626e0ed670f32cf08bbb02492844dbdde8
Latoslo/treasure-island-start-1
/main.py
1,905
4.3125
4
print(''' _________________________ __ / ,------++---. .-------.`. / / // | || |.`. __ / / // | || | `.`. __ | '------++------' |`-------+--[)| `---..___ __ !] _ | | ______"""-. _!]__________ |_| | | ,,----.\___|_ |___ /',--. \\ |_____________| // ,--.\\____| \_-/'| |! \----------------------'| | |!|_/ \ `--' /!'----------------------' \ `--' / `'---' `'---' ''') print("Welcome to Treasure Island.") print("Your mission is to find the treasure.") left_right = input('Which way do you choose to go? left or right? ') if left_right == 'right'.lower() or 'r'.lower(): print('game over') elif left_right == 'left'.lower() or 'l'.lower(): swim_wait = input('Would you like to swim or wait? swim or wait? ') if swim_wait == 'swim'.lower() or 's'.lower(): print('game over') elif swim_wait == 'wait'.lower() or 'w'.lower(): door = input('which door do you want to follow? Red or Blue or Yellow? ') if door == 'Yellow'.lower() or 'Y'.lower(): print('You Win!') elif door == 'Red'.lower() or 'R'.lower(): print('Burned by fire. Game Over.') elif door == 'Blue'.lower() or 'B'.lower(): print('Eaten by beasts. Game Over.') else: print('please select one of the choices to continue') else: print('please select one of the choices to continue') else: print('please select one of the choices to continue') #https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload
false
bfa628b7981e482ed4a873e3eb0e667677152e03
ParthShuklaa/KIT_2019_MTA_Python
/demo_collections.py
445
4.125
4
#myList = ["Apple","Samsung","OnePlus"] #myList.insert(3,"Oppo") #print(myList) #myList.pop() #for i in myList: # print(i) #myTuple = ("Audi","Mercedes","Ferrari","Audi") #myCount = myTuple.count("Audi") #print(myCount) #mySet = {"Red","Blue","White","Red"} #print(mySet) myDictionary = {"Maharashtra":"Mumbai","West Bengal":"Kolkata","Rajashthan":"Jaipur"} #print(myDictionary["Maharashtra"]) print(myDictionary)
false
b5f1fbd6e685d161624289598c4c402e5ca8f097
Caesar-droid/python-projects
/remember_me.py
488
4.28125
4
#saving and reading user-generated data #load the username, if it has been stored previously #otherwise,prompt for the username and store it. import json filename='username.json' try: with open(filename) as f: username=json.load(f) except FileNotFoundError: username=input("What is your name?") with open(filename,'w') as f: json.dump(username,f) print(f"We'll remember you when you come back, {username}!") else: print(f"Welcome back,{username}")
true
6b2a0f163bdb268ad36e442d51983a327f91f9cd
Caesar-droid/python-projects
/car.py
1,676
4.15625
4
cars=['audi','bmw','honda','isuzu'] for car in cars: if car=='bmw': print(car.upper()) else : print(car.title()) #implementing functions in class class Car: """A simple attempt to represent a car.""" def __init__(self,make,model,year): """Initialize attributes to describe a car.""" self.make=make self.model=model self.year=year self.odometer_reading=100 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back.""" if mileage>=self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer") def increment_odometer(self,miles): """Add the given amount to the odometer reading.""" if miles < 0: print("We can't roll back an odometer") else: self.odometer_reading+=miles my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(110) my_new_car.read_odometer() print("\n") my_used_car=Car('subaru','outback',2015) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(23_500) my_used_car.read_odometer() my_used_car.increment_odometer(20) my_used_car.read_odometer()
true
747da71176f7ec5388f7981a4d21093e7a5c0b7b
Caesar-droid/python-projects
/stages_of_life.py
287
4.125
4
age=45 if age<2: print('the person is a baby') elif age<4: print('the person is a toddler') elif age<13: print('the person is a kid') elif age<20: print('the person is a teenager') elif age<65: print('the person is an adult') else: print('the person is an elder')
false
c51aca0f01e895231f4a88cdd1c208f0c699c703
aidataguy/python_learn
/recursion.py
722
4.40625
4
#! /usr/bin/python3 """ Advantages of Recursion Recursive functions make the code look clean and elegant. A complex task can be broken down into simpler sub-problems using recursion. Sequence generation is easier with recursion than using some nested iteration. Disadvantages of Recursion Sometimes the logic behind recursion is hard to follow through. Recursive calls are expensive (inefficient) as they take up a lot of memory and time. Recursive functions are hard to debug. """ def factorialnum(x): if x == 1: return 1 else: return (x * factorialnum(x-1)) # number = 5 # print("Factorial is ", factorialnum(number)) def recursion(): recursion() recursion()
true
b2ee7b794bd8148d274e1eb76b28d18241f9eef8
eric496/leetcode.py
/trie/1268.search_suggestions_system.py
2,786
4.21875
4
""" Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return list of lists of the suggested products after each character of searchWord is typed. Example 1: Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" Output: [ ["mobile","moneypot","monitor"], ["mobile","moneypot","monitor"], ["mouse","mousepad"], ["mouse","mousepad"], ["mouse","mousepad"] ] Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"] After typing m and mo all products match and we show user ["mobile","moneypot","monitor"] After typing mou, mous and mouse the system suggests ["mouse","mousepad"] Example 2: Input: products = ["havana"], searchWord = "havana" Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] Example 3: Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags" Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]] Example 4: Input: products = ["havana"], searchWord = "tatiana" Output: [[],[],[],[],[],[],[]] Constraints: 1 <= products.length <= 1000 There are no repeated elements in products. 1 <= Σ products[i].length <= 2 * 10^4 All characters of products[i] are lower-case English letters. 1 <= searchWord.length <= 1000 All characters of searchWord are lower-case English letters. """ class TrieNode: def __init__(self): self.children = {} self.words = [] class Trie: def __init__(self) -> None: self.root = TrieNode() def insert(self, word: str) -> None: cur = self.root for c in word: if c not in cur.children: cur.children[c] = TrieNode() cur = cur.children[c] cur.words.append(word) cur.words.sort() while len(cur.words) > 3: cur.words.pop() def find(self, word: str) -> List[List[str]]: res = [] cur = self.root for c in word: if c not in cur.children: break cur = cur.children[c] res.append(cur.words[:]) for _ in range(len(word) - len(res)): res.append([]) return res class Solution: def suggestedProducts( self, products: List[str], searchWord: str ) -> List[List[str]]: trie = Trie() for product in products: trie.insert(product) return trie.find(searchWord)
true
17e8bba4c133304cc9534450627b615816279773
eric496/leetcode.py
/linked_list/21.merge_two_sorted_lists.py
2,425
4.15625
4
""" Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ """ Thought: 1. Use a sentinel node to track the head of the result list; 2. Traverse l1 and l2, comparing node values from the two list nodes. Append the smaller one to the walking pointer. 3. l1 and l2 are possible of different length. In this case, append what is left in the longer linked list to the walking pointer. """ # Definition for singly-linked list. class ListNode: def __init__(self, val): self.val = val self.next = None # Solution 1: Recursive class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if None in (l1, l2): return l1 or l2 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 # Solution 2: Iterative # First version class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: sentinel = walk = ListNode(None) while l1 or l2: if l1 and l2: if l1.val < l2.val: walk.next = l1 l1 = l1.next else: walk.next = l2 l2 = l2.next elif l1: walk.next = l1 break elif l2: walk.next = l2 break walk = walk.next return sentinel.next # Second version class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # Pythonic way to check the empty linked lists if None in (l1, l2): return l1 or l2 sentinel = walk = ListNode(-1) while l1 and l2: if l1.val < l2.val: walk.next = l1 l1 = l1.next else: walk.next = l2 l2 = l2.next # Remember to move walking pointer forward walk = walk.next # This is Pythonic! walk.next = l1 or l2 # Compare to the following # if l1: # walk.next = l1 # if l2: # walk.next = l2 return sentinel.next
true
d3daf0dd775d52f3086e958f7aecfb583bc8ad76
eric496/leetcode.py
/stack/150.evaluate_reverse_polish_notation.py
1,661
4.125
4
""" Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. Example 1: Input: ["2", "1", "+", "3", "*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: ["4", "13", "5", "/", "+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 """ class Solution: def evalRPN(self, tokens: List[str]) -> int: if not tokens: return 0 stk = [] operations = {"+", "-", "*", "/"} for token in tokens: if token in operations: op2 = stk.pop() op1 = stk.pop() if token == "+": stk.append(op1 + op2) elif token == "-": stk.append(op1 - op2) elif token == "*": stk.append(op1 * op2) elif token == "/": # This is a Python specific issue # that negative integer division does not truncate. stk.append(int(float(op1) / op2)) else: stk.append(int(token)) return stk[0]
true