blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b942302e280c289fceac406b562b7fb05b7cab36
36rahu/codewar_works
/22-4-2015/product_of_diagonal.py
341
4.3125
4
''' Description: Given a list of rows of a square matrix, find the product of the main diagonal. Examples: main_diagonal_product([[1,0],[0,1]]) => 1 main_diagonal_product([[1,2,3],[4,5,6],[7,8,9]]) => 45 ''' def main_diagonal_product(mat): result = 1 for i in range(len(mat[0])): result *= mat[i][i] return result
true
153705a0ea3ff05d7e59fcd5bee4f28ac60ce413
muhammeta7/CodeAcademyPython
/strings_cons_output.py
1,542
4.375
4
# Create a string by surrounding it with quotes string = "Hello there " # For words with apostrophe's us a backslash \ print "There isn\'t flying, this is falling with style!" # Accesing by index print fifth_letter = "MONTY"[4] # Will return Y # String methods parrot = "Parrot" print len(parrot) # will return number of letters in a string which in this case is 6 print parrot.lower() # will return parrot with all lowercase letters print parrot.upper() # will return PARROT with all captialized letters pi = 3.14 print str(pi) # will turn non-strings into strings # String Concatenation print "Green Eggs " + "and " + "ham!" # Must take into account spaces # String formatting with % name = "Moe" state = "New Jersey" print "Hello my name is %s! I am from %s" %(name, state) # String concatination with raw_inputs name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?") # \ is simply a continuation marker print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color) # Getting current data and time from datetime import datetime now = datetime.now print now # will print date in following format year-month-day 23:43:37.127290 print now.year # will return current year print now.month # will return current month print now.day # will return current day # To properly format everything simply use %s print "%s/%s/%s" % (now.month, now.day, now.year) # Same can be done for time using hour, minute, second
true
598768ac97d73068511606617b003142fcbcc7c1
anbarasanv/PythonWB
/Merge Sort Recursive.py
890
4.21875
4
#Time complexity O(n log n) def merge(left,right): '''This Function will merge 2 array or list''' result = [] i,j = 0,0 #Comparing two list for smallest element while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i +=1 else: result.append(right[j]) j +=1 #left elements appends to the result list result += left[i:] result += right[j:] return result def mergeSort(lst): '''This is the recursive sorting array''' if(len(lst) <= 1): return lst #Finding the mid mid = int(len(lst)/2) #Recursive call for left and right array or list left = mergeSort(lst[:mid]) right = mergeSort(lst[mid:]) #Merginging splited lists or array return merge(left,right) A = [1,-2,0,-3,10,999999,20] print(mergeSort(A))
true
3000f9b65ad6926b0274a5d94ea41a7e2608781f
bimri/programming_python
/chapter_1/person_start.py
1,107
4.125
4
"Step 3: Stepping Up to OOP" 'Using Classes' class Person: def __init__(self, name, age, pay=0, job=None): self.name = name self.age = age self.pay = pay self.job = job if __name__ == '__main__': bob = Person('Bob Smith', 42, 30000, 'software') sue = Person('Sue Jones', 45, 40000, 'hardware') print(bob.name, sue.pay) print(bob.name.split()[-1]) sue.pay *= 1.10 print(sue.pay) ''' This isn’t a database yet, but we could stuff these objects into a list or dictionary as before in order to collect them as a unit: >>> from person_start import Person >>> bob = Person('Bob Smith', 42) >>> sue = Person('Sue Jones', 45, 40000) >>> people = [bob, sue] # a "database" list >>> for person in people: print(person.name, person.pay) >>> x = [(person.name, person.pay) for person in people] >>> x [('Bob Smith', 0), ('Sue Jones', 40000)] >>> [rec.name for rec in people if rec.age >= 45] # SQL-ish query ['Sue Jones'] >>> [(rec.age ** 2 if rec.age >= 45 else rec.age) for rec in people] [42, 2025] '''
true
9ae6c269b41521b7ededa35ccae246557185174f
bimri/programming_python
/chapter_7/gui2.py
492
4.28125
4
"Adding Buttons and Callbacks" import sys from tkinter import * widget = Button(None, text='Hello GUI world!', command=sys.exit) widget.pack() widget.mainloop() ''' Here, instead of making a label, we create an instance of the tkinter Button class. For buttons, the command option is the place where we specify a callback handler function to be run when the button is later pressed. In effect, we use command to register an action for tkinter to call when a widget’s event occurs. '''
true
f46676e4e06c7657a92b10f6ac48f8a13f199d02
bimri/programming_python
/chapter_1/tkinter102.py
964
4.15625
4
"Step 5: Adding a GUI" 'Using OOP for GUIs' ''' In larger programs, it is often more useful to code a GUI as a subclass of the tkinter Frame widget—a container for other widgets. ''' from tkinter import * from tkinter.messagebox import showinfo class MyGui(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) button = Button(self, text='press', command=self.reply) button.pack() def reply(self): showinfo(title='popup', message='Button pressed!') if __name__ == '__main__': window = MyGui() window.pack() window.mainloop() ''' The button’s event handler is a bound method—self.reply, an object that remembers both self and reply when later called. but because it is now a subclass of Frame, it automatically becomes an attachable component—i.e., we can add all of the widgets this class creates, as a package, to any other GUI, just by attaching this Frame to the GUI. '''
true
73e6e2712fc736f21f7818bef2c63815de570750
hymhanraj/lockdown_coding
/range.py
266
4.40625
4
''' Given start and end of a range, write a Python program to print all negative numbers in given range. Example: Input: start = -4, end = 5 Output: -4, -3, -2, -1 Input: start = -3, end = 4 Output: -3, -2, -1 ''' for num in range(-3,4): if num<0: print(num)
true
040cdf085336c553e8b0951a59a25028577999f7
helper-uttam/Hacktober2020-5
/Python/calc.py
1,011
4.1875
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("Select operation.") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter choice(1/2/3/4):") result = 0 if choice == '1': result = add(num1, num2) elif choice == '2': result = subtract(num1, num2) elif choice == '3': result = multiply(num1, num2) elif choice == '4': if(num2 !=0): result = divide(num1, num2) else: result="Divide by 0" else: print("Invalid Input") print("Result = ", result) quit = input("Do you want to continue (y/n) ?") if quit == 'n': break
true
20e5713218979589bc452c464c4e9d52216d2b2b
mishra28soumya/Hackerrank
/Python/Basic_Data_Types/second_largest.py
673
4.125
4
#Find the Runner-Up Score! # Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. # You are given n scores. Store them in a list and find the score of the runner-up. # Input Format # The first line contains N. The second line contains an array A[] of N integers each separated by a space. # Constraints # 2 <= N <= 10 # -100 <= A[i] <= 100 # Output Format # Output the value of the second largest number. if __name__ == '__main__': n = int(raw_input()) l = list(map(int, raw_input().split())) s = set(l) #to get all the unique numbers result = sorted(list(s)) print(result[-2])
true
91e6153e75db60860bd2f486effad5dd468c456a
nath-btx/hi-python
/ex03_rps/rps.py
1,377
4.125
4
import random moves=['rock','paper','scissors'] def convert_input(move): if (move == "r"): return 'rock' elif(move == "p"): return 'paper' elif(move == "s"): return 'scissors' else: return move def game(): tie = True while tie: tie = False AI_move = random.choice(moves) move = convert_input(input('Do you want to play Rock, Paper, or Scissors (r or rock / p or paper / s or Scissors)')) convert_input(move) if (move == AI_move): tie = True print(f"You both played {move}, it's a tie !") elif(move == "r" or move == "rock"): if(AI_move == "scissors"): print("Rock > Scissors, you win !") else: print("Rocks < Paper, you lose !") elif(move == "p" or move == "paper"): if(AI_move == "rock"): print("Paper > Rock, you win !") else: print("Paper < Scissors, you lose !") elif(move == "s" or move == "scissors"): if(AI_move == "paper"): print("Scissors > Paper, you win !") else: print("Scissors < Rock, you lose !") else: tie = True print("Please select a valid input") if __name__ == "__main__": while True: game() play_again = input("Do you want to play again ? (y/n)") if(play_again == "y"):continue else: exit()
false
8763f32cd9ae69553a4554c0223283a51c5522be
crypto4808/PythonTutorial_CoreySchafer-master1
/intro.py
1,731
4.3125
4
#import as a smaller name so you don't have to type 'my_modules' each time # import my_modules # #from my_module import find_index # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = my_modules.find_index(courses,'math')# # print(index) #Use shorthand for my_modules so you don't have to type it out all the time # import my_modules as mm # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = mm.find_index(courses,'math') # print(index) # #import the function itself # from my_modules import find_index # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = find_index(courses,'math') # print(index) # #import the function itself # #access the test variable from my_modules # from my_modules import find_index,test # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = find_index(courses,'math') # print(index) # print(test) # #import the function itself # #access the test variable from my_modules # from my_modules import find_index as fi, test # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = fi(courses,'math') # print(index) # print(test) #import everything though it's frowned upon #Reason is if something goes wrong with find_index #it's virtually impossible to find which module it was imported from #access the test variable from my_modules # from my_modules import * # courses = ['history', 'math' , 'physics' , 'compsci' ] # index = find_index(courses,'math') # print(index) #how does python know where is the module? #py checks multiple locations for this modules from my_modules import find_index, test import sys courses = ['history', 'math' , 'physics' , 'compsci' ] index = find_index(courses,'math') print(index) print(sys.path)
true
ec022a502128acdcdc7b933a49ee215814f39c71
statusyaza/hacktoberfest2021-5
/Python/diamond_star.py
481
4.125
4
rows = int(input("Enter you number:")) n = 0 for i in range(1, rows + 1): n = 0 # loop to print spaces n = (rows - i) print(" " * n, end = "") # loop to print star n = (2 * i - 1) print(str(i) * n, end = "") print() #### for i in range(rows-1, 0, -1): # loop to print spaces n = (rows - i) print(" " * n, end = "") # loop to print star n = (2 * i - 1) print(str(i) * n, end ="") print()
false
b9b1a64e80fe8d1a4e9038e36d98f84b56f75ba8
Cassie-bot/Module-3
/Area.py
340
4.40625
4
#Casandra Villagran #1/30/2020 #This is a program that computes the area of a circle using the radius and it prints a message to the user with the answer. radius = int(input ("What is the radius of the circle? ")) Area= 3.14 * radius ** 2 print ("I loved helping you find the area of this circle, here is your answer " + str(Area))
true
13091fa05d4d93a37a34f95520e6de8746a93763
avijitkumar2011/My-Python-programs
/middle_letter.py
213
4.1875
4
#To find middle letter in a string def middle(strg): if len(strg) % 2 == 1: n = len(strg)//2 print('Middle letter in string is:', strg[n]) else: print('enter string of length odd number') middle('kuma')
true
dcd1d7304fd1d7dbf55602f6f95150d98d92ea66
Ma11ock/cs362-asgn4
/avg_list.py
226
4.125
4
#!/usr/bin/env python # Calculate the average of elements in a list. def findAvg(lst): if(len(lst) == 0): raise ValueError("List is empty") avg = 0 for i in lst: avg += i return avg / len(lst)
true
af211c4fb797589561c443a8593c3cc3bf122d47
purnimagupta17/python-excel-func
/string_indexing_slicing_usingpython.py
967
4.65625
5
print('Hello World') #to shift the 'World' to next line, we can use \n in the symtax as follows: print('Hello \nWorld') #to count the number of characters in a string, we use len function as follows: str1="Hello" print(len(str1)) #to assign the index number to a string, for example: ss="Hello World" print(ss[0]) print(ss[3:8]) #to jump on the string: str2="abcdefghijk" print(str2[::]) #to exclude the 2nd character from string print(str2[::2]) #to reverse the string print(str2[::-1]) #to edit the name in a string name='sam' #name[0]='P' last_letters=name[1:] last_letters 'P'+last_letters #to combine two sentences/stings x='Hello World' x=x+ " It is beautiful outside" x #to concatenate the string letter='z' letter*10 #to concatenate the string 2+3 '2'+'3' #to change the string to uppercase and lowercase x='Hello World' x x.upper() x.lower() #to split the string x.split() #to split the string based on some specific characters x.split('o')
true
7a71cc280ae6302fc83eebd003a4693c17f8bc2a
krallnyx/NATO_Alphabet_Translation
/main.py
527
4.1875
4
import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") alphabet = {row.letter: row.code for (index, row) in data.iterrows()} def generate_phonetic(): to_translate = input("Please enter the word you want to translate into NATO Alphabet.\n").upper() try: output = [alphabet[letter] for letter in to_translate] except KeyError: print("Please enter a valid word, only letters in the alphabet are allowed") generate_phonetic() else: print(output) generate_phonetic()
true
eb7076d9c7d75d4b0ce59b5a1f74c6cdfe311b7e
jessiecantdoanything/Week10-24
/CodesAndStrings.py
1,531
4.125
4
# strings # concatenation firstName = "Jesus" lastName = "Monte" print(firstName + " " + lastName) name = firstName + " " + lastName lastFirst = lastName + ", " + firstName print(lastFirst) # repition print("uh "*2 + "AAAAAAAAA") def imTiredofSchool(): print("me, "*3 + "young Jessie,") print("is extremely exhausted") print("Why must you ask?") print("school "*3) imTiredofSchool() # indexing name = "Roy G Biv" firstChar = name[0] print(firstChar) middleCharIndex = len(name) // 2 print(middleCharIndex) print(name[middleCharIndex]) print(name[-3]) for i in range(0, len(name)): print(name[i]) #slicing and dicing print(name[0:3]) for i in range(0, len(name)+1): print(name[0:i]) # searching print("biv" in name) print("y" not in name) # String Methods to investigate: # Method Use Example Explanation # center aStr.center(w) # ljust aStr.ljust(w) # rjust aStr.rjust(w) # upper aStr.upper() # lower aStr.lower() # index aStr.index(item) # rindex aStr.rindex(item) # find aStr.find(item) # rfind aStr.rfind(item) # replace aStr.replace(old, new) # Be sure to include multiple examples of all of them in use # Character functions from mapper import * print(letterToIndex('M')) print(indexToLetter(24)) from crypto import * print(scramble2Encrypt("THE MEETING IS AT FIVE OCLOCK")) print(scramble2Decrypt("H ETN SA IEOLCTEMEIGI TFV COK"))
false
efb19779c940b3f7d1f8999d089c2b2849764f1c
rckc/CoderDojo
/Python-TurtleGraphics/PythonIntro2-1Sequences.py
1,435
4.5625
5
# Author: Robert Cheung # Date: 29 March 2014 # License: CC BY-SA # For CoderDojo WA # Python Intro Turtle Graphics # Python has a rich "library" of functions. # We are going to use "turtle" to do some simple graphics. import turtle # see https://docs.python.org/2/library/turtle.html#filling if __name__ == "__main__": # Setup our drawning surface turtle.setup(800,600) # Sets up the size of the window turtle.Screen() # Turns on the graphics window # Set how fast we want the turtle to draw turtle.speed(6); # 0 (fastest) .. 10 (slowest) width = 20 # Create a variable called "width" # and make it equal to 10 # In programming, computer follows instructions # A "sequence" of instructions is the most basic construct # It is simply a list of instructions turtle.forward(width) # Step 1: Move forward 20 steps turtle.right(90) # Step 2: Turn right 90 degrees turtle.forward(width) # Step 3: Move forward 20 steps turtle.right(90) # ... and so on turtle.forward(width) turtle.right(90) turtle.forward(width) turtle.right(90) ret = input("Press enter to exit.") turtle.Screen().bye() # Turn off the graphics window # Library reference: http://docs.python.org/2/library/turtle.html
true
786073c2e842f81fd71fc391628f6161546b5a9e
yyuuliang/codingchallenges
/hackerrank/Reverse-a-doubly-linked-list.py
2,556
4.15625
4
''' File: Reverse-a-doubly-linked-list.py Source: hackerrank Author: yyuuliang@github ----- File Created: Thursday, 12th March 2020 4:21:54 pm Last Modified: Thursday, 12th March 2020 4:21:58 pm ----- Copyright: MIT ''' # Reverse a doubly linked list # https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=linked-lists # Sample Input # 4 # 1 # 2 # 3 # 4 # Sample Output # 4 3 2 1 #!/bin/python3 import math import os import random import re import sys class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = DoublyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node node.prev = self.tail self.tail = node def print_doubly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the reverse function below. # # For your reference: # # DoublyLinkedListNode: # int data # DoublyLinkedListNode next # DoublyLinkedListNode prev # # # use recursion to solve the problem class node: data=0 nextnode=None prevnode=None def __init__(self, dvalue): self.data=dvalue def printvalue(self): print(self.data) def printlinkedlist(head): while head is not None: head.printvalue() head=head.nextnode # double linked list def reversedoublelinkedlist(head): if head is None: return None tmp=reversedoublelinkedlist(head.nextnode) if tmp is not None: tmp.nextnode=head tmp.nextnode.prevnode=tmp tmp.nextnode.nextnode=None return tmp.nextnode else: tmp=head tmp.prevnode=None tmp.nextnode=None return tmp def reverse(head): tail =reversedoublelinkedlist(head) # con=None while tail.prevnode is not None: # con=tail.prevnode tail=tail.prevnode return tail n=node(1) n2=node(2) n3=node(3) n4=node(4) n.nextnode=n2 n2.nextnode=n3 n3.nextnode=n4 n2.prevnode=n n3.prevnode=n2 n4.prevnode=n3 printlinkedlist(n) t=reverse(n) printlinkedlist(t) # now I want to practice to reverse linkedlist in recursion # which means dont use prev
true
7b04023a27193cf35c7c4db27c72cbb265193ddf
manusoler/code-challenges
/projecteuler/pe_1_multiples_3_and_5.py
364
4.3125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def multiples_of(*nums, max=1000): return [i for i in range(max) if any([i % n == 0 for n in nums])] if __name__ == "__main__": print(sum(multiples_of(3,5)))
true
74b4f4975aff361161aaa469e959a1652b22a77d
manusoler/code-challenges
/projecteuler/pe_9_special_pythagorean_triplet.py
723
4.3125
4
import functools from math import sqrt from utils.decorators import timer """ A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2+b**2=c**2 a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def pythagorean_triplet(summ): for a in range(1,summ): for b in range(a+1, summ): c = sqrt(a**2+b**2) if a + b + c == summ: return (a,b,int(c)) @timer def main(): triplet = pythagorean_triplet(1000) print("Triplet: {}, Product: {}".format(triplet, functools.reduce(lambda x,y: x*y, triplet))) if __name__ == "__main__": main()
true
ab110fc6c142c9981d0e034eba28dbae82a5afa6
dersenok/python3_Les2
/venv/HomeworkLes2/Les_2_HW_8.py
717
4.125
4
# 8. Посчитать, сколько раз встречается определенная цифра в # # # введенной последовательности чисел. Количество вводимых # # # чисел и цифра, которую необходимо посчитать, # # # задаются вводом с клавиатуры. n = int(input("Сколько будет чисел? ")) d = int(input("Какую цифру считать? ")) count = 0 for i in range(1, n + 1): m = int(input("Число " + str(i) + ": ")) while m > 0: if m % 10 == d: count += 1 m = m // 10 print("Было введено %d цифр %d" % (count, d))
false
d3c3a3cf50793588756306288b30433842460b60
littlejoe1216/Chapter-6-Exercies
/Python Chapter 6 Exercises/Chp 6 Excercise 4.py
596
4.21875
4
#Exercise 4: #There is a string method called count that is similar to the function in the previous exercise. #Read the documentation of this method at https://docs.python.org/3.5/library/stdtypes.html#string-methods #and write an invocation that counts the number of times the letter a occurs in "banana". word = "banana" let = input("Enter a letter in the word banana.") def counter(): count = 0 for letter in word: if letter == let: count = count + 1 return count print (counter()) print ("is the number of times this letter is in the word banana.")
true
e3ddbeb215a0d6419b2ae83f2a0933ffc6fcb459
mmengote/CentralParkZoo
/sketch_181013b/sketch_181013b.pyde
971
4.34375
4
#this library converts the random into integers from random import randint #lists of animals included in the simulation #divided into two types, the zoo animals will have a starting state position of zoolocation. #local animals will have a starting position of something else. zoo_animals = ["Penguins", "Zebras", "Monkeys", "Sloths"] local_animals = ["Humans", "Squirrels", "Racoons", "Coyotes"] #this chooses the type of zoo animal that will escape randomly. they're stored in variables. escapedAnimalRandom = zoo_animals[randint(0,3)] numberOfescaped = randint(0,100) #maybe change the max to the capacity of population for the zoo #this is the variable of which animal escaped and how many of them escaped wantedAnimals = { "animal escaped": escapedAnimalRandom, "number escaped": numberOfescaped } #random escaped #will need to visualize this instead of words eventually. print wantedAnimals ## where would the penguin go##
true
4f03b52ca0f1f596bfe78b065f44ee8eb0f3b10c
markcharyk/data-structures
/tests/insert_sort_tests.py
1,085
4.125
4
import unittest from data_structures.insert_sort import insertion_sort class TestInsertSort(unittest.TestCase): def setUp(self): """Set up some lists to be sorted""" self.empty = [] self.single = [5] self.sorted = [1, 2, 3, 10] self.unsorted = [8, 1, 94, 43, 33] def testEmpty(self): """Test an empty list""" expected = [] actual = insertion_sort(self.empty) self.assertEqual(expected, actual) def testSingle(self): """Test a list of one item""" expected = [5] actual = insertion_sort(self.single) self.assertEqual(expected, actual) def testSorted(self): """Test an already sorted list""" expected = [1, 2, 3, 10] actual = insertion_sort(self.sorted) self.assertEqual(expected, actual) def testUnsorted(self): """Test an unsorted list""" expected = [1, 8, 33, 43, 94] actual = insertion_sort(self.unsorted) self.assertEqual(expected, actual) if __name__ == '__main__': unittest.main()
true
9689a252589118db6d6623abb196aff8c3efa9ab
vielma24/playground
/bank.py
1,337
4.40625
4
#!/usr/bin/python '''Program will intake customer information and account information. Account management will also be added.''' from datetime import date #******************************************************************************* class person: """ Returns a ```Person``` object with the given name, DOB, and phone number. """ import datetime def __init__(self, name, DOB, phone_num): self.name = name self.DOB = date(DOB[0], DOB[1], DOB[2]) self.phone_num = phone_num print("A student object is now created.") def print_details(self): """ Prints the details of the student. """ print("Name:", self.name) print("DOB:", self.DOB.year, self.DOB.month, self.DOB.day) print("phone number:", self.phone_num) #******************************************************************************* def main(): # Test '''This is how you create a new Person object and print the details. The constructor must include 3 arguments as listed below.''' aPerson = person('John Doe', (1982, 12, 15), 1) aPerson.print_details() ''' TODO: Obtain the information of 5 new people and store them in a list when complete print their details one at a time.''' if __name__ == "__main__": main()
true
9d625b9f273e27a48db58a2694b0b8e1eb537063
dolapobj/interviews
/Data Structures/Array/MaximumProductSubarray.py
1,155
4.3125
4
#Maximum Product Subarray #LC 152 """ Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. """ #idea--> at every step we have three options # 1. we get a max product by multiplying by current max so far with current element # 2. we get a max product by multiplying current min so far with current element (multiply negs) # 3. the current element can be the start for the maximum product subarray def maxProductSubarray(nums): maxProduct,minProduct,ans = nums[0],nums[0],nums[0] for i in range(1,len(nums)): tempMax = max(nums[i], nums[i]*maxProduct,nums[i]*minProduct) tempMin = min(nums[i], nums[i]*maxProduct,nums[i]*minProduct) maxProduct,minProduct = tempMax,tempMin ans = max(ans,maxProduct) return ans #RT: O(n) --> loop through once #SC: O(1) --> store 4 variables that are updated in each iteration
true
4076f61a183fac23c05fbf162dde7289caff5a74
sndp2510/PythonSelenium
/basic/_04Geometry.py
432
4.28125
4
sideCount=int(input("Enter Number of side: ")) if(sideCount==1): print("Its square") side=int(input("Enter length of side : ")) print("Area of the square is : " , (side*side)) elif(sideCount==2): print("Its Rectangle") length = int(input("Enter length of side : ")) breadth =int(input("Enter length of side : ")) print("Area of the square is : " , (length*breadth)) else: print("Invalid Entry")
true
d60ccaf31fe2c293d566effaf936c5c17e6064e3
ksu-is/Commute-Traffic-Twitter-Bot
/Practice/user_funct.py
1,027
4.28125
4
## will create text file for new users with info on each line. (not able to do OOP yet reliably so this is the best I've got) # do you have an account? user_ask = input("Before we start, lets specify what user this is for\nHave you used this program before?\nType 'y' or 'n' only: ") if user_ask.lower() == "n": filename = input("Okay, new user! What is your name?\nType your first name here to create your username: ").lower() + ".txt" user_file = open(filename, 'w+') print("\nNow lets load up all the highways that you use for your commute into your user account.") #at this point, i am able to make a custom text file for any new user while True: append = input("\nEnter one highway at a time\nType '75', '85, '285', '20', or '400'\nOr type 'end' to finish.\nEnter here: ") if append.lower() == "end": break else: user_file.write(append) user_file.write("\n") user_file.seek(0) print(user_file.readlines()) #def make_user():
true
1e3cc57af263476e1346cccf480a6ed62e7c891d
jenshurley/python-practice
/python_early_examples.py
1,836
4.125
4
# Initial variable to track game play user_play = "y" # While we are still playing... while user_play == "y": # Ask the user how many numbers to loop through user_number = input("How many numbers? ") # Loop through the numbers. (Be sure to cast the string into an integer.) for x in range(int(user_number) + 1): # Print each number in the range print(x) # Once complete... user_play = input("Continue: (y)es or (n)o? ") # Ask for how many numbers # Print them out # Ask again or quit # if you get more numbers, add that many to the highest original number playing = True current_num = 1 while playing: number = input("How many numbers would you like or q to quit: ") if number != 'q': number = int(number) for x in range(current_num, current_num + number): print(x) current_num += number else: playing = False # In 2 lists, we have dogs and their meals # eg, Chance eats steak, lucky eats chow, etc... dogs = ['chance', 'scout', 'rover', 'lucky', 'boss'] meals = ['steak', 'chicken', 'bones', 'chow', 'vegan'] # If someone gives us a dog, how can we return their meal? def find_meal(some_dog): pass #Return the meal the dog eats # Hit, you'll have to use an index lookup and # Use that to find the meals #Rover --> Bones as an example # Ask for how many numbers # Print them out # Ask again or quit # if you get more numbers, add that many to the highest original number playing = True current_num = 1 while playing: number = input("How many numbers would you like or q to quit: ") if number != 'q': number = int(number) for x in range(current_num, current_num + number): print(x) current_num += number else: playing = False 3 CommentsCollapse 
true
0be835d18fae63f8b63fbae296f65250f8b38ac4
koaning/scikit-fairness
/skfair/common.py
1,752
4.4375
4
import collections def as_list(val): """ Helper function, always returns a list of the input value. :param val: the input value. :returns: the input value as a list. :Example: >>> as_list('test') ['test'] >>> as_list(['test1', 'test2']) ['test1', 'test2'] """ treat_single_value = str if isinstance(val, treat_single_value): return [val] if hasattr(val, "__iter__"): return list(val) return [val] def flatten(nested_iterable): """ Helper function, returns an iterator of flattened values from an arbitrarily nested iterable >>> list(flatten([['test1', 'test2'], ['a', 'b', ['c', 'd']]])) ['test1', 'test2', 'a', 'b', 'c', 'd'] >>> list(flatten(['test1', ['test2']])) ['test1', 'test2'] """ for el in nested_iterable: if isinstance(el, collections.abc.Iterable) and not isinstance( el, (str, bytes) ): yield from flatten(el) else: yield el def expanding_list(list_to_extent, return_type=list): """ Make a expanding list of lists by making tuples of the first element, the first 2 elements etc. :param list_to_extent: :param return_type: type of the elements of the list (tuple or list) :Example: >>> expanding_list('test') [['test']] >>> expanding_list(['test1', 'test2', 'test3']) [['test1'], ['test1', 'test2'], ['test1', 'test2', 'test3']] >>> expanding_list(['test1', 'test2', 'test3'], tuple) [('test1',), ('test1', 'test2'), ('test1', 'test2', 'test3')] """ listed = as_list(list_to_extent) if len(listed) <= 1: return [listed] return [return_type(listed[: n + 1]) for n in range(len(listed))]
true
7a5d6f9bdd12a2aa3d4d1ce7c50723742a23cd46
Azoad/Coursera_py4e
/chapter7/ex_07_01.py
220
4.375
4
"""Take a file as input and display it at uppercase""" fname = input('Enter the file name: ') try: file = open(fname) except: print('Error in file!') quit() for line in file: print(line.strip().upper())
true
7b6fd1b192bf2fdacb41ce57cef67bd6ca3db41c
Azoad/Coursera_py4e
/test.py
1,944
4.1875
4
print('this is the first one:') print('let\'s do this!') print('add 5 and -3') f = 5 t = -3 print('addition of',str(f),'and',str(t),'is :',str(f+t)) print('-----------------------------') print('this is the second one:') x = 'It is not America but it is Bangladesh' lens = len(x) print('Length of \'' +x+ '\' is : '+str(lens)) print('------------------------------') print('this is the third one:') a = 5 if a<10: print('Smaller!') if a>20: print('Larger!') print('Finish') print('------------------------------') print('this is the fourth one:') n = 5 while n>0: print(n) n = n-1 print('Blastoff!') print('------------------------------') print('this is the fifth one:') hrs = input("Enter Hours:") fhrs = float(hrs) rate = input("Enter rate:") frate = float(rate) pay = fhrs*frate spay = str(pay) print("Pay:",spay) print('------------------------------') print('this is the sixth one:') print('Multiplication table:') num = input('Enter a number:') for n in range (1,11): print(str(num)+' X '+str(n)+' =',int(n)*int(num)) print('------------------------------') print('this is the seventh one:') x = 5 if x > 2: print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5): print(i) if i > 2: print('Bigger than 2') print('Done with i',i) print('All done') print('------------------------------') print('this is the eighth one:') x = 15 if x < 2 : print('Small') elif x < 10 : print('Medium') elif x < 20 : print('Big') elif x < 40 : print('Large') elif x < 100 : print('Huge') else : print('Ginormous') print('------------------------------') print('this is the ninth one:') x = input('Enter a positive number : ') try : ix = int(x) except : ix = -1 print('The value is ',ix) if ix > 0 : print('Number') else : print('Not a number')
false
6dafc193f5e2f1731df5462295131e2cee3236b8
victorrayoflight/Foudil
/Examen 2019-02-18/6.py
582
4.15625
4
x = True y = False z = False # False OR True == True # True OR False == True # True OR True == True # False OR False == False # True AND True = True # True AND False = False # False AND True = False # False AND False = False # False XOR True == True # True XOR False == True # True XOR True == False # False XOR False == False if not x or y: # False or False == False print(1) elif not x or not y and z: # False or True and False == False print(2) elif not x or y or not y and x: # False or False or True and True == True print(3) else: print(4)
true
8b6e4666bf75fc6b7023e8c93717384f56183890
hayuzi/py-first
/base/dealwithexp.py
2,766
4.25
4
# 异常处理 # 语法错误是错误 # 异常是 语法正确,但是执行时候出现错误。 # 异常处理使用 try except 格式 # 与其他一些语言一样,责任链的模式,如果不做 except获取,会反馈到上一层. while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("that was no valid number, try again ") # 一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组,例如 # except (RuntimeError, TypeError, NameError): # pass # 最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。 # try except 语句还有一个可选的else子句,如果使用这个子句,那么必须放在所有的except子句之后。 # 这个子句将在try子句没有发生任何异常的时候执行。 # try: # ...... # except OSError: # ...... # except: # print("Unexpected error:", sys.exc_info()[0]) # raise # else: # ...... # 抛出异常使用 raise # raise 的异常必须是一个异常的实例或者异常的类( Exception的子类 ) # raise NameError('HiThere') # 用户自定义异常 # 你可以通过创建一个新的异常类来拥有自己的异常。 # 异常类继承自 Exception 类,可以直接继承,或者间接继承,例如: class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # 定义清理行为 # try 语句还有另外一个可选的子句,它定义了无论在任何情况下都会执行的清理行为。 # 如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住, # 那么这个异常会在 finally 子句执行后被抛出 # 预定义的清理行为 # 一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。 # 这面这个例子展示了尝试打开一个文件,然后把内容打印到屏幕上: for line in open("myfile.txt"): print(line, end="") # 以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭。 # 关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法: with open("myfile.txt") as f: for line in f: print(line, end="") # python3 assert 断言 # Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。 # assert expression [, arguments] # end
false
9d848849b6d688b2872bd9923a86319e3ad73807
Anchals24/InterviewBit-Practice
/Topic - String/Longest Common Prefix.py
1,216
4.25
4
#Longest Common Prefix. #Arr = ["aa" , "aab" , "aabvde"] """ Problem Description >> Given the array of strings A, you need to find the longest string S which is the prefix of ALL the strings in the array. Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. For Example: longest common prefix of "abcdefgh" and "abcefgh" is "abc". """ #Solution : 1 def longestcommonprefix(Arr): smallest = min(Arr) #Find the smallest element of the array #print(smallest) lmini = len(smallest) #length of the smallest element of the array i = 0 common = "" while i < lmini: for A in Arr: if A[i] != smallest[i]: return common common += smallest[i] i += 1 return common print(longestcommonprefix(["aaaaaa" , "aab" , "aabvde" , "aabb"])) #Solution : 2 def longestcommonprefix2(Arr): minele = min(Arr) maxele = max(Arr) count = 0 for i in range(min(len(maxele) , len(minele))): if minele[i] == maxele[i]: count += 1 return minele[:count] print(longestcommonprefix2(["aa" , "aabse" , "a" ]))
true
ac81f1e984700b6b3993e1b60e29812dc82e69c4
emlemmon/emlemmon.github.io
/python/Week6/check06b.py
1,121
4.4375
4
class Phone: """Parent class that has 3 member variables and 2 methods""" def __init__(self): self.area_code = 0 self.prefix = 0 self.suffix = 0 def prompt_number(self): self.area_code = input("Area Code: ") self.prefix = input("Prefix: ") self.suffix = input("Suffix: ") def display(self): print("Phone info:") print("({}){}-{}".format(self.area_code, self.prefix, self.suffix)) class SmartPhone(Phone): """Child class of Phone that includes the member variables from Phone as well as an email address""" def __init__(self): super().__init__() self.email = "" def prompt(self): Phone.prompt_number(self) self.email = input("Email: ") def display(self): Phone.display(self) print(self.email) def main(): newPhone = Phone() newCell = SmartPhone() print("Phone:") newPhone.prompt_number() print() newPhone.display() print() print("Smart phone:") newCell.prompt() print() newCell.display() if __name__ == "__main__": main()
true
0e821086fd74aebd7e245509f1507fc3ac6ccec2
Jrufino/ListaRepeticaoPython
/ex22.py
638
4.21875
4
sair='N' divisivel=[] while sair !='S': num=int(input('Digite um numero inteiro: ')) if num==2 or num==3 or num==5 or num==7: print('Primo') else: if num%2==0 or num%3==0 or num%5==0 or num%7==0: if num%2==0: divisivel.append(2) if num%3==0: divisivel.append(3) if num%5==0: divisivel.append(5) if num%7==0: divisivel.append(7) print('Nao eh primo. Divisivel por {}'.format(divisivel)) else: print('Primo') sair=str.upper(input('S- Sair, outra tecla continua'))
false
41f61ba806ae6942a62b114ae624ab00ce0d6b7d
kobecow/algo
/NoAdjacentRepeatingCharacters/problem.py
543
4.15625
4
""" Given a string, rearrange the string so that no character next to each other are the same. If no such arrangement is possible, then return None. Example: Input: abbccc Output: cbcbca """ def rearrangeString(s: str) -> str or None: pass print(rearrangeString("gahoeaddddggrea")) # no order required # ahgogrgededadad print(rearrangeString("cccciiiiiddddssskkdddcc")) # no order required # ckckcscscsdidididididcd # improvement # this is too complicated comarared to answer.py. # use only slice operation, not priority queue.
true
b6a1309a07f6203b3d183552e30e4e05c5582713
Kishy-nivas/ds-in-python
/linked list.py
522
4.15625
4
# linked list implementation class Node(object): def__init__(self,value,pointer=None) self.value =value self.next =None class LinkedList(object): def __init__(self): self.head =None self.tail =None def add(self,value ): if self.head==None: self.head =self.tail = Node(value ) self.head.next =self.tail.next =None else: self.head.next = Node(value ) self.head = self.head.next def traverse(self): r= self.tail while r: print(r.value ) r=r.next if __name__ == '__main__':
false
c47370697303df60b4e50e91092a5564b047a718
stephenforsythe/crypt
/shift.py
1,172
4.125
4
""" This is essentially a substitution cypher designed to avoid fequency analysis. The idea is to shift the char to the right by an increasing number, until n = 25, at which time the loop will start again. Spaces are treated as a character at the end of the alphabet. """ import string FULL_ALPHABET = string.lowercase + ' ' MOD_NUM = len(FULL_ALPHABET) def encrypt_decrypt(instr, direction): shift = 0 encrypted_message = '' for char in instr.lower(): pos = string.index(FULL_ALPHABET, char) mod_pos = pos % MOD_NUM if direction == 'en': shift_pos = (mod_pos + shift) % MOD_NUM else: shift_pos = (mod_pos - shift) % MOD_NUM encrypted_message += FULL_ALPHABET[shift_pos] shift += 1 return encrypted_message eord = raw_input('Encrypt or decrypt? (e/d):\n') if eord == 'e': user_input = raw_input('Message to be encrypted:\n') print 'encrypted message:\n' print encrypt_decrypt(user_input, 'en') elif eord == 'd': user_input = raw_input('Message to be decrypted:\n') print 'plain text:\n' print encrypt_decrypt(user_input, 'de') else: print 'error'
true
dfed06b4bbf51b8d57511753a08f09e26e3605d0
MuhammetEser/Class4-PythonModule-Week4
/4- Mis Calculator.py
2,631
4.28125
4
# As a user, I want to use a program which can calculate basic mathematical operations. So that I can add, subtract, multiply or divide my inputs. # Acceptance Criteria: # The calculator must support the Addition, Subtraction, Multiplication and Division operations. # Define four functions in four files for each of them, with two float numbers as parameters. # To calculate the answer, use math.ceil() and get the next integer value greater than the result # Create a menu using the print command with the respective options and take an input choice from the user. # Using if/elif statements for cases and call the appropriate functions. # Use try/except blocks to verify input entries and warn the user for incorrect inputs. # Ask user if calculate numbers again. To implement this, take the input from user Y or N. import math from addition import Addition from subtraction import Subtraction from multiplication import Multiplication from division import Division afronden = math.ceil def num_input(): while True: try: number = float(input("Please enter a float number: ")) break except ValueError: print("""Please enter a valid float number using "." """) return number def operant(): while True: try: symbol = input("Please enter a mathematical operator symbol (+,-,*,/): ") if symbol != '+' and symbol != '-' and symbol != '*' and symbol != '/': raise ValueError break except ValueError: print("Please enter a valid mathematical operator!") return symbol def yes_no(): while True: try: letter = input("Would you like to make another calculation (Y,N): ") if letter != 'Y' and letter != 'y' and letter != 'N' and letter != 'n': raise ValueError break except ValueError: print("Oops! That was no valid symbol. Try again...") return letter while True: symbol = operant() if symbol == '+': print("Result: " + str(afronden(Addition(num_input(), num_input())))) elif symbol == '-': print("Result: " + str(afronden(Subtraction(num_input(), num_input())))) elif symbol == '*': print("Result: " + str(afronden(Multiplication(num_input(), num_input())))) elif symbol == '/': print("Result: " + str(afronden(Division(num_input(), num_input())))) antwoord = yes_no() if antwoord == 'N' or antwoord == 'n': break
true
444256bdb2ae5b3aa29aec5acf93bfbb5875a8c7
ivanakonatar/MidtermExample
/task4.py
985
4.21875
4
""" =================== TASK 4 ==================== * Name: Convert To Upper * * Write a function `convert_2_upper` that will take * a string as an argument. The function should * convert all lowercase letter to uppercase without * usage of built-in function `upper()`. * Note: Please describe in details possible cases * in which your solution might not work. * * Use main() function to test your solution. =================================================== """ def mala_u_velika(recenica): if not isinstance(recenica,str): print("Pogresan unos! ") nova_recenica = '' for karakter in recenica: broj_chr = ord(karakter) if broj_chr > 96 and broj_chr < 123: broj_veliko_slova = broj_chr - 32 karakter = chr (broj_veliko_slova) nova_recenica+= karakter return nova_recenica def main(): recenica="IvaNa KONatAr" print("Velikim slovima napisana je: ", mala_u_velika(recenica)) pass main()
false
5cae2691b29e74917c55007405b67e7fcf1a60de
KennethNielsen/presentations
/python_and_beer_lesser_known_gems/ex6_namedtuple.py
2,143
4.21875
4
"""namedtuple example""" from __future__ import print_function from collections import namedtuple def arange(start, end, step): """Arange dummy function""" print('arange', start, end, step) def get_data_from_db(data_id): """Get data from db dummy function""" print('get_data_from_db', data_id) def plot(x, y, title): """plot dummy function""" print('plot with title: "{}"'.format(title)) ################################### Without named tuple def without_named_tuple(): """Without named tuple""" print('Without named tuple') # A dataset is: data_id, comment, step, start, end datasets = ( (1234, 'this is the one', 0.1, 45, 55), (1345, 'no wait this is', 0.2, 40, 60), (1456, 'I know I got it now', 0.2, 40, 60), (1567, 'OK maybe not .. let\'s try something else', 0.05, 40, 60), (1678, 'here we go again', 0.05, 40, 62), ) for dataset in datasets: print('\n### Process dataset', dataset) # Remember a dataset is: data_id, comment, step, start, end x = arange(dataset[3], dataset[4], dataset[2]) y = get_data_from_db(data_id=dataset[0]) plot(x, y, title=dataset[1]) ####################################### With named tuple def with_named_tuple(): """With named tuple""" print('\n\nWith named tuple') dataset = namedtuple('dataset', 'data_id comment step start end') #dataset = namedtuple('dataset', ['data_id', 'comment', 'step', 'start', 'end']) datasets = ( dataset(1234, 'this is the one', 0.1, 45, 55), dataset(1345, 'no wait this is', 0.2, 40, 60), dataset(1456, 'I know I got it now', 0.2, 40, 60), dataset(1567, 'OK maybe not .. let\'s try something else', 0.05, 40, 60), dataset(1678, 'here we go again', 0.05, 40, 62), ) for dataset in datasets: print('\n### Process', dataset) x = arange(dataset.start, dataset.end, dataset.step) y = get_data_from_db(data_id=dataset.data_id) plot(x, y, title=dataset.comment) if __name__ == '__main__': #without_named_tuple() with_named_tuple()
true
de31bc761ac04f9c15ac4a74328d74b907fbd822
oliviamillard/CS141
/coinAdder.py
1,690
4.28125
4
#Olivia Millard - Lab 3a #This program will add up a user's coins based off of their input. #Short welcome message. print("Hello. This program will add up all of your change!\nCool! Let's get started.\n") """ This function, first, take input from the user asking how many coins they have. Next, it takes input for what type of coin they have. And last, it adds up the total coins depending on their value ### Variables ### value = how much the individual coin is worth. coinNumber = which coin of theirs they are inputting the type for (penny, nickel, dime, quarter). total = the total amount of their coins added together. dollarAmount = the quotient from doing integer division on the total. centsAmount = the remainder from using modulus on the total. """ def addUpCoins(): value = 0 coinNumber = 1 total = 0 numOfCoins = int(input("How many coins do you have? ")) while coinNumber <= numOfCoins: coin = str(input("What is coin #" +str(coinNumber)+ "? (q for quarter, d for dime, n for nickel, p for penny): ")) coinNumber = coinNumber + 1 if coin == "p": value = 0.01 total = total + value elif coin == "n": value = 0.05 total = total + value elif coin == "d": value = 0.10 total = total + value elif coin == "q": value = 0.25 total = total + value dollarAmount = total // 100 centsAmount = total % 100 print("\n") print("Whoa... you have a lot of monies!\n" +str(dollarAmount)+ " dollars and " +str(centsAmount)+ " cents if we're being exact.") print("Now go buy yourself something nice.") addUpCoins()
true
e287eb63af5781999f148ef1aecf4dc2752e2ed1
a-ruzin/python-base2
/lesson_11/homework/task5.py
2,064
4.15625
4
""" 5. Продолжить работу над первым заданием. Разработайте методы, которые отвечают за приём оргтехники на склад и передачу в определённое подразделение компании. Для хранения данных о наименовании и количестве единиц оргтехники, а также других данных, можно использовать любую подходящую структуру (например, словарь). """ class StoreError(Exception): pass class Store: def __init__(self): self.store = {} def add(self, entity, department): self.store.setdefault(department, []) self.store[department].append(entity) def remove(self, entity, department): try: self.store[department].remove(entity) except: raise StoreError(f'На складе в департаменте {department} нет техники {entity}') def move(self, entity, department_from, department_to): self.remove(entity, department_from) self.add(entity, department_to) class Entity: def __init__(self, name, price): self.name = name self.price = price def __str__(self): return self.name def __repr__(self): return self.name class Printer(Entity): def __init__(self, name, price, print_size): super().__init__(name, price) self.print_size = print_size class Scanner(Entity): def __init__(self, name, price, is_color): super().__init__(name, price) self.is_color = is_color class Copier(Entity): def __init__(self, name, price, is_multipage): super().__init__(name, price) self.is_multipage = is_multipage store = Store() copier = Copier('Xerox', 20000, True) store.add(copier, 'Бухгалтерия') print(store.store) store.move(copier, 'Бухгалтерия', 'Продажи') print(store.store)
false
52c44bc5f786ab5c741fce402acf47ee901c5818
a-ruzin/python-base2
/lesson_3/homework/task3.py
1,367
4.15625
4
""" 3. Написать функцию thesaurus(), принимающую в качестве аргументов имена сотрудников и возвращающую словарь, в котором ключи — первые буквы имен, а значения — списки, содержащие имена, начинающиеся с соответствующей буквы. Например: >>> thesaurus("Иван", "Мария", "Петр", "Илья") { "И": ["Иван", "Илья"], "М": ["Мария"], "П": ["Петр"] } Подумайте: полезен ли будет вам оператор распаковки? Сможете ли вы вернуть отсортированный по ключам словарь? """ def thesaurus(*args): dictionary = {} for name in args: first_letter = name[0] dictionary.setdefault(first_letter, []) dictionary[first_letter].append(name) return dictionary d = thesaurus("Иван", "Мария", "Петр", "Илья") for first_letter in sorted(d.keys()): print(f'{first_letter}: {d[first_letter]}') # Подумайте: полезен ли будет вам оператор распаковки? нет # Сможете ли вы вернуть отсортированный по ключам словарь? нет
false
4660fcbd2bc5df305214bffd4b4bc073abe6c1f5
samwata/Python-Is-Easy
/Dictionaries-And-Sets/dictionary-assignment.py
531
4.1875
4
#Songs dictionary Songs = {"Laugh Now, Cry Later":"Drake","Dark Lane Demo Tapes":"Drake", "Sounds from the Other Side":"Wizkid","Joro":"Wizkid","jeje":"Diamond Platnumz","A Boy from Tandale":"Diamond Platnumz", "Tambarare":"Eunice Njeri"} #Function to check if the Song exists in Songs dictionary while (True): SongName = input("Please enter the song title and artist seperated by colon i.e song_name:artist :") List=SongName.split(":") if List[0] in Songs and List[1] in Songs.values(): print("True") else: print("False")
false
173ecefb3bd3070bff1b3cd83e91dab2dd2eb4bd
renan-suetsugu/WorkshopPythonOnAWS
/Labs/Loops/lab_6_step_1_Simple_Loops.py
545
4.125
4
#fruit = ['apples','oranges','bananas'] #for item in fruit: # print(f'The best fruit now is {item}') #numbers = [0,1,2,3,4,5,6,7,8,9,10] #for number in numbers: # print(f'The next number is {number}') #for number in range(10): # print(f'The next number is{number}') #for number in range(10): # print(f'The actual number is {number} and next number is {number+1}') #for number in range(1,10): # print(f'The next number is {number}') for number in range(1,10,2): print(f'The next number is {number}')
true
2a4dd3b8574142a991f73761bd43d6e2688c83a0
blackicetee/Python
/python_games/simple_games/MyValidator.py
451
4.125
4
"""This self written python module will handle different kinds of user input and validate it""" # This is a module for regular expressions see python documentation "Regular expression operations" import re class MyValidator: @staticmethod def is_valid_from_zero_to_three(user_input): regex_pattern = r'[0-3]' if re.match(regex_pattern, user_input) is not None: return True else: return False
true
8190dd1f19c1c918cd16997aae5a2c0b77c60607
CoitThomas/Milestone_7
/7.1/test_string.py
480
4.3125
4
"""Verify the correct returned string value of a list of chars given to the funtion string(). """ from reverse_string import string def test_string(): """Assert the correct returned string values for various lists of chars given to the string() function. """ # Anticipated input. assert string(['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']) == 'Hello world' # 1 input. assert string(['A']) == 'A' # No input. assert string([]) == ''
true
f4ad480c6b9e7d8754506f060649b77b99049268
taisei-s/nlp100
/swings/swing09.py
1,051
4.15625
4
# coding:utf-8 """ 09. Typoglycemia スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ. """ import random def shuffle_inside(word): if len(word) <= 4: return word inside = list(word[1:-1]) random.shuffle(inside) new_word = word[0] + ''.join(inside) + word[-1] return new_word def swing09(str): word_list = str.split() shuffled = ' '.join([shuffle_inside(word) for word in word_list]) return shuffled if __name__ == "__main__": str = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." print(swing09(str))
false
313947b60813bec8b6956a808f7c5ee1efed7618
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/5 - Learning the Python 3 Standard Library/code-training/3 - Python Input_Output/input_output.py
2,875
4.1875
4
#1 - Command line arguments #python3 input_output.py 0 1 2 #in CLI ist alles immer ein String import sys #um auf die CLI-Param zugreifen zu können sys.argv print("Number of arguments: " + str(len(sys.argv))) print("Arguments: ", sys.argv) #<- erstes Argument ist Name (bzw. Pfad der Datei) sys.argv.remove(sys.argv[0]) #erstes Argument löschen. Funktioniet mit remove, da argv ist eine Liste print("Arguments: ", sys.argv) arguments = sys.argv sum = 0 for i in arguments: try: #hier wird veruch in Zahl zu konvertieren number = int(i) sum = sum + number except e: print("Keine Zahl") print(sum) print() #2 - Input and Output print("Hello !") color = input("What is your favourite color? ") #Eingaben aus CLI einlesen print("Your color: " + color) print() #3 - Files and file writing myFile = open("scores.txt", "w") #w -> write; r -> read; r+ -> read and write; a -> append #Eigenschften der Datei print("Name " + myFile.name) print(("Mode " + myFile.mode)) myFile.write("GBJ : 100 \nKHD : 99 \nBBB : 89\n") myFile.close() myFile = open("scores.txt", "r") print("Reading ...\n" + myFile.read()) myFile.seek(0, 0) print("Reading... " + myFile.read(10)) #liest nur 10 Char. myFile.close() print() #4 - File seeking in Python #Seek-Pointer = zeigt auf Char in Datei, wenn man aus/in Datei liest/schreibt => wird dieser Seek-Pointer verschoben #Beim öffnen der Datei wird Seek-Pointer auf 0 gesetzt. myFile = open("scores.txt", "r") print("Reading... " + myFile.read(10)) #liest nur 10 Char. myFile.seek(0) print("Reading... " + myFile.read(10)) #liest nur 10 Char. myFile.close() print() #5 - Iterative files # = Datei zeilenweise lesen myFile = open("scores.txt", "r") print("One line : " + myFile.readline()) myFile.seek(0) print("One line : " + myFile.readline()) for line in myFile: newHeighScorer = line.replace("BBB", "PDJ") # in der Zeile: BBB durch PDJ ersetzen <- !! nicht in der Datei erstetz sondern im String line print(newHeighScorer) myFile.close() print() #6 - Tempfile import tempfile # um Temporäre Dateien zu benutzen tempFile = tempfile.TemporaryFile() tempFile.write(b"Save this special number for me: 567896") #in Tempfile schreiben, braucht aber Byte-Object => b davor tempFile.seek(0) print(tempFile.read()) #alles aus dem Tempfile lesen print() #7 - Manipulate zip files in Python import zipfile zip = zipfile.ZipFile("archiv.zip", "r") #zip-Datei öffnen print(zip.namelist()) #Metadaten auslesen for meta in zip.infolist(): print(meta) info = zip.getinfo("purchased.txt") #Metadaten bestimmter Datei print(info) print(zip.read("scores.txt")) with zip.open("scores.txt") as f: #öffnet wishlist.txt in zip-Datei und konvertiert es zu file (as f) print(f.read()) #zip.extract("purchase.txt") # Datei aus Zip auspacken und speichern #zip.extractall() zip.close()
false
52e700eccf6b8b453f6680c9a991b150774033e4
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/4 - Python Essential Training/code-training/11 - String Objects/string_objects.py
1,442
4.28125
4
# 1 - Overview of string objects #String sind Objekte # Strin-Methoden, print("TestString".upper()) print("TestString".swapcase()) print("TestString {}".format(4)) print('''Test Str ing {}'''.format(4)) s = "Test String {}" print(s.format(4)) class myString(str): def __str__(self): return self[::-1] s = myString("TestString") # 2 - Common string methods print("\n # - 2\n") print("Test string".title()) print("TestString".casefold()) # auch für UNICODE #Stirng ist imuteble = nicht veränderbar s1 = "Hello World1" s2 = "Hello World2".upper() print(id(s1)) print(id(s2)) #Zwei Strings verbinden print(s1 +' '+ s2) print("TestString") # 3 - Formatting strings print("Test {xx} String{bb}".format(xx = 10, bb = 20)) print("Test {1} String{0}".format(10, 20)) print("Test {0:<5} String{1:+05}".format(10, 20)) print("Test {} String{:,}".format(10, 20000000)) print("Test {} String{:,}".format(10, 20000000).replace(",", ".")) # mit ...f kann man Nachkommastellen spezifizieren print("Test {:f} String{}".format(10, 20)) #hexadezimal print("Test {:x} String{}".format(10, 20)) #oktal print("Test {:o} String{}".format(10, 20)) #binär print("Test {:b} String{}".format(10, 20)) #print(f'Test String {10}') x = 10 #print(F'Test String{x}') # 4 - Splitting and Joining s = "grosser String mit Leerzeilen" print(s.split()) print(s.split('e')) #Teilt String in Liste auf l = s.split() #Verbinden + statt _ : s2 = ":".join(l)
false
bc58fb8b971f9a907786caac451b8d603a7ec1c0
llduyll10/backup
/Backup/BigOGreen/classPython.py
1,960
4.34375
4
#Create Class class MyClass: x=5 print(MyClass) #Create object p1 = MyClass() print(p1.x) #__innit__() function class Person: def __init__(self,name,age): self.name = name self.age = age p1 = Person("DuyNND",22) print(p1.name) print(p1.age) #Object METHOD #Object can also cotain method class People: def __init__(self,name,age): self.name = name self.age = age def myFunction(self): print("Hello my name is: " + self.name) p1 = People("DuyNguyenVJPPRO",20) p1.myFunction() #Self parameter #parameter is a reference to the current instance of the class, # and is used to access variables that belong to the class. #Use the words mysillyobject and abc instead of self class UpdatePerson: def __init__(duyobject,name,age): duyobject.name = name duyobject.age = age def myFunction(abc): print("Hello my name is: " + abc.name) p1 = UpdatePerson("John", 30) p1.myFunction() #Delete Objects # p2 = UpdatePerson("Test", 20) # del p2.age # print(p2.age) #Python Inheritance class ParentClass: def __init__(self,fname,lname): self.firstName = fname self.lastName = lname def printName(self): print(self.firstName, self.lastName) P1 = ParentClass("Nguyen","Duy") P1.printName() #Create child class class ChildClass(ParentClass): pass P2 = ChildClass("Duy","Pro") P2.printName() #Add properties in Child class #And add method in Child class class People: def __init__(self,fname,lname): self.firstName = fname self.lastName = lname def printName(self): print(self.firstName, self.lastName) class Student(People): def __init__(self,fname,lname,year): super().__init__(fname,lname) self.graduationyear = year def welcomeNewbie(self): print(self.firstName, self.lastName, self.graduationyear) x = Student("DuyNND","Vippro",2020) x.welcomeNewbie() print(x.graduationyear)
true
56dac0836a399dfb331f7dad49cde574aea01446
Clobbster/hackerrank
/Python/If_Else/test_sample_code.py
529
4.3125
4
# For a input variable, write if/then ladder for the following: # If is odd, print Weird # If is even and in the inclusive range of to , print Not Weird # If is even and in the inclusive range of to , print Weird # If is even and greater than , print Not Weird N = int(input("Please enter a number: ")) if N % 2 != 0: print("Weird") elif N % 2 == 0: if (N >= 2) & (N <= 5): print("Not Weird") elif (N >= 6) & (N <= 20): print("Here") print("Weird") else: print("Not Weird")
false
b210549d4b32f01909c03f2a85f0127a3c4c3c1f
Clobbster/hackerrank
/Python/Write_A_Function/test_sample_code.py
406
4.25
4
# Write a function that determines if a given input year is a leap year. def is_leap(year): leap = "" # Write your logic here if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap = True else: leap = False else: leap = True else: leap = False print(leap) is_leap(1900)
false
950af6a1c4cd4ffe12ff99061bb44cfd0104fec6
regismagnus/challenge_python
/is_list_palindrome.py
1,390
4.15625
4
''' Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in l, since this is what you'll be asked to do during an interview. Given a singly linked list of integers, determine whether or not it's a palindrome. Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l of the linked list Example For l = [0, 1, 0], the output should be isListPalindrome(l) = true; For l = [1, 2, 2, 3], the output should be isListPalindrome(l) = false. ''' # Singly-linked lists are already defined with this interface: class ListNode(object): def __init__(self, x): self.value = x self.next = None def isListPalindrome(l): a=convertToArray(l) for i in range(int(len(a)/2)): if a[i]!=a[len(a)-i-1]: return False return True def convertToArray(l): a=[] if(l!=None): a.append(l.value) c=l.next while(c!=None): a.append(c.value) c=c.next return a ''''l=ListNode(1) l.next=ListNode(1000000000) l.next.next=ListNode(-1000000000) l.next.next.next=ListNode(-1000000000) l.next.next.next.next=ListNode(1000000000) l.next.next.next.next.next=ListNode(1)''' l=ListNode(0) l.next=ListNode(1) l.next.next=ListNode(0) print(isListPalindrome(l))
true
0f9ba273804db8997bd5ec73e7c233c11d58eac5
regismagnus/challenge_python
/longest_word.py
611
4.34375
4
''' Define a word as a sequence of consecutive English letters. Find the longest word from the given string. Example For text = "Ready, steady, go!", the output should be longestWord(text) = "steady". best solution by dnl-blkv: return max(re.split('[^a-zA-Z]', text), key=len) ''' def longestWord(text): rex='[\[\],!@#$%&{}+-=~^`_*/:()<>|?*]|(\\\)' m=None w=None text=re.sub(rex, ' ',text) for word in text.split(): word=re.sub(rex, '',word) if m==None or m<len(word): m=len(word) w=word return w print(longestWord('Ready, steady, go!'))
true
bee95c39ec36fa669a574732be32e6a85d024117
bvishny/basic-algos
/mergesort_inversions.py
2,008
4.25
4
# Basic Merge Sort Implementation # Components # 1. split_array(array) array array - takes an array and splits it at the midpoint into two other arrays # 2. merge(array, array) array - takes two split arrays and merges them together sorted # 3. mergesort(array) array - takes an array and sorts it using mergesort def split_array(array): split_pt = (len(array) / 2) return (array[:split_pt], array[split_pt:]) # Tests: # Empty Array: arr1, arr2 = split_array([]) if not (len(arr1) == 0 and len(arr2) == 0): print("Empty array failed") # 1 Elem Array arr1, arr2 = split_array([1]) if not (len(arr1) == 0 and len(arr2) == 1 and arr2[0] == 1): print("1 Elem array failed") # Odd Elem Array arr1, arr2 = split_array([1,2,4]) if not (len(arr1) == 1 and len(arr2) == 2 and arr2[-1] == 4): print("Odd Elem Array Failed") # Even Elem Array arr1, arr2 = split_array([1,2,3, 4]) if not (len(arr1) == 2 and len(arr2) == 2 and arr1[-1] == 2): print("Even Elem Array Failed") # MERGE: class Counter(object): def __init__(self): self.total = 0 def incr(self, amt): self.total += amt def count(self): return self.total def merge(array1, array2, counter): idx1, idx2, result = 0, 0, [] while idx1 < len(array1) or idx2 < len(array2): if idx2 >= len(array2) or (idx1 < len(array1) and array1[idx1] <= array2[idx2]): result.append(array1[idx1]) idx1 += 1 else: result.append(array2[idx2]) idx2 += 1 counter.incr(len(array1) - idx1) return result # MERGESORT: def mergesort(array, counter = Counter()): if len(array) > 1: arr1, arr2 = split_array(array) else: return array return merge(mergesort(arr1, counter), mergesort(arr2, counter), counter) c = Counter() f = [int(x) for x in open("/Users/10gen/Downloads/IntegerArray.txt", 'r').read().split("\r\n")[:-1]] result3 = mergesort(f, c) print(c.count())
true
b98c45e58694e05b7fadee7721ce57a4e625c603
shubhamPrakashJha/selfLearnPython
/6.FunctionalProgramming/6.Recursion.py
328
4.1875
4
def factorial(x): if x == 1: return 1 else: return x*factorial(x-1) print(factorial(int(input("enter the number: ")))) def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_even(23)) print(is_odd(1)) print(is_odd(2))
true
f9a34ec2cd69deb1bc020afd803e3abd5f3ac877
juechen-zzz/LeetCode
/python/0207.Course Schedule.py
2,706
4.125
4
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. """ # BFS class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # 存储有向图 edges = collections.defaultdict(list) # 存储每个节点的入度 indeg = [0] * numCourses # 存储答案 visited = 0 for info in prerequisites: edges[info[1]].append(info[0]) indeg[info[0]] += 1 # 将所有入度为 0 的节点放入队列中 q = collections.deque([u for u in range(numCourses) if indeg[u] == 0]) while q: visited += 1 u = q.popleft() for v in edges[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) return visited == numCourses # DFS class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # 存储有向图 edges = collections.defaultdict(list) # 标记每个节点的状态:0=未搜索,1=搜索中,2=已完成 visited = [0] * numCourses # 用数组来模拟栈,下标 0 为栈底,n-1 为栈顶 result = list() # 判断有向图中是否有环 valid = True for info in prerequisites: edges[info[1]].append(info[0]) def dfs(u: int): nonlocal valid visited[u] = 1 for v in edges[u]: if visited[v] == 0: dfs(v) if not valid: return elif visited[v] == 1: valid = False return visited[u] = 2 result.append(u) for i in range(numCourses): if valid and not visited[i]: dfs(i) return valid
true
837c95fb0a7b12b26dd16d0c3c693ac16ed1bfd1
juechen-zzz/LeetCode
/python/0075.Sort Colors.py
1,075
4.21875
4
''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] ''' class Solution: def sortColors(self, nums: List[int]) -> None: ''' 荷兰三色旗问题解 ''' # 对于所有 idx < p0 : nums[idx < p0] = 0 # curr是当前考虑元素的下标 p0 = curr = 0 # 对于所有 idx > p2 : nums[idx > p2] = 2 p2 = len(nums) - 1 while curr <= p2: if nums[curr] == 0: nums[p0], nums[curr] = nums[curr], nums[p0] p0 += 1 curr += 1 elif nums[curr] == 2: nums[curr], nums[p2] = nums[p2], nums[curr] p2 -= 1 else: curr += 1
true
de7e65a78aeb655fb91579b349f8f2c2c697e0aa
Phoenix795/lesson1
/ld.py
986
4.1875
4
# step 5(Комплексные типы данных: списки) my_list = [3,5,7,9,10.5] print('My list: ', my_list) my_list.append('Python') print('Length of my_list: ', len(my_list)) print('First element: ', my_list[0]) print('Last element: ', my_list[-1]) print('From second to fourth element: ',my_list[1:4]) print('My list: ', my_list) del my_list[-1] print('My list after removing: ',my_list) # step 6(Комплексные типы данных: словари) my_dictionary = { "city": "Москва", "temperature": "20" } print('Name of city: ', my_dictionary.get('city')) my_dictionary['temperature'] = int(my_dictionary['temperature']) - 5 print('Changed temperature: ', my_dictionary['temperature']) print('Country key in My dictionary is: ', my_dictionary.get('country')) print('Default value for country key: ', my_dictionary.get('country', 'Россия')) my_dictionary['date'] = "27.05.2019" print('Length of My dictionary: ', len(my_dictionary))
false
c22a3a2358c43fa2010303fa125199b77168d3b5
colemai/coding-challenges
/leetcode_challenges/L267-PalindromeP2.py
2,627
4.28125
4
#!/usr/bin/env python3 """ Author: Ian Coleman Input: Output: Challenge: Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form. For example: Given s = "aabb", return ["abba", "baab"]. Given s = "abc", return []. """ from sys import argv import pdb from itertools import permutations from sympy.utilities.iterables import multiset_permutations # 1. Test case x # 2. Brute # 3. Optimise # 4. Run Edge cases # 5. Write Tests # TODO make sure even numbers of each letter x # make sure palindromic perm possible (only one uneven count) x # use is palandrome as test # def make_permutations (s): # """ # Input: STRING s # Output: List of permutations of s # """ # perms = permutations(s) # perms = [''.join(x) for x in perms] # return(list(perms)) def is_palindrome (s): """ Input: STRING s Output: BOOLEAN, True if s is a palindrome """ if s[::-1] == s: return True else: return False def get_symmetrical_half (s): """ Input: STRING s, must have even numbers of each char (except optionally for one letter) Output: STRING, Symmetrical half of s """ assert isinstance(s, str), 'Argument must be string' even = len(s) % 2 == 0 letters = list(set(list(s))) # crudely get unique letters counts = [] symm_half = '' for letter in letters: counts.append(s.count(letter)) # Actually let's get the odd letter here (in the case of uneven length) odd_letter = '' if not even: # Check string valid (odd length): if not len([x for x in counts if x % 2 != 0]) == 1: exit('[]') odd_letter = [x for x in letters if s.count(x) % 2 != 0][0] letters.remove(odd_letter) counts = [x for x in counts if x % 2 == 0] # Check valid string (even length): if not len([x for x in counts if x % 2 != 0]) == 0: exit('[]') for i in range(0, len(letters)): symm_half += ((counts[i]//2) * letters[i]) return(symm_half, odd_letter) def get_pal_perms (sym_half, odd_letter): """ Input: STRING sym_half - half the string as split by letter, STRING odd_letter - the odd letter if there is one Output: LIST of all palindromic permutations of s """ perms = list(multiset_permutations(list(sym_half))) perms = [''.join(x) for x in perms] pal_perms = [x + odd_letter + x[::-1] for x in perms] return pal_perms if __name__ == "__main__": s = 'aabbc' # Edge Cases if len(s) == 1: print(s) exit() elif len(s) == 0: print('Error: must give non-empty string') exit() sym_half, odd_letter = get_symmetrical_half(s) pal_perms = get_pal_perms(sym_half, odd_letter) print(pal_perms)
true
afc794d1882bbfb28ea270f7b4a723762b3a246c
envisioncheng/python
/pyworkshop/1_intro_python/chapter5/exercise.py
553
4.21875
4
# Part 1 10 > 5 5 > 10 10 > 10 10 >= 10 5 < 10 5 < 5 5 <= 5 5 == 5 5 != 10 # Part 2 5 == True # The number 5 does not equal True, but... if 5: print("The number 5 is truthy!") # The number 5 is truthy for an if test! # Part 3 1 == True 0 == False # Part 4 True or False [] or [1, 2, 3] "Hello" or None True and False 5 and 0 [1] and [1, 2, 3] "Hello" and None # Of course, you can use `and` and `or` aren't limited to two operands a = False b = False c = False a or b or c b = True a or b or c a and b and c a = True c = True a and b and c
false
0c0e23c15708325ec523a31bd9b7bea1044ad2e4
prameya21/python_leetcode
/Valid_Palindrome.py
800
4.25
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false ''' class Solution: def isPalindrome(self,s:str) -> bool: s=s.lower() l,r=0,len(s)-1 while l<=r: if not s[l].isdigit() and not s[l].isalpha(): l+=1 elif not s[r].isdigit() and not s[r].isalpha(): r-=1 else: if s[l]!=s[r]: return False l+=1;r-=1 return True obj=Solution() print(obj.isPalindrome("A man, a plan, a canal: Panama"))
true
92cc8732044e9fc0a64a3d7de55ec4393b6b4beb
kangwonlee/16pfa_kangwonlee
/ex29_if/ex29.py
714
4.1875
4
# -*-coding:utf8 # http://learnpythonthehardway.org/book/ people = 10 cats = 30 dogs = 15 if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("No many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry!") dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs: print("People are less than or equal to dogs.") if people == dogs: print("People are dogs.") # 여기까지 입력 후 add, commit # 각 행 주석 입력 후 commit # 각자 Study drills 시도 후 필요시 commit # 오류노트 에 각자 오류노트 작성
true
24dad66dd22395fc2a92f2a403de09dcb82fbfe4
Maschenka77/100_Day_Python
/day_2_tip_project_calculator.py
625
4.21875
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: You might need to do some research in Google to figure out how to do this. print("Welcome to the tip calculator!") total_bill = float(input("What is the total bill? ")) percent = int(input("What percentage tip would you like to give? ")) percent_div = percent/100 split = int(input("How many people to split the bill? ")) bill_splitted = total_bill/split with_tip = round(bill_splitted*(1+percent_div),2) print(f"Each person should pay: ${with_tip}")
true
9d0dec604ab6ca5aefcec6aca0a3766082e1419d
Aravind-39679/tri.py
/triangle.py
658
4.125
4
t=True while(t): A=int(input('Enter first side of the triangle:')) B=int(input('Enter second side of the triangle:')) C=int(input('Enter third side of the triangle:')) if(A+B>C and B+C>A and A+C>B): print("It is a triangle") if(A==B==C): print('It is an equailateral triangle') break elif(A==B!=C or A==C!=B or B==C!=A): print('It is isosceles triangle') break elif(A!=B!=C): print('It is scalene triangle') break else: print("It is not a triangle") print('input correct inputs') #t=True
true
cae0951dcb0aaed9aa287c1e924211365b6bcf80
Lynch08/pands-problem-sheet
/squareroot.py
1,061
4.3125
4
#Programme that uses a function so when you input a number it will return the square root #Author Enda Lynch #REF https://medium.com/@sddkal/newton-square-root-method-in-python-270853e9185d #REF https://www.youtube.com/watch?v=WsQQvHm4lSw - Understand Calculas #REF https://www.homeschoolmath.net/teaching/square-root-algorithm.php #REF https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/ #REF https://www.school-for-champions.com/algebra/square_root_approx.htm#.YD102-j7TDe #REF Automate the Boring Stuff - Chapter 3 Functions newt = input("Number to get square root of:" ) def sqrt(number, iterations = 100): newt = float(number) # number to get square root of for i in range(1, iterations): # iteration number number = 0.5 * (newt / number + number) # √ number ≈ .5*(newt/number + number) return round((number), 1) # return number in for loop and set to 1 decimal place print ("Square number of", newt, "is approx:", (sqrt(float(newt))))
true
b96c473a1b366efebf30f888dcfe9aba5e53b2c6
VladKrupin/DemoGit
/Calculator v1.0.py
419
4.1875
4
from math import pow a = float(input("Enter the first number:")) op = input("Input the operation:") b = float(input("Enter the second number:")) result = None if op == "+": result = a+b elif op == "/": result = a/b elif op == "-": result = a-b elif op == "*": result = a*b elif op == "pow": result=pow(a,b) if not result: print("Invalid input") else: print("Result: {:.2f}".format(result))
false
53b9d3683feff9adfa34c88be6c856db960072ad
sheelabhadra/LeetCode-Python
/1033_Moving_Stones_Until_Consecutive.py
2,232
4.21875
4
"""PROBLEM: Three stones are on a number line at positions a, b, and c. Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y. The game ends when you cannot make any more moves, ie. the stones are in consecutive positions. When the game ends, what is the minimum and maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves] """ """SOLUTION: The maximum number of moves would be the total number of empty spots between the stones. The minimum number of moves can be obtained by analyzing the following 4 cases: 1. If the number of empty spots between any one of the pairs of successive stones is 1, e.g. [1, 3, 5], and [3, 5, 10], then only 1 move is required which fills the empty spot between the pair of stones. 2. If there are no empty spots between both the successive pair of stones, e.g. [1, 2, 3], then no move is required. 3. If there is no empty spot between any one of the pairs of successive stones, e.g. [2, 10, 11] or [2, 3, 10], then only 1 move is required. 4. For all the other possible configurations, at least 2 moves are required. """ class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: stones = sorted([a, b, c]) max_moves = (stones[1] - stones[0] - 1) + (stones[2] - stones[1] - 1) # points between the stones # add cases for min_moves if stones[1] - stones[0] == 2 or stones[2] - stones[1] == 2: # [1, 3, 5] min_moves = 1 elif stones[1] - stones[0] == 1 and stones[2] - stones[1] == 1: # [1, 2, 3] min_moves = 0 elif stones[1] - stones[0] == 1 or stones[2] - stones[1] == 1: # [2, 10, 11] or [2, 3, 10] min_moves = 1 else: # all other cases min_moves = 2 return [min_moves, max_moves]
true
22e6457a4791af6292a17bbb294566aefdb9834e
sheelabhadra/LeetCode-Python
/728_Self_Dividing_Numbers.py
1,425
4.125
4
#A self-dividing number is a number that is divisible by every digit it contains. # For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. # Also, a self-dividing number is not allowed to contain the digit zero. # Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. # Example 1: # Input: # left = 1, right = 22 # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] class Solution(object): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ res = [] for num in range(left,right+1): digits = [] temp = num print(num) while temp != 0: lsd = temp%10 flag1 = 0 if lsd == 0: print("Contains 0") flag1 = 1 break digits.append(lsd) temp = temp//10 if flag1: continue for d in digits: flag2 = 0 if num%d != 0: flag2 = 1 break if flag2: continue else: res.append(num) print(res) return res
true
8f977472fd05fb250e180589c6545a545805a2ac
zahraaassaad/holbertonschool-machine_learning
/math/0x06-multivariate_prob/0-mean_cov.py
854
4.28125
4
#!/usr/bin/env python3 """ calculates the mean and covariance of a data set """ import numpy as np def mean_cov(X): """ X is a numpy.ndarray of shape (n, d) containing the data set: n is the number of data points d is the number of dimensions in each data point Returns: mean, cov: mean numpy.ndarray of shape (1, d) containing the mean of the data set cov numpy.ndarray of shape (d, d) containing the covariance matrix of the data set """ if not isinstance(X, np.ndarray) or len(X.shape) != 2: raise TypeError("X must be a 2D numpy.ndarray") if X.shape[0] < 2: raise ValueError("X must contain multiple data points") d = X.shape[1] mean = np.mean(X, axis=0) a = X - mean c = np.matmul(a.T, a) cov = c/(X.shape[0] - 1) return mean.reshape((1, d)), cov
true
e4a322de533519abc12a1819ef9bcea84113c488
kwierman/Cards
/Source/Shuffle.py
1,032
4.125
4
""" @package Shuffle Performs shuffling operations on decks """ import Deck ## splits the deck into two decks # @param deck The deck to be split # @param split_point how many cards from the top of the deck to split it def split_deck(deck, split_point=26): deck_1 = Deck.Deck() deck_2 = Deck.Deck() for x, card in enumerate(deck.private.cards): if(x<split_point): deck_1.add_card(card) else: deck_2.add_card(card) return (deck_1, deck_2) ## performs a tent shuffle def tent_shuffle(deck, split_point=26, groups=[], shuffle_left=True): #first split it into two decks deck1, deck2 = split_deck( deck, split_point ) if(shuffle_left): deck3=deck1 deck1=deck2 deck2=deck3 #for each of the groups of cards result_deck=Deck.Deck() for x,i in enumerate(groups): tent_group=Deck.Deck() if(x%2==0 ): tent_group,deck1 = split_deck(deck1, i) else: tent_group,deck2 = split_deck(deck2, i) result_deck.add_deck(tent_group) result_deck.add_deck(deck1) result_deck.add_deck(deck2) return result_deck
true
5fd87282bd2429a43a83feb00c542b07da1a4259
simiyub/python
/interview/practice/code/arrays/SortedSquareFromSortedArray.py
642
4.28125
4
""" Given an array of sorted integers, this function returns a sorted array of the square of the numbers """ def sorted_square_array(array): result = [0 for _ in array] smaller_value_index = 0 larger_value_index = len(array) - 1 for index in reversed(range(len(array))): smaller_value = array[smaller_value_index] larger_value = array[larger_value_index] if (abs(smaller_value) > abs(larger_value)): result[index] = smaller_value ** 2 smaller_value_index += 1 else: result[index] = larger_value ** 2 larger_value_index += 1 return result
true
6e713b61bedbe73121c1326b8d17ae7cd5d1ef06
simiyub/python
/interview/practice/code/recursion/Permutations.py
1,724
4.15625
4
""" Requirement:This function will receive an array of integers and create an array of unique permutations or ordering of integers that can be created from the integers in the array. Implementation: We build all permutations for the array within the array in place using pointers. We select the first element in the array and use it as a starting element of all the combinations of permutations that can be formed from the rest of the elements in the array. We swap the first element in the remaining array of elements with the current anchor index. Then we iteratively call the helper method a second time with the next element in the array of remaining elements, the array and the array of permutations. When we are done with this call, we swap back the elements to how they were before and move on to the next index after the anchor index. When the index is the last one in the array, we copy the array into the array of permutations. Complexity: O(n*n!) T and O(n.n!) S For each element in the array, we make calls to the helper equivalent to the position of the element in the array which means the last one will have n.n! calls. """ def __swap(array, i, j): array[i], array[j] = array[j], array[i] def __permutations_helper(anchor_index, array, all_permutations): if anchor_index == len(array) - 1: all_permutations.append(array[:]) else: for j in range(anchor_index, len(array)): __swap(array, anchor_index, j) __permutations_helper(anchor_index + 1, array, all_permutations) __swap(array, anchor_index, j) def permutations(array): permutations_found = [] __permutations_helper(0, array, permutations_found) return permutations_found
true
61066f828ffa00dd2652b07ea8e546e255682cf8
simiyub/python
/interview/practice/code/linked_lists/ReverseLinkedList.py
1,248
4.15625
4
""" Requirement: Given a linked list where each node points to the next node, this function will return the linked list in reverse order Implementation: Conceptually, a node is reversed when the next pointer points to the previous node. However, as this is a singly linked list, we do not have a pointer to the previous node. So we need to create one. We do this using a temporary node that we initialise to None as we start traversing the linked list from head. We also need to keep a reference to the next node after the current node because if we move the next pointer of the current node to the previous node, we would lose connection to the rest of the linked list. Once we have these two temporary references in place, we start moving our pointers along recursively until the current node is null and at that point the linked list will be reversed. Complexity: O(n) T O(1) S as we have to recursively traverse the whole linked list. However, we do not use any additional space than that of the linked list. """ def reverse(head): previous = head current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous
true
fe1c5e5cea9e34e329b658982acd5bd7fd8f23af
shorya97/AddSkill
/DS & Algo/Week 2/Stack/Implement Stack using Queues.py
1,420
4.15625
4
from queue import Queue class MyStack: def __init__(self): """ Initialize your data structure here. """ self.q1 = Queue() #inbuilt queues self.q2 = Queue() self.cur_size = 0 #contains number of elements def push(self, x: int) -> None: """ Push element x onto stack. """ self.cur_size+=1 self.q2.put(x) while (not self.q1.empty()): self.q2.put(self.q1.queue[0]) self.q1.get() self.q = self.q1 self.q1 = self.q2 self.q2 = self.q def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ if (self.q1.empty()): return return self.q1.get() self.cur_size -= 1 def top(self) -> int: """ Get the top element. """ if self.q1.empty(): return -1 return self.q1.queue[0] def empty(self) -> bool: """ Returns whether the stack is empty. """ if self.q1.empty(): return True else: return False # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
true
be1b56dc341fc45d7c0d017bc979c4d1426f7afa
prabhu30/Python
/Strings/Set - 1/maketrans_translate.py
743
4.5625
5
""" maketrans() :- It is used to map the contents of string 1 with string 2 with respective indices to be translated later using translate(). translate() :- This is used to swap the string elements mapped with the help of maketrans(). """ # Python code to demonstrate working of # maketrans() and translate() from string import maketrans # for maketrans() str = "geeksforgeeks" str1 = "gfo" str2 = "abc" # using maktrans() to map elements of str2 with str1 mapped = maketrans( str1, str2 ) # using translate() to translate using the mapping print "The string after translation using mapped elements is : " print str.translate(mapped) """ Output : The string after translation using mapped elements is : aeeksbcraeeks """
true
bdbfdd41268b98866a0eb26d1d335267b1a4f0b9
prabhu30/Python
/Lists/Set - 1/indexing_negative.py
666
4.375
4
""" Negative indexing :- In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc. """ List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks'] # accessing a element using # negative indexing print("Accessing element using negative indexing") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3]) """ Output: Accessing element using negative indexing Geeks For """
true
e8bc8d4d3b21a4e6525a0e23a3e462f4feabb9a0
Manish674/Cs50-problem-sets
/pset6/mario/mario.py
201
4.15625
4
height = int(input("Height: ")) while height < 0: height = int(input("Height: ")) col = 0 row = 0 while row <= height: while col <= row: print("#"*col) col += 1 row += 1
false
df60640085e6f84ebd72aee33d3dd29dfc4d950e
TrevorSpitzley/PersonalRepo
/PythonProjects/listCheck.py
920
4.25
4
#!/usr/bin/env python # This file is used for comparing two lists. # If there is an element in the input_list, # and it is not in the black_list, then it # will be added to the out_list and printed def list_check(input_list, black_list): out_list = [] for element in input_list: if element not in black_list: out_list.append(element) return out_list chars = ['a', 'b', 'c', 'd'] chars2 = ['e', 'f', 'g', 'h'] chars3 = ['a', 'c'] chars4 = ['e', 'h'] ints = [1, 2, 3, 4] ints2 = [5, 6, 7, 8] ints3 = [1, 2, 3] ints4 = [5, 6, 7, 8] # Should return ['b', 'd'] print(list_check(chars, chars3)) # Should return ['f', 'g'] print(list_check(chars2, chars4)) # Should return [4] print(list_check(ints, ints3)) # Should return [] print(list_check(ints2, ints4)) # Should return ['e', 'f', 'g', 'h'] print(list_check(chars2, ints)) # Should return [1, 2, 3] print(list_check(ints3, chars3))
true
fba0793e6a6508be9717c0db93287d455ed13d5d
nathan-create/assignment-problems
/linked_list.py
1,601
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None self.index = 0 class LinkedList: def __init__(self, data): self.head = Node(data) def append(self, data): current_node = self.head node_index = 0 while current_node.next != None: current_node = current_node.next node_index += 1 current_node.next = Node(data) current_node.next.index = current_node.index + 1 def print(self): current_node = self.head while current_node != None: print(current_node.data) current_node = current_node.next def length(self): current_node = self.head nodes_visited = 1 while current_node.next != None: current_node = current_node.next nodes_visited += 1 return nodes_visited def push(self, data): former_head = self.head self.head = Node(data) self.head.next = former_head current_node = former_head while current_node != None: current_node.index += 1 linked_list = LinkedList('b') linked_list.append('e') linked_list.append('f') linked_list.push('a') assert linked_list.length() == 4, linked_list.length() assert linked_list.head.index == 0, linked_list.head.index assert linked_list.head.next.index == 1 assert linked_list.head.next.next.index == 2 assert linked_list.head.next.next.next.index == 3, linked_list.head.next.next.next.index assert linked_list.get_node(0) == 'a', linked_list.get_node(0)
false
62615472dad8b7cbd47655acab1ee1dcafcfc4f3
cbolson13/Pyautogui_CO
/Personality_Survey_C.py
1,876
4.21875
4
print("What's your name?") name = input().title() if name == "Connor": print("Same here!") else: print(name + " is a pretty cool name.") print("What's your favorite sport") sport = input().title() if sport == "Soccer": print("Cool, what's your favorite team!") soccerteam = input().title() if soccerteam == "Liverpool": print("That is my favorite team also!") elif soccerteam == "Manchester United" or soccerteam == "Everton": print("Oh no, I like Liverpool and not " + soccerteam) else: print(soccerteam + " is not my favorite team, but I don't mind them") elif sport == "Tenis": print("Cool, sometimes I like to play tenis too!") else: print("Wow, " + sport + " sound fun!") print("What's your favorite TV Show?") tvshow = input().title() if tvshow == "Flash" or tvshow == "Rick And Morty" or tvshow == "The Flash": print("I love " + tvshow + " too! Who is your favorite character?") character = input().title() if character == "Cisco" or character == "Barry" or character == "The Flash" or character == "Joe" or character == "Wally" or character == "Kid Flash" or character == "HR" or character == "Rick" or character == "Morty" or character == "Beth" or character == "Jerry" or character == "Summer" or character == "Mr.Meeseeks": print("Awesome, " + character + " is one of my favorite character too!") elif character == "Iris": print("I don't really like " + character + " that much.") else: print(character + " isn't my favorite, but I don't mind them.") elif tvshow == "Leverage" or tvshow == "Psych" or tvshow == "Wizards Of Waverly Place": print("I used to watch " + tvshow + " too!") else: print("I don't know about " + tvshow + " but it sounds good!")
true
e120d6a0b5708af15a2a50b654ef68837a12c03e
Abhiaish/GUVI
/ZEN class/day 1/fare.py
236
4.15625
4
distance=int(input("enter the distance")) peaktime=int(input("enter the peaktime")) if(distance>5): distance=distance-5 else: print("fare is 100") fare=int(distance*8+100) if(peaktime==1): fare=fare+0.25*fare print(fare)
true
bbdb68232f6a2d04d342d4cc274faa2d3d083aeb
renzhiliang/python_work
/chapter4/4-10.py
293
4.34375
4
#numbers=range(3,31,3) numbers=[number**3 for number in range(1,11)] print(numbers) print("The first three items in the list are:") print(numbers[0:3]) print("Three items from the middle of the list are:") print(numbers[5:8]) print("The last three items in the list are:") print(numbers[-3:])
true
cabc815a05896d9d72e0f904eac1aede308438e7
thu4nvd/project_euler
/prob014.py
1,184
4.15625
4
#!/usr/bin/env python3 ''' Longest Collatz sequence Problem 14 The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. 23.73s user 0.00s system 99% cpu 23.734 total https://projecteuler.net/problem=14 ''' def collatz_seq(n): length = 1 while n != 1: if n % 2 == 0 : n = n // 2 else: n = 3 * n + 1 length += 1 return length def solve(N): max_length = 1 for i in range(2, N): if max_length < collatz_seq(i): max_length = collatz_seq(i) max_i = i return max_i def main(): print(solve(1000000)) if __name__ == "__main__": main()
true
a3b53793279b63e1facca3a5b4bef20146aff93d
leemanni/receiving-GV_Python
/6.30/stackModule.py
1,583
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[27]: class Stack : # constructor def __init__(self, size = 5) : self.size = size self.stack = list() self.top = 0 # push def push(self, data): if data not in self.stack : if self.size > self.top: self.stack.append(data) print('데이터 저장 완료') self.top += 1 else: print('overflow') else : print('중복!...{} 데이터는 받을 수 없습니다'.format(data)) self.view() #pop def pop(self): if self.top == 0 : print('제거할 데이터 없음') else : data = self.stack.pop() self.top -= 1 # pop() 은 제거할 데이터를 가지고 있다가 없애는 것을 이용 print('{} 가 제거되었습니다'.format(data)) self.view() #view def view(self) : if self.top != 0 : print('stack==> ',end ='') for i in range(self.top): print(self.stack[i],end=' ') else : # 데이터가 없을 때 print('underflow!! 데이터가 없어용') print() # In[34]: if __name__ == '__main__' : st = Stack() st.push(25) st.push(34) st.push(33) st.push(34) st.push(1) st.push(2) st.push(33) print('='*35) st.pop() st.pop() st.pop() st.pop() st.pop() st.pop()
false
12abd510bd551ccafd2101bb6392c35357bdbe47
mtmccarthy/langlearn
/bottomupcs/Types.py
1,530
4.71875
5
from typing import NewType, Dict """ In Chapter 1, we learned that 'Everything is a File!'. Here we've created a new type, 'FileType' which models a file as its path in the filesystem. """ FileType = NewType('FileType', str) """ In Chapter 1, we learned about FileDescriptors, which are essentially integer indexes into a table stored by the kernel called the file descriptor table (shocking!) Since a file descriptor is essentially just an integer, we can model it as such. """ FileDescriptorType = NewType('FileDescriptorType', int) """ We can model the table as a dictionary with key file descriptor and value file. The fd table is generated for every process and holds a pointer to the system fd table, but the model still holds up. """ FileDescriptorTableType = Dict[FileDescriptorType, FileType] """ In Chapter 1, we learned about Device Drivers are software which provide an abstraction between the kernel and external devices such as a keyboard, mouse, monitor etc. """ DeviceDriverType = NewType('DeviceDriverType', None) """ Programs are files that can also be executed. We can model that like this: """ ProgramType = NewType('ProgramType', FileType) """ In Chapter 1, the kernel was mentioned. The kernel is essentially a program executed when the system boots. The kernel is responsible for processing low level system calls, examples include input/output and memory management. Since the kernel is just a special type of program, we can model it like this: """ KernelType = NewType('KernelType', ProgramType)
true
6bb5fbe258c60e039c2380dcbbf50dc6b8e5d803
mtmccarthy/langlearn
/dailyredditor/easy/imgurlinks_352.py
1,574
4.25
4
from common import * from typing import Union """ Finds the greatest exponent of n that is less than or equal to another number m Example: if n = 2 and m = 17 return 4 """ def get_base62_character(index: int) -> Union[str, None]: capital_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' lower_case = 'abcdefghijklmnopqrstuvwxyz' if index < 10: return str(index) elif 10 <= index < 36: return lower_case[index - 10] elif 36 <= index < 62: return capital_letters[index - 36] else: return None def find_greatest_exponent_of_n_loe_than_m(n: int, m: int) -> int: current_exponent = 0 while n ** current_exponent <= m: current_exponent += 1 return current_exponent - 1 def convert_from_base10ton(baseN: int, num: int) -> str: conversion = [] power = find_greatest_exponent_of_n_loe_than_m(baseN, num) while power > 0: place_value = baseN ** power digit = 0 while num - place_value > 0: digit += 1 num -= place_value conversion.append(digit) power -= 1 conversion.append(num) # One's place return ''.join(list(map(lambda digit: get_base62_character(digit), conversion))) def generate_output(path: str) -> str: lines = get_file_lines(path) output = "" for line in lines: output += convert_from_base10ton(62, int(line.rstrip())) + '\n' return output def main(): path = 'easytests/imgurlinks_352_challenge_input.txt' print(generate_output(path)) if __name__ == '__main__': main()
true
17ce6e5c354abe914abb538356201ed5cfc55a25
lamyai-norn/algorithsm-week11
/week11/thursday1.py
279
4.15625
4
def sumFromTo(start,end): result=0 if start>end: return 0 else: for index in range(start,end+1): result=result+index return result startValue=int(input("Start value : ")) endValue=int(input("End value : ")) print(sumFromTo(startValue,endValue))
true
3ce463b0b5860ae48129db242597bb45d7620ecc
NikolasSchildberg/guesser
/guesser_simple.py
1,218
4.21875
4
""" Welcome to the number guesser in python! The logic is to use the bissection method to find a number chosen by the user, only providing guesses and asking to try a bigger or smaller one next time. """ # Initial message print("Welcome to the number guesser!\nThink of a number between 1 and 1000 (including them).I'll take only 10 guesses (or less) to find out which number you picked.\nYou'll just have to tell me if your number is smaler or bigger than my guess. Wanna try it?") print("Please enter '0' if I'm already right, '1' if your number is smaller, and '2' if your number is bigger.\n") right = False smaller = 0 bigger = 1000 guess = int((smaller + bigger)/2) count_guesses = 0 while(right != True): whattodo = input("Is it "+str(guess)+"?\n>>> " ) if whattodo == '0': right = True elif whattodo == '1': bigger = guess guess = int((smaller + bigger)/2) elif whattodo == '2': smaller = guess guess = int((smaller + bigger)/2) else: print("Try again...") count_guesses += 1 else: if(count_guesses == 1): print("Gotcha! Needed",count_guesses,"guesse!\nBye!") else: print("Gotcha! Needed",count_guesses,"guesses!\nBye!")
true
6150528fcd6ecb0f9a68655746318a2f680ee546
Antonio24ch/BEDU-281120
/01_tabla_multiplicar.py
485
4.15625
4
#Preguntar el numero que el usuario quiere multiplicar numero = int(input('Que número quieres multiplicar?\t')) print(f'A continuacion se muestra la tabla del {numero}') print('------------------------------------------------') #Esta función hace esto: # n * 1 = n # n * 2 = n # n * 3 = n # ... for n in range(10): indice = n + 1 #Sirve para que si queremos multiplicar cada 2, 3, etc. solo se cambie el numero(1) r = numero * indice print(f'{numero} * {indice} = {r}')
false
826f03f9f1dc41fe4aca2c70b505d7381ba091bf
EagleRock1313/Python
/circle.py
523
4.40625
4
# Load the Math Library (giving us access to math.pi and other values) import math # Ask for the radius of a circle that will be entered as a decimal number radius = eval(input(("Enter the radius of the circle: "))) # Computer circumference and area of this circle circumference = 2 * math.pi * radius area = math.pi * (radius ** 2) # Results print() print("Circumference is", circumference) print("Area is", area) print("\nRounded: ") print("Circumference is", round(circumference,2)) print("Area is", round(area,2))
true
ebcf7ae783f11ff6e8908df29b9c0c46cd0b54af
petemulholland/learning
/Python/ThinkPython/Chapter18/MyCard.py
1,364
4.15625
4
class Card(object): """ Represents a playing card""" #suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] #rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', # '8', '9', '10', 'Jack', 'Queen', 'King'] suit_names = ('C', 'D', 'H', 'S') rank_names = (None, 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank # class variables def __str__(self): #return '%s of %s' % (Card.rank_names[self.rank], return '%s%s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) # for this implementation suit is more important than rank, # so all Spaces outrank all diamonds etc. def __cmp__(self, other): c1 = self.suit, self.rank c2 = other.suit, other.rank return cmp(c1, c2) def cmp_to_string(res): if res > 0: return ">" if res < 0: return "<" return "=" if __name__ == '__main__': card1 = Card(1, 11) card2 = Card(1, 11) card3 = Card(2, 8) print card1, cmp_to_string(cmp(card1, card2)), card2 print card1, cmp_to_string(cmp(card1, card3)), card3 print card3, cmp_to_string(cmp(card3, card2)), card2 print card1
false
fdeecfeec4bbea1b1c5bd1738bbadf905dcb3772
Kapilmundra/Complete-Python-for-Lerner
/4 set.py
691
4.21875
4
#Create set print("Create set") s={"teena","meena","reena"} print(s) # it can print in unorder way #pop the element from the set print("\npop the element from the set") s.pop() # it can pop the element in unorder way print(s) #Add element in the set print("\nAdd element in the set") s.add("priya") # it can add the new value in unorder way print(s) s.add("priya") # distinct(not return same value in set) print(s) #Operation print("\nOperation") p={"rajesh","manish","reena"} print(p) print("Difference") x=s.difference(p) print(x) print("Intersection") z=s.intersection(p) print(z) print("Difference_update") y=s.difference_update(p) print(y)
true
d86d7fdc1e4fb8c3e6c328b2d4141f5b2e078f66
das-jishu/data-structures-basics-leetcode
/Leetcode/hard/regular-expression-matching.py
2,506
4.28125
4
""" # REGULAR EXPRESSION MATCHING Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". Example 4: Input: s = "aab", p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab". Example 5: Input: s = "mississippi", p = "mis*is*p*." Output: false Constraints: 0 <= s.length <= 20 0 <= p.length <= 30 s contains only lowercase English letters. p contains only lowercase English letters, '.', and '*'. It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. """ class Solution: def isMatch(self, s: str, p: str) -> bool: table = [[None for _ in range(len(p) + 1)] for _ in range(len(s) + 1)] table[0][0] = True for row in range(1, len(s) + 1): table[row][0] = False for col in range(1, len(p) + 1): if p[col - 1] == "*": table[0][col] = table[0][col - 2] else: table[0][col] = False for row in range(1, len(s) + 1): for col in range(1, len(p) + 1): if p[col - 1] == ".": table[row][col] = table[row - 1][col - 1] elif p[col - 1] != "*": table[row][col] = table[row - 1][col - 1] and s[row - 1] == p[col - 1] else: if p[col - 2] == ".": table[row][col] = table[row][col - 1] or table[row][col - 2] or table[row - 1][col - 1] or table[row - 1][col] else: table[row][col] = table[row][col - 1] or table[row][col - 2] or (table[row - 1][col - 1] and p[col - 2] == s[row - 1]) for row in range(len(s) + 1): print(table[row]) return table[-1][-1]
true