blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7132b01f8aefc39d775455c3cb1e6343de6e738e
evensteven01/pythonTricks_sf
/oop.py
2,314
4.5
4
# Classes vs instance variables class Car: color = 'Red' # this is an class variable def __init__(self, name): self.name = name # This is an instance variable my_car = Car('My car') other_car = Car('Other car') other_car.color = 'Blue' print(f'My car color: {my_car.color} Other car color: {other_car.color}') # Result: My car color: Red Other car color: Blue Car.color = 'Orange' print(f'My car color: {my_car.color} Other car color: {other_car.color}') # Result: My car color: Orange Other car color: Blue # By doing other_car.color, we created a instance variable with the same name as # the class variable, and hence ended up shadowing/overriding and hiding the # class variable # You can access class variables from an instance variable. # IE to keep track of instances of a class: class CountedObject: num_instances = 0 def __init__(self): self.__class__.num_instances += 1 print(f'{CountedObject.num_instances} insantiations of CountedObject') co1 = CountedObject() print(f'{CountedObject.num_instances} insantiations of CountedObject') co2 = CountedObject() print(f'{CountedObject.num_instances} insantiations of CountedObject') # Class vs instance vs static methods class MyClass: def method(self): return 'instance method called', self @classmethod def classmethod(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called' mc = MyClass() print(mc.method()) # You can also do: print(MyClass.method(mc)) print(mc.classmethod()) print(MyClass.classmethod()) print(mc.staticmethod()) print(MyClass.staticmethod()) class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients!r})' # These are class methods that are useful as factory functions @classmethod def margherita(cls): # Its better to use cls here instead of Pizza to follow DRY, and makes easier # to later change the class name more easily return cls(['mozzarella', 'tomatoes']) #Class factory methods are in a way a method to add constructors to a class @classmethod def prosciutto(cls): return cls(['mozzarella', 'tomatoes', 'ham']) print(Pizza.margherita())
true
df28bae3acee935a691689482bb39d4d14a31334
giahienhoang99/C4T-BO4
/session7/Part II/bt4.py
223
4.375
4
from turtle import * numofsides = int(input("Enter number of sides: ")) length = int(input("Enter length of sides: ")) Angle = 360 / numofsides for i in range(numofsides): forward(length) right(Angle) mainloop()
true
00e6a5d4bfa0db65475fdcefafecdde02470a345
sandeepgit32/Data_Structure_Tutorial_Python_Latex
/src/sort/bubblesort2.py
639
4.25
4
def bubble_sort(input_list): L = len(input_list) Round_num = L-1 Iterations_per_round = [L-x for x in range(1, L)] for rnd in range(Round_num): for iteration in range(Iterations_per_round[rnd]): for i in range(0, L-1-iteration): if input_list[i] > input_list[i+1]: swap_value_by_index(input_list, i, i+1) def swap_value_by_index(a_list, a, b): a_list[b], a_list[a] = a_list[a], a_list[b] input_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print("Before sorting:") print(input_list) bubble_sort(input_list) print("After bubble sort:") print(input_list)
false
21421a62659e44c410d2c46083120d2473cbff6e
sandeepgit32/Data_Structure_Tutorial_Python_Latex
/src/sort/selectionsort2.py
662
4.125
4
def selection_sort(input_list): L = len(input_list) Round_num = L-1 Iterations_per_round = [L-x for x in range(1, L)] for rnd in range(Round_num): for iteration in range(Iterations_per_round[rnd]): for i in range(iteration, L-1): if input_list[iteration] > input_list[i+1]: swap_value_by_index(input_list, iteration, i+1) def swap_value_by_index(a_list, a, b): a_list[b], a_list[a] = a_list[a], a_list[b] input_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print("Before sorting:") print(input_list) selection_sort(input_list) print("After selection sort:") print(input_list)
false
b86d9a07ff57f36252fc262af668330b41438f08
swapnil2188/python-myrepo
/parsing/find_dupes-words.py
360
4.25
4
#!/usr/bin/python ex ='This is sample file. This is not a sample file. Not a sample file' def freq(str): # break the string into list of words str_list = str.split() # gives set of unique words unique_words = set(str_list) print unique_words for words in unique_words: print(words, str_list.count(words)) # calling the freq function freq(ex)
true
e87162070ec2b7e8b8332005452023b913ab115f
swapnil2188/python-myrepo
/lists/lists_methods.py
1,805
4.59375
5
#!/usr/bin/python print "\n append - The append() method appends an element to the end of the list" fruits = ['apple', 'banana', 'cherry'] fruits.append("Orange") print fruits print "\n The clear() method removes all the elements from a list" #fruits.clear() #print (fruits) print "\n The copy() method returns a copy of the specified list" #x = fruits.copy() #print (x) print "\n The count() method returns the number of elements with the specified value" x = fruits.count("cherry") print (x) print "\n The extend() method adds the specified list elements (or any iterable) to the end of the current list" fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print fruits print "\n Returns the index of the first element with the specified value" print "\n The insert() method inserts the specified value at the specified position" fruits.insert(1, "GUAVA") print fruits print "\n The pop() method removes the element at the specified position" print "default value is -1, which returns the last item ****IMPORTANT \n" fruits.pop(1) print fruits print "\n The remove() method removes the first occurrence of the element with the specified value" fruits.remove("apple") print fruits print "\n The reverse() method reverses the sorting order of the elements" fruits.reverse() print fruits print "\n The sort() method sorts the list ascending by default." print "sort Ascending reverse=FALSE (DEFAULT), sort Descending reverse=TRUE" cars = ['Ford', 'BMW', 'Volvo'] cars.sort() print cars #cars.sort(reverse=TRUE) #print cars #A function that returns the length of the value: def myfunc(e): return len(e) print "\n Sort Based on length of each item in List - smallest to largest" cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(key=myfunc) print cars
true
e292a2649a8257eafd078d2a1054aa2c32a03f88
Manoo-hao/project
/Exercises/function_exercise2.py
2,003
4.125
4
from __future__ import division def get_percentage(sequence, amino_acids): '''This is a more flexible version of function_exercise1 which can return the percentage of a list of amino acids as specified in the argument 'amino_acids' above. It will also work when entering an empty string, a single amino acid, and an amino acid that is not actually present in the argument'sequence' This function is as yet unresolved!''' length = len(sequence) #calculates length of sequences and stores it in variable length #hydrophobic = ['A','I','L','M','F','W','Y','V'] #not_hydrophobic = ['G','P','C','H','K','R','Q','N','E','D','S','T'] #non hydrophobic aa: or amino_acid == 'G' or amino_acid == 'P' or amino_acid == 'C' or amino_acid == 'H' or amino_acid == 'K' or amino_acid == 'R' or amino_acid == 'Q' or amino_acid == 'N' or amino_acid == 'E' or amino_acid == 'D' or amino_acid == 'S' or amino_acid == 'T' #DMAM 30/1 amino_acids is a list. You have to count each element in the list separately hydrophobic_amino_acid_count = 0 for amino_acids in sequence: if amino_acid == 'A' or amino_acid == 'I' or amino_acid == 'L' or amino_acid == 'M' or amino_acid == 'F' or amino_acid == 'W' or amino_acid == 'Y' or amino_acid == 'V': hydrophobic_amino_acid_count = hydrophobic_amino_acid_count +1 non_hydrophobic_amino_acid_count = 0 for amino_acids in amino_acids: if amino_acid == 'G' or amino_acid == 'P' or amino_acid == 'C' or amino_acid == 'H' or amino_acid == 'K' or amino_acid == 'R' or amino_acid == 'Q' or amino_acid == 'N' or amino_acid == 'E' or amino_acid == 'D' or amino_acid == 'S' or amino_acid == 'T' non_hydrophobic_amino_acid_count = non_hydrophobic_amino_acid_count+1 amino_acid_count = sequence.count(str(amino_acids)) #set amino_acid count to 0 #loop through amino_acids, adding the count for each amino acid to amino_acid_count percentage = amino_acid_count / length return round(percentage, 2)
true
cdc4cb894dff239cc436d3b1e88d6edfa466e6ad
ilailabs/python
/tutorials/trash/SimpleCalculator.py
1,581
4.3125
4
while True: print('Options:') print ("Enter 'add' to add two numbers") print("Enter 'sub' to subtract two numbers") #print 'Enter 'mul' to multiply two numbers' #this will through a print error print "Enter 'mul' to multiply two numbers" print "Enter 'div' to divide two numbers" print "Enter 'quit' to quit the programe" userip=raw_input("Enter a Option : ") if userip=='quit': break elif userip=='add': n1=float(input("Enter a number: ")) n2=float(input("Enter a another number: ")) ans=str(n1+n2) print "The answer is "+ans elif userip=='sub': n1=float(input("Enter a number: ")) n2=float(input("Enter a another number: ")) ans=str(n1-n2) print "The answer is "+ans elif userip=='mul': n1=float(input("Enter a number: ")) n2=float(input("Enter a another number: ")) ans=str(n1*n2) print "The answer is "+ans elif userip=='div': n1=float(input("Enter a number: ")) n2=float(input("Enter a another number: ")) ans=str(n1/n2) print "The answer is "+ans else: print("Unknown input") #Points to remember: # Py2.7, input() evaluates the input as code, so strings need to be quoted. Numbers or string can be used. # Py2.7 has raw_input() that treats all input as strings (no quotes needed). Numbers are also treated as string. # Py3.x, the Py2.7 raw_input() was renamed input() and the Py2.7 input() functionality was replaced by eval(input()) # So switch to raw_input() or to Py3.x
false
1cf57e5d4f09523be84f5e773a40dbbe0c5ff92d
ilailabs/python
/tutorials/class.py
852
4.5
4
##example01 class MyClass: prop1 = 5 # "MyClass" is a class with property "prop1" object1 = MyClass() print(object1.property) ##example02 class Person: def __init__(self, name, age): self.name = name self.age = age #all classes have function called __init__() which is executed when class is initiated; called automatically #`self` parameter is a reference to the current instance of the class; you can call with any name def myMethod(self): print("Hello"+self.name+" have a good day") p1 = Person("Ilai",25) #new object `p1` with `name` and `age` properties print(p1.name) print(p1.age) p1.myMethod() p1.age = 26 #reasign property value del p1.age #delete object property del p1 #delete object class Student(Person): #creates a new class `Student` with properties and methods from class `Person`x.
true
aa55d8043cf23aa0032d1ec5faf2122ea901f250
ilailabs/python
/tutorials/trash/GetInputDict.py
467
4.21875
4
pairs={ 1:"apple", "Orange":[2, 3, 4], True:False, None:"True", } print(pairs) #Number *1:'apple'* isn't added to dic print(pairs.get("Orange")) print(pairs["Orange"]) #same as above line print(pairs.get(7)) # >>None print(pairs.get(1,'ae its there'))# >>False print(pairs.get(123,'its not in dic')) # >>its not in dic print(pairs.get(11,'ae its there')) #print(dic_name.get(int,'your comments')) #your comments will be printed if int is not in your dic_name
true
b041376f95bcc64f7f9ec23524a2fe6bd7194238
mbrown34/PowdaMix
/enemylist.py
1,054
4.15625
4
#!/usr/bin/env python ''' Originally created on Oct 28, 2012 Updated/revised on November 27, 2012 @author: matthew ''' #changed enemylist from the need to create a list variable and then add that list variable to the enemylist [] #now the person adding a new enemy can simply add another list into the main list by using the syntax below #syntax for creating a new enemy type == #[ 1, 2, 3, 4, 5, 6, 7, 8 ] #user entered string to create new enemy == ", ["Name", "description", hp_dice, base_attack, base_defense, xp_value, renown_value, gold_die]" #begin list of foes #", [ 1, 2, 3, 4, 5, 6, 7, 8]" #", ['barbarian', "A brutish barbarian", 15, 8, 5, 15, 5, 5]" enemylist = [ ['barbarian', "A brutish barbarian", 15, 8, 5, 15, 5, 5], ['rat', "A fairly weak rat", 10, 3, 1, 5, 2, 2], ['soldier', "A well-trained soldier", 17, 9, 7, 17, 8, 10] ]#end of list of foes
true
3e44d163733cda5584a266a6bf898b3d6f59cd8b
carlsose/Coursera-PY4E
/8.4.py
583
4.40625
4
#Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. #The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append #it to the list. When the program completes, sort and print the resulting words in alphabetical order. fname = open(input("Enter file name: ")) lst = list() for line in fname: line = line.rstrip() l = line.split(" ") for words in l: if words in lst: continue else: lst.append(words) lst.sort() print (lst)
true
6cba2036bcf586e38298d3a079715c0b7d1277a9
zhyordanova/Python-Basics
/Exam/06_passengers_per_flight.py
729
4.15625
4
import sys import math airline = int(input()) max_passengers = -sys.maxsize max_name = '' for name in range(1, airline + 1): name_airline = input() current_name = '' passengers = input() average = 0 counter = 0 total_passengers = 0 while passengers != "Finish": total_passengers += int(passengers) counter += 1 passengers = input() current_name = name_airline average += total_passengers / counter if average > max_passengers: max_passengers = average max_name = current_name print(f'{current_name}: {math.floor(average)} passengers.') print(f'{max_name} has most passengers per flight: {math.floor(max_passengers)}')
true
a7559245d2e38ef9b06700fa09831cd71ef71b97
jorzel/hackerrank
/30_days_of_code/day17_more_exceptions.py
2,122
4.46875
4
""" Objective Yesterday's challenge taught you to manage exceptional situations by using try and catch blocks. In today's challenge, you're going to practice throwing and propagating an exception. Check out the Tutorial tab for learning materials and an instructional video! Task Write a Calculator class with a single method: int power(int,int). The power method takes two integers, and , as parameters and returns the integer result of . If either or is negative, then the method must throw an exception with the message: n and p should be non-negative. Note: Do not use an access modifier (e.g.: public) in the declaration for your Calculator class. Input Format Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, , the number of test cases. Each of the subsequent lines describes a test case in space-separated integers denoting and , respectively. Constraints No Test Case will result in overflow for correctly written code. Output Format Output to stdout is handled for you by the locked stub code in your editor. There are lines of output, where each line contains the result of as calculated by your Calculator class' power method. Sample Input 4 3 5 2 4 -1 -2 -1 3 Sample Output 243 16 n and p should be non-negative n and p should be non-negative Explanation : and are positive, so power returns the result of , which is . : and are positive, so power returns the result of =, which is . : Both inputs ( and ) are negative, so power throws an exception and is printed. : One of the inputs () is negative, so power throws an exception and is printed. """ #Write your code here class Calculator(object): def power(self, n, p): if p < 0 or n < 0: raise Exception('n and p should be non-negative') return n ** p myCalculator = Calculator() T = int(input()) for i in range(T): n, p = map(int, input().split()) try: ans = myCalculator.power(n, p) print(ans) except Exception as e: print(e)
true
e911e0833e1f5a387fb95d180ae241339cac2b74
jooguilhermesc/cursoPython
/Scripts/Example.py
755
4.34375
4
#Pedir o nome do usuário utilizando o input e forçando que seja um texto com str() nomeCompleto = str(input("Oi tudo, bem? Como é seu nome? ")) #Exibir no terminal uma mensagem de saudção personalizada com o nome inserido ateriormente print("Olá "+nomeCompleto+" seu nome é muito legal!") """nomeCompleto = "João Guilherme Silva Cabral" usuerTwitter = "ztfeelings" tamanhoNome = len(nomeCompleto) print(tamanhoNome) print(nomeCompleto)""" """from math import sqrt as raiz a = 3 b = 2 print(raiz(a+b))""" """#Adição print('Adição') print(a+b) #Subtração print('Subtração') print(a-b) #Multiplicação print('Multiplicação') print(a*b) #Divisão print('Divisão') print(a/b) #Concateção print('Concateção') a = str(a) b = str(b) print(a+b)"""
false
e065d4ba52fd31959bc4b08bad45b9fa82a9cc79
Luciano-T-L/Books
/PTHW/ex39.1.py
884
4.28125
4
# Creating states map states = { 'São Paulo': 'SP', 'Rio de Janeiro': 'RJ', 'Santa Catarina': 'SC', 'Paraná': 'PR', 'Rio Grande do Sul': 'RS' } # Creating cities map cities = { 'SC': 'Florianópolis', 'PR': 'Curitiba', 'SP': 'São Paulo', 'RJ': 'Rio de Janeiro' } # Add a city cities['RS'] = 'Porto Alegre' cities['SC'] = 'Palhoça' # Add a state states['Rondônia'] = 'RO' """ # Prints print(cities['SC']) # Here Python takes just one item print(cities['SP']) print(' ') print(states) print(' ') print(states['Paraná']) # Priting every state abbreviation for x, y in list(states.items()): print(f'State: {x}, Abbreviation: {y}')""" # Priting every city in state for abbrevi, city in list(cities.items()): # Take just one city from every state print(f"City: {city}, State: {abbrevi}")
false
6d1dd4459823ab8bca1993b137d7b1208d2a1030
sonya-sa/guessing-game
/game.py
2,553
4.15625
4
import random import requests from api import get_word #create a function that randomly selects a word #create function that checks word and guess #function has 3 paramaters: word selected, guess letter, list of guesses taken def check(word, guesses, guess): show = '' matches = 0 for letter in word: if letter == guess: matches += 1 if letter in guesses: show += letter else: show += '-' if matches > 1: print('Yes, there are {} {}'.format(matches,guess) + "'"+ 's in the word.') elif matches == 1: print ('Yes! The word contains the letter: ' + guess + "'") else: print (show) print ('Sorry. The word does not contain the letter "' + guess + '".') return show #main function that runs game def main(): #logic for calling linkedin API in api.py word = get_word(input('Choose a difficulty level between 1-10: ')) #print(word) guesses = [] guessed = False incorrect = 0 max_guesses = 6 while not guessed and incorrect < max_guesses: text = 'Please enter one letter or a {}-letter word: '.format(len(word)) print('Letters already guessed: {}'.format(guesses)) print () print ('You have {} incorrect guesses remaining.'.format(max_guesses-incorrect)) guess = input(text).lower() #if we already guessed the letter, try again if guess in guesses: print('You already guessed:' + guess + ". Try again.") #check word for match elif len(guess) == len(word): guesses.append(guess) if guess == word: guessed = True #word was incorrect guess else: incorrect += 1 print ('Sorry! That is incorrect.') elif len(guess) == 1: guesses.append(guess) #returns a string of checked guesses result = check(word,guesses,guess) #if guess not in return string, then letter was incorrect if guess not in result: incorrect += 1 elif result == word: guessed = True else: print(result) else: print('Invalid entry.') if incorrect == max_guesses: print ('Sorry! You hit the maximum attempts. You lose.') else: print ('Yes, the word is', word + '. It took you', len(guesses), 'tries.') main()
true
4d7323eddc94f6cb5870a74f0ff2308b91ec808c
sanjaykumardbdev/pythonProject_1
/32_Functions.py
595
4.125
4
# define a function # call a function def greet(): print("first function in python") print("Hello ! Good Morning") greet() print("-----------") # pass 2 arguments def add(x,y): z = x + y print("sum of two num", z) add(3,3) add(12, 12) # function that return value def add_return(x, y): z = x + y return z # return val is stored in ret_val : ret_val = add_return(3, 3) print("function that return value", ret_val) # return 2 values def add_sub(x, y): a = x + y b = x - y return a, b add1, sub1 = add_sub (20, 10) print('add1 ->', add1, "sub1 ->", sub1)
true
890a83f6f42250c8ce00ec9df3eaa9328552017a
adamjford/CMPUT296
/Lecture-2013-01-30/example-orig.py
1,767
4.25
4
""" Graph example G = (V, E) V is a set E is a set of edges, each edge is an unordered pair (x, y), x != y """ import random # from random import sample # from random import * def neighbours_of(G, v): """ >>> G = ( {1, 2, 3}, { (1, 2), (1, 3) }) >>> neighbours_of(G, 1) == { 2, 3 } True >>> neighbours_of(G, 3) == { 1 } True >>> neighbours_of(G, 1) {3, 2} """ (V, E) = G neighbours = set() for (x,y) in E: if v == x: neighbours.add(y) if v == y: neighbours.add(x) return neighbours def generate_random_graph(n, m): V = set(range(n)) E = set() max_num_edges = n * (n-1) // 2 if m > max_num_edges: raise ValueError("For {} vertices, you want {} edges, but can only have a maximum of {}".format(n, m, max_num_edges)) while len(E) < m: pair = random.sample(V, 2) E.add(tuple([min(pair), max(pair)])) return (V, E) n = 20 m = 5 G = generate_random_graph(n, m) (V, E) = G print(G) print("Number of edges is {}, we want {}".format(len(E), m)) start = random.choice(list(V)) stop = random.choice(list(V)) cur = start print("Starting at {}".format(cur)) if len(neighbours_of(G, cur)) == 0: raise Exception("Bad luck, {} has no neighbours".format(cur)) num_steps = 0 max_num_steps = 1000 while cur != stop and num_steps < max_num_steps: num_steps += 1 # pick a neighbour of cur at random neighbours = neighbours_of(G, cur) # print(neighbours) # pick one of the neighbours # cur = random.sample(neighbours, 1)[0] # or cur = random.choice(list(neighbours)) print("At {}".format(cur)) print("Finished at {}".format(cur)) """ if __name__ == "__main__": import doctest doctest.testmod() """
true
8603b7a58ef620a11bd69db086e9add33f21dab5
smart9545/Python-assignments
/Q2.py
2,914
4.3125
4
############################################# # COMPSCI 105 SS C, 2018 # # Assignment 2 # # # # @author FanYu and fyu914 # # @version 10/2/2018 # ############################################# """ Description: Implement the functionality for the read_sentence() recursive function without using loops. This function take a list of words as its input to represent a sentence. It will also take an integer to determine how long a word must be before its definition must be looked up. The function print the sentence, ensuring no words longer than the integer are printed. Instead their definitions would be printed. The function get_definition() will take a word as its input and return a list of words representing the dictionary definition of the passed in word. """ def read_sentence(sentence, max_letters): ##You need to implement this recursive function if sentence==None: return None if len(sentence)>=1: if len(sentence[0])> max_letters: read_sentence(get_definition(sentence[0]),max_letters) else: print(sentence[0],end=" ") read_sentence(sentence[1:],max_letters) ##This function will return a list of words to represent ##the definition of the word. ##This function will be implemented for you and you may ##assume that the definition of the word will be returned if necessary ## ##Feel free to follow the example below to add your own words and their ##definitions for testing purposes! def get_definition(word): if word == 'sentence': return ['set', 'of', 'words'] if word == 'difficult': return ['not', 'easy'] if word == 'extraordinary': return ['better', 'than', 'ordinary'] if word == 'ordinary': return ['normal'] if word == 'discover': return ['come', 'by'] if word == 'mitochondria': return ['cells', 'in', 'cytoplasm','that','convert','energy'] if word == 'cytoplasm': return ['gel', 'outside', 'a','nucleus'] if word == 'powerhouse': return ['main', 'source', 'of','power'] print() ##should print: better than normal people are not easy to come by read_sentence(['extraordinary', 'people', 'are', 'difficult', 'to', 'discover'], 7) print() ##should print: better than ordinary people are not easy to discover read_sentence(['extraordinary', 'people', 'are', 'difficult', 'to', 'discover'], 8) print() ##should print: cells in gell outside a nucleus that convert energy are the main source of power of the cell read_sentence(['mitochondria', 'are', 'the', 'powerhouse', 'of', 'the', 'cell'], 7) print() ##should print: mitochondria are the powerhouse of the call read_sentence(['mitochondria', 'are', 'the', 'powerhouse', 'of', 'the', 'cell'], 20)
true
d152916196ff4743c4a07146039cbfb920f19b6a
Tishacy/Algorithms
/code/0 pick_based_on_prob.py
2,648
4.1875
4
# -*- coding: utf-8 -*- """Given an array with each element has a probability, choose one element according to its probability. 0.1 Giant array pool method step 1: Generate a new array by repeating the each element for multiple times according to its probability. step 2: Randomly pick one from the array. 0.2 Accept/Rejection method step 1: Randomly pick one element. step 2: Get a random float number from 0 to 1. If the number is less than the probability of the element, accept this element and return it. Else back to step 1 to pick again. 0.3 Bar method (RECOMMENDED) step 1: Set default picked element is the first element. step 1: Get a random float number (r) form 0 to 1. step 2: While r is greater than 0 r = r - probability of picked element picked element index ++ step 3: return picked element """ import random, time from pprint import pprint def pick_one_by_giant_array_pool(array): giant_array = [elem for elem in array for i in range(elem['score'])] picked_index = random.randint(0, len(giant_array)-1) return giant_array[picked_index] def pick_one_by_accept_rejection(array): while True: picked_index = random.randint(0, len(array)-1) r = random.random() if r < array[picked_index]['prob']: return array[picked_index] def pick_one_by_bar_method(array): picked_index = 0 r = random.random() while r > 0: r -= array[picked_index]['prob'] picked_index += 1 picked_index -= 1 return array[picked_index] def test(N, array, pick_func): """Pick for N times, and count distribution of each element. """ # Initialize the array by adding vars of 'count' and 'prob'. sum = 0 for elem in array: sum += elem['score'] for elem in array: elem['count'] = 0 elem['prob'] = float('%.4f' %(elem['score'] / sum)) # Pick for i in range(N): elem = pick_func(array) elem['count'] += 1 return array if __name__=="__main__": fruits = [ {"name":"mango", "score":5}, {"name":"blueberry", "score":3}, {"name":"cherry", "score":1}, {"name":"banana", "score":7}, {"name":"apple", "score":1}, ] pick_func_list = [ pick_one_by_giant_array_pool, pick_one_by_accept_rejection, pick_one_by_bar_method ] for pick_func in pick_func_list: print("\nPick function: %s." %(pick_func.__name__)) time0 = time.time() test(100000, fruits, pick_func) pprint(fruits) print("Costs %.4f sec." %(time.time() - time0))
true
1dbea5c313b920cc6e4520af126a4516802910c7
Tishacy/Algorithms
/leetcode/python_vers/4 Median of Two Sorted Arrays.py
1,189
4.1875
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ p, q = 0, 0 ans = [] while p < len(nums1) and q < len(nums2): if nums1[p] < nums2[q]: ans.append(nums1[p]) p += 1 else: ans.append(nums2[q]) q += 1 ans.extend(nums2[q:]) ans.extend(nums1[p:]) mid = len(ans) // 2 if len(ans)%2: return ans[mid] * 1. else: return (ans[mid - 1] + ans[mid]) / 2 if __name__ == '__main__': nums1, nums2 = [1, 2], [3, 4] s = Solution().findMedianSortedArrays(nums1, nums2) print(s)
true
2270fa9645a16015bc8440859b039802c1e4e7d6
summerqiu7/python-practice
/test.py
1,894
4.125
4
# This line prints "hello world!" # print('hello world!') # print('hello world 2!') # myverylongstring # MyVeryLongString #Upper camel case # myVeryLongString #camel case # my_very_long_string #snake case # myString = 'summer' # print(myString) # print(myString+"hello world") # x = 2 # print(x) # two = str('2') # print(1 + 2) # print('1' + two) # print(int('1') + int('2')) # list or array # summer=10 # if summer%2==0: # print("this is even") # else: # print("this is odd") # print(summer) # l = [1,2,3,4,5] # for number in l: # if number%2==0: # print(number) # i = 0 # while i < 5: # print(i) # i = i + 1 # print('hello') # i=0 # while i<100: # if i%2==0: # print (i) # i=i+1 # a=[] # i=1 # while i<=100: # a.append(i) # i += 1 # i = i + 1 # # print(a) # for number in a: # if number%2==0: # print(number) # result = add(1, 5) # resultTwo = add(result, 10) # print(resultTwo) # def isEvenNumber(i): # if i%2==0: # return True # else: # return False # n=0 # while n<100: # if isEvenNumber(n): # print (n) # n += 1 # def isOddNumber(i): # if i%2==0: # return False # else: # return True # n=0 # while n<=100: # if isOddNumber(n): # print (n) # n=n+1 # def isPrimeNumber(i): # n=2 # while n < i: # if i%n==0: # return False # n=n+1 # return True # n=0 # while n<=100000: # if isPrimeNumber(n): # print(n) # n=n+1 # with open('alice.txt', 'r') as file: # novel = file.read().replace('\n', '') # words = novel.split(' ') # # print(words) # count=0 # for name in words: # if name=="Alice": # count=count+1 # print(count) star =[] n=0 while n<=5: star.append("*") print(' '.join(star)) n=n+1
false
228c88cf0ebb2bc8a2d6777efdd99e61cab79149
gungeet/python-programming
/unit-2/classwork.py
955
4.4375
4
classmates = ['Ros', 'Marcus', 'Flavio', 'Joseph', 'Maham', 'Vinay', 'Gungeet', 'Faris'] ''' #prints number of items in list print(len(classmates)) #prints the first item in the list print(classmates[0]) #prints last element in list print(classmates[-1]) #adds element to list classmates.append('John') print(classmates[-1]) #inserts element in list classmates.insert(1, 'Mishoo') print(classmates[1]) #remove elemnet from end of the list classmates.pop() print(classmates[-1]) #print all elements in the list for name in classmates: print(name) #search for item in list for name in classmates: if name == 'Maham': print('Maham found in the list') ''' if 'Maham' in classmates: print('Found Maham in the list!') #using indices in for loop for idx, name in enumerate(classmates): print(idx, name) name = 'Gungeet' for x in range(len(name)-1, -1, -1): print(name[x]) #shortest way print(name[::-1]) print(name[1:3])
true
7bf7df412be0dee227b8929b2e0c5fb5506cc361
rebel47/Python-Revison
/chapter3.py
1,631
4.4375
4
# # WAP to display a user entered name followed by Good Afternoon using input() function # a = input("Enter your good name: ") # print(f"Good Afternoon, {a}") # f string is used in the print function # WAP to fill in a letter template given below with name and date # letter = ''' Dear <|NAME|>, # You are selected! # <|DATE|>''' # name = input("Enter the Name: ") # x = letter.replace("<|NAME|>",name) # import datetime # today = datetime.datetime.today() # tada = str(today) # b = x.replace("<|DATE|>", tada) # print(b) # ANOTHER WAY TO CODE THIS PROBLEM # import datetime # today = datetime.datetime.today() # name = input("Enter the Candidate Name:") # print(f'''Dear {name}, #We can also use string.replace function to done this task # You are Selected! # {today: %B %d, %Y}''') # # WAP to detect double spaces in a string # a = "Hello my lady I am Ayaz Alam and I am here to protect you" # print(a.find(" ")) # print(a) # a = a.replace(' ',' ') # print(a) # # WAP t format the following letter using escape sequence charaacters # letter = "Dear Harry,\n\tThis Python course is nice.\n\t Thanks!" # print(letter) # # Slicing # name = "Ayaz Alam is learning python right now." # print(name[-2]) # print(name[-8:-1]) # print(name[::-1]) # print(name[::-2]) # print(name[::2]) # print(len(name)) # print(name.endswith('lam')) # print(name.capitalize()) # print(name.upper()) # print(name.lower()) # print(name.find("python")) # find only the first occurence in the string # print(name.count("a")) # We can also count string using this
true
f504a392c39c12bd9f6fffb187959142c9d74649
MicahJank/cs-module-project-hash-tables
/applications/markov/markov.py
2,254
4.125
4
import random words_list = None data_set = {} punctuation = [".", "!", "?"] # Read in all the words in one go with open("./markov/input.txt") as f: words = f.read() words_list = words.split(" ") f.close() # TODO: analyze which words can follow other words ''' iterate over the words list for each word i will need to check and see if the word exists in the data set yet or not if it does exist in the data set i need to take the next word in the list and add it to the array at the position in the data set if it does not exist in the data set i need to create that word in the data set and add the next word in the list to the array associate with the newly created key ''' # this is the function that creates the crazy sentence # eg - "Pink brown bunnies!" def create_nonsense(word): print(word, end=" ") if word[-1] == '"' and word[-2] in punctuation: return word elif word[-1] in punctuation: return word # current_word = word next_word = random.choice(data_set[word]) return word + " " + create_nonsense(next_word) def choose_start_word(): possibilities = random.choices(words_list, k=5) for word in possibilities: if word[0].isupper(): return word elif word[0] == '"' and word[1].isupper(): return word # if none of the 5 choices are what i want then i use recursion to re run the function until i get start word return choose_start_word() def create_data_set(): for i, word in enumerate(words_list): # at the end of the list there cannot be any words that follow, so in that case i should just skip if i == (len(words_list) - 1): continue else: next_word = words_list[i+1] if word in data_set: data_set[word].append(next_word) else: data_set[word] = [next_word] create_data_set() # make sure start word begins with a capital or " followed by a capital start_word = choose_start_word() nonsense = create_nonsense(start_word) # # clear the output.txt before filling it out with the nonsense with open('./markov/output.txt', "r+") as data: data.truncate(0) data.write(nonsense) data.close()
true
7d77e601bdc517610a6301ca5f3a68e6bf32b838
adellario/pythonthw
/Exercises/ex11.2.py
558
4.46875
4
# This program calculates your longest maximum training run distance. # First, ask some basic questions. first_name = input("What's your first name? ") last_name = input("What's your last name? ") race_length = int(input("How long is your race? ")) # Calculate the max training run length max_train_run = race_length / 2 # Print the result print(f"Hello, {first_name} {last_name}!\nCongratulations on signing up for a {race_length} mile race!") print(f"Your maximum training run distance should be:\n\t\t***{max_train_run} miles long.") print("Good luck!")
true
0383b22e52ef1cbf524782e1e9cac487842d04ea
adellario/pythonthw
/Exercises/ex7.py
846
4.25
4
# Print the first phrase print("Mary had a little lamb.") # Print the a string with an empty variable, using .format() to fill that variable with the word "snow." print("Its fleece was white as {}.".format('snow')) # Print another string in the poem print("And everywhere that Mary went.") # Use math to multiply the "." string 10x print("." * 10) #What'd that do? # set "end" variables in numerical order to the letters required to spell out Cheese Burger end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # Concatenate the letters assigned to variables above, using end=' ' to avoid the linebreak between the two # lines and add a space between them. print(end1 + end2 + end3 + end4 + end5 + end6, end =' ') print(end7 + end8 + end9 + end10 + end11 + end12)
true
d365b1ce01214a62267e9a88a52fd4ee190e5525
robgan/Ciphers
/caesar.py
992
4.375
4
alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25} def caesar(): #message that is going to be encrypted plaintext = input("Provide the message you would like to encrypt") #how much the message will be shifted by a = int(input("How much would you like to shift the message by?")) #checks if the value is more than 26 while a > 26: a = int(input("Please provide a value between 0 and 26")) ciphertext = "" #encryption of the plaintext for char in plaintext: char = char.lower() if char == " ": ciphertext = ciphertext + " " else: newValue = alphabet[char] + a for letter,value in alphabet.items(): if value == newValue: ciphertext = ciphertext + str(letter) return ciphertext print(caesar())
true
15a33dd8388cdb23a0e0768b394a12d6f9206bae
AdirthaBorgohain/python_practice
/Drawing/draw.py
755
4.125
4
import turtle def draw_square(): baby = turtle.Turtle() #grabs the turtle and names it chutiya baby.color("green") baby.shape("turtle") baby.speed(2) for i in range(0,4): baby.forward(100) baby.right(90) def draw_circle(): jhon = turtle.Turtle() jhon.shape("arrow") jhon.color("black") jhon.speed(2) jhon.circle(100) def draw_triangle(): tangy = turtle.Turtle() tangy.shape("turtle") tangy.color("yellow") tangy.left(180) for i in range(0,3): tangy.forward(50) tangy.right(120) window = turtle.Screen() window.bgcolor("red") #drawing square draw_square() #drawing circle draw_circle() #drawing rectangle draw_triangle() window.exitonclick()
false
ffd75ca34c884132ddea7f8536ad2f3c280d705e
JohnADeady/PROGRAMMING-SCRIPTING
/Dice.py
1,017
4.5
4
#John Deady, 2018-23-02 #Dice Rolling Simulator # Adapted from https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/ # The Goal: this program involves writing a program that simulates a rolling dice. # When the program runs, it will randomly choose a number between 1 and 6. # It should then ask you if you’d like to roll again. # For this project, you’ll need to set the min and max number that your dice can produce i.e minimum of 1 and a maximum of 6. # You’ll also want a function that randomly grabs a number within that range and prints it. # The references I used to solve this problem were from Stackflow and Codecademy. from random import randint # Randint is a function that is part of the random module. print(randint(1,6),"Would you like to roll again") # Randint will pull a random number between 1 and 6. # It will then ask, would you like to roll again.
true
1a7116b2effe44c4edfbded20adefa9a1b640a01
topefremov/mit6001x
/oddTuples.py
376
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 8 08:55:56 2018 @author: efrem """ def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' result = () tupleLength = len(aTup) i = 0 while (i < tupleLength): result = result + (aTup[i],) i += 2 return result
true
9821fcd9ed69fc7b195f0586e83b557a840fe353
topefremov/mit6001x
/psets/ps1/p3.py
985
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 3 14:09:14 2021 Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print: Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print; Longest substring in alphabetical order is: abc @author: aefremov """ #s = "azcbobobegghakl" #s = "qbrgsldsh" s = 'abcdefghijklmnopqrstuvwxyz' longest_substr = "" cur_substr = "" for c in s: if len(cur_substr) == 0 or cur_substr[-1] <= c: cur_substr += c else: if len(cur_substr) > len(longest_substr): longest_substr = cur_substr cur_substr = c if len(cur_substr) > len(longest_substr): longest_substr = cur_substr print("Longest substring in alphabetical order is: " + longest_substr)
true
0bda046862f59efa69e0436da5461bae8712100f
ry-blank/Module-8
/assign_average.py
523
4.46875
4
""" Program: selection_using_dictionary_assignment Author: Ryan Blankenship Last date modified: 10/14/2019 The purpose of this program is to use a dictionary to mimic a switch statement to return the value of a key. """ def switch_average(key): """ function to use dict to mimic switch :param key: key of value to be found :return: value of key or KeyError message """ return { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5 }.get(key, KeyError)
true
3d538be12ed11eca5b813157f68b9726caa21d91
JenVest2020/CSPT17repls
/mod1Obj2.py
464
4.3125
4
""" Use the print function, the variables below, and your own literal argument values to print the following output to the screen (your printed output should have the same format as below): 1 ~ two ~ 3 ~ Lambda ~ School ~ 4 ~ 5 ~ 6 ---> *Note*: you will need to change the default values for the `sep` and `end` keyword arguments. """ one = 1 two = "two" school = "Lambda" five = 5 print(one, two, 3, school, "School", 4, five, 6, sep=" ~" + " \n", end=" --->")
true
c84dff9f1eb441fa427605385e28ccd176b193f1
Lhotse867745418/Python3_Hardway
/ex3.py
958
4.28125
4
#------------------------------------------------------------------------------- # Name: numbers and math # Purpose: learn math # # Author: lhotse # # Created: 17/03/2018 # Copyright: (c) lhotse 2018 # Licence: #------------------------------------------------------------------------------- print("i will now count my chickens") print("hens", 25 + 30/6) # difference between floating and integer #print("roosters", 100 - 25*3%4) print("roosters", 100 - 25*3.0%4) print("now i will count the eggs:") print(3 + 2 + 1 - 5 + 4%2 - 1/4 + 6) print("is it true that 3 + 2 < 5 - 7 ?") print(3 + 2 < 5 - 7) print("what is 3 + 2?", 3 + 2) print("what is 5 - 7?", 5 - 7) print("oh!,that's why it's false.") print("how about some more.") print("is it greater or equal?", 5 >= -2) print("is it less or equal?", 5 <= -2) def main(): pass if __name__ == '__main__': main()
true
00318b5bce676767d620c64f9ef08f799177e692
gathonicatherine/mkulima-
/test.py
1,885
4.375
4
# Given this list of students containing age and name, # students = [{"age": 19, "name": "Eunice"}, {"age": 21, "name": "Agnes"}, # {"age": 18, "name": "Teresa"}, {"age": 22, "name": "Asha"}], # write a function that greets each student and tells them the year they were born. # e.g Hello Eunice, you were born in the year 2002. class Person: person="details" def __init__(self,name,year): self.name=name self.year=year def greetings(self): return f"Hello {self.name} you were born in {self.year}" # Given list x = [100,110,120,130,140,150], use list comprehension # to create another list containing each number in the list multiplied by list_x=[100,110,120,130,140,150] for a in list_x: print(a*5) # Write a function named divisible_by_seven that; # using the range function and a for loop returns a list # containing all the numbers between 100 and 200 that are divisible by 7. class Divisible: def __init__(self,divisible_by_seven): self.divisible_by_seven=divisible_by_seven def numbers(self): for numbers in self.divisible_by_seven: range in ("100..200") print(range*7) # Create a Class Rectangle with the following Attributes and Methods # Attributes: The class has attributes width and length that represent the two sides of a rectangle # Methods: # Add a method named area which returns the area (A) of the rectangle using the formula A=width*length # Add a method named perimeter which returns the perimeter (P) of the rectangle using the formula P=2(length+width) class Rectangle: def __init__(self,width,length): self.width=width self.length=length def area(self): return f"A ={self.width}*{self.length}" def perimeter(self): return f"P=2{self.length}+{self.width}"
true
c06c242f1f429f55fb0078b4c21498dbff9f2c15
erick2014/hackerRankChallenges
/validateArraySubsequence.py
2,445
4.125
4
""" Given two non-empty arrays of integers, write a function that determines whether the second array is a subsequence of the first one. A subsequence of an array is a set of numbers that aren't necessarily adjacent in the array but that are in the same order as they appear in the array. For instance, the numbers [1, 3, 4] form a subsequence of the array [1, 2, 3, 4], and so do the numbers [2, 4]. Note that a single number in an array and the array itself are both valid subsequences of the array. """ def getTestCases(): return { 1: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [1, 6, -1, 10] }, 2: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [5, 1, 22, 25, 6, -1, 8, 10] }, 3: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [5, 1, 22, 6, -1, 8, 10] }, 4: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [22, 25, 6] }, 5: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [1, 6, 10] }, 6: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [5, 1, 22, 10] }, 7: { "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence":[5, -1, 8, 10] }, 8:{ "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [5, 1, 22, 25, 6, -1, 8, 10, 12] }, 9:{ "array": [5, 1, 22, 25, 6, -1, 8, 10], "sequence": [1, 6, -1, -2] } } def isValidSubsequence(array, sequence): validSequenceNumberCounter = 0 for number in array: if validSequenceNumberCounter < len(sequence): isNumberInSequence = sequence[validSequenceNumberCounter] if number == isNumberInSequence: if validSequenceNumberCounter < len(sequence): validSequenceNumberCounter+=1 if validSequenceNumberCounter == len(sequence): return True else: return False tests = getTestCases() for i in tests: testArray = tests[i]["array"] testSequence = tests[i]["sequence"] message = "array:{}, sequence: {}".format(testArray,testSequence) print(message) result = isValidSubsequence(testArray,testSequence) print("my output= {}".format(result)) print("")
true
ac5ce534e2ac23361f387a80d3a962df2657df56
RussellSB/mathematical-algorithms
/task3.py
2,714
4.1875
4
#Name: Russell Sammut-Bonnici #ID: 0426299(M) #Task: 3 import time #used for execution time comparison #checks if number is prime def isPrime(n): ''' The range for the loop is set from 2 to n, as we are concerned with finding factors that aren't 1 and n itself. If no factors that aren't 1 and n are found then by definition it is a prime number. ''' #if 2 then prime number if(n==2): return True else: #if n is not 2 then test if n has a factor between 2-n for x in range(2,n): r = n%x #calculating remainder for current test if(r==0): #if a factor is found, n is not prime return False # if a factor isn't found in the loop, n is prime return True #finds all prime numbers less than or equal to n using isPrime() def findPrimes1(n): start_time=time.time() #gets time at start primes = [] #initialized to later store prime numbers #for loop from range 2-n (including n) for x in range(2,n+1): # appends prime numbers to list "primes" when isPrime(x) is True if(isPrime(x)==True): primes.append(x) end_time = time.time() #gets time at end print("Total time: %0.5fs"%(end_time-start_time)) #prints executuion time return primes #finds all prime numbers less than or equal to n using Sieve of Eratosthenes Algorithm def findPrimes2(n): start_time = time.time() #gets time at start primes = [] #initializes list of prime numbers as empty #initializes Boolean list from 2-n (including n) sieve = [True for _ in range(n+1)] #starts by setting 0 and 1 to False as they are not prime numbers sieve[0:1] = [False, False] #for loop from 2-n for p in range(2, n + 1): #if True, access nested loop if sieve[p]: #set multiples of p to false, starting from 2*p and incrementing by p each iteration for i in range(2 * p, n + 1, p): sieve[i] = False #for loop from 2-n for i in range(2, n + 1): #if True, after the procedure above, then prime, so add to primes list if sieve[i]: primes.append(i) end_time = time.time() #gets time at end print("Total time: %0.5f" % (end_time - start_time)) #prints executuion time return primes n1=101 print("Is %d a prime number?: %s"%(n1,isPrime(n1))) print("------------------------------------") n2=10000 primes1 = findPrimes1(n2) print("List of prime numbers up to %d using isPrime() are: "%n2) print primes1 print("------------------------------------") primes2 = findPrimes2(n2) print("List of prime numbers up to %d using Sieve of Eratosthenes are: "%n2) print primes2
true
4f61092e6850fae2fbc1ebd8a360c5ba8a9b4eeb
jchinedu/alx-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
595
4.21875
4
#!/usr/bin/python3 # 0-add_integer.py # Brennan D Baraban <375@holbertonschool.com> """Defines an integer addition function.""" def add_integer(a, b=98): """Return the integer addition of a and b. Float arguments are typecasted to ints before addition is performed. Raises: TypeError: If either of a or b is a non-integer and non-float. """ if ((not isinstance(a, int) and not isinstance(a, float))): raise TypeError("a must be an integer") if ((not isinstance(b, int) and not isinstance(b, float))): raise TypeError("b must be an integer") return (int(a) + int(b))
true
be68c214ca60501c534739ce26b12c704c6659aa
jchinedu/alx-higher_level_programming
/0x01-python-if_else_loops_functions/6-print_comb3.py
452
4.28125
4
#!/usr/bin/python3 # 6-print_comb3.py # Brennan D Baraban <375@holbertonschool.com> """Print all possible different combinations of two digits in ascending order. The two digits must be different - 01 and 10 are considered identical. """ for digit1 in range(0, 10): for digit2 in range(digit1 + 1, 10): if digit1 == 8 and digit2 == 9: print("{}{}".format(digit1, digit2)) else: print("{}{}".format(digit1, digit2), end=", ")
true
229fd965d0e8b0185d3396ea2c6b6ab744b80f22
JGRobinson17/hello_world
/test_input.py
1,629
4.375
4
# Starting to write python #name=input('Enter Name') #print('hello', name) #password program def main_menu(): print('Enter "New" for New Account') print('Enter "Login" to access program') print('Enter "Exit" to exit program') user_login = {'Josh': 'jigger', 'Jenny':'asstastic'} user_name = None user= None password= None enter_pass= None menu_choice= None pasword1= None Paswor2= None ###New Account while menu_choice != 'Exit': menu_choice = input('Enter Command: ') if menu_choice == 'New': user= input('User Name: ') password1= input('Create a Password: ') password2= input('Retype Pasword:') if password1 == password2: password=password2 user_login[user]=password else: print("Password doesn't Match") ### LOGIN Script elif menu_choice == 'Login': user= input('User Name: ') if user in user_login: password= user_login[user] else: print('No User Login Found. Please Create an Account or Try Again') while enter_pass != password: enter_pass = input('Enter Password: ') print ('Good Morning', user) ### Delete Account elif menu_choice == 'Remove': user=input('User to be Removed: ') if user in user_login: del user_login[user] else: print('User not Found') # if password != 'jigger': # pcount= pcount-1 # if pcount < 1: # print ("You're not", user_name)
false
b6f811070299d8131da41bf0c4794b66b6ad7161
murphy-codes/challenges
/Python_edabit_Easy_ATM-PIN-Code-Validation.py
1,688
4.4375
4
''' Author: Tom Murphy Last Modified: 2019-10-18 22:00 ''' # https://edabit.com/challenge/K4Pqh67Y9gpixPfjo # ATM PIN Code Validation # ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. Your task is to create a function that takes a string and returns True if the PIN is valid and False if it's not. import re def is_valid_PIN(num): #x = re.search("^[0-9]+$", num) x = re.fullmatch("^[0-9]+$", num) if (len(num) == 4 or len(num) == 6) and x: return True else: return False print(is_valid_PIN("1234")) # ? True print(is_valid_PIN("12345")) # ? False print(is_valid_PIN("a234")) # ? False print(is_valid_PIN("")) # ? False def validate_PIN_entry(): # ask for and validate user input flag = 'a' while type(flag) is not int: try: user_input = int(input('Please enter a 4-digit or 6-digit PIN: ')) # prevent neg int inputs if user_input < 0: print('Negative numbers are not accepted') # prevent PINs that are less than 4-digits elif user_input >= 0 and user_input < 1000: print('PIN contains too few digits') # prevent 5-digits PINs elif user_input >= 10000 and user_input < 100000: print('5-digit PINs are not accepted') # prevent PINs that are greater than 6-digits elif user_input >= 1000000: print('PIN contains too many digits') else: flag = user_input except ValueError: # Handle the exception print('Only integers are accepted') print('PIN has been set to ' + str(user_input)) print() validate_PIN_entry()
true
e27d0e78e57057a06e4b5f998399a1375751feee
JZDBB/Python-ZeroToAll
/python_basis/list_learn.py
1,778
4.125
4
list_1 = [1, 2, 3, 4] print(list_1) list_2 = ['a', 'b', 'c'] print(list_2) list_3 = [1, 2.33, 'python', 'a'] print(list_3) list_4 = [1, 3.3, 'haha', list_3] print(list_4) list_5 = [] type(list_5) #索引 print(list_1[0]) print(list_3[2]) #连接 print(list_1 + list_2) #复制阵列 print(list_1 * 3) #列表长度 len(list_2) for i in list_1: print(i) #是否存在 print(2 in list_1) print(6 in list_1) #删除 del list_1 del list_2[2] #返回最大/小值 max(list_2) min(list_2) #索引 [起始:终止:间隔] list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(list_1[5:8]) print(list_1[1:6:2]) print(list_1[3:]) print(list_1[:5]) print(list_1[::2]) print(list_1[::-1])#逆序索引 #id操作?? id(list_1) id(list_1[:]) list_6 = list_1[:] id(list_6) #改变数据 list_1[2] = 'python' list_1[4:6] = ['a', 'b', 'c'] print(list_1) #增加对象 list_1.append('Alice') list_1.append(1) list_1.append('1') #次数统计 list_1.count(1) list_1.count('1') #追加 print(list_2) list_2.extend('a') print(list_2) list_2.extend(['b', [1, 2, 3]]) #索引位置找到第一个所在 list_3 = [1, 2, 3, 3, 5, 2, 7, 8] list_3.index(1) list_3.index(2) print(list_3) list_3.insert(2, 'a') print(list_3) list_3.pop() print(list_3) list_3.pop(2) print(list_3) #移走某一个匹配值 list_3.remove(2) #反向 print(list_3) list_3.reverse() print(list_3) print(list_3[::-1]) #排序 list_3 = [2, 4, 1, 3, 6, 8, 5, 9, 0] list_3.sort() print(list_3) list_7 = ['a', 'cc', '1', 'Python'] list_7.sort() print(list_7) list_7.sort(reverse = True) print(list_7) print([i**2 for i in range(1,10)]) print([i*j for j in range(1, i) for i in range(1,10) if j<=i]) print([m+n for m in 'ABC' for n in 'abc']) # 反转 list_8 = ['a', 'b', 'c', 'd', 'e'] print(list_8[::-1])
false
0a84867032b885b44c0da874bf70935473bff9d7
arunrajput17/PSTUD
/4_Strings.py
1,279
4.5625
5
## Strings can be stored in variables first_name = 'Christopher' last_name = 'Harrison' print(first_name+last_name) print('Hello '+ first_name +' '+ last_name) ## Use of functions to modify strings sentence = 'the dog is named Sammy' print(sentence.upper()) print(sentence.lower()) print(sentence.capitalize()) print(sentence.count('a')) ##The functions help us format strings we save to files and databases, or display to users first_name = input('What is your first name? ') last_name = input('What is your last name ') print ('Hello ' + first_name.capitalize() + ' '+ last_name.capitalize()) ## Custom string formatting output = 'Hello 1, ' + first_name + ' '+ last_name print(output) output = 'Hello 2, {} {}' .format(first_name,last_name) print(output) output = 'Hello 3, {0}, {1}'.format(first_name,last_name) print(output) # Only availble in Python 3 output= f'Hello format, {first_name} {last_name}' print(output) ####################################### #Access string vaue by index text='ice cream' print(text[5]) print(text[0:3]) print(text[4:9]) print(text[:3]) print(text[4:]) t1= 'Earth revolves around the sun' print(t1[6:14]) print(t1[-3:]) # Save multiline in string address='''add line1 add line2''' print(address) print(address.encode())
true
4b8745c9de1353a4d8eb535565ec650408de3bc1
arunrajput17/PSTUD
/10-1_Functions_Parametrization.py
1,421
4.28125
4
## Functions can accept multiple parameters def get_initial(name, force_uppercase): if force_uppercase: initial = name[0:1].upper() else: initial = name[0:1] return initial first_name = input('Enter your first name: ') first_name_initial = get_initial(first_name, False) print('Your initial is : ' + first_name_initial) ################################################### ## You can specify default value for a parameter ## like def get_initial(name, force_uppercase=True): ## call as get_initial(first_name) ################################################### ##You can also assign the values to parameters by name when you call the function ## i.e. get_initial(force_uppercase=True, name = first_name) ################################################### ## Using the named notation when calling the functions makes your code more readable def error_logger(error_code, error_severity, log_to_db, error_message, source_module): print('Oh no error: ' + error_message) #Imagine code here that logs our error to a database or file first_number = 10 second_number = 5 if first_number > second_number: error_logger(45,1,True,'Second number greater than first', 'my_math_method') ### if first_number > second_number: error_logger(error_code=45,error_severity = 1,log_to_db=True, error_message='Second number greater than first', source_module='my_math_method')
true
43f64ac2af0fc45f3ca5f59e2784646d48cbaaa5
arunrajput17/PSTUD
/23_ListSetDict_Comprehension.py
931
4.5625
5
## List / set / dict Comprehension : It provides a way to transform one list into another # General way to find the even numbers from list is numbers=[1,2,3,4,5,6,7,8,9] even=[] for i in numbers: if i%2 ==0: even.append(i) print(even) ## Comprehension even = [i for i in numbers if i%2==0] print(even) sqr_numbers =[i*i for i in numbers] print (sqr_numbers) ## Set : set is an unordered collection of unique items. # Set Comprehension s=set([1,2,3,4,5,2,3]) print(s) even ={ i for i in s if i%2==0} print(even) ## Dict comprehension cities =['mumbai','new york','paris'] countries =['india','usa','france'] #-- to create a dict where key is name of city and value is country name # zip is builtin function in python, it will zip two lists together z = zip(cities,countries) print(z) for a in z: print(a) # Comprehension d ={city:countries for city, countries in zip(cities,countries)} print(d)
true
680a2b53d3c7539db114823758567c6e7a22ff48
SoumyaSwaraj/DSA
/FileRecursion/program_2.py
982
4.4375
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ mylist = [] dirs = os.listdir(path) # This would print all the files and directories for filex in dirs: f = os.path.join(path, filex) isdir = os.path.isdir(f) if isdir: new_path = os.path.join(path, filex) newlist = find_files(".c", new_path) mylist.extend(newlist) isfile = os.path.isfile(f) if isfile and filex.endswith(".c"): mylist.append(f) return mylist find_files(".c", "C:\\Users\\user\\Desktop\\testdir")
true
3de2b9372bff4b2eb7da0564f846333dafa3c5a2
prasadmodi-pm/Python_Assign
/JulyTraining/ListInsert.py
273
4.15625
4
__author__ = 'prasadmodi' list = [] num = int(input("Number of elements in list: ")) # Total Number of elements list accepts for i in range(num): nums = input("enter elements to be added to list: ") # Elements taken from user list.append(nums) print(list)
true
49ad4a8627275d3f27f619c0f44bdf3e8b12830d
aurelo/lphw
/source/ex11.py
689
4.375
4
# comma will force the user input inline with question, and will prevent print to end with new line chr ''' print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weight?", weight = raw_input() ''' # raw_input([prompt]) => If the prompt argument is present, it is written to standard output without a trailing newline age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weight? ") print "So you're %r old, %r tall and %r heavy" % (age, height, weight) # int will try to convert to integer print "So you're %s old, %s tall and %s heavy" % (int(age), height, weight)
true
631e2ba5480490d9e8d04f13adf05b08506ba966
q-riku/Python3-basic2
/01 函数式编程-匿名函数和高阶函数/test4.py
459
4.25
4
""" map接受一个函数和一个迭代器作为参数,并返回一个新的迭代器,该函数应用于每个参数; 语法:列表名 = map(一个函数,一个可迭代序列) """ def add_five(x): return x + 5 nums = [11, 22, 33, 44, 55] #对列表中的每个值都加5 result = list(map(add_five, nums)) print(result) #用lambda表达式也可以达到效果; nums = [11, 22, 33, 44, 55] result = list(map(lambda x: x+5, nums)) print(result)
false
3688c587241abfa8abb14457d41cc4bfd1cee5d9
dunton-zz/coderbyte
/DistinctList.py
584
4.21875
4
# Have the function DistinctList(arr) take the array of numbers # stored in arr and determine the total number of duplicate entries. # For example if the input is [1, 2, 2, 2, 3] then your program # should output 2 because there are two duplicates of one of the elements. def DistinctList(arr): # code goes here # Note: don't forget to properly indent in Python numbers = sorted(arr) dupes = 0 for i in range(len(numbers)): if numbers[i] == numbers[i-1]: dupes += 1 return dupes # keep this function call here print DistinctList(raw_input())
true
01a6bd4eaab38f5715d5a84906741fe3ce233dfc
adreg0/automate-the-boring-stuff-with-python
/Chapter-07/passdetection.py
698
4.125
4
import re def strongPassword(password): passlen = re.compile(r'(.{8,})') passnum = re.compile(r'[0-9]+') passlower = re.compile(r'[a-z]') passupper = re.compile(r'[A-Z]') if passlen.search(password)==None: print('Password must be atleast 8 characters long') elif passnum.search(password)==None: print('Password must contain atleast one number') elif passlower.search(password)==None: print('Password must contain atleast one lower case letter') elif passupper.search(password)==None: print('Password must contain atleast one upper case later') else: print('Strong password') password=input() strongPassword(password)
false
ccacaad967091b63213d29438c24fcdfc6f8d8fa
sharonLuo/LeetCode_py
/valid-palindrome.py
2,465
4.125
4
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ i, j = 0, len(s)-1 while i < j: while i < j and not (s[i].isalpha() or s[i].isdigit()): i += 1 while j > i and not (s[j].isalpha() or s[j].isdigit()): j -= 1 if s[i].lower() != s[j].lower(): return False i, j = i+1, j-1 return True """ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s_lower = s.lower() base_a = ord("a") rst = True if len(s_lower): begin = 0 end = len(s_lower)-1 while begin < end: while begin < end and not self.isNumberLetter(s_lower[begin]): begin += 1 while end > begin and not self.isNumberLetter(s_lower[end]): end -= 1 if s_lower[begin] != s_lower[end]: return False begin += 1 end -= 1 return rst def isNumberLetter(self,element): rst = False if ord(element)-ord("a") >= 0 and ord(element)-ord("z") <= 0: rst = True if ord(element)-ord("0") >= 0 and ord(element)-ord("9") <= 0: rst = True return rst """ You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
true
cf90fab781c1c6a79bac24d75e854439f010edd6
sharonLuo/LeetCode_py
/reverse-integer.py
1,416
4.375
4
""" Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: # @return an integer def reverse(self, x): if x<0: sign = -1 else: sign = 1 strx=str(abs(x)) r = strx[::-1] rst = sign*int(r) if rst < -2**31 or rst >= 2**31: return 0 return rst class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ new_x = 0 if x >= 0: sign = 1 else: sign = -1 x = -x while x != 0: new_x = new_x * 10 + x % 10 x = x / 10 if sign*new_x >= 2147483647 or sign*new_x < -2147483648: return 0 else: return sign*new_x
true
1b9f2258b688de5c8293a4d3eddb3cd4f8eebc45
sharonLuo/LeetCode_py
/palindrome-number.py
1,611
4.15625
4
""" Determine whether an integer is a palindrome. Do this without extra space. Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem. """ ###### 为了避免倒置可能出现的溢出现象, 最好是不断取第一位和最后一位(10进制下)进行比较, 相等则取第二位和倒数第二位, ###### 直到完成比较, 或者中途找到不一致的位为止 import math class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False divider = 1 while x/divider >= 10: divider *= 10 while x > 0: p = x/divider q = x%10 if p != q: return False x = x%divider/10 # 或者 x = (x- (q + p*divider))/10 divider /= 100 return True ### beat 90%, but use extra space class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ x = str(x) head = 0 tail = len(x)-1 while head < tail: if x[head] != x[tail]: return False head += 1 tail -= 1 return True
true
2cf6eb9a2d88f00823b912d762b3694e25013767
Rushaniia/Python.Basic-course
/Lesson_7/Les_7_task_1.py
909
4.3125
4
''' 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована в виде функции. По возможности доработайте алгоритм (сделайте его умнее).''' import random a = [random.randint(-100, 100) for i in range(10)] print(f'Исходный список :\n{a}') def bubble_sort(a): n = 1 while n < len(a): for i in range(len(a) - n): if a[i] > a[i + 1]: a[i], a[i + 1] = [a[i + 1], a[i]] n += 1 print(f'Новый список:\n {a}') bubble_sort(a)
false
2db201616dcb7a2eb53fb3e67ee3040763bd3de4
rossoskull/python-beginner
/sumofn.py
257
4.1875
4
def summation_by_formula(n): return (n * (n+1)) // 2 if __name__ == "__main__": num = int(input("Enter the number until which you want to find the sum : ")) print("The sum of first %d numbers is %d." % (num, summation_by_formula(num)))
true
831e6f60382305fc67edd13f091e8be295e57a50
DQTRUC/DeepLearningCV
/Ex01_PyCharm.py
271
4.125
4
# Write a Python program to add the digits of a positive integer repeatedly until the result has a single digit A = input("Enter any number:") while len(A) > 1: S = 0 for i in range(len(A)): S = S + int(A[i]) A = str(S) print("Result:",S)
true
46ca4d5ac950f85f1621915d3e1aba2a979e4770
pavankumarag/ds_algo_problem_solving_python
/ADT/linked_list_all.py
1,874
4.1875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def reverse(self): prev = None cur = self.head while cur is not None: next = cur.next cur.next = prev prev = cur cur = next self.head = prev def reverse_util(self, cur, prev): if cur.next is None: self.head = cur cur.next = prev return next = cur.next cur.next = prev self.reverse_util(next, cur) def reverse_recursive_from_iterative(self): # converting iterative to recursive if self.head is None: return self.reverse_util(self.head, None) def reverse_recursive(self, p): if p.next is None: self.head = p return self.reverse_recursive(p.next) q = p.next q.next = p p.next = None # insert new node at the beginning def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def print_list(self): temp = self.head while (temp): print temp.data, temp = temp.next def print_recursive(self, node): if node is None: print return print node.data, self.print_recursive(node.next) def print_end_recursive(self, node): if node is None: print return self.print_end_recursive(node.next) print node.data, if __name__ == "__main__": l = LinkedList() l.push(10) l.push(12) l.push(2) l.push(3) l.push(5) l.print_list() l.reverse() print "\nReversing the linked list\n" l.print_list() print "\nReversing the linked list using recursion built from iterative method\n" l.reverse_recursive_from_iterative() l.print_list() print "\nReversing the linked list using direct recursion\n" l.reverse_recursive(l.head) l.print_list() print "\nPrinting from Beginning using recursion\n" l.print_recursive(l.head) print "\nPrinting from the end using recursion" l.print_end_recursive(l.head)
true
75d13c3ce016a33223138479c0f487bd0d973a96
pavankumarag/ds_algo_problem_solving_python
/practice/medium/_32_powerset.py
2,698
4.15625
4
""" Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}. If S has n elements in it then P(s) will have 2^n elements https://rosettacode.org/wiki/Power_set#Python https://www.geeksforgeeks.org/power-set/ """ import math class Solutions: def __init__(self, inp_str): self.inp_str = inp_str self.out = "" self.res = set() def powerset(self, start): ''' This is also combinationsOfString :param start: :return: ''' for i in range(start, len(self.inp_str)): self.out = self.out + self.inp_str[i] self.res.add(self.out) if i < len(self.inp_str): self.powerset(i+1) self.out = self.out[0:len(self.out)-1] self.res.add('') return self.res def powerset_binary(self, set_size): """ Set = [a,b,c] power_set_size = pow(2, 3) = 8 Run for binary counter = 000 to 111 Value of Counter Subset 000 -> Empty set 001 -> a 010 -> b 011 -> ab 100 -> c 101 -> ac 110 -> bc 111 -> abc :param set_size: :return: """ pw_set_size = int(math.pow(2, set_size)) for counter in range(0, pw_set_size): for j in range(0,set_size): if counter & (1 << j) > 0: # Check if jth bit in the counter is set If set then print jth element from set print self.inp_str[j], print def list_powerset(self, lst): # the power set of the empty set has one element, the empty set result = [[]] for x in lst: # for every additional element in our set # the power set consists of the subsets that don't # contain this element (just take the previous power set) # plus the subsets that do contain the element (use list # comprehension to add [x] onto everything in the # previous power set) result.extend([subset + [x] for subset in result]) return result # the above function in one statement def list_powerset2(self, lst): return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]]) def powerset_frozenset(self, s): return frozenset(map(frozenset, self.list_powerset(list(s)))) def powerset_recursive(self, l): if not l: return [[]] return self.powerset_recursive(l[1:]) + [[l[0]] + x for x in self.powerset_recursive(l[1:])] if __name__ == "__main__": s = Solutions("abc") print s.powerset(0) s.powerset_binary(len(s.inp_str)) print s.list_powerset([1,2,3]) print s.list_powerset2([1,2,3]) print s.powerset_frozenset(frozenset([1,2,3])) print s.powerset_recursive([1,2,3])
true
a0fd0a169bf028c408878baba7bb56eefe2c5b45
pavankumarag/ds_algo_problem_solving_python
/practice/hard/_42_minimum_points.py
2,227
4.15625
4
""" Minimum Initial Points to Reach Destination Given a grid with each cell consisting of positive, negative or no points i.e, zero points. We can move across a cell only if we have positive points ( > 0 ). Whenever we pass through a cell, points in that cell are added to our overall points. We need to find minimum initial points to reach cell (m-1, n-1) from (0, 0). Constraints : From a cell (i, j) we can move to (i+1, j) or (i, j+1). We cannot move from (i, j) if your overall points at (i, j) is <= 0. We have to reach at (n-1, m-1) with minimum positive points i.e., > 0. Example Input: points[m][n] = { {-2, -3, 3}, {-5, -10, 1}, {10, 30, -5} }; Output: 7 Explanation: 7 is the minimum value to reach destination with positive throughout the path. Below is the path. (0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2) We start from (0, 0) with 7, we reach(0, 1) with 5, (0, 2) with 2, (1, 2) with 5, (2, 2) with and finally we have 1 point (we needed greater than 0 points at the end). reference: https://www.geeksforgeeks.org/minimum-positive-points-to-reach-destination/ """ import math as mt def min_initial_points(points, m, n): ''' dp[i][j] represents the minimum initial points player should have so that when starts with cell(i, j) successfully reaches the destination cell(m-1, n-1) ''' dp = [[0 for x in range(n + 1)] for y in range(m + 1)] if points[m - 1][n - 1] > 0: dp[m - 1][n - 1] = 1 else: dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1 ''' Fill last row and last column as base to fill entire table ''' for i in range(m - 2, -1, -1): dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1) for i in range(2, -1, -1): dp[m - 1][i] = max(dp[m - 1][i + 1] - points[m - 1][i], 1) ''' fill the table in bottom-up fashion ''' for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1]) dp[i][j] = max(min_points_on_exit - points[i][j], 1) return dp[0][0] if __name__ == "__main__": points = [[-2, -3, 3], [-5, -10, 1], [10, 30, -5]] print("Minimum Initial Points Required:",min_initial_points(points, 3, 3))
true
d9851b96c4e8d23807887b3adddc09a44349cff9
pavankumarag/ds_algo_problem_solving_python
/practice/medium/_37_group_anagrams.py
974
4.40625
4
""" Group Anagrams from given list Anagrams are the words that are formed by similar elements but the orders in which these characters occur differ Example: The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum'] The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']] """ def group_anagrams(lst): occurrence = dict() for string in lst: sorted_str = "".join(sorted(string)) if sorted_str in occurrence.keys(): occurrence[sorted_str].append(string) else: occurrence[sorted_str] = list() occurrence[sorted_str].append(string) return occurrence.values() def group_anagrams_2(lst): from itertools import groupby temp = lambda test_list : sorted(test_list) result = [] for key, val in groupby(sorted(lst, key=temp), temp): result.append(list(val)) return result if __name__ == "__main__": print group_anagrams(['lump', 'eat', 'me', 'tea', 'em', 'plum']) print group_anagrams_2(['lump', 'eat', 'me', 'tea', 'em', 'plum'])
true
4c8c08e10ad29fa24864e3cba12f07d5bb3a13a5
kindlyhickory/python_algorithms
/les_1/les_1_task_5.py
1,194
4.3125
4
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, # составленного из этих отрезков. Если такой треугольник существует, то определить, # является ли он разносторонним, равнобедренным или равносторонним. print('Введите длины отрезков') a = float(input('Первая длина отрезка: ')) b = float(input('Вторая длина отрезка: ')) c = float(input('Третья длина отрезка: ')) if a + b > c and a + c > b and c + b > a: print('Треугольник существует') if a == b and a == c: print('Треугольник равносторонний') elif (a == b and a != c) or (a == c and a != b) or (c == b and c != a): print('Треугольник равнобедренный') else: print('Треугольник разносторонний') else: print('Треугольника не существует')
false
d6ad86b51e3ef3aad2f37d8e75130c7e090d383c
skilldisk/Python_Basics_Covid19
/list/append_func.py
210
4.375
4
even = [0, 2, 4, 6] print("###### Before Appending #########") print(even) # append will add data to the end of the list even.append(8) print("###### After Appending 8 to the list even #########") print(even)
true
097e4b3e913afb3725b3a9c653ac05ad9377a85c
felipeadner/python-brasil-exercicios
/estrutura-sequencial/05centimetros.py
234
4.21875
4
""" Faça um Programa que converta metros para centímetros. """ def main(): meters = float(input("Digite a metragem: ")) centimeter = float(meters*100) print(meters,"m corresponde a" ,centimeter,"cm") main()
false
ca34b80e8aeb9ef1cffa096020cbc5471f5054d9
felipeadner/python-brasil-exercicios
/estrutura-de-decisao/05aluno.py
918
4.21875
4
""" Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; A mensagem "Reprovado", se a média for menor do que sete; A mensagem "Aprovado com Distinção", se a média for igual a dez. """ def main(): parcial1 = float(input("Informe a Parcial 01: ")) parcial2 = float(input("Informe a Parcial 02: ")) nota = float((parcial1 + parcial2) / 2) if nota == 10.0: print("Parabéns, sua nota é %f. Você foi aprovado com distinção." %nota) elif nota >= 7.0: print("Parabéns, sua nota é %f. Você foi aprovado." %nota) elif nota < 7.0: print("Que pena, sua nota é %f. Você foi reprovado" %nota) else: print("Não foi possível calcular sua nota") main()
false
807be92c31db9b6f6ad427831c60402ffae667c1
felipeadner/python-brasil-exercicios
/estrutura-de-decisao/09decrescente.py
1,012
4.21875
4
""" Faça um Programa que leia três números e mostre-os em ordem decrescente. """ def decrescente(): a = float(input("Informe o 1º número: ")) b = float(input("Informe o 2º número: ")) c = float(input("Informe o 3º número: ")) if a > b and b > c: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(a, b, c)) elif a > c and c > b: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(a, c, b)) elif c > a and a > b: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(c, a, b)) elif c > b and b > a: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(c, b, a)) elif b > a and a > c: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(b, a, c)) elif b > c and c > a: print("Seus números em ordem decrescente: %2.f, %2.f, %2.f " %(b, c, a)) else: print("Informe apenas números distintos") decrescente()
false
f4b85f8857a986d7296d14b644ae3b9bebd9e4d9
ameru/cs-fundamentals-101
/labs/lab5.py
1,985
4.4375
4
def is_lower(char) -> bool: """ Determines if given character is lowercase. Arguments: char (bool): character that is either lowercase or uppercase Returns: boolean: True if lowercase, False if other """ if char >= 'a' and char <= 'z': return True else: return False def char_rot_13(char) -> str: """ Returns a caesar-cypher encryption ROT-13 of a given character. Arguments: char (str): character that will be replaced with ROT-13 character. Returns: str: Character of the alphabet 13 places forward or backward of given character """ if char.islower(): return chr((((ord(char) - 97) + 13) % 26) + 97) elif char.isupper(): return chr((((ord(char) - 65) + 13) % 26) + 65) else: return char # this only works on characters of the alphabet # lowercase -> lowercase, uppercase -> uppercase # others remain unchanged # may use functions: str.isalpha(), str.islower(), str.isupper() def str_rot_13(my_str) -> str: """ Returns a caesar-cypher encryption ROT-13 of a given string. Arguments: my_str (str): string that will be replaced with ROT-13 string. Returns: str: String of the alphabet 13 places forward or backward of given string """ word = '' for i in range(len(my_str)): word += char_rot_13(my_str[i]) return word def str_translate(my_str, old, new) -> str: """ Replaces each "old" character in "my_str" with a "new" character. Arguments: my_str (str): given string old (str): a character that will be replaced in my_str new (str): a character that will replace another one in my_str Returns: str: new string with every "old" character replaced with "new" """ word = '' for i in range(len(my_str)): if my_str[i] != old: word += my_str[i] else: word += new return word
true
c4b6568ee5aa7f320e47295b7ce8e4a6b2d5544e
UChicagoInterviewPrep/algos
/matrix/rotate_matrix.py
1,153
4.28125
4
def rotate_matrix(matrix): # assuming square matrix n = len(matrix) ''' 1 2 3 7 4 1 4 5 6 => 8 5 2 7 8 9 9 6 3 ''' # transposing matrix across diagonal line for i in range(n): for j in range(i+1, n): tmp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = tmp # swapping columns of matrix for i in range(n/2): for j in range(n): tmp = matrix[j][i] matrix[j][i] = matrix[j][n - i - 1] matrix[j][n - i - 1] = tmp def simpler_rotate(matrix): # generating new matrix n = len(matrix) new_matrix = [[0 for l in range(n)] for k in range(n)] for i in range(n): for j in range(n): new_matrix[j][n-1-i] = matrix[i][j] return new_matrix def print_matrix(matrix): for row in matrix: print row def main(): matrix = [[1,2,3], [4,5,6], [7,8,9]] print 'initial matrix' print_matrix(matrix) rotate_matrix(matrix) print 'final matrix' print_matrix(matrix) if __name__ == '__main__': main()
false
b0c7264f12b3d6afc931232a0cbbf0fe834fcb05
nachande/PythonPrograms
/Max_NumberUsingFunction.py
295
4.21875
4
def largest_number(list): max=list[0] for number in list: if number>max: max=number return max numbers=[13,5,7,8,2,10,14,5,7,4] print("Actual List:" ,numbers) max_number=largest_number(numbers) print ("Largest Number in list is:", max_number)
true
c2b20d07828890dacab6cd2e332c61074c1be23c
joeyviolacode/advent-of-code-2020
/dec_3/dec3.py
718
4.15625
4
from dec3_input import hill, width, height slope_0 = {"x": 1, "y": 1} slope_1 = {"x": 3, "y": 1} slope_2 = {"x": 5, "y": 1} slope_3 = {"x": 7, "y": 1} slope_4 = {"x": 1, "y": 2} slope_list = [slope_0, slope_1, slope_2, slope_3, slope_4] def find_slope(hill_map, slope): x = 0 y = 0 tree_count = 0 while y < height: if hill_map[y][x] == "#": tree_count += 1 x = (x + slope["x"]) % width y += slope["y"] return tree_count def find_many_slopes(hill_map, slopes): total_slopes = 1 for slope in slopes: total_slopes *= find_slope(hill_map, slope) return total_slopes print(find_slope(hill, slope_1)) print(find_many_slopes(hill, slope_list))
false
01a336f2c934ecba449af75a5fbba1890b3f3fca
kildarev7507/CTI110
/P4HW3_SumNumbers_VeronicaKildare.py
697
4.34375
4
# Program will add the sum of positive numbers entered by user. # 7/9/19 # CTI-110 P4HW3 - Sum of Numbers # Veronica Kildare # # Program will ask the user to enter positive numbers. # Program will calculate positive numbers until user enter a negative number. # Program will display the total of all numbers entered. def main(): total = 0 print('Please enter a positive number to calculate.') print('The program will conclude when a negative number is entered.') number = int(input('Enter positive number: ')) while number >= 0: total += number print('The total is', total) number = int(input('Enter positive number: ')) main()
true
55aaad972d7586a688d70f104acf64719caa9dfd
okoth-lydia/modcom
/lesson6/lesson7.py
1,005
4.34375
4
#inheritance #one object can borrow properties/functions from another object class Fish(): def __init__(self, name, weight, age): self.name = name self.weight = weight self.age = age def swim(self): print("a fish can swim") def swim_backwards(self): print("it's moving backwards") def jump(self): print("look it just jumped") # Trout inherits from Fish # fish is a parent class - class Trout(Fish): # IS A - Relationship def singing(self): print("a trout can sing") class Shark(Fish): def eat(self): print("Sharks eat anything literally") #inherits from Trout/ Fish class Omena(Trout): def small_size(self): print("it's very small") # method overriding def swim(self): print("shhhhhhhhhh") # create a class BrownFish that extends Omena class class BrownFish(Omena): def guggle(self): print("I can guggle") object = Omena("BrownFish", 56, 8) object.swim()
true
d6f55c7a795a4839fddbb2d9d8ad9e5914ba10e9
afausti/query_builder
/model/tree.py
1,117
4.28125
4
""" It has the data_structure Node and methods to facilitate the creation of trees. """ class Node(object): """ It represents the basic data structure of a tree. """ def __init__(self, data=None, level=0): self.data = data self.level = level self.sub_nodes = [] def __repr__(self): return '\n{indent}Node({name},{sub_nodes})'.format( indent=self.level*'\t', name=self.data['name'], sub_nodes=repr(self.sub_nodes)) def add_child(self, node): self.sub_nodes.append(node) def traverse_post_order(node): """ Given a node, it returns the nodes in post order sequence. """ for sub_nodes in node.sub_nodes: traverse_post_order(sub_nodes) return node def tree_builder(obj, level=0): """ Creates a tree using a dict -obj- as input. """ node = Node(data=obj, level=level) for child in obj.get('sub_op', []): node.add_child(tree_builder(child, level=level+1)) return node
true
f75d0dd9324cfdfe80d9cb09862655debd799fed
go-bears/python-study-group-puzzles
/brick_wall_sample.py
2,854
4.875
5
""" Brick Wall exercise: Functions are used to isolate different small specific tasks. Functions abstract action, grouping several actions as a single object, and then you group those actions to create more bigger and more advanced objects. to Goal: I've given you "starter functions" of that create different size bricks. use the individual brick functions to create rows of bricks to build a "strong" wall. You have to design your "row" functions so that the seams do not meet. (there's a sample below) Finally, create a small_wall() function that automatically builds the brick wall so it matches the sample output below. Note the seams of the bricks should not line up to make the strongest wall print small_wall() is the trigger to build the entire wall, all the functions return outputs until the last function call. Take it further: make a medium_wall() function and a large_wall() function, making sure to use all the brick sizes. learning goals: abstraction, chaining functions, return vs. print statements, calling functions, passing values through function parameters and arguments, calling elements from a list, global & local scope """ import time from itertools import permutations, combinations import random bricks = [ "[]", "[__]", "[____]", "[______]" ] def row1(brick3, mortar): mortar = bricks[0] #sample code, you should replace it brick3 = bricks[2] #sample code, you can replace it row1 = (mortar + brick3 + mortar) #sample code, you can replace it return row1 def row2(brick2,brick1): brick2 = bricks[2] brick1 = bricks[1] row2 = brick2 + brick1 return row2 def row3(brick1,mortar): #do something brick1 = bricks[1] mortar = bricks[0] row3 = (brick1 * 2) + mortar return row3 def row4(brick3,mortar): #do something brick3 = bricks[3] mortar = bricks[0] row4 = mortar + brick3 return row4 def row5(brick3, mortar): #do something brick3 = bricks[3] mortar = bricks[0] row5 = brick3 + mortar return row5 def small_wall(): print row1(bricks[3], bricks[0]) time.sleep(1) print row2(bricks[2], bricks[1]) time.sleep(1) #call row function with relevant argument(s) print row3(bricks[1],bricks[0]) time.sleep(1) #call row function with relevant argument(s) print row4(bricks[3],bricks[0]) time.sleep(1) #call row function with relevant argument(s) print row5(bricks[3], bricks[0]) small_wall() #automate brick wall with for loop & shuffle def big_wall(bricks): for item in range(6): random.shuffle(bricks) print "".join(bricks) big_wall(bricks) """ sample output of a wall. Note how the seams between the bricks meet at in the middle of another brick. [__][__][] [][__][__] [__][__][] [][__][__] [__][__][] """
true
d28c2e044c4c0d4d6f7dec57f8f74c97c6c22ee5
ZachMillsap/VS
/input_while_exit/input_while_exit/input_while_exit.py
604
4.125
4
'''Takes user inputs, check the sentinel, and addes them to a list. Then prints list''' '''Also give a breakout in the inner while loop''' n = int(input('Enter a number between 1 and 100 or -99 to stop.')) list= [] exit = -99 min = 1 max = 100 while n != exit: list.append(n) while n < min or n > max: n = int(input('Enter a number between 1 and 100 or -99 to stop.')) if n == -99: break print(n) n = int(input('Enter a number between 1 and 100 or -99 to stop.')) for nums in list: print(nums) print('Good bye') # input expected output output # 1,2,3,-99 1,2,3,-99 1,2,3,-99 # #
true
43c389b1429650de486a64eef615ab931ad011de
PowerLichen/pyTest
/HW5_final/3.py
1,371
4.25
4
""" Project: draw polygon Author: Minsu Choe StudentID: 21511796 Date of last update: Apr. 5, 2021 """ import turtle import math # draw polygon function def drawPolygon(x,y,n,width): # check polygon vertex number if n<3: return # define turtle t= turtle.Turtle() # initialize turtle t.color("blue") t.width(4) # move to main coordinates t.up() t.goto((x,y)) t.down() # draw dot and write (x,y) in main coordinates t.dot(10,"red") t.write(t.position()) loop_count=0 # set start coordinates if n%2==0: # set start coordinates if even number start_x = x - width/2 start_y = y + (width/2)/math.tan(math.radians(180/n)) t.up() t.goto((start_x,start_y)) t.down() else: # set start coordinates if odd number start_x = x start_y = y + width/2/math.sin(math.radians(180/n)) t.up() t.goto((start_x,start_y)) t.down() t.right(180/n) # draw line while loop_count<n: t.dot(10,"red") t.write(t.position()) t.forward(width) t.right(360/n) loop_count+=1 #input arguments x, y, num, width = map(int, input("input center_x, center_y, num_vertex and side_length : ").split()) drawPolygon(x,y,num,width) input("press any key to exit")
false
f9be69b3acbd500a061ea22c846f2a22e52dba00
PowerLichen/pyTest
/HW2/draw_circle.py
495
4.5
4
# Draw Circle """ Project: Draw Circle Author: Minsu Choe Date of last update: Mar. 12, 2021 """ import turtle # init t=turtle.Turtle() t.shape("turtle") # define variable print("===Draw Circle Program===") start_x = float(input("input x = ")) start_y = float(input("input y = ")) radius = int(input("input radius = ")) # move cursor location t.home() t.up() t.goto(start_x,start_y-radius/2) t.down() # draw circle on canvas t.circle(radius) # end message input("press any key to exit")
false
399193cb6c2595dfaa10fe444aa9ced1b243f0ae
PowerLichen/pyTest
/HW2/circle.py
387
4.1875
4
# Area and Circumference of Circle """ Project: Area and Circumference of Circle Author: Minsu Choe Date of last update: Mar. 12, 2021 """ #define const value PI = 3.141592 #define radius value radius = int(input("input radius = ")) # calculate answer area = radius * radius * PI circumference = 2*radius*PI # print answer print("area:", area) print("circumference:",circumference)
true
5c3b4f2b6f4e35a879d7b43256ab27561b528f20
Raffipam12/Data-Analysis-with-Python3
/Numpy_Statistics.py
1,885
4.375
4
##################################### STATISTICS WITH NUMPY ####################################### # Statistics with Numpy # Those are the different methos t calculate statistical properties of a dataset: # -Mean # -Median # -Percentiles # -Interquartile Range # -Outliers # -Standard Deviation # The first statistical concept is mean, which means finding the average. # The NumPy built-in function to calculate the average of arrays is "np.mean". # Syntax Example: movie_ratings = [87, 68, 92, 79] movie_ratings = np.array(movie_ratings) np.mean(movie_rating) 81.5 # Calculating the mean of a 2-D array: # Syntax Example: coin_toss = np.array([[0, 1, 0], [0, 0, 1], [0, 1, 1]]) # To find the means of each interior array, we specify axis 1 (the “rows”): # Syntax Example: np.mean(coin_toss, axis=1) # Sorting Outliers # To quickly identify outliers in our data, we can sort it. # Syntax Example: heights = np.array([57.7, 59.9, 61.2, 74, 60.2, 62.1]) np.sort(heights) # Numpy and Median # The median is the middle value of a dataset (from lowest to highest). # Syntax Example: new_array = np.array([120, 31, 98, 224, 64, 78]) np.median(new_array) # Percentile calculates the percentage of an array. # In NumPy, we can calculate percentiles using the function "np.percentile". # Syntax Example: x = np.array([1, 1, 2, 3, 4, 4, 4, 6, 6, 7, 8, 8, 9, 9, 10]) np.percentile(x, 40) # This will calculate 40% of x. # Some percentiles have specific names: # -The 25th percentile is called the first quartile # -The 50th percentile is called the median # -The 75th percentile is called the third quartile # Standard Deviation in Numpy # The standard deviation tells us the spread of the data. # Syntax Example: nums = np.array([89, 35, 79, 77, 41, 59]) np.std(nums) # I hope this was helpfull. # Thank you very much.
true
43173c18d53c47c28154b7a4385f61c7a2b771b0
mendesivan/Python-the-Basics
/Iterators.py
1,028
4.34375
4
# -*- coding: utf-8 -*- # Technically, in Python, an iterator is an # object which implements the iterator # protocol, which consist of the methods # __iter__() and __next__(). # Example 1 from a tuple mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) # Example 2 from a string mystr = "Apple" myit2 = iter(mystr) print(next(myit2)) print(next(myit2)) print(next(myit2)) print(next(myit2)) print(next(myit2)) # Looping through an iteration. Through a tuple mytuple = ("apples","bananas","mangos") for i in mytuple: print(i) # Create an iterator w/ StopIteration class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration Myclass = MyNumbers() myiter = iter(Myclass) for x in myiter: print(x)
false
f95944ee706588fd85079edf8db226d397542b02
laubonesire/Portfolio
/Basics/controlflow.py
454
4.25
4
# Examples of control flow using Python # Prints numbers 1 to 10 using a for loop for i in range(1, 11): print(i) # Prints numbers 1 to 10 using a while loop i = 1 while i <= 10: print(i) i += 1 # Compares the value of a and b using an if/elif/else statement a = 10 b = 20 if a < b: print("{} is less than {}".format(a, b)) elif a == b: print("{} is equal to {}".format(a, b)) else: print("{} is greater than {}".format(a, b))
true
fbcf7fa3cb0ec22eaf652d3feaeb1445f999c4f8
Amarix/cti110
/M4T1_BugCollector_AllieBeckman.py
893
4.25
4
# A program that adds the amount of bugs collected per day for five days and displays # a total at the end of the five days # 6/15/2017 # CTI-110 M4T1 - Bug Collector # Allie Beckman while True: totalBugs = 0 dayLeft = 5 dayOn = 1 while dayLeft > 0: try: totalBugs = totalBugs + int(input('How many bugs were gathered on day ' + str(dayOn) + ': ')) dayOn = dayOn+1 dayLeft = dayLeft-1 except ValueError: print('please only enter a number') print('The total number of bugs captured this week is ' + str(totalBugs) + '.') while True: yOrN = input('Would you like to calculate another week? y/n: ') if yOrN == 'y' or yOrN == 'Y': break elif yOrN == 'n' or yOrN == 'N': quit() else: print('Please enter a y or n value.')
true
437f0a21139996ef4ca62073c2e3e303cc4b58c3
ericwhyne/MIDS0901
/number_tree_optional_exercise.py
1,370
4.15625
4
#!/usr/bin/python # Prints a christmas tree on the terminal made up of ascending and descending integers # 2014 datamungeblog.com import sys import random size = int(sys.argv[1]) # first argument is an integer which is the height of the tree probability_green = .7 # how much of the tree will be green vs a random ornament class colors: # colors purple = '\033[95m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' end = '\033[0m' ornaments = [colors.purple, colors.blue, colors.yellow, colors.red, ''] def decorate(s): if random.random() > probability_green: color = random.choice(ornaments) return color + str(s) + colors.end else: return colors.green + str(s) + colors.end for i in range(1,size+1): line = "" for s in range(i, size): # this will loop over each digit left for c in range(0,len(str(s))): # prepend a space for each character of each digit line += " " for j in range(1,i+1): line += decorate(j) for j in range(i-1,0,-1): line += decorate(j) print line trunk_length = 3 #TODO: if this wasn't a joke I'd make this an argument for i in range(0, trunk_length): line = "" for s in range(1, size): # this will loop over each digit left for c in range(0,len(str(s))): # prepend a space for each character of each digit line += " " print line + "00"
true
667b1f62ff3ac5909b77784018f4a4653e06a185
shahbaazsheikh7/Learn-Python
/ex_9_2.py
920
4.3125
4
"""Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter). """ fname = input("Enter the filename: ") try: fhand = open(fname) except: print("Invalid input") exit() days = {} #initialize the dictionary for line in fhand: # parse through the file line by line words = line.split() #make a list of words in a line by the split method if len(words)==0 or words[0]!="From": #ignore the uninteresting lines continue days[words[2]] = days.get(words[2],0) + 1 #add to dictionary by the GET method #keys = list(days.keys()) #keys.sort() #for key in keys: # print(key,days[key]) print(days)
true
377e3aaa3b75b32f2a52b2f38075f6ba044d35ee
shahbaazsheikh7/Learn-Python
/revisionex7_2.py
1,059
4.40625
4
"""Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475 When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence. Enter the file name: mbox.txt Average spam confidence: 0.894128046745 Enter the file name: mbox-short.txt Average spam confidence: 0.750718518519 Test your file on the mbox.txt and mbox-short.txt files.""" fname = input("Enter a filename: ") fhand = open(fname) count = 0 sum = 0 for line in fhand: line = line.rstrip() if not line.startswith("X-DSPAM-Confidence:"): continue else: colpos = line.find(":") nstr = line[colpos+1:] num = float(nstr) count += 1 sum = sum + num print("Average spam confidence:",sum/count)
true
38598e1f4f5ce19800be9b20c7d0a584078bc6f4
shahbaazsheikh7/Learn-Python
/revisionex9_2.py
647
4.21875
4
"""Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter).""" fname = input("Enter the filename: ") fhand = open(fname) counts = {} for line in fhand: line = line.rstrip() words = line.split() if len(words) == 0 or words[0]!="From": continue for index in words: counts[words[2]] = counts.get(words[2],0) + 1 print(counts)
true
6a04f434a0d90beba779c8845ac14f1ddca49d4a
shahbaazsheikh7/Learn-Python
/revisionex5_2.py
532
4.25
4
"""Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.""" max = None min = None while True: num = input("Enter the number: ") if(num == "done"): break try: numi = int(num) except: print("Invalid input") continue if max is None or max < numi: max = numi if min is None or min > numi: min = numi print("Max:",max,"Min:",min)
true
2d1e0f35150c9aa4af7f2458386d69172f5b4422
shahbaazsheikh7/Learn-Python
/ex_9_5.py
859
4.3125
4
"""This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print out the contents of your dictionary. python schoolcount.py Enter a file name: mbox-short.txt {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8} """ fname = input("Enter the filename: ") domains = [] counts = {} try: fhand = open(fname) except: print("Invalid input") exit() for line in fhand: words = line.split() if len(words)==0 or words[0]!="From": continue addr = str(words[1]) atpos = addr.find("@") domain = addr[atpos+1:] domains.append(domain) for var in domains: counts[var] = counts.get(var,0) + 1 print(counts)
true
e43bce7ecd15bec2705a64c055d87197add8f8f5
sbobbala76/Python.HackerRank
/2 - Data Structures/2 - Linked Lists/6 - Print in Reverse.py
434
4.15625
4
""" Print elements of a linked list in reverse order as standard output. Head could be None as well for empty list. """ from . import Node def print_reverse_iterative(head): if head: stack = [head] while stack[-1].next: node = stack[-1] stack.append(node.next) while stack: node = stack.pop() print(node.data) def print_reverse_recursive(head): if head: print_reverse_iterative(head.next) print(head.data)
true
49216354dc668bca433a1ee313daa1f3a1ec2fc4
miguelvelezmj25/coding-interviews
/python/euler-project/problem4.py
1,254
4.28125
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def main(): # List of all palindromes palindromes = [] x = 1 y = 1 # While x is less than 1000 while x < 1000: # While x is less than 1000 while y < 1000: # Multiply the two numbers product = x * y # If it is a palindrome if is_palindrome(product): # Add to the list palindromes.append(product) # Update y y += 1 # Update numbers x += 1 y = 1 # Return the maximum palindrome return max(palindromes) def is_palindrome(number): # Convert number to string string = str(number) # Find the middle point middle = len(string)/2 # Loop through half of the string for i in range(0, middle): # If the characters are not the same if string[i] != string[len(string) - 1 - i]: # Not a palindrome return False # It is a palindrome return True if __name__ == '__main__': print main()
true
5d7df64e4c3ca726b6605923d6c734657cedc345
alu-rwa-dsa/implementations-Zubrah
/Week 8/Question_3.py
944
4.1875
4
""" The time Complexity to run the algorithm is O(n) as it moves through all the nodes and count the levels associated with them The Space complexity will be O(1) as it doesn't add anything the overall memory. """ # define a binary tree node class Node: # Constructor for data def __init__(self, data): self.data = data self.left = None self.right = None # define a Maximum Height func def Max_Height(node): if node is None: return 0 else: Left_Height = Max_Height(node.left) Right_Height = Max_Height(node.right) # compare the right and left nodes and add on either side if Left_Height > Right_Height: return Left_Height + 1 else: return Right_Height + 1 Root = Node(1) Root.left = Node(2) Root.right = Node(3) Root.left.left = Node(4) Root.left.right = Node(5) print(Max_Height(Root))
true
5fb9d92f1b15088e05576b3b988ce480c40d152e
nshefeek/udacity
/P0/Task4.py
1,225
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) texts_sender = set() texts_receiver = set() for i in range(len(texts)): texts_sender.add(texts[i][0]) texts_receiver.add(texts[i][1]) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) a_party = set() b_party = set() for i in range(len(calls)): a_party.add(calls[i][0]) b_party.add(calls[i][1]) non_telemarketers = texts_sender | texts_receiver | b_party telemarketers = set() for i in a_party: if i not in non_telemarketers: telemarketers.add(i) print("These numbers could be telemarketers: \n {}".format('\n'.join(sorted(telemarketers)))) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
true
1e5b97d55031b8c0378549ec0668c8a05adeaf20
SerhiiTkachuk/Softserve-Internship
/Elementary Tasks/task2.py
1,560
4.40625
4
''' Analysis of envelopes There are two envelopes with sides (a, b) and (c, d) to determine if one envelope can be nested inside the other. The program must handle floating point input. The program asks the user for the envelope sizes one parameter at a time. After each calculation, the program asks the user if he wants to continue. If the user answers “y” or “yes” (case insensitive), the program continues from the beginning, otherwise it exits. ''' def envelope(): start_game = "YES" while start_game.upper().startswith("Y"): try: side_a = float(input("Enter dimension of first side of first envelope: ")) side_b = float(input("Enter dimension of second side of first envelope: ")) side_c = float(input("Enter dimension of first side of second envelope: ")) side_d = float(input("Enter dimension of second side of second envelope: ")) except ValueError: print("Dimension must be a number!") else: if side_a>side_c and side_b>side_d or side_a>side_d and side_b>side_c: print("We can put second envelope in first!") elif side_c>side_a and side_d>side_b or side_d>side_a and side_c>side_b: print("We can put first envelope in second!") else: print("We can't put an envelope to another one!") finally: start_game = input('If you want to continue type "yes" or "y", if you want to exit type something else: ') envelope()
true
ff9156316bf2bdde0a12ad340210151fe053640c
billwurles/apps-in-general
/python/Employees/main.py
2,938
4.125
4
__author__ = 'Will' from staff import * database = Staff() def menuInput(): valid=['A','R','I','D','S','L','Q','a','r','i','d','s','l','q'] ok = False while not ok: choice=input('Enter the command you would like to run: ') if choice in valid: if len(choice) == 1: ok = True return choice else: print('You did not enter a valid option, please try again') def displayMenu(): print('A to add an employee\nR to remove an employee\nI to increase an employees salary\nD to display all employees\nS to save the list to a text file (This will delete current list)\nL to load the list from a text file\n') def numInput(type): try: if type == 'number': x = int(input('Enter the employee number: ')) if type == 'years': x = int(input('Enter how long the employee has worked here: ')) if type == 'salary': x = int(input('Enter the salary of the employee: ')) return x except ValueError: print('You did not enter a number, please try again') choice = 0 while choice != 'q' or choice != 'Q': displayMenu() choice = menuInput() if choice == 'A' or choice == 'a': name = input('Enter the name of the Employee: ') unique=False while not unique: number = numInput('number') pos = database.findEmployee(number) if pos >= 0: print('That number is already taken, please try again') else: unique = True years = numInput('years') salary = numInput('salary') database.addEmployee(name,number,years,salary) if choice == 'R' or choice == 'r': if len(database._employeeList) == 0: print('There are no employees to delete\n') else: number = numInput('number') pos = database.findEmployee(number) if pos >= 0: database.removeEmployee(pos) elif pos == -1: print('Error, that employee cannot be found, returning to menu') if choice == 'I' or choice == 'i': if len(database._employeeList) == 0: print('There are no employees to increase\n') else: number = numInput('number') salary = numInput('salary') pos = database.findEmployee(number) if pos >= 0: database.increaseSalary(pos,salary) elif pos == -1: print('Error, that employee cannot be found, returning to menu') if choice == 'D' or choice == 'd': if len(database._employeeList) == 0: print('There are no employees to display\n') else: database.displayAllEmployees() if choice == 'S' or choice == 's': database.saveTable() if choice == 'L' or choice == 'l': database.loadTable()
true
9cd501fea212ea2fdf905d4ef63007db5486b444
dbrak/rpi_scripts
/Graphics/Dot_Game/Turtle_Chase_method.py
1,347
4.21875
4
#!/usr/bin/env python import random import time import turtle d = 80 t = turtle.Turtle() t.pensize(10) t.speed(0) t.color('blue') t.shape("turtle") wn = turtle.Screen() wn.bgcolor("black") #wn.title(" ") t2 = turtle.Turtle() t2.pensize(10) t2.speed(10) t2.color('red') t2.shape("circle") t2.goto(-100,-100) t3 = t2.clone() x = input ("Select a number.") y = input ("Select another number.") t.goto(y,x) print("Let The Chase Begin!") class Turtle: def follow(self,target): pos = target.position() angle = self.towards(pos) fward = random.randrange(0,100) self.setheading(angle) self.forward(fward) distance = t2.distance(t) print(distance) if (15.0 >= distance >= -15.0) : #self.write("Ha Ha Gotcha! You are Pesky Turtle! Ha Ha Ha Ha",font=("impact", 15, "normal")) #self.write("Press space to play agen.",font=("Arial Black", 15, "normal"))\ def forward(): t.up() t.forward(d) t2.follow() def right(): t.up() t.right(90) t.forward(d) t2.follow() def left(): t.up() t.left(90) t.forward(d) t2.follow() def backward(): t.up() t.right(180) t.forward(d) t2.follow() def setup(): wn.onkey(forward,"Up") wn.onkey(right,"Right") wn.onkey(left,"Left") wn.onkey(backward,"Down") wn.onkey(setup,"space") wn.listen() setup() turtle.done()
false
a09569c79f0485d2f8f5ad6db42e595ab183b469
NiramayThaker/N-Queen
/n_queen_(n x n)/NQueen_backtracking_advance.py
2,468
4.15625
4
import copy import random def board_size_input(): # Taking user input for the size of the board while True: # Using try except to give multiple chance to user for input if entered wrong try: chess_board_size = int(input('Enter the size of chessboard (chess_board_size) -> ')) if chess_board_size <= 3: print("Enter a value greater than or equal to 4") continue return chess_board_size except ValueError: print("Invalid value ..! Enter again") # checking that is queen safe from attack def is_queen_safe(board, row, col, n): for j in range(col): if board[row][j] == "Q": return False i, j = row, col while i >= 0 and j >= 0: if board[i][j] == "Q": return False i = i - 1 j = j - 1 x, y = row, col while x < n and y >= 0: if board[x][y] == "Q": return False x = x + 1 y = y - 1 # if all of these upper condition in not true it means that queen is safe to place return True def create_board(n): board = ["x"] * n for i in range(n): board[i] = ["x"] * n return board def output(solutions, n): # Prints one of the solutions randomly random_solution = random.randint(0, len(solutions) - 1) for row in solutions[random_solution]: print(" ".join(row)) def copy_save_solution(board): # creating global variable which will save all the solutions global solutions saved_board = copy.deepcopy(board) solutions.append(saved_board) def solve(board, col, n): if col >= n: return for i in range(n): if is_queen_safe(board, i, col, n): board[i][col] = "Q" if col == n - 1: copy_save_solution(board) board[i][col] = "x" return solve(board, col + 1, n) # Recursive[repetitive] call # Backtracking board[i][col] = "x" # Saving user input of board size in n named variable n = board_size_input() # Binding ready board to board variable board = create_board(n) # Creating list to save all the solution solutions = [] solve(board, 0, n) print() print("One random solution is :- \n") output(solutions, n) print() # Randomly printing any of the one solution from all the possible ones print(f"There are total ['{len(solutions)}'] way possible to solve it")
true
402e4368764e8f9f0e27bd3188bd106dcc18bcd8
AamodPaud3l/python_assignment_dec15
/cubeandappendlist.py
341
4.53125
5
#Program to cube each elements in a list and append it to another list list = [1,2,4,4,3,5,6] def cube_list(arbitary_list): new_list = [] for each in arbitary_list: each = each ** 3 print(each) new_list.append(each) new_list1 = [7,8,9] new_list.append(new_list1) print(new_list) cube_list(list)
true
959d371a52cb965cecd013cc6915c60dc7578adf
seema1711/My100DaysOfCode
/Day 3/linkedListAtTheEnd.py
1,172
4.3125
4
''' This involves pointing the next pointer of the current last node of the linked list to the new data node. So, the current last node of the linked list becomes the second last data node & the new node becomes the last node of the LL. ''' ### LINKED LIST INSERTION AT THE END ### class Node: def __init__(self,dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Function to add newnode def AtEnd(self, newdata): NewNode = Node(newdata) if self.headval is None: self.headval = NewNode return last = self.headval while (last.nextval): last = last.nextval last.nextval = NewNode # Print the LL def listprint(self): printval = self.headval while printval is not None: print(printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node('Mon') node2 = Node('Tue') node3 = Node('Wed') list.headval.nextval = node2 node2.nextval = node3 list.AtEnd('Thu') print("Adding new element to LL at the end") list.listprint()
true