blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
95297b99949e123fbeaa89f84c7c4f14521b3187
adhuliya/bin
/hidesplit
2,288
4.125
4
#!/usr/bin/env python3 """ Splits a file into two chunks. The first chunk is only few bytes. """ import sys import os.path as osp PREFIX = "hidesplit" SIZE_OF_FIRST_CHUNK = 64 # bytes BUFF_SIZE = 1 << 24 usageMsg = """ usage: hidesplit <filename> note: file should be at least {} bytes. It splits a file into two chunks. The first chunk is only few bytes. """.format(SIZE_OF_FIRST_CHUNK) def genNextStrSeq(currStrSeq): currIntSeq = int(currStrSeq) nextIntSeq = currIntSeq+1 nextStrSeq = str(nextIntSeq) if len(nextStrSeq) == 1: nextStrSeq = "00" + nextStrSeq elif len(nextStrSeq) == 2: nextStrSeq = "0" + nextStrSeq return nextStrSeq def getExt(filename): return filename.rsplit(".")[-1] def main(filename): if not osp.exists(filename): print("hidesplit: error: file {} doesn't exists".format(filename), file=sys.stderr) exit(2) currStrSeq = "001" try: file1 = open(filename, "rb") except Exception as e: print("hidesplit: error: cannot open file {}".format(filename), file=sys.stderr) exit(3) try: file2 = open(PREFIX+currStrSeq+"."+getExt(filename), "wb") except Exception as e: print("hidesplit: error: cannot create file {}".format(filename), file=sys.stderr) exit(4) try: bb = file1.read(SIZE_OF_FIRST_CHUNK) # if len(bb) == SIZE_OF_FIRST_CHUNK: file2.write(bb) file2.close() except: print("hidesplit: error: cannot write to first chunk", file=sys.stderr) exit(5) try: file3 = open(PREFIX+genNextStrSeq(currStrSeq)+"."+getExt(filename), "wb") while True: bb = file1.read(BUFF_SIZE) file3.write(bb) if len(bb) != BUFF_SIZE: file3.close() file1.close() break except Exception as e: print("hidesplit: error: cannot create/write-to second chunk", file=sys.stderr) if file1 is not None: file1.close() if file3 is not None: file3.close() exit(6) if __name__ == "__main__": if len(sys.argv) != 2: print(usageMsg) exit(1) main(sys.argv[1])
true
4cff866c37cb8f29fad30abba17cfae985b4e72d
heecer/old
/day2/list.py
336
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Haccer list1=['a','b','c','d','e'] # print(list1[1]) # print(list1[1:3]) # print(list1[-1]) # print(list1[-3:-1]) # print(list1[-3:]) list1.append('f')#追加 list1.insert(-1,'f')#插入 list1.remove('f') list1.pop(-1) del list1[0] print(list1) Index= list1.index('d') print(Index)
false
3bd3eecf4fc50c4edca1f32bae401c39e6cd06a7
deniscostadsc/becoming-a-better-programmer
/src/problems/cracking_the_code_interview/is_unique.py
1,170
4.15625
4
from typing import Dict """ Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? """ def is_unique(s: str) -> bool: """ Time: O(n) Space: O(n) """ chars: Dict[str, int] = {} for char in s: if char in chars: return False else: chars[char] = 1 return True def is_unique_with_no_extra_space(s: str) -> bool: """ Time: O(n log n) Space: O(1) """ if len(s) == 1: return True s = "".join(sorted(s)) for char in s: begin = 0 end = len(s) - 1 while begin < end: middle = begin + (end - begin) // 2 if s[middle] == char: if middle >= 1 and s[middle - 1] == char: return False if middle <= len(s) - 2 and s[middle + 1] == char: return False break elif s[middle] > char: begin = middle + 1 else: end = middle - 1 return True __all__ = [ "is_unique", "is_unique_with_no_extra_space", ]
true
07561b35e66d0ead5615059c3c56744da1e67280
kamalkundal/PythonProjects
/prime.py
214
4.125
4
n = int(input("Enter any num")) if n<2: print("not a prime") else: for i in range (2,n): if (n%i==0): print("not a prime") break else: print("num is prime")
false
f40b9ded5cd4c74fa5b67a77902b4b0778f0ff7e
anilasebastian-94/pythonprograms
/Functions/prime.py
553
4.125
4
num=int(input('enter number')) if num>1: for i in range(2,num): if num%i==0 : print('number is not prime') break else: print('number is prime') #..................print not used here because print continously executes in for loop............................# # num=int(input('enter number')) # flag=0 # if num>1: # for i in range(2,num): # if num%i==0 : # print('number is not prime') # break # else: # flag=1 # if flag==1: # print('number is prime')
true
3e49cf303d7e05de993dada0d63c803c04401b13
anilasebastian-94/pythonprograms
/flowofcontrols/looping/factorial.py
294
4.125
4
num=int(input('enter number')) fact=1 if num>0 : for i in range(1,num+1) : fact*=i print(fact) elif num == 0: print('Factorial of zero is 1') else : print('factorial doesnt exist for negative number') # i=1 # while i<=num : # prdct*=i # i+=1 # print(prdct)
true
12e0c0d33ee64f94b6624fcc6b67099cbe4a24a2
jjgagne/learn-python
/ex20.py
1,237
4.28125
4
# Author: Justin Gagne # Date: July 4, 2014 # File: ex20.py # Usage: python ex20.py ex20_sample.txt # Description: Use functions to print an entire file or a file line-by-line # allow command line args from sys import argv # unpack args script, input_file = argv # print entire contents of file def print_all(f): print f.read() # return to the beginning of the file def rewind(f): f.seek(0) # print one line at a time; readline() reads the line from the current seek position (set to start of file using rewind function above) # note: could add a comma after readline() to prevent \n\n from occurring def print_a_line(line_count, f): print line_count, f.readline() # create file object current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" # NOTE: current_line is just used for debugging purposes and is not actually passed to readline() current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) # don't forget to close the file afterwards current_file.close()
true
37279fce63c80eb1f39475815db70ef9a412f3f9
jjgagne/learn-python
/ex15.py
717
4.125
4
# import argv, which allows user to pass in parameters from command line from sys import argv # unpack argv script, filename = argv # create file object from the filename file (ex15_sample.txt in this case) txt = open(filename) # print out the contents to the console by calling txt.read() print "Here's your file %r:" % filename print txt.read() # since we are done with the file, we should close it txt.close() # grab filename from user input print "Type the filename again:" file_again = raw_input("> ") # create new file object from user inputted filename txt_again = open(file_again) # then print its contents print txt_again.read() # since we are done with the file, we should close it txt_again.close()
true
cc29f8ab6be4e6148ddfcbd89bbe8e5e2c611dd5
jshamsutdinova/TFP
/8_lab/task_4.py
1,826
4.25
4
#!/usr/bin/env python3 """ Laboratory work 8. Task 4 """ from abc import ABC, abstractmethod class Edication(): """ This class defines the interface of edication to client """ def __init__(self, edication_system): self._edication_system = edication_system @property def edication_system(self): return self._edication_system @edication_system.setter def set_edication_system(self, edication_system): self._edication_system = edication_system def get_edication_information(self): """ Return information about edication system """ result = self._edication_system.system_interface() return result class EdicationSystem(ABC): """ This class declares an interface common to all suppoted systems """ @abstractmethod def system_interface(self): pass class Schoolchild(EdicationSystem): def system_interface(self): print("Школьник учится 11 лет") class StudentBachelor(EdicationSystem): def system_interface(self): print("Бакалавр длится 4 года") class StudentMaster(EdicationSystem): def system_interface(self): print("Магистратура длится 5 лет") if __name__ == "__main__": edication = Edication(Schoolchild()) print("Сначала ребенок учится в школе:") edication.get_edication_information() print() print("Далее поступает в университет:") edication.set_edication_system = StudentBachelor() edication.get_edication_information() print() print("Студент может получить магистерскую степень:") edication.set_edication_system = StudentMaster() edication.get_edication_information()
true
68f4607b1bc028ac64a29fc55b40f44bebef3b85
creuter23/fs-tech-artist
/Staff/JConley/Scripts/Python Book Scripts/Chapter 2/trivia_script.py
626
4.125
4
#Trivia Script #Minor exersice in using different types of data from user input name = raw_input("Name? ") age = int(raw_input("Age? ")) weight = int(raw_input("Weight?")) print "\nHi, " + name dog_years = age * 7 print "\nYou are ", dog_years , "in dog years." seconds = age * 365 * 24 * 60 * 60 print "You are over ", seconds , "seconds old." moon_weight = weight / 6.0 print "\nYour weight on the moon would be ", moon_weight , "pounds." sun_weight = weight * 27.1 print "\nYour weight on the sun would be ", sun_weight , "pounds." raw_input("\n\nPress the enter key to exit.")
false
59764f581af46fe1f43de830f3c8a09f641cd28b
edaniszewski/molecular_weight
/csv_reader.py
802
4.1875
4
import csv class CSVReader(): """ Implementation of a simple CSV reader. Contains a read method which operates on the filename which the reader is instantiated with. This reader is tailored to read the resources/element_weights.csv to create a dictionary, which is stored in the data member. """ def __init__(self, file_name): self.file_name = file_name self.data = None def read(self): """ Read a .csv file, create a dictionary of data, and store the data within the CSVData.data variable :return: None """ if not self.data: with open(self.file_name, 'rb') as f: reader = csv.reader(f, delimiter=',', quotechar='"') self.data = {row[0]: float(row[1]) for row in reader}
true
c233e6da46e7b2dc25d0e43c204745c15959b779
hammam1311/age-calculator
/age_calculator.py
971
4.21875
4
from datetime import datetime from datetime import date def check_birthdate(year, month, day): # write code here today = date.today() if int(year) > int(today.year): return False elif int(year) == int(today.year): if int(month) > int(today.month): return False elif int(month) == int(today.month): if int(day) > int(today.day): return False else: return True else: return True else: return True def calculate_age(year, month, day): today = date.today() ans = (int(today.year) - int(year)) + ((int(today.month) - int(month))/12) + ((int(today.day) - int(day))/365) print ("you are "+str(int(ans//1))+"years old") def main(): # write main code here today = date.today() y1 = input("Enter year of birth: ") m1 = input("Enter month of birth: ") d1 = input("Enter day of birth: ") if check_birthdate(y1, m1, d1): calculate_age(y1, m1, d1) else : print ("the birthdate is invalid.") if __name__ == '__main__': main()
false
efea2dfab3ed94a02d298ef65fbe913d8f669785
charliedavidhoward/Learn-Python
/meanMedianMode.py
1,244
4.40625
4
# [Function] Mean, Median, and Mode # # Background # # In a set of numbers, the mean is the average, the mode is the number that occurs the most, and if you rearrange all the numbers numerically, the median is the number in the middle. # # Goal # # Create three functions that allow the user to find the mean, median, and mode of a list of numbers. If you have access or know of functions that already complete these tasks, do not use them. # # Subgoals # # In the mean function, give the user a way to select how many decimal places they want the answer to be rounded to. # # If there is an even number of numbers in the list, return both numbers that could be considered the median. # # If there are multiple modes, return all of them. import math input_numbers = input("your numbers separated by a space: ") list = input_numbers.split(" ") def mean_function(myList=[]): sum = 0 for number in myList: sum = sum + int(number) mean = sum / len(myList) return mean def median_function(myList=[]): print(myList) myList.sort() print(myList) middle_number = myList[math.floor(len(myList) / 2)] return middle_number def mode_function(myList=[]): return max(myList, key=myList.count)
true
8e1fc385e39c1e0c355a07238880bf087096ce5d
Gaurav-dawadi/Python-Assignment-III
/A/question1.py
563
4.15625
4
# Bubble Sort Algorithm import timeit start = timeit.default_timer() def bubbleSort(array): n = len(array) for i in range(n): already_sorted = True for j in range(n - i - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] already_sorted = False if already_sorted: break return array print("The sorted array is ", bubbleSort([8, 2, 6, 4, 5])) end = timeit.default_timer() print("The total time required: ", end-start, " seconds")
true
4f57b9b429695ba7b4b84e52c822db4037d11288
kanekko/python
/02-Introducción/Calculator.py
1,253
4.15625
4
def operaciones(opcion, numero_a, numero_b): if opcion == 1: return numero_a + numero_b elif opcion == 2: return numero_a - numero_b elif opcion == 3: return numero_a * numero_b elif opcion == 4: return numero_a / numero_b else: print('Opción inválida') print('Bienvenido a la calculadora') while True: print('Estas son las operaciones que puedes realizar:') print('1 - Suma') print('2 - Resta') print('3 - Multiplicación') print('3 - División') try: opcion = int(input('Introduce el número de operación que quieres realizar: ')) if opcion < 1 or opcion > 4: print('Número de operación inválida\n') continue numero_a = int(input('Introduce el primer número: ')) numero_b = int(input('Introduce el segu1ndo número: ')) except ValueError: print('Opción o número inválido') else: numero_c = operaciones(opcion, numero_a, numero_b) print('El resultado es: ' + str(numero_c)) continuar = input("¿Deseas continuar? [si/no] ") print('\n\n') # if continuar == "no": if continuar != "si": break print('¡Gracias!')
false
3e21d6d44a01c7d0129fb42cfcd76b93a9e5e171
sojournexx/python
/Assignments/TanAndrew_assign4_problem1.py
1,498
4.1875
4
#Andrew Tan, 2/16, Section 010, Roll the Dice from random import randint result = False while result == False: s = int(input("How many sides on your dice? ")) #Check for valid data if s < 3: print("Sorry, that's not a valid size value. Please choose a positive number.") continue #Roll the dice and display roll result else: print() print("Thanks! Here we go ...") print() counter = 0 doubles = 0 t1 = 0 t2 = 0 while result == False: counter += 1 d1 = randint(1, s) d2 = randint(1, s) t1 = t1 + d1 t2 = t2 + d2 print("%d. die number 1 is %d and die number 2 is %d." %(counter, d1, d2)) #Check for doubles if d1 != d2: continue else: doubles += 1 #Check for snake eyes if d1 != 1 and d2 != 1: continue else: print() print("You got snake eyes! Finally! On try number %d!" %(counter)) print("Along the way you rolled doubles %d times" %(doubles)) print("The average roll for die #1 was %.2f" %(t1 / counter)) print("The average roll for die #2 was %.2f" %(t2 / counter)) result = True
true
da8c803202a2c3e2b428e4298dac3c19b80eecdd
sojournexx/python
/Assignments/TanAndrew_assign2_problem2.py
1,188
4.28125
4
#Andrew Tan, 2/2, Section 010, Grade Calculator #Ask user for name and class name = input("What is your name? ") course = input("What class are you in? ") print() #Ask user for weightage and test scores weight_test = float(input("How much are tests worth in this class (i.e. 0.40 for 40%): ")) test1 = float(input("Enter test score #1: ")) test2 = float(input("Enter test score #2: ")) test3 = float(input("Enter test score #3: ")) print() #Calculate and display test avg test_avg = (test1 + test2 + test3) / 3 print("Your test average is: %.2f" %(test_avg)) print() #Ask user for weightage and hw scores weight_hw = float(input("How much are homework assignments worth in this class (i.e. 0.60 for 60%): ")) hw1 = float(input("Enter homework score #1: ")) hw2 = float(input("Enter homework score #2: ")) hw3 = float(input("Enter homework score #3: ")) print() #Calculate and display hw avg hw_avg = (hw1 + hw2 + hw3) / 3 print("Your homework average is: %.1f" %(hw_avg)) print() #Calculate and display final score total = hw_avg * weight_hw + test_avg * weight_test print("Thanks, %s. Your final score in %s is %.2f" %(name, course, total))
true
bffda2bd72fee372c85344b5274f7060e327aa47
cecilmalone/PythonFundamentos
/Cap03/Lab02/calculadora_v1.py
1,147
4.15625
4
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! print("\n******************* Python Calculator *******************") print() print("""Selecione o número da operação desejada: 1 - Soma 2 - Subtração 3 - Multiplicação 4 - Divisão""") print() opcao = int(input("Digite sua opção (1/2/3/4): ")) print() primeiro = int(input("Digite o primeiro número: ")) print() segundo = int(input("Digite o segundo número: ")) print() if opcao not in (1, 2, 3, 4): print("Opção Inválida!") elif opcao == 1: resultado = primeiro + segundo print("{} {} {} = {}".format(primeiro, '+', segundo, resultado)) elif opcao == 2: resultado = primeiro - segundo print("{} {} {} = {}".format(primeiro, '-', segundo, resultado)) elif opcao == 3: resultado = primeiro * segundo print("{} {} {} = {}".format(primeiro, '*', segundo, resultado)) elif opcao == 4: resultado = primeiro / segundo print("{} {} {} = {}".format(primeiro, '/', segundo, resultado))
false
760be593820d8aaf4ff443aa3892f1b96d577a9d
pulosez/Python-Crash-Course-2e-Basics
/#6: Dictionaries/favorite_numbers.py
842
4.1875
4
# 6.2. favorite_numbers = { 'john': 1, 'anna': 7, 'edward': 22, 'jane': 5, 'kate': 3, } print(favorite_numbers) num = favorite_numbers['john'] print(f"John's favorite number is {num}.") num = favorite_numbers['anna'] print(f"Anna's favorite number is {num}.") num = favorite_numbers['edward'] print(f"Edward's favorite number is {num}.") num = favorite_numbers['jane'] print(f"Jane's favorite number is {num}.") num = favorite_numbers['kate'] print(f"Kate's favorite number is {num}.") print("\n") # 6.10. favorite_numbers = { 'john': [1, 11, 3], 'anna': [7, 5, 100], 'edward': [22, 42], 'jane': [5, 1, 10], 'kate': [3, 17], } for name, numbers in favorite_numbers.items(): print(f"\n{name.title()} likes the following numbers:") for number in numbers: print(f" {number}")
false
73682e4924c8d23279b3ef56c65ac5715bc2d7b2
pulosez/Python-Crash-Course-2e-Basics
/#5: if Statements/favourite_fruits.py
417
4.1875
4
# 5.7. favourite_fruits = ['orange', 'apple', 'tangerine'] if 'orange' in favourite_fruits: print("You really like oranges!") if 'apple' in favourite_fruits: print("You really like apples!") if 'tangerine' in favourite_fruits: print("You really like tangerines!") if 'banana' in favourite_fruits: print("You really like bananas!") if 'peach' in favourite_fruits: print("You really like peaches!")
true
6c383b3dc9c39f8963ef2afac3eccfba06c378f4
Jamesong7822/Python-Tutorials
/0) Introduction To Python/tutorials.py
2,460
4.125
4
# def myfunction(a,b,c): # # Myfunction checks if any number from 0 - 99 is divisible by a, b and c # ans_list = [] # for i in range(100): # if i % a == 0 and i % b == 0 and i % c == 0: # ans_list.append(i) # return ans_list # print(myfunction(1,2,3)) # D) Write a function that randomly chooses a number from 1 to 100. The player will have to guess \ # correctly within 5 tries for that number, with hints(too small or too big) given # from random import randint # def guess(): # # Let comp choose random number # ans = randint(1, 101) # randomise from 1 to 100. Eg. 88 # max_num_of_tries = 5 # num_of_tries = 1 # while num_of_tries <= max_num_of_tries: # print("Guess a Number from 1 to 100") # user_guess = int(input("Try Num {}--> Tell me your guess>>".format(num_of_tries))) # # Hints - conditionals # if user_guess > ans: # print("Guess is too HIGH") # elif user_guess < ans: # print("Guess is too LOW") # else: # same as user_guess == ans # print("Congrats You guess correctly in {} tries.".format(num_of_tries)) # return # num_of_tries += 1 # print("HA U SUCK U DIDNT GUESS CORRECTLY") # print("The correct ans is {} YOU FOOL!".format(ans)) # guess() # Imports from random import randint def guess2(max_tries, range1, range2): """ This improved function allows the user to set parameters for his game """ # Randomise choice from range1 to range2 ans = randint(range1, range2+1) # Set up variables to check/update during the game loop try_count = 1 # Game loop while try_count <= max_tries: print("Guess a Number from {} to {}. You have {} tries left".format(range1, range2, max_tries - try_count + 1)) # Takes in input from user user_guess = int(input("Try {} --> Guess: ".format(try_count))) # Hints if user_guess < ans: print("Too Low") elif user_guess > ans: print("Too High") else: print("Congrats! That took {} tries!".format(try_count)) # Quit out of function return # Increment try_count by 1 try_count += 1 print("Boo, you SCRUB. My secret number is {}!!".format(ans)) # Call the function with user set params max_tries = int(input("Max Tries: ")) range1 = int(input("Guess range from: ")) range2 = int(input("to: ")) guess2(max_tries, range1, range2)
true
90acca5899c8ecf3891bcc8339ad16a0fcb2fbca
strawsyz/straw
/ProgrammingQuestions/牛客/对称的二叉树.py
928
4.15625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 画个二叉树就能理解 # 一个节点左右节点的值相同 # 左节点的左节点要与右节点的右节点相同 # 左节点的右节点要与右节点的左节点相同 class Solution: def isSymmetrical(self, pRoot): # write code here if not pRoot: return True return self.is_symmertrical(pRoot.left, pRoot.right) def is_symmertrical(self, left, right): if not left and not right: # 如果两边都是空,说明两边相等 return True if not left or not right: return False if left.val == right.val: return True & self.is_symmertrical(left.left, right.right) & self.is_symmertrical(left.right, right.left) else: return False
false
4612293ef47d0ac146502d3ba6b5373b904fa951
Metalscreame/Python-basics
/functions/zip.py
368
4.25
4
# В Pyhon функция zip позволяет пройтись одновременно по нескольким итерируемым объектам (спискам и др.): a = [10, 20, 30, 40] b = ['a', 'b', 'c', 'd', 'e'] for i, j in zip(a, b): print(i, j) # (10, a) zip_obj = zip(a, b) list_zip = list(zip_obj) # list of tuples print(list_zip)
false
8fd2ebf33486069e8e7939bd54465ceefe6370a3
Metalscreame/Python-basics
/date.py
2,670
4.125
4
from datetime import datetime, timedelta # parsing date now = datetime.now() some_date = '01/02/1903' date_format = '%d/%m/%Y' parsed_date = datetime.strptime(some_date, date_format) print(parsed_date) one_day = timedelta( days=1, minutes=2 ) new_date = parsed_date-one_day print('Parsed minus one day: ', new_date) print('Day: ' + str(now.day)) print('Month: ' + str(now.month)) print('Hour: ' + str(now.hour)) # added some_date = '01/02/1903 12:30:12' date_format = '%d/%m/%Y %H:%M:%S' parsed_date = datetime.strptime(some_date, date_format) print(parsed_date) ''' Note: Examples are based on datetime.datetime(2013, 9, 30, 7, 6, 5) Code Meaning Example %a Weekday as locale’s abbreviated name. Mon %A Weekday as locale’s full name. Monday %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 1 %d Day of the month as a zero-padded decimal number. 30 %-d Day of the month as a decimal number. (Platform specific) 30 %b Month as locale’s abbreviated name. Sep %B Month as locale’s full name. September %m Month as a zero-padded decimal number. 09 %-m Month as a decimal number. (Platform specific) 9 %y Year without century as a zero-padded decimal number. 13 %Y Year with century as a decimal number. 2013 %H Hour (24-hour clock) as a zero-padded decimal number. 07 %-H Hour (24-hour clock) as a decimal number. (Platform specific) 7 %I Hour (12-hour clock) as a zero-padded decimal number. 07 %-I Hour (12-hour clock) as a decimal number. (Platform specific) 7 %p Locale’s equivalent of either AM or PM. AM %M Minute as a zero-padded decimal number. 06 %-M Minute as a decimal number. (Platform specific) 6 %S Second as a zero-padded decimal number. 05 %-S Second as a decimal number. (Platform specific) 5 %f Microsecond as a decimal number, zero-padded on the left. 000000 %z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). %Z Time zone name (empty string if the object is naive). %j Day of the year as a zero-padded decimal number. 273 %-j Day of the year as a decimal number. (Platform specific) 273 %U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 39 %W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 39 %c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013 %x Locale’s appropriate date representation. 09/30/13 %X Locale’s appropriate time representation. 07:06:05 %% A literal '%' character. % '''
true
2f8b4ee8c6145451ed2d9b588314bc1ee117fb9e
JomHuang/PythonStudy
/Day_2/Preview/OOP/person.py
936
4.46875
4
""" 开始OOP学习 1.结构 2.封装 3.定制 定义一个类 """ class Person: # 相当与构造函数 def __init__(self, name, age, pay=0, job=None): self.name = name; self.age = age; self.pay = pay; self.job = job; # 取lastname def lastname(self): return self.name.split()[-1]; # 加薪 def giveRaise(self, percent): self.pay *= (1.0 + percent); # 格式化输出 理解不了 def __str__(self): return '<%s => %s : %s : %s>' % (self.__class__.__name__, self.name, self.job, self.pay); if __name__ == "__main__": bob = person('Bob Smith', 42, 40000, 'software'); sue = person('Sue Jones', 45, 50000, 'hardware'); print ('bob name:', bob.name, '\n sue pay:', sue .pay); print (bob.name.split()[-1]); sue.pay += 200; print (sue.pay); print (bob.lastname()); sue.giveRaise(0.2); print (sue.pay);
false
fb1158f7b2802185143717b1dfc4b1ebc28c7cbd
rahulvennapusa/PythonLearning
/SquareInt.py
240
4.15625
4
number = input("Enter the integer :") if int(number) > 0: iteration = int(number) ans = 0 while iteration != 0: ans = ans + int(number) iteration = iteration - 1 print("Square of %s is %s :" % (number, ans))
true
33b4192303fd75f5cf8c60653820ec03589902cd
SuyeshBadge/Python-in-30-Days
/Day 1/DataType.py
1,561
4.34375
4
''' Data type in python int float string list tuple dictionary set boolean (true or false) ''' ################################ ''' Iterable {list string tuples set dictionary} non iterable {int float} ''' ####################### # int float str """ int #integer for numbers 1,2,3,4 float #float for decimal numbers eg. 0.0 0.5 str #string for characters like "hello there" """ ''' integer stores all the numbers non iterable ''' a = 5 b = 10 print("a is "+str(a)+" and b is "+str(b)) # traditional method print("a is {0} and b is {1}".format(a, b)) # string formatting print(f'a is {a} and b is {b}') # f string method # a is 5 and b is 10 # float """ Float stores all the decimal points non iterable """ f = 37.5 print(f) # string c = 'himanshu' c1 = 'h' print(c) # list ''' mutable iterable ''' list1 = [1, 2, 3, 4, 5, 6, 7] # integer list list2 = ['a', 'b', 'c'] # characters list slist = [1, 1, 1, 1, 1.0, 1, 2, 1, 1] # list1.pop() print(list1[1]) print(slist) # Tuples ''' Tuples are immutable iterable ''' tup1 = (1, 2, 3, 4, 5) # tup1[1]=5 # set ''' address is not assinged to the block only has distinct values ''' s1 = {1, 2, 4, 3, 4, 100, 3, 4, 500, 4, 4} s1list = set(slist) # Dictionary ''' dict_name={ key:value, key:value, key:value, key:value } dict_name[key] => value ''' himasnshu = [20, 'himanshu', 9384938493] # list print(himasnshu[2]) himanshu = { 'Rollno': 20, 'name': 'himanshu', 'mobile': 9898938493 } # dictionary print(himanshu['mobile']) # boolean ismale = True isfemale = False
false
dc29468021664d1d55e42ac4d0121816655aeb85
David-H-Afonso/python-basic-tests
/coinExchange.py
818
4.21875
4
# Function def exchange(coin): return coin / dollars # Inputs dollars = input("Write the amount of dollars you want to exchange: ") dollars = float(dollars) coin = input(""" Choose the coin that you want to exchange the value by typing the number. By default this value is "Euros" 1 - Euros 2 - Pesos argentinos 3 - Pesos colombianos Type it here: """) coin = int(coin) # Coin values euro_value = 1.19 peso_argentino = 95.89 peso_colombiano = 3834.74 # Coin comprobation if coin == 1: coin_value = euro_value elif coin == 2: coin_value = peso_argentino elif coin == 3: coin_value = peso_colombiano else: coin_value = euro_value # Showing the data to the user coin_value = exchange(coin_value) coin_value = round(coin_value,2) print(f"With {dollars}$ you have {coin_value} on the other coin")
true
e922fc7376a58caf2606224a864acd068c7e975a
SelimRejabd/Learn-python
/string method.py
552
4.25
4
# few useful method for string name = "reja" # lenth of string print(len(name)) # finding a charecter print(name.find("a")) # Capitalize "reja" to "Reja" print(name.capitalize()) # uppercase of a string print(name.upper()) # lowecase of a string print(name.lower()) # is string digit or not print(name.isdigit()) # is string alphabatic or not print(name.isalpha()) # count charecter in string print(name.count("e")) # replace charecter print(name.replace("j", "z")) # string print multiple time print(name*2)
true
893ae9a7901c8ce7030ca0efdb4c81dba293c3ba
nicolealdurien/Assignments
/week-02/day-1/user_address.py
1,673
4.4375
4
# Week 2 Day 1 Activity - User and Address # Create a User class and Address class, with a relationship between # them such that a single user can have multiple addresses. class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.addresses = [] def get_first_name(self, first_name): return self.first_name def get_last_name(self, last_name): return self.last_name def add_address(self, address): str_address = str(address) self.addresses.append(str_address) def display_addresses(self): print(f"""Addresses listed for {self.first_name} {self.last_name}:\n {self.addresses}""") def __str__(self): return f"{str(self.first_name)} {str(self.last_name)}" class Address: def __init__(self, street, city, state, zip_code): self.street = street self.city = city self. state = state self.zip_code = zip_code def get_street(self, street): return self.street def get_city(self, city): return self.city def get_state(self, state): return self.state def get_zip_code(self, zip_code): return self.zip_code def __str__(self): return f"{str(self.street)}, {str(self.city)}, {str(self.state)} {str(self.zip_code)}" mickey_mouse = User('Mickey', 'Mouse') magic_kingdom = Address('1180 Seven Seas Dr', 'Lake Buena Vista', 'FL', '32836') epcot = Address('200 Epcot Center Dr', 'Orlando', 'Florida', '32821') mickey_mouse.add_address(magic_kingdom) mickey_mouse.add_address(epcot) mickey_mouse.display_addresses()
true
6011e9272ce81b903109d50f6c82fab57b46a60c
fpoppe/How-Many-Times-I-Have-to-Fold
/n_fold.py
1,008
4.28125
4
import math def main (): print("\n Welcome to 'HOW MANY TIMES DO I HAVE TO FOLD?' \n") distance = float(input("\n Give me the distance (a number) \n")) #usuário nao pode botar algo diferente de numero unit = input("Give me its unit (km, m or mm) \n") unit = unit.lower() while unit != "km" and unit != "m" and unit != "mm": print("\n Invalid Unit \n") unit = input() unit = unit.lower() n_fold = calculate_dist_fold(distance,unit) print("\n You have to fold your piece of paper " + str(n_fold) + " times to reach " + str(distance) + " " + unit + "\n\n") def calculate_dist_fold(distance,unit): if unit == "km": thick = pow(10,-7) n_fold = math.log((distance/thick),2) elif unit == "m": thick = pow(10,-4) n_fold = math.log((distance/thick),2) else: thick = 0.1 n_fold = math.log((distance/thick),2) n_fold = math.ceil(n_fold) return n_fold main()
false
980c11b94a9ee491ee2095727036a6ed2b966145
sichkar-valentyn/Dictionaries_in_Python
/Dictionaries_in_Python.py
1,597
4.75
5
# File: Dictionaries_in_Python.py # Description: How to create and use Dictionaries in Python # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Dictionaries in Python // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Dictionaries_in_Python (date of access: XX.XX.XXXX) # Creating an empty dictionary a = dict() d = {} print(a) print(d) # Creating filled dictionary in form of Key --> Value d = {'a': 101, 10: 202} print(d) print(d['a']) print(d[10]) # Operations with dictionaries print('a' in d) print(11 not in d) d['a'] = 102 # Reassigning value for the existing key print(d) # Getting the value of the element of the dictionary by the key print(d[10]) # If there is no such key it will show mistake print(d.get(11)) # If there is no such key it will show 'None' # Deleting information from the dictionary del d['a'] # It will delete the pair Key --> Value print(d) # Using loops for the dictionaries a = {'A': 15, 'B': 23, 'C': 35, 'D': 43} for x in a: print(x, end=' ') # It will show keys print() for x in a.keys(): print(x, end=' ') # Again it will show keys print() for y in a.values(): print(y, end=' ') # It will show values print() for x, y in a.items(): print(x, y, end='; ') # It will show pairs Key --> Value print() # It is possible to store value as a list in the dictionary print(a) a['D'] = ['Diana', 'Rose'] print(a) a['D'] += ['Sun'] print(a)
true
ca2e22bf764551e91fdaf13c469258ff3821462c
leinad520/Monty-Hall-Game
/mp_game_simulation.py
1,867
4.125
4
from random import randrange, choice win_count = 0 def monty_python_game(): # print("You have three doors to choose from. Behind one door is the prize; two other doors have nothing. Which do you choose?") choicesArr = ["1","2","3"] prize = choice(choicesArr) # your_choice = input("type 1 2 or 3\n> ") your_choice = "1" choicesArr.remove(prize) if prize != your_choice: choicesArr.remove(your_choice) opendoor = choice(choicesArr) choicesArr.remove(opendoor) choicesArr2 = ["1","2","3"] choicesArr2.remove(your_choice) choicesArr2.remove(opendoor) # print(f"You chose door {your_choice}. Now let me open one of the remaining two doors that does not have the prize, door {opendoor}.") # print(f"*opens door {opendoor} to show there is nothing there.") # print(f"You now have the option to stick with your original choice, door {your_choice}, or switch to the other remaining door, door {choicesArr2[0]}. Do you want to?") # switch_decision = input("Type y or n \n> ") switch_decision = "y" if switch_decision == "y": if your_choice == prize: return # print(f"You lose by switching to door {choicesArr[0]}! Your original door {your_choice} had the prize") if your_choice != prize: # print(f"You win by switching! You switched from door {your_choice} to door {prize} which had the prize") global win_count win_count += 1 if switch_decision == "n": if your_choice == prize: print(f"You win by not switching! Your original door {your_choice} had the prize") win_count += 1 if your_choice != prize: print(f"You lose by not switching! The other door, door {prize}, has the prize") for i in range(10000): monty_python_game() print(win_count)
true
1d0abd1db93be3e724570699313277d0c0970653
rbdjur/Python
/Practice_Modules/Python_object_and_Data_Structure_basics/sets/set.py
402
4.15625
4
myset = set() #add number 1 to set myset.add(1) print(myset) #add number 2 to the set myset.add(2) #add number 2 again to the set myset.add(2) #see what the results of a set are print(myset) #Only {1,2} are in set despite adding two 2's. this is because a set only holds unique values. IF the value already exists, it wont take another number that is already identical to the number in the set.
true
0a79efb7b2540019d6d572528ec99a71d41313a3
rbdjur/Python
/Practice_Modules/Errors_handling_exceptions/try_except_else.py
696
4.21875
4
#The try block will execute and examine the code in this block try: result = 10 + 10 print(result) except: #if the code contains an error, the code in the except block will execute print("Adding is not happening check type") #The try block will execute and examine the code in this block try: # add = 5 + '5' add = 5 + 5 print(add) except: #if the code contains an error, the code in the except block will execute print("adding is not happening.") else: #If the code is clean and has no errors, then this code will run print(add) print("Went well.") finally: #This code runs regardless if there is an error or not print("Thee End")
true
c427137c075c714607fc7b740437824b7fe4aae3
rbdjur/Python
/Practice_Modules/Python_object_and_Data_Structure_basics/variable_assignments/variable_assignments.py
235
4.125
4
my_dogs = 2 my_dogs = ["Sammyy", "Frankie"] #Above is an example of dynamic typing that allows user to assign different data type a = 5 print(a) a = 10 print(a) a = a + a print("should be 20", a) print(type(a)) print(type(my_dogs))
true
98806536f6a7adea80fa82bdfaf9876ce8e57b00
laszlokiraly/LearningAlgorithms
/ch04/linked.py
1,740
4.40625
4
""" Linked list implementation of priority queue structure. Stores all values in descending. """ from ch04.linked_entry import LinkedEntry class PQ: """Heap storage for a priority queue using linked lists.""" def __init__(self, size): self.size = size self.first = None self.N = 0 def __len__(self): """Return number of values in priority queue.""" return self.N def is_full(self): """If priority queue has run out of storage, return True.""" return self.size == self.N def enqueue(self, v, p): """Enqueue (v, p) entry into priority queue.""" if self.N == self.size: raise RuntimeError('Priority Queue is Full!') self.N += 1 to_add = LinkedEntry(v, p) if self.first: # find first node SMALLER than key, and keep track of # prev so we can insert properly n = self.first prev = None while n: if p > n.priority: # Stop once in the right place if prev: to_add.next = n prev.next = to_add else: to_add.next = self.first self.first = to_add return prev, n = n, n.next prev.next = LinkedEntry(v, p) else: self.first = to_add def dequeue(self): """Remove and return value with highest priority in priority queue.""" if self.first: val = self.first.value self.first = self.first.next self.N -= 1 return val raise RuntimeError('PriorityQueue is empty!')
true
f9e1c7f094f2104fa7975c4e843e8ca1cfc1e96d
arthurleemartinez/InterestTools
/high_interest_loan.py
2,948
4.15625
4
user_principle: float = float(input("How much is the principle amount of your loan?")) def get_boolean_user_plans(): user_answer: str = input("Do you plan to pay off at least some of it soon? Answer 'yes' or 'no'.") if user_answer != 'yes' or 'Yes' or 'YES' or 'y' or 'Y': return False else: return True user_plans:bool = get_boolean_user_plans() def get_user_apr() -> float: u_apr: float = float(input("How much is your APR? Use a percentage without a symbol.")) return u_apr user_apr = get_user_apr() print('Your interest rate is {}%.'.format(user_apr)) def get_user_daily_interest() -> float: user_daily_interest: float = user_principle * (user_apr / 365 / 100) return user_daily_interest daily_interest: float = get_user_daily_interest() print('You are spending ${} on interest every day.'.format(daily_interest)) user_pay_period: int = int(input("How many days long is your pay period?")) def get_pay_check_cost() -> float: weekly_interest_cost = daily_interest * 7 biweekly_interest_cost = daily_interest * 14 monthly_interest_cost = daily_interest * 30 if user_pay_period > 6: pay_period_interest_cost = weekly_interest_cost elif user_pay_period > 13: pay_period_interest_cost = biweekly_interest_cost elif monthly_interest_cost > 27: pay_period_interest_cost = monthly_interest_cost return round(pay_period_interest_cost, 2) pay_check_cost: float = 2*round(get_pay_check_cost(),2) user_pay_check_amount = float(input("How much do you get paid every pay period?")) def get_paycheck_percentage(): pay_check_percentage1: float = round((pay_check_cost / user_pay_check_amount * 100), 2) return pay_check_percentage1 pay_check_percentage = round(get_paycheck_percentage() , 2) # determine how much money you will save on each minimum payment if you pay down a certain principle amount. def pay_down_implications(): payment_more_than_minimum: float = float(str(input("How much do you want to pay toward the principle this pay-check?"))) new_daily_interest = (user_principle - payment_more_than_minimum)/365/100*user_apr new_pay_check_percentage: float = round((100*(new_daily_interest * user_pay_period) / user_pay_check_amount), 2) new_pay_check_cost:float = round((new_pay_check_percentage/100*user_pay_check_amount) , 2) message = 'If you make a payment of ${} before the next due date, this loan will change to taking up %{} of your pay-checks. This means that your next payment would be ${}'.format(payment_more_than_minimum, new_pay_check_percentage, new_pay_check_cost) return message print('Your pay period is {} days long'.format(user_pay_period)) print('You are spending approximately ${} per pay-check on this loan'.format(pay_check_cost)) print('Your high-interest loan will eat up %{} of your paycheck this pay period.'.format(pay_check_percentage)) print(pay_down_implications())
true
6e4fd23cb4a7129f0a9b5ca3ffb6fb1647f0e321
nawaraj-b5/random_python_problems
/Python Basics/datatype_conversion.py
391
4.5
4
#Find the length of the text python and convert the value to float and convert it to string length_of_python = ( len('python') ) length_of_python_in_float = float(length_of_python) length_of_python_in_string = str( length_of_python ) print ('Length of the python in integer is {}, float is {}, and string is {} '.format(length_of_python,length_of_python_in_float,length_of_python_in_string))
true
67d38a1b0a4d052650402639c71eb1b6807f8d00
heba-ali2030/examples
/largest_number.py
423
4.40625
4
#Python Program to Find the Largest Among Three Numbers num1= int(input('choose first number: ')) num2= int(input('choose second number: ')) num3= int(input('choose third number: ')) if num1 > num2 and num1 > num3 : print('num 1 is the largest') elif num2 > num1 and num2 > num3 : print('num 2 is the largest') else: print('num 3 is the largest') #how to do this for more than 3 samples
false
a78fae1eb24fbb75cf328d20e83cec97d051356d
oluwafenyi/code-challenges
/CodeWars/6Kyu/Valid Braces/valid_braces.py
737
4.3125
4
# https://www.codewars.com/kata/valid-braces # Write a function that takes a string of braces, and determines if the order # of the braces is valid. It should return true if the string is valid, # and false if it's invalid. def validBraces(string): while '[]' in string or '{}' in string or '()' in string: string_list = list(string) if '[]' in string: string_list.remove('[') string_list.remove(']') elif '{}' in string: string_list.remove('{') string_list.remove('}') elif '()' in string: string_list.remove('(') string_list.remove(')') string = ''.join(string_list) return not bool(string)
true
1db206efd070dfa46493a2cdabf2f268e8d7cad0
oluwafenyi/code-challenges
/CodeWars/6Kyu/Find the Missing Letter/find_missing_letter.py
294
4.25
4
#https://www.codewars.com/kata/find-the-missing-letter from string import ascii_letters def find_missing_letter(chars): ind = ascii_letters.index(chars[0]) corr_seq = list(ascii_letters[ind:ind+len(chars)+1]) return [char for char in corr_seq if char not in chars][0]
true
345c2f179becc434547007db6863d0cd1b1226cf
l0neaadil/Python_for_beginner
/10_if_elif_else.py
860
4.21875
4
# if...elif ...else x = float(input("enter a no.: ")) if x == 0: print("no. is neither positive nor negative") elif x < 0: print("no. is negative") else: print("no. is positive") print("Done") # Nested if_else x = int(input("enter any integer: ")) if x == 0: print("no. is neither positive nor negative") elif (x > 0) and x <= 100: print("no. is positive but very small") if (x % 2) == 0: print("even") else: print("odd") elif (x < 0) and x >= -100: print("no. is negative but very small") if (x % 2) == 0: print("even") else: print("odd") elif 100 < x < 10000 or -10000 < x < -100: print("no. contains three or more digits") if (x % 2) == 0: print("even") else: print("odd") else: print("only smaller integral values are to be entered") print("Done")
false
3a38adf993db23d3b0dca7820c04e4e57ec4db9d
l0neaadil/Python_for_beginner
/14_for_loop.py
552
4.15625
4
# For Loop string = "3456789" list = [3, 4, 5, 6, 7, 8, 9] tuple = (3, 4, 5, 6, 7, 8, 9) set = {3, 4, 5, 6, 7, 8, 9} dictionary = {1: 'a', 2: 'b', 3: 'c'} print(string, list, tuple, set, dictionary) for element in string: print(element) for element in list: print(element) for element in tuple: print(element) for element in set: print(element) for element in dictionary.keys(): print(element) for element in dictionary.values(): print(element) for element in range(0, 31, 2): print(element % 2) print(element / 2)
false
f78d289529201648db63dbc4981b5ab121b3c61f
pathakamaresh86/python_class_prgms
/day5_assign.py
1,119
4.28125
4
#!/usr/bin/python num1=input("Enter number") print "Entered number ", num1 # if LSB(last bit) is zero then even if 1 then odd if num1&1 == 0: print str(num1) + " is even number" else: print str(num1) + " is odd number" num1=input("Enter number") print "Entered number ", num1 if num1&15 == 0: print str(num1) + " is divisible by 16" else: print str(num1) + " is not divisible by 16" num1,num2,num3=input("Enter lenght of three sides of triangle") print "Entered side1", num1 print "Entered side2", num2 print "Entered side3", num3 if num1>num2 and num1>num3 : side3=num1 temp=num2 + num3 elif num2>num3 : side3=num2 temp=num1 + num3 else : side3=num3 temp=num1 + num2 if temp > side3: print "It is triangle" else: print "not triangle" ''' D:\F DATA\python_class>python day5_assign.py Enter number12 Entered number 12 12 is even number Enter number144 Entered number 144 144 is divisible by 16 Enter lenght of three sides of triangle5,6,7 Entered side1 5 Entered side2 6 Entered side3 7 It is triangle '''
true
e48a1567b7c529cb7a6ff50ab7cf22844dc2b19f
pathakamaresh86/python_class_prgms
/day4_assign.py
1,011
4.21875
4
#!/usr/bin/python str=input("Enter string") print "Entered string ", str print "first tow and last two char string ", str[1:3:1]+str[-1:-3:-1] str1=input("Enter string") print "Entered string ", str1 print "occurance replaced string", str1[:1]+str1[1:].replace("b", "*") str1,str2=input("Enter two strings") print "str1=", str1 print "str2=", str2 print "swapped first two character strings", str2[:2] + str1[2:], str1[:2] + str2[2:] str1,str2=input("Enter two strings") print "str1=", str1 print "str2=", str2 size1=len(str1) size2=len(str2) if size1 != size2: print "2nd string is not right rotation of 1st" temp=str1+str1 #if (temp.count(str2)> 0): if (str2 in temp): print "2nd string is right rotation of 1st" else: print "2nd string is not right rotation of 1st" str1=input("Enter string") print "Entered string ", str1 str2="not bad" if (str2 in str1): print str1.replace("not bad", "good") else: print "string not contain not bad"
true
4e012bf0e6c051ee2585c2c27d33cd92c9babbe0
krishnagoli/python
/Harikah/test5.py
836
4.1875
4
my_string="Hello world" print(my_string.isalpha()) Output : False str1="HelloWorld" print(str1.isalpha()) Output : True str="hfdgkjfdhg" print(str.isdigit()) Output : False str="hfdgkjfdhg123" print(str.isdigit()) Output : False str="45435435435h" print(str.isdigit()) Output : False str="45435435435" print(str.isdigit()) Output : True a="Hello world" print(a.isalnum()) Output : False str2="356546" print(str2.isalnum()) Output : True str1="HELLO" print(str1.isupper()) Output : True str5="H78" print(str5.isupper()) Output : True str="Hello" print(str.isupper()) Output : False a='hello' print(a.islower()) Output : True a='Hello' print(a.islower()) Output : False a="hkh6767" print(a.islower()) Output : True b='Hello World' print(b.endswith('d')) Output : True b='Hello World' print(b.startswith('H')) Output : True
false
08ab6206785466e01758fc3df211b289d73e4fb6
MunsuDC/visbrain
/examples/signal/02_3d_signals.py
1,665
4.15625
4
""" Plot a 3D array of data ======================= Plot and inspect a 3D array of data. This example is an extension to the previous one (01_2d_signals.py). This time, instead of automatically re-organizing the 2D grid, the program use the number of channels for the number of rows in the grid and the number of trials for the number of columns. To illustrate this point, we generate a random EEG dataset composed with 20 channels, 10 trials of 4000 points each. The 2D grid will have a shape of (20 rows, 10 columns). .. image:: ../../picture/picsignal/ex_3d_signal.png """ from visbrain import Signal from visbrain.utils import generate_eeg sf = 512. # sampling frequency n_pts = 4000 # number of time points n_channels = 20 # number of EEG channels n_trials = 10 # number of trials in the dataset """Generate a random EEG dataset of shape (n_channels, n_trials, n_pts). Also get the associated time vector with the same length as the data. """ data, time = generate_eeg(sf=sf, n_pts=n_pts, n_trials=n_trials, n_channels=n_channels, smooth=200, noise=1000) time += 8. # force the time vector to start at 8 seconds time *= 1000. # millisecond conversion """The data have a shape of (20, 10, 4000). Hence, the time dimension is defined as the last axis i.e `axis=2` """ axis = 2 # localization of the time axis """Add a label to the x-axis (xlabel), y-axis (ylabel) and a title """ xlabel = 'Time (ms)' ylabel = 'Amplitude (uV)' title = 'Plot of a 1-d signal' Signal(data, sf=sf, axis=axis, time=time, xlabel=xlabel, ylabel=ylabel, title=title, bgcolor=(.1, .1, .1), axis_color='wlite', color='white').show()
true
82d1b9ee2f5a78cd095960a36a58e19b6239409e
zoeyouyu/GetAhead2020
/Q3 - solution.py
1,240
4.25
4
# Longest path in the Tree class Tree: def __init__(self, value, *children): self.value = value self.children = children # We walk the tree by iterating throught it, # yielding the length of the path ending at each node we encounter, # then take the max of that. def longest_path(tree): def rec(current, parent_value = 0, parent_path_length = 0): # Length of the longest chain this node is part of. current_path_length = (parent_path_length + 1 if current.value == parent_value + 1 else 1) # Emit the length of this node. yield current_path_length # Recurse into the children for child in current.children: # For each of the descendant nodes, emit their lengths as well for value in rec(child, current.value, current_path_length): yield value # Take the overall maximum length. return max(rec(tree)) # Tests if __name__ == "__main__": assert longest_path(Tree(1)) == 1 assert longest_path( Tree(1, Tree(2, Tree(4)), Tree(3)) ) == 2 assert longest_path( Tree(5, Tree(6), Tree(7, Tree(8, Tree(9, Tree(15), Tree(10))), Tree(12))) ) == 4
true
d54ce4cf2c186d149f51a6a37de807fbabdca25f
ritomar/ifpi-404-2017
/Simulado01-Q02.py
297
4.15625
4
quantidade = 0 soma = 0 n = int(input("Digite um valor qualquer, zero para terminar: ")) while n != 0: quantidade += 1 soma += n n = int(input("Digite um valor qualquer, zero para terminar: ")) print("Quantidade:", quantidade) print("Soma:", soma) print("Média:", soma/quantidade)
false
d386a27c06a6252f2331beff919a290887cd4825
saikumarsandra/My-python-practice
/Day-5/variableLengthArg.py
418
4.25
4
# when * is added before any argument then t act as the variable length argument #it act as a parameter that accepts N number of values to one argument act as a tuple def myFun(a,*b): print (a,b) myFun("sai",2.0) #type 2 myFun("this is 'a'",2.0,1,2,3,4,5,6,[1,2,3],(1,2,3),{9,8,10}) def avg(*vals): Average= sum(vals)/len(vals) print("avarage of the values",Average) avg(1,2,3,4,5,6,9,8,7,)
true
684e219a422c35b538a6acfe6a780d3d04c06b89
xpony/LearnPython
/def_function.py
1,777
4.28125
4
#自定义一个求绝对值的my_abs函数为例:\ # 方式 依次写 def 函数名 括号(及参数) : def my_abs(x): if x >= 0: return x #return 返回函数值 else: return -x print(my_abs(-3)) #注意,函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕,并将结果返回。 #如果没有return语句,函数执行完毕后也会返回结果,只是结果为None。return None可以简写为return。 #如果你已经把my_abs()的函数定义保存为abstest.py文件了,那么, #可以在该文件的当前目录下启动Python解释器,用from abstest import my_abs来导入my_abs()函数, #注意abstest是文件名 #空函数 如果想定义一个什么事也不做的空函数,可以用pass语句: def nop(): pass #pass可以用来作为占位符,比如现在还没想好怎么写函数的代码, #就可以先放一个pass,让代码能运行起来。 # 检查参数 用内置函数 isinstace() def my_Newabs(x): if not isinstance(int, float): raise TypeError('bad operand type') if x >= 0: return x else: return -x #print(my_Newabs('12')) #返回多个值 import math #导入math包,后续代码就可以使用math包里的sin、cos等函数了 def move(x, y, step, angle = 0): nx = x + step * math.cos(angle) ny = y + step * math.sin(angle) return nx, ny print(move(100, 100, 60, math.pi/6)) #但其实这只是一种假象,Python函数返回的仍然是单一值 r = move(100, 100, 60, math.pi/6) print(r) # 返回值其实是一个tuple (151.96152422706632, 130.0) #在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值, #list,set,dict 都类似可以这样赋值给变量
false
9a756fc8eac6f99a6e95a7cbe9e99c04ce777eb0
xpony/LearnPython
/filter.py
2,078
4.25
4
#filter( )函数 用于过滤序列。同样接收一个函数和一个序列,把传入的函数依次作用于每个元素, #然后根据返回值是True还是False决定保留还是丢弃该元素。和map()一样返回的是Iterator #例如,在一个list中,删掉偶数,只保留奇数,可以这么写: def is_odd(n): return n % 2 == 1 # 判断是否为奇数 num = filter(is_odd, [1, 2, 3, 4, 5, 6, 10]) print(list(num)) #把一个序列中的空字符串删掉,可以这么写: def not_empty(s): return s and s.strip() #strip()去除字符串首尾空格,对单个空格作用后,bool值为False s = filter(not_empty, ['A', 'B', '', None, ' ']) # None的bool值为False print(list(s)) #用filter求素数 #构造一个从3开始的奇数序列 def _odd_iter(): n = 1 while True: n = n + 2 yield n #这是个一个生成器函数 #生成器函数可以用for循环来不断输入结果,也可以生成个对象,然后用next()函数返回下个值 #g = _odd_iter() # print(next(g)) #定义一个帅选函数 def _not_divisible(n): return lambda x: x % n > 0 # 再定义一个生成器,不断返回下一个素数 def primes(): yield 2 it = _odd_iter() #生成一个对象,其包括大于3的奇数 while True: n = next(it) #返回序列的第一个数 yield n #返回素数 it = filter(_not_divisible, it) # 构造新序列 for n in primes(): # 打印100以内的素数: if n < 100: print(n) else: break # 练习 数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数: #教训!: 命名变量时千万不要用一些内置函数名,否则找找bug找到你哭 # 自然正整数生成函数 def _add_nums(): n = 10 while True: yield n n = n + 1 # 判断是否为回数 def number_h(n): return str(n) == str(n)[::-1] numbers = _add_nums() #生成自然是想序列的对象 nums = filter(number_h, numbers) # 生成回数序列 for n in nums: #打印出1000以内的回数 if n < 1000: print(n) else: break
false
790c398b7699707dd0881780f58dd63961956cf5
xpony/LearnPython
/slice.py
1,795
4.125
4
#切片(Slice): #取一个list或tuple的部分元素是非常常见的操作。比如,取前n个元素,我们可以用循环,但是太麻烦了。如果用切片就会非常简单: L = [1, 2, 3, 4, 5] print(L[0:2]) #取前两个元素 print(L[:2]) # 从索引零开始,可以省略 print(L[1:]) # 前 print(L[2:5]) #可以从索引2开始取,取到第五个 print(L[2:]) #默认取完 #既然Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片 print(L[-2:]) #从倒数第二个开始,取完 print(L[-2:-1]) print(L[1:3]) print(L[1:2]) #切片操作十分有用。我们先创建一个0-99的数列: L = list(range(100)) #range(100)表示从0开始生成含100个整数的序列 print(L[:10]) #取出前十个元素 print(L[-10:]) #取出后十个元素 print(L[10:20]) #前十一个到第二十个元素 print(L[:10:2]) #前十个每两个取一个 print(L[::5]) #所有数每五个取一个 print(L[:]) #原模原样复制出一个 print('---------------------------------------------------------------') #tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple: t = (1,2,3,4,5) print(t[:3]) #取出前三个 #字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串: s = 'mahongwei' print(s[:2]) #取出前两个 ### 练习 切除字符串首尾的空格 def trim(str): if len(str) == 0: print('请输入有效的字符串') return str elif str[0] == ' ': str = str[1:] return trim(str) elif str[-1] == ' ': str = str[0:-1] return trim(str) return str, len(str) print(trim(' ma ')) ## if、 elif 后边都要跟条件语句
false
0eb90832223c089e86b7ca5c0eda3f576f7b414f
mondon11/leetcode-top100
/0021mergeTwoLists.py
1,585
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/6/14 下午9:06 # @Author : jt_hou # @Email : 949241101@qq.com # @File : 0021mergeTwoLists.py # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ res = ListNode() cur = res while(l1 is not None and l2 is not None): if l1.val < l2.val: cur.next = ListNode(l1.val) cur = cur.next l1 = l1.next else: cur.next = ListNode(l2.val) cur = cur.next l2 = l2.next ''' while(l1 is not None): cur.next = ListNode(l1.val) cur = cur.next l1 = l1.next while(l2 is not None): cur.next = ListNode(l2.val) cur = cur.next l2 = l2.next ''' if l1 is not None: cur.next = l1 if l2 is not None: cur.next = l2 return res.next def genListNode(l): start = ListNode() cur = start for i in l: cur.next = ListNode(i) cur = cur.next return start.next if __name__ == '__main__': sol = Solution() l1 = [1, 2, 4] l2 = [1, 3, 4] l1_node = genListNode(l1) l2_node = genListNode(l2) res = sol.mergeTwoLists(l1_node,l2_node) print(res)
false
03edbcdf7a43db403c91d9499f8c7c90a1afdcbe
tsoporan/exercises_and_algos
/python/observer.py
1,096
4.28125
4
""" An example of the Observer pattern in Python. A Subject keeps track of its observers and has a method of notifying them. """ class Subject(object): def __init__(self): self.observers = [] def register_observer(self, observer): self.observers.append(observer) def unregister_observer(self, observer): self.observers.remove(observer) def notify_observers(self, *args, **kwargs): for obs in self.observers: obs.notify(*args, **kwargs) class Observer(object): def __init__(self, name): self.name = name def notify(self, *args, **kwargs): print("Called with args: %s %s" % (args, kwargs)) def __repr__(self): return 'Observer: %s' % self.name if __name__ == '__main__': sub = Subject() obs1 = Observer('1'); obs2 = Observer('2'); obs3 = Observer('3'); sub.register_observer(obs1) sub.register_observer(obs2) print(sub.observers, len(sub.observers) == 2) sub.unregister_observer(obs2) print(sub.observers, len(sub.observers) == 1) sub.register_observer(obs3) sub.notify_observers('notifying!')
true
f0407174a9908c1a73ee250296d334ae73bb178a
tsoporan/exercises_and_algos
/python/utopian_tree.py
762
4.34375
4
""" Utopian tree goes through 2 cycles of growth a YEAR. First cycle in spring: doubles in height Second cycle in summer: height increases by 1 Tree is planted onset of spring with height 1. Find the height of tree after N growth cycles. """ def growthAfterCycles(lst): out = [] for cycle in lst: height = 1 if cycle == 0: out.append(height) else: for run in range(cycle): if run % 2 == 0: height += height else: height += 1 out.append(height) return out if __name__ == '__main__': r1, r2, r3, r4 = growthAfterCycles([3,4,0,1]) print(r1 == 6) print(r2 == 7) print(r3 == 1) print(r4 == 2)
true
bb8bb6ca07ad5d3793b8e24fdee189d83657e294
wprudencio97/csc121
/wprudencio_lab6-8.py
1,759
4.40625
4
#William Prudencio, Chapter 6 - Lab 8, 8/18/19 ''' This program reads the random numbers that were generated into randomNumbers.txt and will display the following: 1)Count of the numbers in the file, 2)Total of the numbers in the file, 3)Average of the numbers in the file, 4)Largest and smallest number in the file. ''' #-----------------Define the main function--------------------- def main(): randomNumbers = open("randomNumbers.txt", "r") #open randomNumbers.txt readFile(randomNumbers) #send the file to the file reader function randomNumbers.close() #close randomNumbers.txt #-----------------Define the file reader function-------------- def readFile(randomNumbers): #start the counter and sum of the numbers counter, total = 0, 0 #declare the variables to store the biggests and smallest numbers smallestNumber, biggestNumber = 500, 0 print("\nNumbers read from file: \n") #print title for line in randomNumbers: #read lines on file line = int(line.rstrip("\n"))#remove new line character print(line) #print the lines #increase the counter and add to the total counter += 1 total += line #compare numbers to find biggest/smallest value if smallestNumber > line: smallestNumber = line if biggestNumber < line: biggestNumber = line #Print the Results print("\nNumbers read from the file: ", counter) print("Sum of the numbers read from the file: ", total) print("Average of the numbers read from the file: ", total/counter) print("Smallest number on the file: ", smallestNumber) print("Biggest number on the file: ", biggestNumber) #-----------call the main function to run the program----------- main()
true
315af1bee922074ca17a8b8002f87057224921e6
deanjingshui/Algorithm-Python
/17_位运算/231. 2的幂.py
1,735
4.3125
4
""" 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 输入: 1 输出: true 解释: 2^0 = 1 示例 2: 输入: 16 输出: true 解释: 2^4 = 16 示例 3: 输入: 218 输出: false 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/power-of-two """ class Solution_iterate: """ date:2020.9.18 author:fenghao 思路: 从0开始尝试,计算2的m次幂是否等于n,当计算结果大于n说明无法满足 时间复杂度:O(log n) """ def isPowerOfTwo(self, n: int) -> bool: m = 0 while 2**m < n: m += 1 if 2**m == n: return True else: return False class Solution_bit_manipulation: """ date:2020.9.18 author:labuladong 思路: 位运算:去除二进制中最右边的 1 n&(n-1) 这个操作是算法中常见的,作用是消除数字 n 的二进制表示中的最后一个 1。 一个整数如果是2的幂,则其二进制表达只有一个1 反证法:num = 2^n + 2^m = 2^n(1 + 2^(m-n)) 括号中的树为基数,则num不可能为2的幂 时间复杂度:O(1) """ def isPowerOfTwo(self, n: int) -> bool: if n <= 0: # 2的幂不可能为负数、零 return True result = True if n & (n-1) == 0 else False return result class Solution_bit_manipulation_simplify_code: """ date:2020.9.18 author:labuladong 思路: 精简代码 时间复杂度:O(1) """ def isPowerOfTwo(self, n: int) -> bool: return n > 0 and n & (n-1) == 0 n = 16 my_sol =Solution_bit_manipulation() print(my_sol.isPowerOfTwo(n))
false
a2989a38d363fa9517600d06844a71e590ae38c4
deanjingshui/Algorithm-Python
/5_二叉树/1. 二叉树的前序遍历.py
2,253
4.375
4
""" 给定一个二叉树,返回它的 前序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal """ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution_recursive: """ date:2020.9.23 author:fenghao 思路:递归 时间复杂度:O(2^n) n为二叉树的高度 空间复杂度:O() """ def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] left = right = [] if root.left: left = self.preorderTraversal(root.left) if root.right: right = self.preorderTraversal(root.right) return [root.val] + left + right class Solution_iterate_stack: """ date:2020.9.27 author:fenghao 思路:迭代 维护一个数据结构(栈),每次弹出栈顶的节点(暂时留着右节点),并将该节点的值存进结果,然后先后压入这个节点的右节点、左节点(注意入栈的顺序) 不断重复,直到这个数据结构(栈)为空 [root] [root.left, root.right] [root.left.left, root.left.right, root.right] 这是深度优先遍历DFS 时间复杂度:O(n) n为二叉树的节点个数 空间复杂度:O(h) h为二叉树的高度 """ def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] result = [] nodes_stack = [root] while nodes_stack: node = nodes_stack.pop(0) result.append(node.val) if node.right: nodes_stack.insert(0, node.right) if node.left: nodes_stack.insert(0, node.left) return result node_1 = TreeNode(1) node_2 = TreeNode(2) node_3 = TreeNode(3) node_1.right = node_2 node_2.left = node_3 my_sol = Solution_iterate_stack() print(my_sol.preorderTraversal(node_1))
false
c841dfbd88298c7f0a27e3a18d0e1533aad0b6e2
deanjingshui/Algorithm-Python
/1_双指针/11. 盛最多水的容器.py
1,411
4.125
4
""" 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water """ from typing import List class Solution_force: """ author:fenghao date:2021.4.5 思路:暴力法 两层循环穷举所有可能 时间:O(n^2) 空间:O(1) """ def maxArea(self, height: List[int]) -> int: pass class Solution_two_pointer: """ author:力扣+fenghao date:2021.4.5 思路:双指针 难点:左右指针移动的条件,应该移动左or右指针? 时间:O(n) 空间:O(1) """ def maxArea(self, height: List[int]) -> int: left = 0 right = len(height) - 1 maxArea = 0 while left < right: tmp = min(height[left], height[right])*(right-left) maxArea = max(maxArea, tmp) if height[left] <= height[right]: left += 1 else: right -= 1 return maxArea height = [1,8,6,2,5,4,8,3,7] my_sol = Solution() print(my_sol.maxArea(height))
false
ff9d8d7b4f3b4cba24822850d4fb1d78f52b9439
Gyol/Multicampus_Cloud
/common_ground/python_programming_stu/mycode/11_Lambda/lambda01.py
1,407
4.125
4
# 보통 함수 def add(x, y): return x + y print(add(10, 20)) # lambda add2 = lambda x, y : x + y print(add2(100, 200)) # 제곱승, 곱하기, 나누기를 람다 함수로 정의해서 호출 print() multi = lambda x, y : x ** y print(multi(2, 4)) mul = lambda x, y : x * y print(mul(18, 2)) dev = lambda x, y : x / y print(dev(20, 4)) mulmul = lambda x: x * 2 print(mulmul(3))\ print() llist = [1, 2, 3, 4, 5] result = map(lambda x: x * 2, llist) print(list(result)) result = list(map(lambda x: x * 2, llist)) print(result) # [1, 2, 3, 4, 5] + [1, 2, 3, 4, 5] # add(1, 1) add(2, 2) add(3, 3) print() ddist = [13, 14, 15, 16, 17] f_add = lambda x, y: x + y print(f_add(1, 88)) result = list(map(f_add, llist, ddist)) print(result) # llist 값을 제곱승해서 다른 리스트에 저장 # lambda 함수랑 map()함수 사용 other = lambda x: x ** 2 # 얘네는 한번에 # result = list(map(other, llist)) # print(result) # 이러면 하나씩 result = map(other, llist) print(next(result)) print(next(result)) print(next(result)) print(next(result)) print(next(result)) # filter 함수 print() result = list(filter(lambda x: x > 2, llist)) print(result) for a in filter(lambda x: x > 2, llist): print(a) # reduce # functools.py 라는 모듈 안에 있는 reduce함수를 불러오기 print() from functools import reduce result = reduce(lambda x, y: x + y, llist) print(result)
false
126540b591dd05de840b78447860cc2130c03326
svetlana-strokova/GB_BigData_1055_Python
/3/3 les 2page.py
817
4.21875
4
# 2 Задание Реализовать функцию, принимающую несколько параметров # переменные name = input('Введите имя - ') surname = input('Введите фамилию - ') year = int(input('Введите год рождения - ')) city = input('Введите город проживания - ') email = input('Введите email - ') telephone = input('Введите телефон - ') #функция с возвращением кортежа def my_func (name, surname, year, city, email, telephone): return ' '.join([name, surname, year, city, email, telephone]) print(my_func(name = 'Иван', surname = 'Иванов', year = '1988', city = 'Санкт-Петербург', email = 'email@mail.ru', telephone = '8-800-100-98-88'))
false
0a889f350a8c1b1efd46316f5786a8191250d934
svetlana-strokova/GB_BigData_1055_Python
/1lesson/1les 2page.py
1,289
4.125
4
# 2 Задание. Переведение секунд в минуты и часы с форматированием строк time = int(input('Введите время в секундах - ')) hours = time // 3600 #целочисленное деление minutes = (time // 60) - (hours * 60) # Из целого остатка часов остаток - минуты seconds = time % 60 # Остаток от деления часов и минут - секунды. 60 - потому что в мин - 60 сек print(f'{hours:02}:{minutes:02}:{seconds:02}') # Вариант, где в формат "часы минуты и секунды" введенное число переводится отдельно, минуты в часы не переводятся и тд #sek = int(input('Введите число секунд -')) #min = sek / 60 #hour = min / 60 or sek / 3600 #print(hour,'часов', ':', min, 'минут', ':', sek, 'секунд') # второй вариант, уже через форматирование строк #sek1 = int(input('Введите число секунд -')) #min1 = sek1 / 60 #hour1 = min1 / 60 or sek1 / 3600 #text: str = '''{0} часов : {1} минут : {2} секунд'''.format(hour1, min1, sek1) #print(text)
false
a9caaccc5a5ade933817c50c8a8daf912b3c0255
Tripl3Six/Rock-paper-scissors-lizard-spock
/rpsls.py
2,206
4.1875
4
# Rock-paper-scissors-lizard-Spock # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random as rand # helper functions def name_to_number(name): if name == 'rock': number = 0 elif name == 'Spock': number = 1 elif name == 'paper': number = 2 elif name == 'lizard': number = 3 elif name == 'scissors': number = 4 else: print "Error - enter a correct name inside quotation marks." return number # convert name to number using if/elif/else def number_to_name(number): if number == 0: name = 'rock' elif number == 1: name = 'Spock' elif number == 2: name = 'paper' elif number == 3: name = 'lizard' elif number == 4: name = 'scissors' else: print "Error number not in the range 0 to 4 inclusive" return name # convert number to a name using if/elif/else def rpsls(player_choice): # print a blank line to separate consecutive games print # print out the message for the player's choice print 'Player choice: ' + str(player_choice) # convert the player's choice to player_number using the function name_to_number() player_number = name_to_number(player_choice) # compute random guess for comp_number using random.randrange() comp_number = rand.randrange(0, 5) # convert comp_number to comp_choice using the function number_to_name() comp_choice = number_to_name(comp_number) # print out the message for computer's choice print 'Computer choice: ' + str(comp_choice) # compute difference of comp_number and player_number modulo five diff = (player_number - comp_number) % 5 # use if/elif/else to determine winner, print winner message if diff == 1 or diff == 2: print "Player wins!!" elif diff == 3 or diff == 4: print "Computer wins" else: print "Tie" player = input("Enter 'rock', 'paper', 'scissors', 'lizard', or 'spock': ") rpsls(player)
true
af76dc1189d8b1985cd069e250ca17ee1bde6dff
MahjubeJami/Python-Programming-01
/python essentials/mod03-exe03.py
994
4.5625
5
""" 3. You are trying to build a program that will ask the user the following: First Name Temperature Based on the user's entries, the program will recommend the user to wear a T-shirt if the temperature is over or equal to 70º or bring a sweater if it is less than 70º. Console Output What shall I wear today? Please Enter Your First Name: John What is Today's Temperature: 33 Hi John , You should probably bring a sweater ____________________________________________ Console Output What shall I wear today? Please Enter Your First Name: Mike What is Today's Temperature: 75 Hi Mike , It will be a warm day , T-shirt time! """ print("What shall I wear today? \n") name = input("Please Enter Your First Name: ") temp = int(input("What is Today's Temperature: ")) print("\n") if temp >= 70: print("Hi" , name, ", It will be a warm day , T-shirt time!") elif temp < 70: print("Hi" , name , ", You should probably bring a sweater")
true
1201f750d7ccc0c120fe4773ec50337bce5dc8c2
MahjubeJami/Python-Programming-01
/python strings/mod06-exe_6.7.py
1,890
4.21875
4
# Using the variable famous_list, write a program to check # if a famous individual is in the list above, if they are # then print: Sorry, the individual did not make the top 20 cut! # Otherwise print: Yup, the individual did make the top 20 cut. # # Console: # # Please Enter the name of the famous individual? Albert Einstein # Yup, Albert Einstein did make the Top 20 cut! # # Please Enter the name of the famous individual? leonardo Da vinci # Sorry, Leonardo Da Vinci did not make the Top 20 cut! famous_list = ''' \ Marilyn Monroe (1926 – 1962) American actress, singer, model Abraham Lincoln (1809 – 1865) US President during American civil war Nelson Mandela (1918 – 2013) South African President anti-apartheid campaigner John F. Kennedy (1917 – 1963) US President 1961 – 1963 Martin Luther King (1929 – 1968) American civil rights campaigner Queen Elizabeth II (1926 – ) British monarch since 1954 Winston Churchill (1874 – 1965) British Prime Minister during WWII Donald Trump (1946 – ) Businessman, US President. Bill Gates (1955 – ) American businessman, founder of Microsoft Muhammad Ali (1942 – 2016) American Boxer and civil rights campaigner Mahatma Gandhi (1869 – 1948) Leader of Indian independence movement Margaret Thatcher (1925 – 2013) British Prime Minister 1979 – 1990 Mother Teresa (1910 – 1997) Macedonian Catholic missionary nun Christopher Columbus (1451 – 1506) Italian explorer Charles Darwin (1809 – 1882) British scientist, theory of evolution Elvis Presley (1935 – 1977) American musician Albert Einstein (1879 – 1955) German scientist, theory of relativity Paul McCartney (1942 – ) British musician, member of Beatles Queen Victoria ( 1819 – 1901) British monarch 1837 – 1901 Pope Francis (1936 – ) First pope from the Americas ''' fullname = input("Please Enter the name of the famous individual? ") if fullname in famous_list: print("Yup,", fullname, "did make the Top 20 cut!") else: print("Sorry,", fullname, "did not make the Top 20 cut!")
true
3ab92c4162bb89747c786a4a6975a083f06dd368
MahjubeJami/Python-Programming-01
/python strings/mod06-exe_6.4.py
834
4.4375
4
""" 4. Write a Python function to create the HTML string with tags around the word(s). Sample function and result are shown below: add_html_tags('h1', 'My First Page') <h1>My First Page</h1> add_html_tags('p', 'This is my first page.') <p>This is my first page.</p> add_html_tags('h2', 'A secondary header.') <h2>A secondary header.</h2> add_html_tags('p', 'Some more text.') <p>Some more text.</p> """ # input from Console to have didffernt entrance for tags and contents input1 = input("Enter The Tag please: ") input2 = input("Enter the contents please: ").title() def add_html_tags(tag, content): print('<'+ tag + '>'+ content +'</' +tag +'>') # insted of repeated method call, I used input and call the function once add_html_tags(input1, input2)
true
be23e3bb52a6a191041264d2430fde3a4a1ebdd6
richardOlson/Intro-Python-I
/src/13_file_io.py
1,172
4.375
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # importing the os to get the path to find the file import os fooPath = os.path.join(os.path.dirname(__file__), "foo.txt") # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" # opening the file f = open(fooPath) print(f.read()) f.close() # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain # making the path for the bar file barPath = os.path.join(os.path.dirname(__file__), "bar.txt") # opening the path theFile = open(barPath, "w") theFile.write("Hey this is the first line in the bar file.\n") theFile.write("This is the second line of the file, yeah!\n") theFile.write("This is now the third line of the file!\n") theFile.close()
true
399553cdf2290f687ec9466a0ccf1353c2a1e2b9
pratikshyad32/pratikshya
/rock paper scissor game.py
1,833
4.1875
4
name=input("Enter your name") while name.isalpha()==False or len(name)<6: name=input("your name is wrong please enter again") else: print("Hello",name) age=(input("Enter your age")) while age.isdigit()==False : age=input("your age is wrong please enter again") else: print("your age is accepted",age) password=int(input("Enter your password")) password=int(1234567) while True: if password ==1234567: print("your password is accepted") break else: password("your password is wrong please enter again") count = 0 choice=input(" \n 1.Play Game \n 2.Exit\n") while choice != "2": if choice =="1": print("Game begins...") import random game_word =["rock","paper","scissor"] pc_result = random.choice(game_word) user_word = str(input("Enter in small letter type :'rock','paper','scissor':")) game_word = ['rock','paper','scissor'] pc_result = random.choice(game_word) if pc_result =='rock' and user_word =='paper' : print('you win') count= count + 1 elif pc_result == 'paper' and user_word == 'scissor': print("you win") count=count + 1 elif pc_result == 'scissor' and user_word == 'rock': print("you win") count=count + 1 elif pc_result == 'rock' and user_word == 'scissor': print("you lose") elif pc_result =='paper' and user_word == 'rock': print("you lose") elif pc_result == 'scissor' and user_word == 'paper': print("you lose") else: print("MATCH IS DRAW...") print("you have entered :",user_word) print("computer entered :",pc_result) print("your score is ",count) print("\n you wanna play again") if choice == "2": print("exit") choice = input("\n 1. play game \n 2.exit\n")
true
a2caca192e370b9e3565139dddb0515cff9ea421
SaiSudhaV/TrainingPractice
/ArraysI/array_square.py
312
4.1875
4
# 3 Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. def squares(ar): return sorted([i ** 2 for i in ar]) if __name__ == "__main__": n = int(input()) ar = list(map(int, input().split())) print(squares(ar))
true
7e60df36ee9effdd2a5b732fb34ad6b33b33b89b
Ap6pack/PythonProjects
/UserMenu
2,436
4.34375
4
#!/usr/bin/env python3 ### What and where the information is being stored userTuples = ["Name", "Age", "Sex"] userList = [ ] age2 = [] sex2 = [] ### I have used def to define my menu so I can use this format over and over. def userDirectory(): print "1. Add your information to the list" print "2. Find out the number of males and the number of females and the average age of each in the list" print "3. Print the list" print "4. Quit" print ### calling the Directory and setting the number of options userDirectory() userDirectory = 0 while userDirectory != 4: ### Printing user prompt and requesting users information userDirectory = input("Pick a number from the menu: ") print if userDirectory == 1: name = raw_input("What is your name? ") userList.append(name) userTuples = tuple(userList) age2 = raw_input("How old are you " + name + "? ") userList.append(age) age.append(age) userTuples = tuple(userList) sex2 = raw_input("What sex do you identify with Male or Female " + name + "? ") userList.append(sex) sex.append(sex) userTuples = tuple(userList) print print "Your name is " + name + ", you are " + age + " years old" + "and you identfy as a " + sex print ### Seconed user option asking if they would like to find out the number of males and the number of females and the average age of each in the list. elif userDirectory == 2: print "Number if Males in the list ", sex.count("male") + sex.count("Male") + sex.count("m") + sex.count("M") print "Number of Females in the list ", sex.count("female") + sex.count("Female") + sex.count("f") + sex.count("F") print "The average age of the Males ",'\n' ### still trying to solve this question print "The average age of the Females ", ### still trying to solve this question print print ### Third user option where they can print the information that has been inputed. elif userDirectory == 3: print userTuples print ### Fourth options is where the user can end the loop. elif userDirectory == 4: print "Thank you, Have a nice day" break
true
c045170367b61dbc0554b69f6c63ccd8caf176fc
chloebeth/codex-celerate
/benchmarks/code_output_4.py
542
4.1875
4
# - Time complexity: O(n) # - Space complexity: O(n) def myPow(x, n): if n == 0: return 1 if n < 0: return 1 / myPow(x, -n) if n % 2: return x * myPow(x, n - 1) return myPow(x * x, n / 2) # Optimize the space complexity of the above code # # - Time complexity: O(n) # - Space complexity: O(1) def myPow(x, n): if n == 0: return 1 if n < 0: return 1 / myPow(x, -n) res = 1 while n > 0: if n % 2: res *= x x *= x n //= 2 return res
false
d311436ad2902a7ccc5ea809669a280ab0aea17a
oekeur/MinProg_DataToolkit
/Homework/Week 1/exercise.py
2,028
4.25
4
# Name : Oscar Keur # Student number : 11122102 ''' This module contains an implementation of split_string. ''' # You are not allowed to use the standard string.split() function, use of the # regular expression module, however, is allowed. # To test your implementation use the test-exercise.py script. # A note about the proper programming style in Python: # # Python uses indentation to define blocks and thus is sensitive to the # whitespace you use. It is convention to use 4 spaces to indent your # code. Never, ever mix tabs and spaces - that is a source of bugs and # failures in Python programs. def split_string(source, separators): ''' Split a string <source> on any of the characters in <separators>. The ouput of this function should be a list of strings split at the positions of each of the separator characters. ''' output = [] j = 0 k = 0 # loop over the source while j in range(len(source)): k = 0 if source[j] not in separators: k = j + 1 # as long as k is not the list of separators, check for the next letter while k in range(len(source)) and source[k] not in separators: k += 1 # when a separator is found, add the characters between the separators to the output output.append(source[j:k]) # if a word was found, skip over the length of that word if k > 1: j += len(output[-1]) # else go to the next letter else: j += 1 # return the outputlist return output if __name__ == '__main__': # You can try to run your implementation here, that will not affect the # automated tests. # should print: ['c', 'd', 'r'] print split_string('abacadabra', 'ab') # should print: ['abc'] print split_string('abc', '') # should print: ['aba', 'adaba', 'a'] print split_string('abacadabra', 'cr') # should print: ['a', 'acada'] print split_string('abacadabra', 'b')
true
9f8efa161d8ef1b8bf35075c4723e4453cc265fc
licup/interview-problem-solving
/Module 7/kBackspace.py
838
4.125
4
''' K Backspaces The backspace key is broken. Every time the backspace key is pressed, instead of deleting the last (non-backspace) character, a '<' is entered. Given a string typed with the broken backspace key, write a program that outputs the intended string i.e what the keyboard output should be when the backspace key works properly. Input One line containing the string that was written in the text editor. Only contains lowercase letters from the English alphabet as well as the character '<'. '<' will not be the first character. ''' def k_backspace(inputString): stack = [] for character in inputString: if character == "<": stack.pop() else: stack.append(character) return "".join(stack) # Test Case testInput = 'a<bc<' actualOutput = k_backspace(testInput) print(actualOutput) #returns 'b'
true
968f323dc9381b444f1341813449e458dcc78e62
licup/interview-problem-solving
/Module 7/sya.py
1,342
4.15625
4
''' Reverse polish notation is a postfix notation for mathematical expressions. For example, the infix expression (1 + 2) / 3 would become 1 2 + 3 /. More detailed explanation here: https://en.wikipedia.org/wiki/Reverse_Polish_notation Task: Given a mathematical expression in reverse polish notation, represented by an array of strings, find the answer to this expression. Operators consist only of +, -, *, /, and all numbers are integer values. When performing a division on two numbers, use python's integer division operator (//). Your output should be a single integer, which is the value of the expression when evaluated. Each expression is guaranteed to be valid. ''' def evaluate_expression(expression): stack = [] for element in expression: if element.isnumeric(): stack.append(int(element)) else: if element == '+': n = stack.pop() n1 = stack.pop() stack.append(n + n1) elif element == '-': n = stack.pop() n1 = stack.pop() stack.append(n1 - n) elif element == '/': n = stack.pop() n1 = stack.pop() stack.append(n1 // n) elif element == '*': n = stack.pop() n1 = stack.pop() stack.append(n1 * n) return stack.pop() print(evaluate_expression(["3","4","+","5","-"])) #( 3 + 4 ) - 5 = 2
true
de6836359ebbac88fe38613153af669a9af33902
thisislola/Tutorials
/temp_calculator.py
1,825
4.28125
4
# Temperature Calculator by L. Carthy import time def intro_options(): """ Takes the option and returns the fuction that correlates """ option = int(input("1 for Fahrenheit to Celsius \n" "2 for Celcius to Fahrenheit \n" "3 for Fahrenheit to Kelvin: ")) if option == 1: ftoc_calc() elif option == 2: ctof_calc() elif option == 3: ftk_calc() else: print("That is not an option. Try again.") time.sleep(2) intro_options() def ftoc_calc(): """Calculates from Fahrenheit to Celsius. Returns the value of the calculation """ try: ftc_input = int(input("Enter the Fahrenheit value: ")) ftc_conversion = (ftc_input - 32) * 5/9 print("Your answer in Celsius is: ", ftc_conversion) except ValueError: print("Error: Your input is not a number. Try again.") time.sleep(2) ftoc_calc() def ctof_calc(): """Calculates from Celsius to Fahrenheit. Returns the value of the calculation """ try: ctf_input = int(input("Enter the Celsius value: ")) ctf_conversion = ctf_input * 9/5 + 32 print("Your answer in Fahrenheit is: ", ctf_conversion) except ValueError: print("Error: Your input is not a number. Try again.") time.sleep(2) ftoc_calc() def ftk_calc(): """Calculates from Fahrenheit to Kelvin. Returns the value of the calculation """ try: ftc_input = int(input("Enter the Fahrenheit value: ")) ftc_conversion = (ftc_input + 459.67) * 5/9 print("Your answer in Kelvin is: ", ftc_conversion) except ValueError: print("Error: Your input is not a number. Try again.") time.sleep(2) ftoc_calc() intro_options()
true
db54e4a06079cbba0c755e0df03afbe2892eb739
satishkr39/MyFlask
/Python_Demo/Class_Demo.py
1,415
4.46875
4
class Sample: pass x = Sample() # creating x of type Sample print(type(x)) class Dog: # def __init__(self, breed): # self.breed = breed # CLASS OBJECT ATTRIBUTE IT will always be same for all object of this class species = 'Mammal' # INIT METHOD CALLED EVERY TIME AN OBJECT IS CREATED def __init__(self, breed, name): self.breed = breed self.name = name # repr returns the string representation of class object. when we print an object this repr is called. def __repr__(self): return f" Breed: {self.breed}, name: {self.name}" # it used to return the len() method def __len__(self): return self.name # myDog = Dog('Lab') # print("Breed of myDog is " + myDog.breed) myDog = Dog('Lab', 'MyDogName') print(myDog.breed, myDog.name) print("Printing objects calls repr method: ", myDog) print(myDog.species) print(len(myDog)) # CIRCLE CLASS DEMO class Circle: pi = 3.14 def __init__(self, radius=1): self.radius = radius def area(self, radius): return self.pi * self.radius * self.radius def circumference(self, radius): return 2 * self.pi * self.radius myCircle = Circle() print("Circle with default value : "+ str(myCircle.area(1))) myCircle2 = Circle() print("Circle with radius 10 : "+ str(myCircle2.area(10))) print("Circumference with radius 10: "+ str(myCircle2.circumference(10)))
true
c9685fe1d887a5f52952043f559ce6e71108ef27
anand-ryuzagi/Data-Structue-and-Algorithm
/Sorting/merge-sort.py
1,123
4.25
4
# mergesort = it is divide and conquer method in which a single problem is divided in to small problem of same type and after solving each small problem combine the solution. # Time complexity : O(nlogn) # Space complexity : O(n) # algorithms : # 1. divide the array into two equal halves # 2. recursively divide each sub arrays into two halves until length of last subarray is equal to 1. # 3. after that apply merge function to join the solution of all the problems. def merge(a,b,arr): len_a= len(a) len_b = len(b) i = 0 j = 0 k = 0 while i<len_a and j<len_b: if a[i] <= b[j]: arr[k] = a[i] i +=1 else: arr[k] = b[j] j+=1 k += 1 while i<len_a: arr[k] = a[i] i += 1 k += 1 while j<len_b: arr[k] = b[j] j += 1 k += 1 def mergeSort(arr): if len(arr) <= 1: return mid = len(arr)//2 left = arr[:mid] right = arr[mid:] mergeSort(left) mergeSort(right) merge(left, right, arr) arr =[1,5,2,3,9,7,0] mergeSort(arr) print(arr)
true
4691857dd272f5ed6cd0bb040dfe7157ad429407
micaris/Data-Structures-and-Algorithms
/Sorting.py
1,715
4.125
4
#Bubble sort def bubble_sort(a_list): for pass_num in range(len(a_list) - 1, 0, -1): for i in range(pass_num): if a_list[i] > a_list[i + 1]: temp = a_list[i] a_list[i] = a_list[i + 1] a_list[i + 1] = temp def selection_sort(a_list): for fill_slot in range(len(a_list) -1 , 0, 1): pos_of_max = 0 for location in range(1, fill_slot + 1): if a_list[location] > a_list[pos_of_max]: pos_of_max = location temp = a_list[fill_slot] a_list[fill_slot] = a_list[pos_of_max] a_list[pos_of_max] = temp def insertion_sort(a_list): for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position - 1] > current_value: a_list[position] = a_list[position - 1] position = position - 1 a_list[position] = current_value def shell_sort(a_list): sublist_count = len(a_list) // 2 while sublist_count > 0: for start_position in range(sublist_count): gap_insertion_sort(a_list, start_position, sublist_count) print("After increments of size", sublist_count, "The list is", a_list) sublist_count = sublist_count // 2 def gap_insertion_sort(a_list, start, gap) : for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while position >= gap and a_list[position - gap] > current_value: a_list[position] = a_list[position - gap] position = position - gap a_list[position ] = current_value def merge_sort(a_list): pass
false
7b498522f914cf3f88d686578da8201adaf2bb10
devathul/prepCode
/DP/boxStacking.py
2,661
4.21875
4
""" boxStacking Assume that we are given a set of N types 3D boxes; the dimensions are defined for i'th box as: h[i]= height of the i'th box w[i]= width of the i'th box d[i]= depth of the i'th box We need to stack them one above the other and print the tallest height that can be achieved. One type of box can be used multiple times. Condition of the stacking is: 1. The box can be placed on top of another box, iff the lower box's top surface area is strictly larger than the upper box's base area 2. Strictly larger area is where the both length and width are higher n = 4 height[] = {4,1,4,10} width[] = {6,2,5,12} length[] = {7,3,6,32} Output: 60 Explanation: One way of placing the boxes is as follows in the bottom to top manner: (Denoting the boxes in (l, w, h) manner) { 2 , 1 , 3 } { 3 , 2 , 1 } { 5 , 4 , 6 } { 6 , 5 , 4 } { 7 , 6 , 4 } { 12 , 10 , 32 } { 32 , 12 , 10 } Hence, the total height of this stack is 10 + 32 + 4 + 4 + 6 + 1 + 3 = 60. No other combination of boxes produces a height greater than this. """ class Box: def __init__(self,length,width,height): self.length=length self.width=width self.height=height self.area=length*width def printbox(self): print("{",self.length,",",self.width,",",self.height,"}") def allBoxesWithDimensions(box): if box is None: return None return [Box(max(box.length,box.width),min(box.length,box.width),box.height),Box(max(box.length,box.height),min(box.length,box.height),box.width),Box(max(box.width,box.height),min(box.width,box.height),box.length)] def stackBoxes(length,width,height): if length is None or width is None or height is None or len(length)!=len(width) or len(length)!=len(height): return None n=len(height) boxes=[] for i in range(n): boxes.append(Box(length[i],width[i],height[i])) boxAllType=[] for i in range(n): boxAllType.extend(allBoxesWithDimensions(boxes[i])) boxAllType=sorted(boxAllType,key=lambda x:x.area)[::-1] #for i in boxAllType: # i.printbox() m=len(boxAllType) maxTillNow=[i.height for i in boxAllType] result=[i for i in range(m)] for i in range(1,m): for j in range(i): if boxAllType[i].length<boxAllType[j].length and boxAllType[i].width<boxAllType[j].width: maxTillNow[i]=maxTillNow[j]+boxAllType[i].height result[i]=j maxVal=max(maxTillNow) print("Max Value:",maxVal) maxIndex=maxTillNow.index(maxVal) i=maxIndex su=0 while i!=result[i]: boxAllType[i].printbox() su+=boxAllType[i].height i=result[i] boxAllType[i].printbox() height = [4,1,4,10] width = [6,2,5,12] length = [7,3,6,32] stackBoxes(length,width,height) height=[4,5] width=[2,2] length=[1,3] stackBoxes(length,width,height)
true
92bcb1209ffeea2320590bd05a442c73bf492dfe
connorholm/Cyber
/Lab2-master/Magic8Ball.py
960
4.125
4
#Magic8Ball.py #Name: #Date: #Assignment: #We will need random for this program, import to use this package. import random def main(): #Create a list of your responses. options = [ "As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don’t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes.", "Yes – definitely.", "You may rely on it." ] #Prompt the user for their question. response = random.choice(options) # Answer question randomly with one of the options from your earlier list. input("Ask the Magic 8 Ball something: ") print(response) main()
true
115595d836d0f9202a444db48c5abb71020eeb00
xMijumaru/GaddisPythonPractice
/Chapter 2/Gaddis_Chap2_ProgEX10_Ingredient/main.py
486
4.125
4
#this program will run the ingredients needed to produce cookies amount=int(input('How many cookie(s) do you wish to make: ')) #this is the amount that makes 48 cookies sugar=1.5/48.0 butter=1/48.0 flour=2.75/48.0 #reminder that // is int division and / is float division print("Amount to make ",amount, " cookie(s)") print("Sugar: ", format(sugar*amount, ',.02f'), "cups") print("Butter: ", format(butter*amount,',.02f'), "cups") print("Flour: ", format(flour*amount,',.02f'), "cups")
true
fe5d02ecda6c3b78d3e3b418211ad508a60c000f
yms000/python_primer
/rm_whitespace_for_file.py
820
4.15625
4
#! /usr/bin/python # -*- coding: utf-8 -*- # rm_whitespace_for_file.py # author: robot527 # created at 2016-11-6 ''' Remove trailing whitespaces in each line for specified file. ''' def rm_whitespace(file_name): '''Remove trailing whitespaces for a text file.''' try: with open(file_name, 'r+') as code: line_list = [item.rstrip() + '\n' for item in code] code.seek(0) code.truncate(0) code.writelines(line_list) print 'Removed trailing whitespaces for file: ' + file_name except IOError as err: print 'File error: ' + str(err) if __name__ == '__main__': import sys argc = len(sys.argv) if argc < 2: print 'Usage: python rm_whitespace_for_file.py /path/to/file' else: rm_whitespace(sys.argv[1])
true
02c841ac52ca32b61b87f71502f072c047ac38ea
BrothSrinivasan/leet_code
/cycle graph/solution.py
1,534
4.1875
4
# Author: Barath Srinivasan # Given an unweighted undirected graph, return true if it is a Cycle graph; # else return false. A Cycle Graph is one that contains a single cycle and every # node belongs to that cycle (it looks like a circle). # Notes: # a cycle is only defined on 3 or more nodes. # adj_matrix is an n-by-n list of lists representing the adjacency matrix of a simple graph. adj_matrix[i][i] = 0 for all i from 0 to n-1 (inclusive). # Explanation of Code """ My reasoning was that for the graph to be a single cycle is if each node has exactly two paths. For example consider this valid example: 4<-1<->2<->3<->4->1. Every node is surrounded by a path foward and a path backward. Using this reasoning, I just run through the matrix to see if row has two paths. """ # Analysis of Code """ The time complexity of this code is O(E^2). This is because a single row has enough elements to correspond to every node in the graph, thus V equals E. Since we we do a count function for each row, the complexity is O(E^2). Space complexity is O(1) since I don't use any additional space for my computation. """ def is_cycle(adj_matrix): if adj_matrix is not None: # checks if we can param is null for c in range(0, len(adj_matrix)): # goes through all rows of the matrix if adj_matrix[c].count(1) is not 2: # checks the number of connections in the node return False; # is there is not exactly 2 connections, then the cycle doesn't exist return True; # exactly 2 connections for all Nodes return False; # param was null
true
fa5ee033646904e358b3f504d3597831a5701336
Tajveez/intermediate-python
/lists.py
629
4.125
4
myList = ["banana", "apple", "cherry"] print(myList) myList2 = list() print(myList2) myList3 = [5, True, "apple", "apple"] print(myList3) print(myList[2]) print(myList[-1]) for x in myList: print(x) if "banana" in myList: print('Yes') else: print('No') print(len(myList3)) myList.append("lemon") myList.insert(1, "blueberry") print(myList) # removing all element myList.pop() myList.remove("cherry") # Delete all item myList.clear() myList3.reverse() myList.sort() new_list = sorted(myList) #sorted method myListNum = [0] * 5 print(myListNum) myListNum2 = [1, 2, 3] new_num_list = myListNum + myListNum2
false
a85e19425d0c1ca0e7d9907fb2d7421acdbfa71e
avneetkaur1103/workbook
/DataStructure/BinaryTree/tree_diameter.py
1,342
4.1875
4
""" Print the longest leaf to leaf path in a Binary tree. """ class Node: def __init__(self, value): self.key = value self.left = self.right = None def diameter_util(root): if not root: return 0, [] left_height, left_subtree_path = diameter_util(root.left) right_height, right_subtree_path = diameter_util(root.right) if left_height + right_height + 1 > diameter_util.max_width: diameter_util.max_width = left_height + right_height + 1 diameter_util.final_path.clear() diameter_util.final_path += left_subtree_path + [root.key] + list(reversed(right_subtree_path)) if left_height > right_height: return 1+left_height, left_subtree_path + [root.key] return 1+right_height, right_subtree_path + [root.key] diameter_util.max_width = float('-inf') diameter_util.final_path = list() def diameter(root): diameter_util(root) print('Ans = ', diameter_util.final_path) if __name__ == '__main__': # Enter the binary tree ... # 1 # / \ # 2 3 # / \ # 4 5 # \ / \ # 8 6 7 # / # 9 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.left.right.right = Node(7) root.left.left.right = Node(8) root.left.left.right.left = Node(9) diameter(root)
true
3fd71c526ccbfcf4ab615d8615084924088c0c3e
natanisaitejasswini/Python-Programs
/OOP/underscoreduplicte.py
997
4.5625
5
""" map => Take a list and a function, and return the list you get by applying that function to every item in the list filter => Take a list and return only the values when a given function is true my_filter([1,2,3,4,5], lambda x: x%2==0) => [2,4] reject => The exact opposite of filter my_reject([1,2,3,4,5], lambda x: x%2==0) => [1,3,5] find => Return the first value in the list where the function is true my_find([1,2,3,4,5], lambda x: x%2==0) => 2 all => Return True if the function is true for every item in the list, false otherwise my_all([1,2,3,4,5], lambda x: x%2==0) => False any => Return True if the function is true for any item in the list, false otherwise my_any([1,2,3,4,5], lambda x: x%2==0) => True """ def my_map(lst, func): output = [] for item in lst: # print("for loop") output.append(func(item)) # print(item) # print(func(item)) return output def square(num): return num**2 a = [1,2,3,4,5] print(my_map(a, square)) print(a) Add Comment
true
4107b89ed8a9320e97038724aff412aad3bc84e4
LVargasE/CS21
/Extracurricular/OOP-Door-Example.py
1,044
4.15625
4
""" OOP example using doors """ class Door: color = 'brown' def __init__(self, number, status): self.number = number self.status = status @classmethod def knock(cls): print("Knock!") @classmethod def paint(cls, color): cls.color = color def open(self): self.status = 'open' def close(self): self.status = 'closed' class SecurityDoor(Door): locked = True def __init__(self, number, status): self.door = Door(number, status) def open(self): if self.locked: return self.door.open() def __getattr__(self, attr): return getattr(self.door, attr) class ComposedDoor: def __init__(self, number, status): self.door = Door(number, status) def __getattr__(self, attr): return getattr(self.door, attr) class Room: def __init__(self, door): self.door = door def open(self): self.door.open()
false
75b5e1c59aa553349af121218c3281442fa60a78
shivakarthikd/practise-python
/single_linked_list.py
1,615
4.28125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print(temp.val) temp = temp.next class Solution: def mergeKLists(self, lists:ListNode) : l=list() for i in lists: temp=i.head while (temp): l.append(ListNode(temp.val)) temp=temp.next for i in l.sort(): print(i.val) # Code execution starts here if __name__ == '__main__': # Start with the empty list ls=list() llist = LinkedList() llist.head = ListNode(1) second = ListNode(2) third = ListNode(3) llist.head.next = second # Link first node with second second.next = third; # Link second node with the third node ls.append(llist) llist1 = LinkedList() llist1.head = ListNode(1) second1 = ListNode(2) third1 = ListNode(3) llist1.head.next = second1 ; # Link first node with second second1.next = third1 ls.append(llist1) llist2 = LinkedList() llist2.head = ListNode(1) second2 = ListNode(2) third2 = ListNode(3) llist2.head.next = second2 # Link first node with second second2.next = third2 ls.append(llist2) #llist.printList() #llist1.printList() #llist2.printList() sol=Solution() sol.mergeKLists(ls)
true
bddacb0f55e6d1b2332f6a48471ad8b0b31c51b6
StRobertCHSCS/ics2o1-201819-igothackked
/life_hacks/life_hack_practice_1.3.py
527
4.34375
4
''' ------------------------------------------------------------------------------- Name: minutes_to_days.py Purpose: converts minutes into days, hours, minutes Author: Cho.J Created: date in 22/02/2019 ------------------------------------------------------------------------------ ''' #PRINT minute= int(input("How many minutes: ")) #COMPUTE days= minute//1440 hours_left= minute%1440 hours= hours_left//60 days_left= minute%60 #PRINT print(minute, "minutes=", days, "days, ", hours, "hours, ", days_left, "minutes")
true
f680f5deb0653aa00c080a84d992f8bacb58d6d0
StRobertCHSCS/ics2o1-201819-igothackked
/unit_2/2_6_4_while_loops.py
276
4.34375
4
numerator = int(input("Enter a numerator: ")) denominator = int(input("Enter denominator: ")) if numerator // denominator : print("Divides evenly!") else: print("Doesn't divide evenly.") while denominator == 0: denominator = int(input("Enter denominator: "))
true
7d05afce4800e027970c6523cb3f83abf677a020
mihaivalentistoica/Python-Fundamentals
/python-fundamentals-master/09-flow-control/while-loop-exercise.py
1,012
4.3125
4
user_input = "" # b. If the input is equal to “exit”, program terminates printing out provided input and “Done.”. while user_input != "exit": # a. Asks user for an input in a loop and prints it out. user_input = input("Provide input: ") # c. If the input is equal to “exit-no-print”, program terminates without printing out anything. if user_input == "exit-no-print": break # d. If the input is equal to “no-print”, program moves to next loop iteration without printing anything. if user_input == "no-print": continue # a. Asks user for an input in a loop and prints it out. # b. If the input is equal to “exit”, program terminates printing out provided input and “Done.”. # e. If the input is different than “exit”, “exit-no-print” and “no-print”, program repeats. print(user_input) else: # b. If the input is equal to “exit”, program terminates printing out provided input and “Done.”. print("Done.")
true
5f37a37f5b8d2ac55c0bdc1b6be249058c8b411e
ShivangiNigam123/Python-Programs
/regexsum.py
381
4.1875
4
#read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. import re name = input ("enter file :") sum = 0 fhandle = open(name) numlist = list() for line in fhandle: line = line.rstrip() numbers = re.findall('[0-9]+',line) for number in numbers : sum = sum + int(number) print(sum)
true
5396067aa7a5580b864123469f232d1c7fce7369
danbeyer1337/Python-Drill--item-36
/item36Drill.py
1,963
4.125
4
#Assign an integer to a variable number = 4 #Assign a string to a variable string = 'This is a string' #Assign a float to a variable x = float (25.0/6.0 ) #Use the print function and .format() notation to print out the variable you assigned print 'The variables are {0}, {1}, {2}'.format(number, string, x) #Use each of these operators +, - , * , / , +=, = , % print 4+2, 3-2, 5*5, 36/6, 9%2 y = 3 y += 2 print y #Use of logical operators: and, or, not if 3 < 4 and 5 > 4: print('condition met') if 10 < 11 or 15 < 223: print('condition met') #Use of conditional statements: if, elif, else x = 10 if x == 10: print'x = 10' elif x == 9: print'x = 9' else: print 'x does not equal 9 or 10' #Use of a while loop counter = 0 while counter < 5: print counter counter += 1 #Use of a for loop for counter in range(0,5): print counter #Create a list and iterate through that list using a for loop to print each item out on a new line favorite_games_list = ['Overwatch', 'PUBG', 'Hearthstone', 'Destiny'] for game in favorite_games_list: print game #11. Create a tuple and iterate through it using a for loop to print each item out on a new line candy = ('apple', 'orange', 'banana', 'chocolate') print ('\n Flavors of candy that we have', candy) print ('Your items: ') for item in candy: print (item) #12. Define a function that returns a string variable #Function that determines if a girl is too young for you or not def allowed_dating_age(my_age): girls_age = my_age/2 +7 return girls_age dans_limit = allowed_dating_age(24) carls_limit = allowed_dating_age(27) glens_limit = allowed_dating_age(40) print('Dan can date girls', dans_limit, 'or older') print('Carl can date girls', carls_limit, 'or older') print('Glen can date girls', glens_limit, 'or older')
true
3506f85dcd5b448b4f0c009e1fa9a239dacc45ba
IamBikramPurkait/100DaysOfAlgo
/Day 3/Merge_Meetings.py
1,451
4.25
4
'''Write a function merge_ranges() that takes a list of multiple meeting time ranges and returns a list of condensed ranges.Meeting is represented as a list having tuples in form of (start time , end time)''' # Time complexity is O(nlogn) def merge_meetings_time(meetinglist): # Sort the meetings by start time meetings_sorted = sorted(meetinglist) # Initialize with the first element of meetings_sorted merged_meetings = [meetings_sorted[0]] for current_meeting_start , current_meeting_end in meetings_sorted[1:]: last_merged_meeting_start , last_merged_meeting_end = merged_meetings[-1] #Last merged will always be the last item in list # First case: Where the two meetings overlap if current_meeting_start <= last_merged_meeting_end: print('Merger done between', (current_meeting_start , current_meeting_end) ,'and' ,(last_merged_meeting_start , last_merged_meeting_end)) merged_meetings[-1] = (last_merged_meeting_start , max(current_meeting_end ,last_merged_meeting_end)) else: # If they don't overlap merged_meetings.append((current_meeting_start, current_meeting_end)) return merged_meetings sample_input = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] print('Given schedule is :', sample_input) print('After compaction the schedule is : ', end = '') print(merge_meetings_time(sample_input))
true
41e0d6d733fba92c65018cb3df37ed00baf1eff3
IamBikramPurkait/100DaysOfAlgo
/Day 4/FirstComeFirstServe.py
1,258
4.21875
4
# Recursive Approach # Problem statement : Write a function to check if a restaurant serves first come , first serve basis # Assumptions: 1)There are three lists dine_in_orders , take_out_orders , served_orders # 2)The orders number will not be ordered and are randomly assigned # 3)They are given as lists ''' Input format : Three lists Output Format: True/False Edge cases : 1) When one or both the lists are empty 2) If few orders were take away and not marked in the being served list''' def is_first_come_first_serve(take_out_orders , dine_in_orders , served_orders): if len(served_orders) == 0: return True if len(take_out_orders) and take_out_orders[0] == served_orders[0]: return is_first_come_first_serve(take_out_orders[1:],dine_in_orders,served_orders[1:]) elif len(dine_in_orders) and dine_in_orders[0] == served_orders[0]: return is_first_come_first_serve(take_out_orders ,dine_in_orders[1:],served_orders[1:]) else: return False take_out_sample = [17 ,8 ,24] dine_in_sample = [12 ,19 ,2] served_sample = [17 ,8 ,12 ,19 ,24 ,2] print(is_first_come_first_serve(take_out_sample , dine_in_sample ,served_sample))
true
1e4d7b0f98b1d63b4bf82cb8f1b353176cc71c42
IamBikramPurkait/100DaysOfAlgo
/Day1/Tower of Hanoi.py
1,367
4.25
4
''' Problem Tower of Hanoi: About: Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk 4) That is we cant have a bigger disk over smaller disk''' '''Sources: https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/ Sources: https://www.khanacademy.org/computing/computer-science/algorithms/towers-of-hanoi/e/move-three-disks-in-towers-of-hanoi''' # Khan Academy link provides excellent visualization of problem # Used a recursive approach def tower_of_hanoi(from_disk , to_disk , aux_disk , n): if(n==1) : #Base case print('Move disk 1 from',from_disk,'To',to_disk) return tower_of_hanoi(from_disk , aux_disk ,to_disk , n-1) #Recursive calling with n-1 disks print('Move disk',n,'from',from_disk ,'To',to_disk) tower_of_hanoi(aux_disk ,to_disk , from_disk, n-1) # Sample inputs print('Enter number of disks :',end='') disks = input() # Sample input tower_of_hanoi('A','B','C',int(disks)) #Passing value to the function
true
c62c719c3585ce32b829726429725e03a650c4a5
G1998P/SEII-GuilhermePeresSilva
/Semana02/prog018.py
617
4.15625
4
''' ordenacao de lista ''' # metodos sort e sorted #sorted cria uma nova lista #sort organiza a propria lista l = [1,4,3,2,10,65,3] l2 = sorted(l) print(l2) print(l)#l nao for ordenada # l.sort() # print(l)# l foi ordenada t = tuple(l) # tuiples nao possui o metodo sort print(sorted(t)) # pode ser passado uma funcao para atribuir um valor ordenavel a um objeto, util para organizar dicionarios d = [] for i in range(len(l)): d.append({'name':f'pessoa{i}','age':l[i]}) # dd = sorted(d) dd2 = sorted(d,key=lambda a:a['age']) for pessoa in dd2: nome , idade = pessoa.values() print(nome,idade)
false
f93e10068776b3ab4e298bf55eae39598a38ec5d
indexcardpills/python-labs
/02_basic_datatypes/2_strings/02_09_vowel.py
444
4.25
4
''' Write a script that prints the total number of vowels that are used in a user-inputted string. CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel in the string and print a count for each of them? ''' #string=input("write a sentence: ") string="the dog ate the cat" a=string.count("a") e=string.count("e") i=string.count("i") o=string.count("o") u=string.count("u") print(a+e+i+o+u)
true