blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
52cd1781be1b9e3559cd251760212a51ffc26d98
corvolino/estudo-de-python
/Atividades-Estrutura-De-Decisao/atividade07.py
882
4.3125
4
''' Faça um Programa que leia três números e mostre o maior e o menor deles. ''' numero1 = float(input("Informe primeiro número: ")) numero2 = float(input("Informe segundo número: ")) numero3 = float(input("Informe terceiro número: ")) if numero1 > numero2 and numero1 > numero3: print("\nPrimeiro número é o maior valor!") if numero2 > numero3: print("\nTerceiro número é o menor!") else: print("\nSegundo número é o menor!") elif numero2 > numero1 and numero2 > numero3: print("\nSegundo número é o maior valor!") if numero1 > numero3: print("\nTerceiro número é o menor!") else: print("\nPrimeiro número é o menor!") else: print("\nTerceiro número é o maior valor!") if numero1 > numero2: print("\nSegundo número é o menor!") else: print("\nPrimeiro número é o menor!")
false
fa1a26561714f20ce09c29bc00ab14fb1e2837a9
SelimOzel/ProjectEuler
/Problem003.py
629
4.21875
4
def FindLargestPrime(Number): primeList = [] currentPrime = 2 primeList.append(currentPrime) currentPrime = 3 primeList.append(currentPrime) while(currentPrime < Number/2): isPrime = True # Only check odd numbers currentPrime += 2 for prime in primeList: # Current prime is not prime if(currentPrime % prime == 0): isPrime = False break # Current prime is prime if(isPrime): primeList.append(currentPrime) if(Number % currentPrime == 0): print("Prime Factor: ", currentPrime) def main(): print("Solve Problem") FindLargestPrime(600851475143) if __name__ == "__main__": main()
true
9dbecf5b08709386a86862878123c2c174d50328
SamuelFolledo/CS1.3-Core-Data-Structures-And-Algorithms
/classwork/class_activity/day8.py
377
4.3125
4
#Day 8: Hash Map # Stack coding challenge # Write a function that will reverse a string using a stack def reverse_string(text): my_stack = [] for letter in text: my_stack.append(letter) reversed_string = "" while len(my_stack) != 0: reversed_string += my_stack.pop(-1) #pop last return reversed_string print(reverse_string("abc"))
true
ab64538489331b6063316db079a915397d7085f5
tomonakar/pythonApp
/01_syntax/05_assigning_character_string.py
980
4.46875
4
# ----------------------- # # 文字列の代入 # ----------------------- # # formatメソッドでブラケットに文字列を代入出来る hoge = 'a is {}'.format('a') print(hoge) # ブラケットは複数書ける. ちなみに、引数で渡した数字は、文字列に型変換されて出力される fuga = 'a is {} {} {}'.format(1, 2, 3) print(fuga) # ブラケットには引数のインデックスを紐づけることができる foo = 'a is {0} {1} {2}'.format(1, 2, 3) print(foo) # インデックスを逆から指定すると、引数を逆順に表示してくれる bar = 'a is {2} {1} {0}'.format(1, 2, 3) print(bar) hogehoge = 'My name is {0} {1}'.format('tomo', 'naka') print(hogehoge) # ブラケットに変数を指定し、formatの引数に変数を初期値を与えて渡すことができる fugafuga = 'My name is {name} {family}'.format(name='tomo', family='naka') print(fugafuga) # strで文字列に変換 x = str(1) print(type(x))
false
807577bc161b60b2a712520fa1a53290c5709240
codemobiles/cm_python_programming
/workshops/demo15.py
337
4.15625
4
# condition if-else data = 1 if data > 3 and data < 5: print("data {}".format(data)) print("data {}".format(data)) print("data {}".format(data)) elif data > 4: print("data > 4 : {}".format(data)) else: print("else data is not > 3") if True: print("a is greater than b") print("Yes") if False else print("No")
false
2a9fc322901e7bb2a32d5a8a75b53cd813f3c00b
FluffyFu/UCSD_Algorithms_Course_1
/week4_divide_and_conquer/3_improving_quicksort/sorting.py
2,005
4.21875
4
# Uses python3 import sys import random def partition3(a, l, r): """ Partition the given array into three parts with respect to the first element. i.e. x < pivot, x == pivot and x > pivot Args: a (list) l (int): the left index of the array. r (int): the right index of the array. Returns: lt(int), gt(int), s.t. a[0, lt-1] < pivot, a[lt, gt] == pivot and a[gt+1, :] > pivot We don't need to worry about lt-1 and gt+1 are out of bound, because they'll be taken care of by the recursion base case. """ x = a[l] lt = l gt = r i = l + 1 while i <= gt: if a[i] < x: lt += 1 a[lt], a[i] = a[i], a[lt] i += 1 elif a[i] == x: i += 1 elif a[i] > x: # i should not be incremented here, because the switch moves # unseen element to i. a[gt], a[i] = a[i], a[gt] gt -= 1 a[l], a[lt] = a[lt], a[l] return lt, gt def partition2(a, l, r): x = a[l] j = l for i in range(l + 1, r + 1): if a[i] <= x: j += 1 a[i], a[j] = a[j], a[i] a[l], a[j] = a[j], a[l] return j def randomized_quick_sort_2(a, l, r): """ Use two partitions to perform quick sort. """ if l >= r: return k = random.randint(l, r) a[l], a[k] = a[k], a[l] m = partition2(a, l, r) randomized_quick_sort(a, l, m - 1) randomized_quick_sort(a, m + 1, r) def randomized_quick_sort(a, l, r): """ Use three partitions to perform quick sort. """ if l >= r: return k = random.randint(l, r) a[l], a[k] = a[k], a[l] lt, gt = partition3(a, l, r) randomized_quick_sort(a, l, lt-1) randomized_quick_sort(a, gt+1, r) if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) randomized_quick_sort(a, 0, n - 1) for x in a: print(x, end=' ')
true
c219e62a3d037e0a82ee047c929ca271dd575082
FluffyFu/UCSD_Algorithms_Course_1
/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py
1,061
4.1875
4
# Uses python3 import sys def get_optimal_value(capacity, weights, values): """ Find the optimal value that can be stored in the knapsack. Args: capacity (int): the capacity of the knapsack. weights (list): a list of item weights. values (list): a list of item values. The order matches weight input. Returns: float, optimal value. """ v_per_w = [(value / weight, index) for index, (value, weight) in enumerate(zip(values, weights))] sorted_v_per_w = sorted(v_per_w, key=lambda x: x[0])[::-1] v = 0 for avg_v, index in sorted_v_per_w: if capacity <= 0: break w = min(capacity, weights[index]) capacity -= w v += avg_v * w return round(v, 4) if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] opt_value = get_optimal_value(capacity, weights, values) print("{:.10f}".format(opt_value))
true
7334abb4a4292b369af8ecbcb18980f127cbc558
FluffyFu/UCSD_Algorithms_Course_1
/week3_greedy_algorithms/5_collecting_signatures/covering_segments.py
1,115
4.3125
4
# Uses python3 import sys from collections import namedtuple Segment = namedtuple('Segment', 'start end') def optimal_points(segments): """ Given a list of intervals (defined by integers). Find the minimum number of points, such that each segment at least contains one point. Args: segments (list of namedtuples): a list of [a_i, b_i] intervals, both of them are integers and a_i <= b_i Returns: a list of points that fulfills the requirement. """ points = [] sorted_segments = sorted(segments, key=lambda x: x.start) end = sorted_segments[0].end for current in sorted_segments: if current.start > end: points.append(end) end = current.end elif current.end < end: end = current.end points.append(end) return points if __name__ == '__main__': input = sys.stdin.read() n, *data = map(int, input.split()) segments = list(map(lambda x: Segment( x[0], x[1]), zip(data[::2], data[1::2]))) points = optimal_points(segments) print(len(points)) print(*points)
true
b85f45db7324fe4acbb6beb920cd38071e01da91
FluffyFu/UCSD_Algorithms_Course_1
/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py
972
4.28125
4
# Uses python3 from sys import stdin def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current * current return sum % 10 def fibonacci_sum_squares(n): """ Calculate the last digit of F(0)^2 + F(1)^2 + ... + F(n)^2 Think the square as the area of a square. And from the geometry, we have the sum is equal to: F(n) * (F(n) + F(n-1)) We know the last digit of F(n) has periodicity of 60. Using this fact, the last digit can be calculated easily. """ if n % 60 == 0: return 0 n = n % 60 previous = 0 current = 1 for _ in range(n-1): previous, current = current, (previous + current) % 10 return (current * (previous + current)) % 10 if __name__ == '__main__': n = int(stdin.read()) print(fibonacci_sum_squares(n))
true
763c4122695531a8de231f3982bdfb070097cf87
AkshayLavhagale/SW_567_HW_01
/HW_01.py
1,585
4.3125
4
""" Name - Akshay Lavhagale HW 01: Testing triangle classification The function returns a string that specifies whether the triangle is scalene, isosceles, or equilateral, and whether it is a right triangle as well. """ def classify_triangle(a, b, c): # This function will tell us whether the triangle is scalene, isosceles, equilateral or right triangle try: a = float(a) b = float(b) c = float(c) except ValueError: raise ValueError("The input value is not number") else: [a, b, c] = sorted([a, b, c]) # sorting the values of a, b and c so it would always remain in order if (a + b < c and a + c < b and b + c < a) or (a or b or c) <= 0: """ The Triangle Inequality Theorem states that the sum of any 2 sides of a triangle must be greater than the measure of the third side. Also none of the side should be equal to zero """ return "This is not a triangle" elif a ** 2 + b ** 2 == c ** 2: if a != b or a != c or b != c: return "Right and Scalene Triangle" if a == b or a == c or b == c: return "Isosceles and Right Triangle" elif a == b == c: return "Equilateral" if a == b or a == c or b == c: return "Isosceles" else: return "Scalene" def run_classify_triangle(a, b, c): # Invoke classify_triangle with the specified arguments and print the result print('classify_triangle(', a, ',', b, ',', c, ')=', classify_triangle(a, b, c), sep="")
true
7aea57ebf09688bf92ff294baee88da50d8b3365
nithinsunny/Learn-Python-The-Hard-Way
/ex42.py
909
4.125
4
## Animal is a object (yes, sort of confusing) look at the extra credit class Animal (object) : pass class Dog (Animal) : def __init__ (self, name) : ## ?? self.name = name class Cat (Animal) : def __init__ (self, name) : ## ?? self.name = name class Person (object) : def __init__ (self, name) : ## ?? self.name = name ## Person has-a pet of some kind self.pet = None class Employee (Person) : def __init__ (self, name, salary) : super (Employee, self).__init__(name) self.salary = salary class Fish (object) : pass class Salmon (Fish) : pass class Halibut (Fish) : pass ## rover is-a Dog rover = Dog ("Rover") ## Satan is-a Cat satan = Cat ("Satan") ## Mary is-a Person mary = Person ("Mary") ## Mary has a pet which is a cat (satan) mary.pet = satan frank = Employee ("Frank", 120000) frank.pet = rover flipper = Fish () crouse = Salmon () harry = Halibut ()
false
68fba9e6b816f2a518ff3bb0947438e88ba3ac0d
cirsyou/python
/senior_maths/sorted.py
811
4.34375
4
# sorted 排序算法 # Python内置的sorted()函数就可以对list进行排序 [-21, -12, 5, 9, 36] print(sorted([36, 5, -12, 9, -21])) # sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序 # [5, 9, -12, -21, 36] print(sorted([36, 5, -12, 9, -21], key=abs)) # 字符串排序 ['Credit', 'Zoo', 'about', 'bob'] print(sorted(['bob', 'about', 'Zoo', 'Credit'])) # 给sorted传入key函数,即可实现忽略大小写的排序 ['about', 'bob', 'Credit', 'Zoo'] print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # 要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True ['Zoo', 'Credit', 'bob', 'about'] print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
false
7c7d3f029730d3c2a2653c367c9dbc45fb9bcd41
Mollocks/Day_at_the_py_shop
/Day1.py
435
4.28125
4
#!/usr/bin/env python3 #This is my first script :) print("Hello World!") x = "Passion fruit" y = x.upper() print(y) #Anything I want age = 49 txt = "My name is Hubert, and I am {}" print(txt.format(age)) """ This is Hubert and he is 49. You can mix strings only using the .format function """ #https://www.w3schools.com/python/python_strings_format.asp # https://www.w3schools.com/python/exercise.asp?filename=exercise_strings1
true
425023cbcc7494f0825c4f9d3122603608033047
sudo-lupus666/ExerciciosPythonDesdeBasico
/Decisões - 7.py
739
4.15625
4
#Faça um Programa que leia três números e mostre o maior e o menor deles. from decimal import * def analisaNumero(): print ("**Programa - lê 3 números e devolve o maior e o menor**") def entrada(): numeros = [] sequencia = 1 while len(numeros) != 3: numero = float(input(f"Informe o número {sequencia}: ")) numeros.append(numero) sequencia +=1 return numeros def verifica_maior(): lista = sorted(entrada()) return lista def retorno_user(): lista = sorted(verifica_maior()) print (f'O maior número é o {lista[2]} e o menor número é o {lista[0]}.') retorno_user() analisaNumero()
false
e963f4ada71184d06e65a39061e2923b115ef910
sudo-lupus666/ExerciciosPythonDesdeBasico
/Decisões - 6.py
781
4.15625
4
#Faça um Programa que leia três números e mostre o maior deles. from decimal import * def analisaNumero(): print ("**Programa - lê 3 números e devolve o maior**") def entrada(): numeros = [] sequencia = 1 while len(numeros) != 3: numero = float(input(f"Informe o número {sequencia}: ")) numeros.append(numero) sequencia +=1 return numeros def verificaMaior(): numeros = entrada() numeros_sortidos = sorted(numeros) listas = (numeros, numeros_sortidos) return listas def retorno_user(): for lista1, lista2 in verificaMaior(): print (lista1, lista2) retorno_user() analisaNumero()
false
e3191a53ef5bf9d9cfb678e35d7cd4bdb75a6786
sudo-lupus666/ExerciciosPythonDesdeBasico
/Exercicio 9_aprimorar.py
653
4.21875
4
#Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. #C = 5 * ((F-32) / 9). def converte_temp(): print ("**Bem-vindo ao seu software de conversão de temperaturas**") temp_fahrenheit = float(input("Insira a temperatura em Fahrenheit: ")) def conversor_temp(): calculo_1 = (temp_fahrenheit - 32)/9 temperatura_em_Celcios = calculo_1 * 5 return round(temperatura_em_Celcios, 0) print (f'{temp_fahrenheit} graus Fahrenheit equivalem a {conversor_temp()} graus Celcius') converte_temp() #Melhorar esse código, convertendo vírgulas para pontos
false
7dbde6bd929b351afb2a4ac320d44f671f7d49c2
sudo-lupus666/ExerciciosPythonDesdeBasico
/Exercicio 11.py
592
4.28125
4
#Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: #o produto do dobro do primeiro com metade do segundo . #a soma do triplo do primeiro com o terceiro. #o terceiro elevado ao cubo. def calculo(): print('**Bem vindo ao programa de realizar cálculos matemáticos**') print('Esse programa solicitará dois números inteiros, um número real e fará alguns cálculos') numero1 = int(input("Digite o primeiro número inteiro: ")) numero2 = int(input("Digite o segundo número inteiro: ")) numero3 = real(input("Digite um número real: "))
false
1f90961ed1977c45cfc1fe27b548fffc01dc7fbf
rRayzer/Zoo-Keeper-App
/Zoo.py
2,616
4.15625
4
# This is a zoo class Animal: population = 0 animals = [] def __init__(self, name): self.name = name self.animals.append(name) Animal.population += 1 def get_animal_name(self): return self.name def print_animal_name(self): print "\nAnimal Name: " + self.get_animal_name() @classmethod def how_many(cls): print cls.animals if len(cls.animals) == 1: print "You have 1 animal in your zoo!\n" elif len(cls.animals) == 0: print "You have no animals in your zoo!\n" else: print "You have %d animals in your zoo!\n" % cls.population @classmethod def animal_die(cls): animal = raw_input("Which animal?: ") cls.animals.remove(animal) Animal.how_many() def print_description(self): print self.description class Mammal(Animal): def print_description(self): self.description = "Mammals have mammary glands and fur." print self.description class Bird(Animal): def print_description(self): self.description = "Birds have feathers and (usually) wings." print self.description class Fish(Animal): def print_description(self): self.description = "Fish live underwater and have fins & gills." print self.description # Function to check if animal type is valid def check_animal(): checking = True while checking: animal = raw_input("Type (Mammal, Bird, Fish): ").lower() if animal == 'mammal': animal_name = raw_input("Name: ") animal_name = Mammal(animal_name) animal_name.print_animal_name() animal_name.print_description() Animal.how_many() checking = False elif animal == 'bird': animal_name = raw_input("Name: ") animal_name = Bird(animal_name) animal_name.print_animal_name() animal_name.print_description() Animal.how_many() checking = False elif animal == 'fish': animal_name = raw_input("Name: ") animal_name = Fish(animal_name) animal_name.print_animal_name() animal_name.print_description() Animal.how_many() checking = False else: print "Please input valid animal type (Mammal, Bird, Fish)." def animal_death(): death = True while death: try: Animal.animal_die() death = False except ValueError: print "Animal not in zoo." death = False # main function def zoo(): print "Welcome to my Zoo program. You can add/update animals to help keep track of your zoo!" running = True while running: action = raw_input("Add/remove animal? (X to exit): ").lower() if action == 'add': check_animal() elif action == 'remove': animal_death() elif action == 'x': running = False else: print "Please follow instructions. " zoo()
false
9470642703b3ac4a62e94276dcd3eb529b38fe31
Austin-Faulkner/Basic_General_Python_Practice
/OxfordComma.py
1,442
4.34375
4
# When writing out a list in English, one normally spearates # the items with commas. In addition, the word "and" is normally # included before the last item, unless the list only contains # one item. Consider the following four lists: # apples # apples and oranges # apples, oranges, and bananas # apples, oranges, bananas, and lemons # Write a function that takes a list of strings as # its only parameter. Your function should return a # string that contains all of the items in the list # formatted in the manner described above. Your function # should work correctly for lists of any length. If the # user does not enter any strings, it should print "<empty>". # Include a main program that prompts the user for items, calls # your function to create the properly formatted string, # and displays the result. def oxfordComma(lst): oCommas = "" if len(lst) == 0: return "<empty>" elif len(lst) == 1: return str(lst[0]) elif len(lst) > 1: for i in range(0, len(lst) - 1): oCommas += str(lst[i]) + ", " oCommas += "and " + str(lst[-1]) + "." return oCommas def main(): words = [] entry = str(input("Enter a series of words (hit 'return' to discontinue): ")) while entry != "": words.append(entry) entry = str(input("Enter a series of words (hit 'return' to discontinue): ")) print(oxfordComma(words)) main()
true
fddd9b1c376193beb4097bdd0ebe7ebc9ffedf91
denisemmucha/aulas
/aula5b.py
311
4.28125
4
#uso de aspas triplas print("""Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), strip(), junção com join().""")
false
7cea87bed8615753466b2cd60712e2c22ce34fb2
nurur/ReplaceFirstCharacter-R.vs.Python
/repFirstCharacter.py
613
4.53125
5
# Python script to change the case (lower or upper) of the first letter of a string # String a='circulating' print 'The string is:', a print '' #Method 1: splitting string into letters print 'Changing the first letter by splitting the string into letters' b=list(a) b[0] = b[0].upper() b=''.join(b) print b print ' ' # Method 2: using regular expression print 'Changing the first letter by using regular expression' import re rep = lambda f: f.group(1).upper() b = re.sub('\A([a-z])', rep, a) #using anchor token \A print b b = re.sub('^([a-z])', rep, a) #using anchor token ^ print b
true
bd5ac9ee6116ebe863436db0dcf969b525beec5e
noahjett/Algorithmic-Number-Theory
/Algorithmic Number Theory/Binary_Exponentiation.py
2,450
4.15625
4
# Author: Noah Jett # Date: 10/1/2018 # CS 370: Algorithmic Number Theory - Prof. Shallue # This program is an implementation of the binary exponentiation algorithm to solve a problem of form a**e % n in fewer steps # I referenced our classroom discussion and the python wiki for the Math.log2 method import math def main(): a,n = 2,3 for e in range(1,10): print("e ==: ", e) result = (PowerMod(a,e,n,1)) print("Answer: ", result) logTest = logbase2(e) print("2 * log base2(e) = ", logTest, "\n") def PowerMod(a,e,n,numSteps): # a ** e % n print("||", a,e,n, "||") if e < 1: print("Steps: ", numSteps) return (a) elif e % 2 == 0: # even case return (PowerMod(a, e/2, n, numSteps+1)**2)%n elif e % 2 != 0: # odd case return (a * PowerMod(a, e-1, n,numSteps+1) % n) # Takes input e, the exponent being calculated in powermod # Outputs 2*log base2(e) # I googled "python log base 2" library, and was directed (stackoverflow?) to the log2 function in the "math" library def logbase2(e): log = (math.log2(e))*2 return log main() """ This algorithm for binary exponentiation should theoretically take <= logbase2(e) *2 steps to solve. I tested this for exponents 1-100 for the equation 2**e % 3. The algorithm did not consistently take <= 2logbase2(e) steps until the exponent was >= 16. With the exceptions of 31 and 63 The exponents that solved in the least steps, around 25% fewer than 2logbase2(e) were: 16,24,32,34,36,48,64,72... There was a positive correlation between even numbers and fewer steps, and an even greater one between powers of 2 and fewer steps. Some exponents that took more steps, being only slightly better than the theoretical limit were: 19,21,23,31,47,79,95. Odd numbers and primes both seem to take more steps to solve Why is this the case? The first fifteen exponents exceed the theoretical upper bound. I suspect this is overhead from python or my specific code. However, it also makes sense that this algorithm will always take at least a few steps, so it might just not work under a certain number. It makes sense that odd numbers would be slightly slower. Algorithmically, the odd case is essentially the # of even stepe +1 Powers of 2 being faster probably has to do with having a base of 2; those numbers would divide perfectly. """
true
8f4cb8ad08d7059e81b3633f12590bcda243ba22
mari00008/Python_Study
/Python_study/10.オブジェクト指向プログラミング/2.クラス変数とインスタンス変数.py
1,868
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #In[1] class My_class: x=100 # In[2]: #In[2] #My_classのクラス変数xを参照 print(My_class.x) # In[3]: #In[3] #クラス変数を上書きする My_class.x = 200 #Mt_classのクラス変数xを参照 print(My_class.x) # In[4]: #In[4] #My_classのインスタンスを作成 My_object = My_class() #クラス変数を参照 print(My_object.x) # In[5]: #In[1] class Class_A: def __init__(self,value): self.x = value # In[6]: #In[2] object_1 = Class_A(100) #インスタンス変数を参照 print(object_1.x) # In[7]: #In[3] object_2 = Class_A("apple") #インスタンス変数を参照 print(object_2.x) # In[8]: #In[4] #インスタンス変数を上書きする object_2.x = "orange" #インスタンス変数を参照 print(object_2.x) # In[9]: #In[5] #インスタンス変数yを追加 object_2.y = "banana" #インスタンス変数yを参照 print(object_2.y) # In[10]: #In[1] #円のクラスを定義 class Circles: #円周率の近似値をクラス変数として定義 pi = 3.141592653589793 #半径、面積、周長をインスタンス変数として定義 def __init__(self,r): self.radius = r self.area = self.pi * self.radius** 2 self.perimeter = 2 * self.pi * self.radius # In[12]: #In[2] #Circlesクラスのインスタンスを生成 c1 = Circles(5) #クラス変数を参照 print("円周率: {:.5f}".format(c1.pi)) #インスタンス変数を参照 print("半径:{:.3f}".format(c1.radius)) print("面積:{:.3f}".format(c1.area)) print("周長:{:.3f}".format(c1.perimeter)) # In[13]: #In[1] class My_class: x = 100 my_object = My_class() my_object.x = 200 print(my_object.x) # In[14]: #In[2] #クラス変数を参照 print(My_class.x)
false
5ab6233b815d03f52bbeb5be1edce7923944eefd
mari00008/Python_Study
/Python_study/5.ループ処理と条件分岐/3.range関数による連続数字を生成.py
658
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[5]: x = (range(10)) print(x) # In[6]: x =list((range(10))) print(x) # In[7]: x = list (range(1,10,2)) print(x) # In[8]: #降順に x = list(range(10,0,-1)) print(x) # In[9]: #range(5)の要素を全て足す #すなわち1+2+3+4+5 s = sum(range(5)) print(s) # In[16]: #rangeオブジェクトから順に値を取り出す for x in range (10): print(x,end ="") # In[18]: #ループ回数をカウント count = 0 for x in range (100): count += 1 print("ループ回数は{}です".format(count)) # In[19]: for x in range (3): print("Pythonは楽しいな") # In[ ]:
false
933ee7b8fa808a76514d2a12be8bf169a7901cf0
EvgeniyZubtsov/Python
/Homework3/Task3_1.py
249
4.25
4
string1 = 'Съешь ещё этих мягких французских булок ДА выпей же чаю' string2 = string1.split() print(string2[3].upper()) print(string2[6].lower()) print(string2[7][2]) for i in string2: print(i)
false
52b915eb36411af0506f770031379f0477c883fe
RaianePedra/CodigosPython
/MUNDO 2/DESAFIO69.py
884
4.15625
4
'''Exercício Python 69: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: A) quantas pessoas tem mais de 18 anos. B) quantos homens foram cadastrados. C) quantas mulheres tem menos de 20 anos.''' tot18 = totH = totM = 0 while True: idade = int(input("Qual a idade? ")) sexo = str(input("Qual o sexo? [M/F]")).strip().upper()[0] if idade >= 18: tot18 += 1 if sexo == "M": totH += 1 if idade <= 20 and sexo == "F": totM += 1 resp = str(input("Deseja continuar? [S/N]")).strip().upper()[0] if resp not in "S": break print(f"\033[33m{tot18}\033[m Pessoas maiores de 18 anos.") print(f"\033[34m{totH}\033[m Homens foram cadastrados.") print(f"\033[35m{totM}\033[m Mulheres tem menos de 20 anos;")
false
2bb71dc00d494fa3407e045b91baf6e20038de58
RaianePedra/CodigosPython
/MUNDO 1/DESAFIO1.py
742
4.125
4
print("============ CALCULADORA ===========") print("1-SOMA") n1 = int(input("Primeiro numero: ")) n2 = int(input("Segundo numero : ")) soma = n1 + n2 print("A soma de {} e {} sera: {}". format(n1, n2, soma)) """ print("\nSUBTRACAO") n1 = int(input("Primeiro numero: ")) n2 = int(input("Segundo numero: ")) sub = n1 - n2 print("A subtracao de {} e {} sera: {}". format(n1, n2, sub)) print("\nMULTIPLICACAO") n1 = int(input("Primeiro numero: ")) n2 = int(input("Segundo numero: ")) mult = n1 * n2 print("A subtracao de {} e {} sera: {}". format(n1, n2, mult)) print("\nDIVISAO") n1 = int(input("Primeiro numero: ")) n2 = int(input("Segundo numero: ")) div = n1 / n2 print("A subtracao de {} e {} sera: {}". format(n1, n2, div)) """
false
f14c4696cc8e4f2db90416bd8e4216a7319c3860
Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code
/Boolean_Operators/Task1.py
761
4.375
4
#Boolean Operators #Boolean values (True, False) # [ ] Use relational and/or arithmetic operators with the variables x and y to write: # 3 expressions that evaluate to True (i.e. x >= y) # 3 expressions that evaluate to False (i.e. x <= y) x = 84 y = 17 print(x >= y) print(x >= y and x >= y) print(x >= y or x >= y) print(x <= y) print(x <= y and x <= y) print(x <= y or x <= y) #Boolean operators (not, and, or) # [ ] Use the basic Boolean operators with the variables x and y to write: # 3 expressions that evaluate to True (i.e. not y) # 3 expressions that evaluate to False (i.e. x and y) x = True y = False print( x and not y ) print( x or not y ) print( y or not y ) print( not x and y) print( not x and x and y ) print( not y and x and y )
true
837bebc2d9fbed6fe2ab8443f09a30bce9554478
Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code
/File_System/Task_2.py
908
4.40625
4
import os.path # [ ] Write a program that prompts the user for a file or directory name # then prints a message verifying if it exists in the current working directory dir_name = input("Please provide a file or directory name: ") if(os.path.exists(dir_name)): print("Path exists") # Test to see if it's a file or directory if(os.path.isfile(dir_name)): print("It's a file") elif (os.path.isdir(dir_name)): print("It's a dir") else: print("Path doesn't exist") # [ ] Write a program to print the absolute path of all directories in "parent_dir" # HINTS: # 1) Verify you are inside "parent_dir" using os.getcwd() # 2) Use os.listdir() to get a list of files and directories in "parent_dir" # 3) Iterate over the elements of the list and print the absolute paths of all the directories dir_list = os.listdir() print(dir_list) for i in dir_list: print(os.path.abspath(i))
true
789ad69b7e081b180ca96143eeb8c4d47cfeb2a8
makfazlic/CommonAlgosAndDataStructures
/data_structures/linked_list/linked_list.py
1,211
4.28125
4
# Regular linked list # Constant complexity - insert_after, insert_before, is_empty, insert_front, delete_front, pop_front # Linear complexity - find, get_element_at, print_all class list_element: def __init__(self, v, n): self.value = v self.next = n L = None def insert_after(x, v): x.next = list_element(v, x.next) def insert_before(x, v): x = list_element(v, list_element) # \Theta(n) def find(x): l = L while l != None: if x == l.value: return True l = l.next return False # \Theta(n) def get_element_at(i): l = L while l != None: if i == 0: return l.value i = i - 1 l = l.next print('index ouf of bounds') def is_empty(): return L == None def insert_front(x): global L L = list_element(x,L) def delete_front(): global L if L == None: print('list empty') else: L = L.next def pop_front(): global L if L == None: print('list empty') else: v = L.value L = L.next return v # \Theta(n) def print_all(): global L l = L while l != None: print(l.value) l = l.next
false
655bf45e09a32b1544b54c5c938b8f5430daf4e7
grimesj7913/cti110
/P3T1_AreaOfRectangles_JamesGrimes.py
733
4.34375
4
#A calculator for calculating two seperate areas of rectangles #September 11th 2018 #CTI-110 P3T1 - Areas of Rectangles #James Grimes # length1 = float(input("What is the length of the first rectangle?:")) width1 = float(input("What is the width of the first rectangle?:" )) area1 = float(length1 * width1) length2 = float(input("What is the length of the second rectangle?:")) width2 = float(input("What is the width of the second rectangle?:")) area2 = float(length2 * width2) if area1 > area2: print('Rectangle 1 has the greater area') else: if area2 > area1: print('Rectangle 2 has the greater area') else: print('Both are the same area') input("Press enter to close the program")
true
78c7fb57d30e08b0c7f0808c3272769d6f2a2726
elnieto/Python-Activities
/Coprime.py
1,342
4.125
4
#Elizabeth Nieto #09/20/19 #Honor Statement: I have not given or received any unauthorized assistance \ #on this assignment. #https://youtu.be/6rhgXRIZ6OA #HW 1 Part 2 def coprime(a,b): 'takes two numbers and returns whether or not they are are coprime' #check if the numbers are divisible by 2 or if both are 2 if (a % 2 != 0 and b % 2 != 0) or (a ==2 and b ==2): classification = 'Coprime' else: classification = 'Not Coprime' return classification def coprime_test_loop(): 'Asks users for two numbers then passes these numbers to function \ coprime which identifies the nuber as coprime or not and returns \ the classification for the user. After it asks the user if they would\ like to repeat the function.' #ask for user to enter two nums a2, b2 = input( 'Enter two numbers seperated by a space(e.g. 34 24) \ or enter "Stop Process" to end this process.').split() #base case to end recursion if a2 == 'Stop': return 'Process Stopped' else: a2 = int(float(a2)) b2 = int(float(b2)) #calls function coprime, format output, loop function result = coprime(a2,b2) print(a2, ' and ', b2, ' are ', result) return coprime_test_loop() #test code print(coprime_test_loop())
true
07079cd63c24d88847a4b4c6a6749c8c2dca2abb
AbhijeetSah/BasicPython
/DemoHiererchialInheritance.py
446
4.15625
4
#hiererchial Inheritance class Shape: def setValue(self, s): self.s=s class Square(Shape): def area(self): return self.s*self.s class Circle(Shape): def area(self): return 3.14*self.s*self.s sq= Square() s= int(input("Enter the side of square ")) sq.setValue(s) print("Area of square",sq.area()) cr= Circle() r= int(input("Enter the radius of circle ")) cr.setValue(r) print("Area of circle : ", cr.area())
true
7bf3778c0dd682739cec943e2f9550e01a517538
itssamuelrowe/arpya
/session5/names_loop.py
577
4.84375
5
# 0 1 2 3 names = [ "Arpya Roy", "Samuel Rowe", "Sreem Chowdhary", "Ayushmann Khurrana" ] for name in names: print(name) """ When you give a collection to a for loop, what Python does is create an iterator for the collection. So what is an iterator? In the context of a for loop, an iterator is a special object that takes each item in the collection and gives it to the for statement. """ # for variable in collection: # block # print("index 0 => " + names[0]) # print("index 1 => " + names[1]) # print("index 2 => " + names[2]) # print("index 3 => " + names[3])
true
3b32018a5f493a622d5aee4bd979813c15c7c86c
vanderzj/IT3038C
/Python/nameage.py
819
4.15625
4
import time start_time = time.time() #gets user's name and age print('What is your name?') myName = input() print('Hello ' + myName + '. That is a good name. How old are you?') myAge = input() #Gives different responses based on the user's age. if myAge < 13: print("Learning young, that's good.") elif myAge == 13: print("Teenager Detected") elif myAge > 13 and myAge <= 26: print("Now you're a double teenager!") elif myAge > 26 and myAge < 34: print("Getting older...") else: print("You're probably older than Python!") #prgmAge = time the program has been running prgmAge = int(time.time() - start_time) print(str(myAge) +"? That's funny, I'm only " + str(prgmAge) + " seconds old.") print(" I wish I was " + str(int(myAge) * 2) + " years old.") time.sleep(3) print("I'm tired. Goodnight!")
true
b598c4d34d7f60ad2a821efaed87e47d7ed16781
vanderzj/IT3038C
/Python/TKinter_Practice/buttons.py
1,002
4.53125
5
# Imports tkinter, which is a built-in Python module used to make GUIs. from tkinter import * # Creates the window that the content of our script will sit in. win = Tk() # This function is being set up to give the button below functionality with the (command=) arguement. # The Command function should be written as (command=x) instead of as (command=x()) like most other functions. If you include the parenthesies the function will run on program start by itself. def myClick(): lbl1 = Label(win, text="Button was clicked.") lbl1.pack() # Creates a button object. The arguements here are (<location of button>, <text shown on button>, <horizontal size of button>, <vertical size of button>) btn = Button(win, text="Click Me!", padx=50, pady=50, command=myClick) # Puts the button into win btn.pack() # The .mainloop() part of this command starts the window's loop. This is what allows the program to run. Clicking the "X" on the window created by this script ends the loop. win.mainloop()
true
1f030e2f733874480af9f92425566e9f593dfe34
ledbagholberton/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
605
4.375
4
#!/usr/bin/python3 def add_integer(a, b=98): """ Function that summ two numbers integer or float. Args: a: First parameter (integer or float) b: Second paramenter (integer of float) Returns: Summ of a & b """ if a is None or (type(a) is not int and type(a) is not float): raise TypeError("a must be an integer") elif type(a) is float: a = int(a) if type(b) is not int and type(b) is not float: raise TypeError("b must be an integer") elif type(b) is float: b = int(b) c = a + b return (c)
true
4cc00acd4bd2bee59ea68225a1dc97950e11a48c
JhonataAugust0/Python
/Estruturas/Estruturas_compostas/Tuplas_e_listas/Validador lógico de expressões matemáticas.py
1,783
4.28125
4
print("Bem vindo ao validador lógico de expressões matemáticas.") chave = [] expressão= str(input("Digite a expressão desejada:\n")).strip().upper()# while expressão[0] not in '{': expressão= str(input("Digite a expressão inicializando com uma chave:\n")).strip().upper()# for simb1 in expressão: if simb1[0] == '{': chave.append('{') colchete = [] for simb2 in expressão:#! if simb2[0] == '[': colchete.append('[') parênteses = [] for simb3 in expressão:#$ if simb3[0] == '(': parênteses.append('(') elif ')' not in expressão: break elif simb3 == ']': if len(parênteses) > 0: parênteses.pop() else: parênteses.append(')') break#$ elif ']' not in expressão: break elif simb2 == ']': if len(colchete) > 0: colchete.pop() else: colchete.append(']') break#! elif '}' not in expressão: break elif simb1 == '}': if len(chave) > 0: chave.pop() else: chave.append('}') break if len(chave) == 0: if len(colchete) ==0: if len(parênteses) == 0: print(f"A sua expressão {expressão} está válida.") else: print("Expressão inválida.") # Este algoritmo percorre uma expressão matemática em forma de uma # string, verificando se suas chaves, colchetes e parênteses estão # devidamente fechados.
false
2eab5dbb4d15a4f53eda4de61087cd7b908cdf5e
JhonataAugust0/Python
/Estruturas/Estruturas_compostas/Tuplas_e_listas/Tuplas.py
1,132
4.4375
4
#tuplas são variáveis compostas onde podemos adicionar vários valores de uma só vez e realizar várias coisas com eles palavras = ('aprender', 'programar') # Acima, acabamos de declarar uma tupla for p in palavras: print(f"\nNa palavra {p.upper()} temos ", end='') for letra in p: if letra.lower() in 'aeiou': print(letra, end="") # Aqui acabamos e fazer uma estrutura que coleta as vogais das palavras contidas na tupla lanche = ['pizza', 'hambúrger', 'suco', 'sorvete'] # Aqui acabamos de definir uma lista for p in lanche: print(lanche) lanche.append('Olá') # Adicionando um elemento for p in lanche: print(lanche) del lanche[3] # Deletando um elemento lanche.insert(0, 'picole') for p in lanche: print(lanche) # Inserindo um elemento numa posição específica del lanche[3] lanche.remove('pizza') # Aqui temos outra forma de remover um elemento if 'pizza' in lanche: lanche.remove('pizza') # Verificando se o elemento existe na lista para removê-lo valores = list(range(0, 10)) print(valores) valores.sort() valores.sort(reverse=True) print(valores) print(len(valores))
false
5b82dd7f7e00b9ed2a8ee39e194384eb32ccc3f0
green-fox-academy/MartonG11
/week-02/day-1/mile_to_km_converter.py
273
4.4375
4
# Write a program that asks for an integer that is a distance in kilometers, # then it converts that value to miles and prints it km = float(input('Put a kilometer to convert to miles: ')) factor = 0.621371192 miles = km * factor print("The distance in miles is: ", miles)
true
cc328013864be876f42b1b7c25117bc3ffcccb4a
green-fox-academy/MartonG11
/week-02/day-2/swap_elements.py
250
4.34375
4
# - Create a variable named `abc` # with the following content: `["first", "second", "third"]` # - Swap the first and the third element of `abc` abc = ["first", "second", "third"] def swap(x): x[0] , x[2] = x[2] , x[0] print(x) swap(abc)
true
210519003481bc2545f6a2dfeab8c81ec67df223
green-fox-academy/MartonG11
/week-03/day-3/rainbow_box_function.py
767
4.1875
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() # create a square drawing function that takes 2 parameters: # the square size, and the fill color, # and draws a square of that size and color to the center of the canvas. # create a loop that fills the canvas with rainbow colored squares. size1 = 145 color1 = "red" size2 = 120 color2 = "yellow" size3 = 100 color3 = "green" size4 = 80 color4 = "blue" size5 = 60 color5 = "purple" def square_draw(x_size, x_color): canvas.create_rectangle(150-(x_size), 150-(x_size),150+(x_size), 150+(x_size), fill=x_color) square_draw(size1, color1) square_draw(size2, color2) square_draw(size3, color3) square_draw(size4, color4) square_draw(size5, color5) root.mainloop()
true
7369d96e116c26b27ba9ce9877f358699f022c77
green-fox-academy/MartonG11
/week-06 - python/word_reverser.py
256
4.21875
4
def reverse(text): reverseWord = " " make_list = text.split() for word in make_list: word = word[::-1] reverseWord = reverseWord + word + " " return reverseWord.strip() print(reverse("lleW ,enod taht saw ton taht drah"))
false
8b6d39bb03692cc8ff81dbfdd62d59ed51b3629f
green-fox-academy/MartonG11
/week-03/day-3/center_box_function.py
535
4.34375
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. size1 = 130 size2 = 100 size3 = 50 def draw_square(square_size): canvas.create_rectangle(150-(square_size), 150-(square_size),150+(square_size), 150+(square_size), fill="green") draw_square(size1) draw_square(size2) draw_square(size3) root.mainloop()
true
b500ce44e4652624e0b5f94e19da756ad190e217
hkscy/algorithms
/Miscellaneous Algorithms/Palindrome Checker/palindrome.py
2,216
4.25
4
# Chris Hicks 2020 # # Based on Microsoft Technical Interview question: # "Given a string, write an algorithm that will determine if it is a palindrome" # Input: string of characters, Output: True (palindrome) False (palindrome) # # What is a palindrome? # - A sequence of characters which reads the same backward as forward # - Sentence-length palindromes may be written when allowances are made for # adjustments to capital letters, punctuation, and word dividers # # Some examples are "02022020":True , "Chris":False, , "Anna":True # "Step on no pets":True, "Lobster Stew":False # # Can I use libraries? if so re for regular expressions could be used # or methods and variables from string library and e.g. string.punctuation import string as strings import timeit examples = {"02022020":True , "Chris":False, "Anna":True, "Step on no pets":True, "Lobster Stew":False, " ":True, "":True} # In the permissive setting, return a string with no capitalisation or whitespace def permissive(string): string = string.casefold() # n comparisons string = string.replace(" ", "") # n comparisons return string # Simply check whether all of the "opposite" characters in string have # the same value. Wasteful since we're duplicating our effort. def basic_is_palindrome(string): return string == string[::-1] # Can we do better? We can compare just n//2 elements def fast_is_palindrome(string): # If string has odd length than ignore middle character n = len(string) if n%2 != 0: string = string[0:n//2]+string[n//2+1:] for idx in range(n//2): if string[idx] != string[-idx-1]: return False return True def main(): for example in examples: # If we want to be disregard punctuation and whitespace example_clean = permissive(example) if basic_is_palindrome(example_clean) == examples.get(example): print("Basic method PASS for example \"{}\"".format(example)) else: print("Basic method FAIL for example \"{}\"".format(example)) if fast_is_palindrome(example_clean) == examples.get(example): print("Fast method PASS for example \"{}\"".format(example)) else: print("Fast method FAIL for example \"{}\"".format(example)) print() if __name__ == "__main__": main()
true
f4891c92ba34699fe80a9d71f66a6ae13c39a75f
JosueOb/Taller1
/Ejercicios/Ejercicio4-6.py
1,577
4.15625
4
from tkinter import * root = Tk() v = IntVar() Label(root, text="""Choose a programming language:""", justify = LEFT, padx = 20).pack() Radiobutton(root, text="Python", padx = 20, variable=v, value=1).pack(anchor=W) Radiobutton(root, text="Perl", padx = 20, variable=v, value=2).pack(anchor=W) mainloop() root = Tk() v = IntVar() v.set(1) # initializing the choice, i.e. Python languages = [ ("Python",1), ("Perl",2), ("Java",3), ("C++",4), ("C",5) ] def ShowChoice(): print (v.get()) Label(root, text="""Choose your favourite programming language:""", justify = LEFT, padx = 20).pack() for txt, val in languages: Radiobutton(root, text=txt, padx = 30, variable=v, command=ShowChoice, value=val).pack(anchor=W) mainloop() root = Tk() v = IntVar() v.set(1) # initializing the choice, i.e. Python languages = [ ("Python",1), ("Perl",2), ("Java",3), ("C++",4), ("C",5) ] def ShowChoice(): print (v.get()) Label(root, text="""Escoja un lenguaje de programación:""", justify = LEFT, padx = 20).pack() for txt, val in languages: Radiobutton(root, text=txt, indicatoron =0, width = 20, padx = 20, variable=v, command=ShowChoice, value=val).pack(anchor=W) mainloop()
true
9c1fdcb0cabca9e2ac660cba53bc54f1205dd022
Znigneering/BioinformaticTurtorial
/Pyfiles/03-14/locating_restriction_sites.py
752
4.125
4
#!usr/pyhton/env pyhton3 def find_reverse_palindrome(seq): result = '' for x in range(0,len(seq)-1): pair = 0 while is_reseverse(seq[x-pair],seq[x+1+pair]) and pair < 6: pair += 1 if pair != 1: result += str(x+2-pair)+' '+str(pair*2)+' \n' if x-pair < 0 or x+1+pair >= len(seq): break return result def is_reseverse(x,y): if x == 'C' and y == 'G': return True elif x == 'G' and y == 'C': return True elif x == 'A' and y == 'T': return True elif x == 'T' and y == 'A': return True else: return False if __name__ == '__main__': print(find_reverse_palindrome(input('enter the DNA seq:')))
false
bffba3eb19fd92bfed2563216c3d7478a8b92fed
LitianZhou/Intro_Python
/ass_4.py
2,635
4.15625
4
# Part 1 while True: RATE = 1.03 while True: print("--------------------------------------") start_tuition = float(input("Please type in the starting tuition: ")) if start_tuition <= 25000 and start_tuition >= 5000: break else: print("The starting tuition should be between 5,000 and 25,000 inclusive, please enter a valid value.") tuition = start_tuition year = "year" for i in range(1,6): tuition = tuition*RATE print("In " + str(i) + " " + year + ", the tuition will be $" + format(tuition, ',.2f') + ".") year = "years" foo = input("To calculate with other start tuition, type *yes* to continue, otherwise the program ends: ") if(foo != "yes"): break # Part 2 print("\n_____________Part 2_______________") while True: print("-----------------------------------------") rate = 1 + float(input("Please input the increment rate per year (enter as decimals): ")) #input start_tuition and validation check while True: start_tuition = float(input("Please type in the starting tuition: ")) if start_tuition <= 25000 and start_tuition >= 5000: break else: print("ERROR: Starting tuition should be between 5,000 and 25,000 inclusive!") #input first year + validation check while True: try: first_year = int(input("Please enter the first year you are interested: ")) except ValueError: print("ERROR: Please input an integer!") continue else: if first_year < 1: print("ERROR: Please input a integer at least 1") else: break #input last year + validation check while True: try: last_year = int(input("Please enter the last year you are interested: ")) except ValueError: print("ERROR: Please input an integer!") continue else: if last_year < first_year: print("ERROR: Please input a integer greater than first year") else: break # calculate and print tuition = start_tuition year = "year" for i in range(1, last_year+1): tuition = tuition*rate if i >= first_year: print("In " + str(i) + " " + year + ", the tuition will be $" + format(tuition, ',.2f') + ".") year = "years" foo = input("To calculate with other tuition and rate, type *yes* to continue, otherwise the program ends: ") if(foo != "yes"): break
true
1de705bec799a785ad37393373fa289e0c3a18bc
manohiro/diveintocode-term0
/03-02-python-set.py
1,354
4.21875
4
course_dict = { 'AIコース': {'Aさん', 'Cさん', 'Dさん'}, 'Railsコース': {'Bさん', 'Cさん', 'Eさん'}, 'Railsチュートリアルコース': {'Gさん', 'Fさん', 'Eさん'}, 'JS': {'Aさん', 'Gさん', 'Hさん'}, } def find_person(want_to_find_person): """ 受講生がどのコースに在籍しているかを出力する。 まずはフローチャートを書いて、どのようにアルゴリズムを解いていくか考えてみましょう。 """ # ここにコードを書いてみる # コースの数分処理を行う for course, person in course_dict.items(): # 集合の積より、共通する要素を抽出 Result = person & want_to_find_person if not Result: # 要素が空の場合 print("{}に{}は在籍していません。".format(course, want_to_find_person)) elif len(Result) == 1: # 要素が1の場合は一人のみ print("{}に{}のみ在籍しています。".format(course, Result)) else: print("{}に{}は在籍しています。".format(course, Result)) def main(): want_to_find_person = {'Cさん', 'Aさん'} print('探したい人: {}'.format(want_to_find_person)) find_person(want_to_find_person) if __name__ == '__main__': main()
false
cd9812c4bce5cf9755e99f06cc75db716499f0e1
edek437/LPHW
/uy2.py
876
4.125
4
# understanding yield part 2 from random import sample def get_data(): """Return 3 random ints beetween 0 and 9""" return sample(range(10),3) def consume(): """Displays a running average across lists of integers sent to it""" running_sum=0 data_items_seen=0 while True: data=yield data_items_seen += len(data) running_sum += sum(data) print('The running average is {}'.format(running_sum / float(data_items_seen))) def produce(consumer): """Produces a set of values and forwards them to the pre-defined consumer function""" while True: data=get_data() print('Produced{}'.format(data)) consumer.send(data) yield #if __name__ == '__main__': consumer = consume() consumer.send(None) producer = produce(consumer) for _ in range(10): print('Producing...') next(producer)
true
3cdbde7f1435ef0fc65ab69b325fed08e1136216
cakmakok/pygorithms
/string_rotation.py
209
4.15625
4
def is_substring(word1, word2): return (word2 in word1) or (word1 in word2) def string_rotation(word1, word2): return is_substring(word2*2,word1) print(string_rotation("waterbottle","erbottlewat"))
true
df61bd0ca36e962e134772f6d7d50200c7a3a7aa
phuongnguyen-ucb/LearnPythonTheHardWay
/battleship.py
2,320
4.34375
4
from random import randint board = [] # Create a 5x5 board by making a list of 5 "0" and repeat it 5 times: for element in range(5): board.append(["O"] * 5) # To print each outer list of a big list. 1 outer list = 1 row: def print_board(board): for row in board: print " ".join(row) # to concatenate all the elements inside the list into one string => to make the board look pretty print "Let's play Battleship!" print_board(board) # display the board # Assign a random location (random row & column) for my ship. This location will be hidden: def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) #print ship_row #print ship_col # User can play 4 turns before game over (turn starts from 0 to 3): for turn in range(4): # Ask user to guess my ship's location: guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Column: ")) # A winning case: if guess_row == ship_row and guess_col == ship_col: # raw_input will return a string => have to make (guess_row & guess_col) become integer to compare with number print "Congratulations! You sunk my battleship!" break # to get out of a loop and stop a game if user wins # Wrong cases: else: # If user's guess is invalid or off the board: if guess_row > len(board)-1 or guess_col > len(board[0])-1: print "Oops, that's not even in the ocean." # If user already guessed a specific location: elif board[guess_row][guess_col] == "X": print "You guessed that one already." # If user guess it wrong: else: print "You missed my battleship!" board[guess_row][guess_col] = "X" # mark X on a location that is already guessed # Notify user when they play all 4 turns: if turn == 3: print "GAME OVER!!! Too bad you just lost your last chance :(. Try again :)" break # to end a game without displaying turn and a board # Display user's turn: if turn == 0: print "You've played ", turn + 1, "turn" else: print "You've played ", turn + 1, "turns" # Display the board again: print_board(board)
true
ac4ecdf8ffd9532f0254c6d848ba74a886122ed8
mvoecks/CSCI5448
/OO Project 2/Source Code/Feline.py
2,173
4.125
4
import abc from Animal import Animal from roamBehaviorAbstract import climbTree from roamBehaviorAbstract import randomAction ''' The roaming behavior for Felines can either be to climb a tree or to do a random action. Therefore we create two roamBehaviorAbstract variables, climbTree and randomAction that we will set appropriately in the subclasses for Feline. ''' climbBehavior = climbTree() randomBehavior = randomAction() ''' Create a abstract class Feline which extends Animal. This class sets the doRoam behavior to the fly class, and impliments the eat and sleep functions defined in the abstract Animal class ''' class Feline(Animal): __metaclass__ = abc.ABCMeta ''' Initializing a Feline object and set its name, type, and behavior in the superclass Animal ''' def __init__(self, name, type, behavior): super().__init__(name, type) super().setRoamBehavior(behavior) ''' All Felines sleep and eat the same, so initialize those function Here ''' def sleep(self): print(super().getType() + "-" + super().getName() +": Back to my natural state, Zzzzz.....") def eat(self): print(super().getType() + "-" + super().getName() +": Purrrr, some food. Don't mind if I do.") ''' Create a class for the cats, which are an extension of Felines. In this class we initialize a cat by giving it a name and defining its behavior, which is to do a random action. This also defines how cats make noise. ''' class Cat(Feline): def __init__(self, name): super().__init__(name, 'Cat', randomBehavior) def makeNoise(self): print(super().getType() + "-" + super().getName() +": Meh, I'm just a cat.") ''' Create a class for the lions, which are an extension of Felines. In This class we initialize a lion by givig it a name and defining its behavior, which is to climb a tree. This also defines how lions make noise ''' class Lion(Feline): def __init__(self, name): super().__init__(name, 'Lion', climbBehavior) def makeNoise(self): print(super().getType() + "-" + super().getName() +": ROAR! Behold the mighty lion!")
true
83424e65bc9b7240d3ff929a22884e2ebef578d3
asvkarthick/LearnPython
/GUI/tkinter/tkinter-label-02.py
620
4.25
4
#!/usr/bin/python3 # Author: Karthick Kumaran <asvkarthick@gmail.com> # Simple GUI Program with just a window and a label import tkinter as tk from tkinter import ttk # Create instance win = tk.Tk() # Set the title for the window win.title("Python GUI with a label") # Add a label label = ttk.Label(win, text = "Label in GUI") label.grid(column = 0, row = 0) def click_button(): button.configure(text = "Clicked") label.configure(foreground = 'red') label.configure(text = 'Button clicked') button = ttk.Button(win, text = "Click Here", command = click_button) button.grid(column = 1, row = 0) # Start the GUI win.mainloop()
true
ee3acb288c29099d6336e9d5fd0b7a54f71573fe
asvkarthick/LearnPython
/02-function/function-05.py
218
4.125
4
#!/usr/bin/python # Author: Karthick Kumaran <asvkarthick@gmail.com> # Function with variable number of arguments def print_args(*args): if len(args): for i in args: print(i); else: print('No arguments passed') print_args(1, 2, 3)
true
8fa01eb2322cd9c2d82e043aedd950a408c46901
optionalg/challenges-leetcode-interesting
/degree-of-an-array/test.py
2,851
4.15625
4
#!/usr/bin/env python ##------------------------------------------------------------------- ## @copyright 2017 brain.dennyzhang.com ## Licensed under MIT ## https://www.dennyzhang.com/wp-content/mit_license.txt ## ## File: test.py ## Author : Denny <http://brain.dennyzhang.com/contact> ## Tags: ## Description: ## https://leetcode.com/problems/degree-of-an-array/description/ ## ,----------- ## | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. ## | ## | Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. ## | ## | Example 1: ## | Input: [1, 2, 2, 3, 1] ## | Output: 2 ## | Explanation: ## | The input array has a degree of 2 because both elements 1 and 2 appear twice. ## | Of the subarrays that have the same degree: ## | [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] ## | The shortest length is 2. So return 2. ## | Example 2: ## | Input: [1,2,2,3,1,4,2] ## | Output: 6 ## | Note: ## | ## | nums.length will be between 1 and 50,000. ## | nums[i] will be an integer between 0 and 49,999. ## `----------- ## ## Basic Idea: ## Complexity: ## -- ## Created : <2017-10-16> ## Updated: Time-stamp: <2017-10-23 18:22:06> ##------------------------------------------------------------------- class Solution(object): def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ # find the degree and digits digit_dict = {} for i in range(0, len(nums)): num = nums[i] if digit_dict.has_key(num) is False: digit_dict[num] = (1, [i]) else: (count, l) = digit_dict[num] l.append(i) digit_dict[num] = (count+1, l) degree = 0 for num in digit_dict.keys(): (count, _l) = digit_dict[num] if count > degree: degree = count min_length = 65535 degree_digits = [] for num in digit_dict.keys(): (count, l) = digit_dict[num] if count == degree: start_index = l[0] end_index = l[-1] length = end_index - start_index + 1 if length < min_length: min_length = length # print "degree: %d, degree_digits: %s" % (degree, degree_digits) # loop the example, only start from digits which are in the target list return min_length if __name__ == '__main__': s = Solution() print s.findShortestSubArray([1, 2, 2, 3, 1]) print s.findShortestSubArray([1,2,2,3,1,4,2]) ## File: test.py ends
true
e24f2c5e5688efbfc9a8e1c041765efc22fa0cc0
optionalg/challenges-leetcode-interesting
/reverse-words-in-a-string/test.py
1,323
4.28125
4
#!/usr/bin/env python ##------------------------------------------------------------------- ## @copyright 2017 brain.dennyzhang.com ## Licensed under MIT ## https://www.dennyzhang.com/wp-content/mit_license.txt ## ## File: test.py ## Author : Denny <http://brain.dennyzhang.com/contact> ## Tags: ## Description: ## https://leetcode.com/problems/reverse-words-in-a-string/description/ ## ,----------- ## | Given an input string, reverse the string word by word. ## | ## | For example, ## | Given s = "the sky is blue", ## | return "blue is sky the". ## | ## | Update (2015-02-12): ## | For C programmers: Try to solve it in-place in O(1) space. ## `----------- ## ## -- ## Created : <2017-10-16> ## Updated: Time-stamp: <2017-10-26 21:41:00> ##------------------------------------------------------------------- class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ ## Basic Idea: ## the sky is blue ## eulb si yks eht ## blue is sky the ## Complexity: Time O(n), Space O(1) # reverse s = s[::-1] res = [] for item in s.split(" "): if item == "": continue res.append(item[::-1]) return ' '.join(res)
true
37cc4a21931e88c5558809dfb756e01e01a92d10
brianpeterson28/Princeton_Python_SWD
/bep_exercises/chapter1.2/contcompinterest/contcompinterest.py
2,227
4.3125
4
''' Author: Brian Peterson | https://github.com/brianpeterson28 Creative Exercise 1.2.21 - Intro to Programming In Python ''' import math import decimal print("Calculates Future Value @ Continuously Compounded Rate.") def askForInterestRate(): while True: try: interestrate = float(input("Enter interest rate: ")) while (interestrate >= 1) or (interestrate < 0): print("Please enter the interest rate as a decimal greater than zero but less than one.") interestrate = float(input("Enter interest rate: ")) break except ValueError: print("That input is not valid.") print("Please enter the interest rate as a decimal greater than zero but less than one.") return interestrate def askForYears(): while True: try: years = int(input("Enter number of years: ")) while (years < 0) or (type(years) != type(1)): print("The number of years must be an integer greater than zero.") years = int(input("Enter number of years:")) break except ValueError: print("That is not a valid entry.") print("Please enter the number of years as a non-negative integer.") return years def askForPrincipal(): while True: try: principal = float(input("Enter amount of principal: ")) while principal <= 0: print("The principal amount must be greater than zero.") principal = float(input("Enter amount of principal: ")) break except ValueError: print("That is not a valid entry.") print("Please enter a principal amount that is greater than zero.") print("Also, please do not include any commas.") return principal def calculateFutureValue(interestrate, years, principal): futureValue = principal * (math.exp(interestrate * years)) return futureValue ''' Excellent article explaining how to use decimal package to do math with and round floating point numbers: https://pymotw.com/3/decimal/ ''' def displayResult(futurevalue): futurevalue = decimal.Decimal(futurevalue) print("The future value is ${:,.2f}.".format(futurevalue)) def main(): principal = askForPrincipal() years = askForYears() inerestRate = askForInterestRate() futurevalue = calculateFutureValue(inerestRate, years, principal) displayResult(futurevalue) if __name__ == "__main__": main()
true
1ad1c2566f099d2de4736fcc5b7f7fbbf30a7bb2
Savinagowda1307/MuchineLearning-Assignments
/multiple.py
640
4.125
4
#MULTIPLE INHERITANCE-----It involves more than one parent class ####MULTIPLE INHERITANCE class Parent: def func1(self,name,salary): self.name=name self.salary=salary print("My name is :"+self.name+" my salary is :"+str(self.salary)+" and my age is :"+str(d.age)) class Parent1: def savi(self,friend,age): self.friend=friend self.age=age print(self.friend +" is my bestiee and her age is "+str(age)) class Child(Parent,Parent1): def func2(self): print("This is function 2") d=Child() d.age=20 d.func1("savina",350000) d.savi("yashu",21)
false
ad8dd825f3f56a5773b4d0bb79f27a3738c13533
crishabhkumar/Python-Learning
/Assignments/Trailing Zeroes.py
299
4.15625
4
#find and return number of trailing 0s in n factorial #without calculation n factorial n = int(input("Please enter a number:")) def trailingZeros2(n): result = 0 power = 5 while(n >= power): result += n // power power *= 5 return result print(trailingZeros2(n))
true
60f2c7a1930e69268bd41975cc3778e545ee9100
sudhansom/python_sda
/python_fundamentals/10-functions/functions-exercise-01.py
306
4.3125
4
# write a function that returns the biggest of all the three given numbers def max_of_three(a, b, c): if a > b: if a > c: return a else: return c else: if b > c: return b else: return c print(max_of_three(3, 7, 3))
true
10f075ee5aff42884240b0a5070d649d3c71d972
sudhansom/python_sda
/python_fundamentals/06-basic-string-operations/strings-exercise.py
420
4.21875
4
# assigning a string value to a string of length more than 10 letters string = "hello" reminder = len(string) % 2 print(reminder) number_of_letters = 2 middle_index = int(len(string)/2) start_index = middle_index - number_of_letters end_index = middle_index + number_of_letters + reminder result = string[start_index:end_index] print(f"Result: {result}") # just for a prictice r = range(0, 20,2) print(r) print(r[:5])
true
8a21cc7dc1f16ae2715479dbc875d4c5e0696f6a
sudhansom/python_sda
/python_fundamentals/00-python-HomePractice/w3resource/conditions-statements-loops/problem43.py
386
4.28125
4
""" Write a Python program to create the multiplication table (from 1 to 10) of a number. Go to the editor Expected Output: Input a number: 6 6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 6 x 7 = 42 6 x 8 = 48 6 x 9 = 54 6 x 10 = 60 """ user_input = int(input("Enter the number: ").strip()) for i in range(1, 11): print(f"{user_input} x {i} = {user_input * i}")
true
8c8ba8bbd6230a3c045971542159acb1ef584596
dlu270/A-First-Look-at-Iteration
/Problem 3-DL.py
683
4.65625
5
#Daniel Lu #08/08/2020 #This program asks the user for the number of sides of a shape, the length of sides and the color. It then draws the shape and colors it. import turtle wn = turtle.Screen() bob = turtle.Turtle() sides = input ("What are the number of sides of the polygon?: ") length = input ("What is the length of the sides of the polygon?: ") line_color = input ("What is the line color of the polygon?: ") fill_color = input ("What is the fill color of the polygon?: ") bob.color(line_color) bob.fillcolor(fill_color) bob.begin_fill() for i in range (int(sides)): bob.forward (int(length)) bob.left (int(360) / int(sides)) bob.end_fill()
true
7ab66c17162421433ec712ebb1bbad0c0afbdd0b
Dianajarenga/PythonClass
/PythonClass/student.py
1,075
4.59375
5
class Student: school="Akirachix" #to create a class use a class keyword #start the class name with a capital letter.if it has more than one letter capitalize each word #do not include spaces #many modules in a directory form a package #when you save your code oin a .py file its called a module #to import a class from any module use . notation eg-from module import class name (import convection) standard libraries,built in modules. #object creation from class instance creation #def__init__(Self,name,age) creating a class contructor self is refers to instance of class def __init__(self,name,age,unit): self.name=name#assignning variables to class instance self.age=age self.unit=unit def speak(self): return f"Hello my name is {self.name} and I am {self.age} years old" def learn(self): return f"I am studying {self.unit} in{self.school}" #create class Car : give it 4 attributes(),behaviour()3, #create class Dog attributes(3) ,method(1) #bank.py class Account(3)method(2)
true
5c0bea2dcc1dfd238969953082c83fa1f7db10a7
errorswan/lianxi
/10_cut_list.py
1,171
4.40625
4
''' 4.4切片练习 ''' ''' 4-10 切片 ''' # 列表前三元素 pizzas = ['new york', 'chicago', 'california', 'pan', 'thick'] list = pizzas[:3] print("The first three items in the list are:") print(list) # 列表中间三元素 pizzas = ['new york', 'chicago', 'california', 'pan', 'thick'] list = pizzas[1:4] print("Three items from the middle of the list are:") print(list) # 列表末尾三元素 pizzas = ['new york', 'chicago', 'california', 'pan', 'thick'] list = pizzas[2:] print("The last three items in the list are:") print(list) ''' 4-11你的比萨和我的比萨 ''' pizzas = ['new york', 'chicago', 'california', 'pan', 'thick'] friend_pizzas = pizzas[:] pizzas.append('kfc') friend_pizzas.append('mac download') print("My favorite pizzas are:") for p in pizzas: print(p) print("My friend's favorite pizzas are:") for m in friend_pizzas: print(m) ''' 4-12 ''' my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") for m in my_foods: print(m) print("\nMy friend's favorite foods are:") for f in friend_foods: print(f)
false
6096598f70d386090efba0a31f1be8a6a483a39e
johnashu/Various-Sorting-and-SEarching-Algorithms
/search/interpolation.py
1,970
4.1875
4
""" Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed. Binary search has a huge advantage of time complexity over linear search. Linear search has worst-case complexity of Ο(n) whereas binary search has Ο(log n). Step 1 − Start searching data from middle of the list. Step 2 − If it is a match, return the index of the item, and exit. Step 3 − If it is not a match, probe position. Step 4 − Divide the list using probing formula and find the new midle. Step 5 − If data is greater than middle, search in higher sub-list. Step 6 − If data is smaller than middle, search in lower sub-list. Step 7 − Repeat until match. """ a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] d = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F'} x = 0 def maf_interpolation(array, value): """ In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed. """ err = "Not Found" lo = 0 mid = -1 hi = len(array) - 1 while value != mid: if lo == hi or array[lo] == a[hi]: print("No Dice! Target NOT Found!") break mid = lo + ((hi - lo) // (array[hi] - array[lo])) * (value - array[lo]) if array[mid] == value: return print("Success, Found in Index: ", mid) break elif array[mid] < value: lo = mid + 1 elif a[mid] > value: hi = mid - 1 maf_interpolation(a, x)
true
11a2948ed09d97d32565e20dcb6ef0f7158a879f
zosopick/mawpy
/Chapters 1 to 5/Chapter 1/1-5 Turtle spiral.py
498
4.28125
4
''' Excersise 1-5: Turtle spiral Make a funciton to draw 60 squares, turning 5 degrees after each square and making each successive square bigger. Start at a length of 5 and increment 5 units every square. ''' from turtle import * shape('turtle') speed(10) length=5 def turtle_spiral(): length=5 for i in range(250): for j in range(4): forward(length) right(90) right(10) length+=5 turtle_spiral()
true
2e432eac8fbcb96bdd568ac0ebb83f08761bc912
zosopick/mawpy
/Chapters 1 to 5/Chapter 5/Exercise__5_1_A_spin_cycle/Exercise__5_1_A_spin_cycle.pyde
771
4.1875
4
''' Exercise 5-1: A spin cycle Create a circle of equilateral triangles in a processing sketch and rotate them using the rotate() function ''' t=0 def setup(): size(1000,1000) rectMode(CORNERS) #This keeps the squares rotating around the center #also, one can use CORNER or CORNERS def draw(): global t background(255) translate(width/2,height/2) rotate(radians(t)) for i in range(12): pushMatrix() translate(200,0) rotate(radians(5*t))#If we add this, the squares rotate faster tri(50) popMatrix() rotate(radians(360/12)) t+=1 def tri(length): triangle(0,-length, -length*sqrt(3)/2, length/2, length*sqrt(3)/2, length/2)
true
bf73c880b2704f1ef37080e4bb18ef0777d6ff5a
vighneshdeepweb/Turtle-corona
/Turtle-Covid/covid.py
676
4.125
4
import turtle #create a screen screen = turtle.Screen() #create a drawer for drawing drawer = turtle.Turtle() #Set the background color of the screen screen.bgcolor("black") #For set a Background,color,speed,pensize and color of the drawer drawer.pencolor("darkgreen") drawer.pensize(3) drawer1 = 0 drawer2 = 0 drawer.speed(0) drawer.goto(0, 200) drawer.pendown() #Create while loop for drawing Corona Virus Shape. while True: drawer.forward(drawer1) drawer.right(drawer2) drawer1 += 3 drawer2 += 1 if drawer2 == 210: break drawer.ht() # For Holding the main Screen screen.mainloop()
true
4ba65c35155b48a53f93cf15fd65dde01ca12f05
ahmetihsankaya/week3
/1st set/3.4.4.6.py
482
4.125
4
exam_mark=float(input("What is the exam mark?\n")) print("The exam mark of %s corresponds to following grade:" %exam_mark) if exam_mark<40: print("F3") elif exam_mark>=40 and exam_mark<45: print("F2") elif exam_mark>=45 and exam_mark<50: print("F1 Supp") elif exam_mark>=50 and exam_mark<60: print("Third") elif exam_mark>=60 and exam_mark<70: print("Second") elif exam_mark>=70 and exam_mark<75: print("Upper Second") elif exam_mark>=75: print("First")
false
d10975f40f51444b69afcee04b30a0347faf0da5
veldc/basics
/labs/02_basic_datatypes/02_04_temp.py
402
4.34375
4
''' Fahrenheit to Celsius: Write the necessary code to read a degree in Fahrenheit from the console then convert it to Celsius and print it to the console. C = (F - 32) * (5 / 9) Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius" ''' Farh = float(input("Enter degree Farh: ")) Celsius = (Farh-32)*(5/9) print (Farh, "degress fahrenheid = ",Celsius, "degress celsius")
true
776fa8276987922284cac8b4a28c8e974242f0ee
veldc/basics
/labs/02_basic_datatypes/02_05_convert.py
799
4.40625
4
''' Demonstrate how to: 1) Convert an int to a float 2) Convert a float to an int 3) Perform floor division using a float and an int. 4) Use two user inputted values to perform multiplication. Take note of what information is lost when some conversions take place. ''' # int to float Num = 8 Div = float(Num) print(Div) # float to int Num = 8 Div = 10 devision = int(Num/Div) print(devision) #Floor division NumInt = 30 NumFl = 9.3 print(NumInt//NumFl) '''#user input int InputUser1 = int(input("Enter number: ")) InputUser2 = int(input("Enter another number: ")) Multi=(InputUser1*InputUser2) print(Multi)''' #user input float InputUser1 = float(input("Enter number: ")) InputUser2 = float(input("Enter another number: ")) Multi=int((InputUser1*InputUser2)) print(Multi)
true
764e49079883e2419c2ed66de6d3b883f3074b10
VanessaVanG/number_game
/racecar.py
1,536
4.3125
4
'''OK, let's combine everything we've done so far into one challenge! First, create a class named RaceCar. In the __init__ for the class, take arguments for color and fuel_remaining. Be sure to set these as attributes on the instance. Also, use setattr to take any other keyword arguments that come in.''' class RaceCar: def __init__(self, color, fuel_remaining, laps=0, **kwargs): self.color = color self.fuel_remaining = fuel_remaining self.laps = laps for key, value in kwargs.items(): setattr(self, key, value) '''OK, now let's add a method named run_lap. It'll take a length argument. It should reduce the fuel_remaining attribute by length multiplied by 0.125. Oh, and add a laps attribute to the class, set to 0, and increment it each time the run_lap method is called.''' def run_lap(self, length): self.fuel_remaining -= (length * 0.125) self.laps += 1 '''Great! One last thing. In Python, attributes defined on the class, but not an instance, are universal. So if you change the value of the attribute, any instance that doesn't have it set explicitly will have its value changed, too! For example, right now, if we made a RaceCar instance named red_car, then did RaceCar.laps = 10, red_car.laps would be 10! To prevent this, be sure to set the laps attribute inside of your __init__ method (it doesn't have to be a keyword argument, though). If you already did it, just hit that "run" button and you're good to go!''' ##I had already done it :)
true
8a09fdfe492076ea41aeed7aa25ff058e7a5a945
anuragk1991/python-basics
/comprehension.py
1,097
4.1875
4
nums = [1,2,3,4,5,6,7,8,9] print(nums) print('List comprehension') my_list = [n for n in nums] print(my_list) print('') print('Create list from another list (n*n) using list map and lambda function') my_list = map(lambda n: n*n, nums) print(my_list) print('') print('Create list from another list (n*n) using list comprehension') my_list = [n*n for n in nums] print(my_list) print('') print('Create list of even numbers another list using list filter and lambda function') my_list = filter(lambda n: n%2==0, nums) print(my_list) print('') print('Create list of even numbers from another list using list comprehension') my_list = [n for n in nums if n%2 == 0] print(my_list) print('') print('Create a list of tuples(char, digit) from two array of same length using list comprehension') letters = 'abcd' numbers = '1234' my_list = [(char, digit) for char in letters for digit in numbers] print(my_list) names = ['Bruce', 'Clark', 'Peter', 'Barry'] heroes = ['Batman', 'Superman', 'Spiderman', 'Flash'] # print(zip(names, heroes)) print({names[i]: heroes[i] for i in range(len(names)) })
false
30288a48048f82daf25da88ed697364d86d0fc4d
OliverTarrant17/CMEECourseWork
/Week2/Code/basic_io.py
1,589
4.21875
4
#! usr/bin/python """Author - Oliver Tarrant This file gives the example code for opening a file for reading using python. Then the code writes a new file called testout.txt which is the output of 1-100 and saves this file in Sandbox folder (see below). Finally the code gives an example of storing objects for later use. In this example my_dictionary is stored as the file testp.p in sandbox. Pickle is used to serialize the objects hieracy""" ######################## # FILE INPUT ######################## # Open a file for reading f = open('../Sandbox/test.txt', 'r') # use "implicit" for loop: # if the object is a file, python will cycle over lines for line in f: print line, # the "," prevents adding a new line # close the file f.close() # same example, skip blank lines f = open('../Sandbox/test.txt', 'r') for line in f: if len(line.strip()) > 0: #removes trailing and leading spaces from line and determines if it is non blank print line, f.close() ################# # FILE OUTPUT ################# list_to_save = range(100) f = open('../Sandbox/testout.txt','w') for i in list_to_save: f.write(str(i) + '\n') ## Add a new line at the end f.close() #################### # STORING OBJECTS #################### # To save an object (even complex) for later use my_dictionary = {"a key": 10, "another key": 11} import pickle f = open('../Sandbox/testp.p','wb') ## note the b: accept binary files pickle.dump(my_dictionary, f) f.close() ## Load the data again f = open('../Sandbox/testp.p','rb') another_dictionary = pickle.load(f) f.close() print another_dictionary
true
e80b0d4d97c6cce390144e17307a65a7fb0cced1
DroidFreak32/PythonLab
/p13.py
2,590
4.75
5
# p13.py """ Design a class named Account that contains: * A private int data field named id for the account. * A private float data field named balance for the account. * A private float data field named annualInterestRate that stores the current interest rate. * A constructor that creates an account with the specified id (default 0), initial balance (default 100), and annual interest rate (default 0). * The accessor and mutator methods for id , balance , and annualInterestRate . * A method named getMonthlyInterestRate() that returns the monthly interest rate. * A method named getMonthlyInterest() that returns the monthly interest. * A method named withdraws that withdraws a specified amount from the account. * A method named deposit that deposits a specified amount to the account. (Hint: The method getMonthlyInterest() is to return the monthly interest amount, not the interest rate. Use this formula to calculate the monthly interest: balance*monthlyInterestRate. monthlyInterestRate is annualInterestRate / 12 . Note that annualInterestRate is a percent (like 4.5%). You need to divide it by 100 .) Write a test program that creates an Account object with an account id of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the id, balance, monthly interest rate, and monthly interest. """ class Account: def __init__(self,id=0,balance=100.0,annualInterestRate=0.0): self.__id=id self.__balance=balance self.__annualInterestRate=annualInterestRate def getId(self): #Accessor Functions return self.__id def getBalance(self): return self.__balance def getannualInterestRate(self): return self.__annualInterestRate def setId(self,id): #Mutator Fucntions self.__id=id def setBalance(self,balance): self.__balance=balance def setannualInterestRate(self,annualInterestRate): self.__annualInterestRate=annualInterestRate def getMonthlyInterestRate(self): return self.__annualInterestRate/(12*100) def getMonthlyInterest(self): return self.__balance*self.getMonthlyInterestRate() def withdraw(self,amt): self.__balance-=amt def deposit(self,amt): self.__balance+=amt a=Account(1122,20000,4.5) a.withdraw(2500) a.deposit(3000) print("Id:",a.getId()," Balance:",a.getBalance()," Monthly Interest Rate:",a.getMonthlyInterestRate()," Monthly Interest:",a.getMonthlyInterest()) #############################################
true
650c23952ab2978697916954ed04761ed800330c
DroidFreak32/PythonLab
/p09.py
592
4.1875
4
# p09.py ''' Consider two strings, String1 and String2 and display the merged_string as output. The merged_string should be the capital letters from both the strings in the order they appear. Sample Input: String1: I Like C String2: Mary Likes Python Merged_string should be ILCMLP ''' String1=input("Enter string 1:") String2=input("Enter string 2:") merged_string="" for ch in String1: if ch.isupper(): merged_string=merged_string+ch for ch in String2: if ch.isupper(): merged_string=merged_string+ch print(merged_string) #############################################
true
79988e9e8f075938284c7f277809625a445adf5d
anmalch/python
/lesson_3_4_2.py
1,350
4.21875
4
''' Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. Второй — более сложная реализация без оператора **, предусматривающая использование цикла. ''' def my_func_1(x, y): positive_y = abs(y) for i in range(positive_y): result = 1 result = result * x return 1 / result x = float(input('Enter a valid positive number: ')) y = int(input('Enter an integer negative number: ')) if x <= 0 or y >= 0: print('Bad input') exit #использовала else, чтобы исключить вывод None в терминале else: print(my_func_1(x, y))
false
64e179dae3eada5e76890da5c412dacddab81a1e
TenckHitomi/turtle-racing
/racing_project.py
2,391
4.3125
4
import turtle import time import random WIDTH, HEIGHT = 500, 500 COLORS = ['red', 'green', 'blue', 'orange', 'yellow', 'black', 'purple', 'pink', 'brown', 'cyan'] def get_number_of_racers(): """Input number of turtles you want to show up on the screen""" racers = 0 while True: racers = input("Enter the number of racers (2 - 10): ") if racers.isdigit(): #Checks if the input is a digit for # of racers. If not prompts for another input racers = int(racers) else: print('Input is not numeric... Try again.') continue if 2 <= racers <= 10: #Checks input of user to see if it falls between 2 & 10 return racers else: print('Number not in range of 2-10...Try again.') def race(colors): #Create colored turtles turtles = create_turtles(colors) while True: #Randomly pass a range through each turtle to determine pixels it moves. The further apart the bigger the gap. for racer in turtles: distance = random.randrange(1, 20) racer.forward(distance) x, y = racer.pos() #Returns index of first turtle to cross the finish line and returns color value if y >= HEIGHT // 2 -10: return colors[turtles.index(racer)] def create_turtles(colors): #Creates Turtle list and evenly spaces each turtle on the screen from each other. turtles = [] spacingx = WIDTH // len(colors) + 1 for i, color in enumerate(colors): racer = turtle.Turtle() racer.color(color) racer.shape('turtle') racer.left(90) #Rotates the turtles to look up on the screen racer.penup() racer.setpos(-WIDTH//2 + (i + 1) * spacingx, -HEIGHT//2 + 20) racer.pendown() turtles.append(racer) return turtles def init_turtle(): """Produces window on screen""" screen = turtle.Screen() screen.setup(WIDTH , HEIGHT) screen.title('Turtle Racing!') #Sets specific name you want to display on window racers = get_number_of_racers() #Returns the number of racers after all conditionals have been passed init_turtle() random.shuffle(COLORS) colors = COLORS[:racers] winner = race(colors) print(f"The winner is the {winner.title()} turtle.") time.sleep(5) #Python leaves window open for 5 seconds after race finishes so you can see results on screen
true
f5c0aa56ad89771487550747ea9edaa2656c0e0a
carlshan/design-and-analysis-of-algorithms-part-1
/coursework/week2/quicksort.py
1,554
4.28125
4
def choose_pivot(array, length): return array[0], 0 def swap(array, i, j): temp = array[i] array[i] = array[j] array[j] = temp def partition(array, low, high): pivot = array[low] i, j = low + 1, high - 1 # initializes i to be first position after pivot and j to be last index while True: # If the current value we're looking at is larger than the pivot # it's in the right place (right side of pivot) and we can move left, # to the next element. # We also need to make sure we haven't surpassed the low pointer, since that # indicates we have already moved all the elements to their correct side of the pivot while (i <= j and array[j] >= pivot): j -= 1 # Opposite process of the one above while (i <= j and array[i] <= pivot): i += 1 # We either found a value for both j and i that is out of order # in which case we swap and continue # or i is higher than j, in which case we exit the loop # after swapping the pivot into its rightful position if i <= j: swap(array, i, j) # The loop continues else: # everything has been partitioned swap(array, low, j) return j def quicksort(array, low, high): if high - low <= 1: return array part = partition(array, low, high) quicksort(array, low, part) quicksort(array, part + 1, high) return array test = [3, 8, 2, 5, 1, 4, 7, 6] print(quicksort(test, 0, len(test)))
true
7c885c274f4103db153970a6ce1476cf415c790e
Mkaif-Agb/Python_3
/zip.py
398
4.46875
4
first_name = ["Jack", "Tom", "Dwayne"] last_name = ["Ryan","Holland", "Johnson"] name = zip(first_name,last_name) for a,b in name: print(a,b) def pallindrome(): while True: string=input("Enter the string or number you want to check") if string == string[::-1]: print("It is a pallindrome") else: print("It is not a pallindrome") pallindrome()
true
a5a5af705de9e836d2af930740fd54fce3d2e042
romataukin/geekbrains
/les_01/1.py
229
4.15625
4
1. name = input('Введите имя: ') 2. surname = input('Введите фамилию: ') 3. age = input('Введите Ваш возраст: ') 4. print('Привет,', name, surname) 5. print('Возраст: ', age)
false
0af9c97699b04830aa12069d4258c5725f8f0c35
sheriline/python
/D11/Activities/friend.py
562
4.21875
4
""" Elijah Make a program that filters a list of strings and returns a dictionary with your friends and foes respectively. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... Output = { "Ryan":"friend", "Kieran":"foe", "Jason":"foe", "Yous":"friend" } """ names = ["Ryan", "Kieran", "Jason", "Yous"] friend_or_foe = {name: "friend" if len(name) == 4 else "foe" for name in names} print(friend_or_foe) # {'Ryan': 'friend', 'Kieran': 'foe', 'Jason': 'foe', 'Yous': 'friend'}
true
030162330c0295f35315dd1d90a688b293a39759
sheriline/python
/D1 D2/ifstatement.py
731
4.3125
4
#!/usr/bin/env python3.7 #example # gender = input("Gender? ") # if gender == "male" or gender == "Male": # print("Your cat is male") # else: # print("Your cat is female") # age = int(input("Age of your cat? ")) # if age < 5: # print("Your cat is young.") # else: # print("Your cat is adult.") #exercises print(""" Make a program that asks the number between 1 and 10\. If the number is out of range the program should display "invalid number". """) number = input("Input a number between 1 and 10: ") if int(number) > 10: print("invalid number") else: print("valid number") print("\n") print("Make a program that asks a password.\n") password = input("Please enter your password: ") print(password)
true
464ddc137e89538fd0a5cc63b58bfc837bdf06c5
scotttct/tamuk
/Python/Python_Abs_Begin/Mod3_Conditionals/3_5_Math_3.py
787
4.59375
5
# Task 3 # PROJECT: IMPROVED MULTIPLYING CALCULATOR FUNCTION # putting together conditionals, input casting and math # update the multiply() function to multiply or divide # single parameter is operator with arguments of * or / operator # default operator is "*" (multiply) # return the result of multiplication or division # if operator other than "*" or "/" then return "Invalid Operator" # [ ] create improved multiply() function and test with /, no argument, and an invalid operator ($) def multiply(operator): x = float(input('Enter number 1: ')) y = float(input('Enter number 2: ')) if operator == "*": return x * y elif operator == "/": return x / y else: return "invalid operator" print(multiply(input("Enter '/' or '*': ")))
true
a8f769fc11e575144fed429fd57165f9b318ee36
scotttct/tamuk
/Python/Python_Abs_Begin/Mod4_Nested/4_3-7_1-While_True.py
1,132
4.1875
4
# Task 1 # WHILE TRUE # [ ] Program: Get a name forever ...or until done # create variable, familar_name, and assign it an empty string ("") # use while True: # ask for user input for familar_name (common name friends/family use) # keep asking until given a non-blank/non-space alphabetical name is received (Hint: Boolean string test) # break loop and print a greeting using familar_name # [ ] create Get Name program # familar_name = "" # while True: # familiar_name = input ("Enter your commonly used name,something your friends or family use: ") # if familiar_name.isalpha(): # print ("Hi",familiar_name.capitalize() + "!", "I am glad you are alive and well!") # break # elif not familiar_name.isalpha: # print("keep going\n") # else: # break #################################33 #2nd Try def familiar_name(): while True: name_input = input("What's a common name your friends and family use?") if name_input.isalpha(): break else: print() print() print("Hey " + name_input.capitalize()) familiar_name()
true
a2d480068f763e0465022ea3ed208a4b4889ac4a
scotttct/tamuk
/Homework/Homework1.py
1,702
4.53125
5
# Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number # and for the multiples of five print “Buzz”. # For numbers which are multiples of both three and five print “FizzBuzz”." # for i in range(0, 101): # print(i) # print() # for t in range(0, 101, 3): # print(t) # print() # for f in range(0, 101, 5): # f="fizz" # print(f) ################################################################### # prints odd numbers as a template for creating a function to perform the task of printing by 3 and replace # def even_numbers(number): # for i in range(number): # if i == 0: # continue # elif i%2 == 0: # print(i) # else: # continue # print(even_numbers(101)) #create a function that prints all the necessary assignment parameters #This attempt printed biff only # def nums(number1, number2): # for i in range(number1, number2): # While i in range(number1, number2, 3) # print("biff") # elif: # continue # print(nums(1,101)) #another attempt that printed all 1's # i = 1 # while i < 101: # print(i) # if (i == 3): # print("biff") # elif (1==5): # print("baff") # elif (i==3 or i==5): # print("biffbaff") # i += 1 # trying for nested for loops, taking from python documentation and modified for n in range(1, 101): print(n) if n in range(1,101,3): print("biff") elif n in range(1,101,5): print('baff') elif n in range(1, 101, 3) or n in range(1,101,5): #this line does not work print("biffbaff") # ... else: # ... # loop fell through without finding a factor # ... print(n, 'is a prime number')
true
9f5ab86e2e150066f02dacc8d1c35defabc1115f
scotttct/tamuk
/Python/Python_Abs_Begin/Mod1/p1_2.py
280
4.125
4
# examples of printing strings with single and double quotes # print('strings go in single') # print("or double quotes") # printing an Integer with python: No quotes in integers/numbers print(299) # printing a string made of Integer (number) characters with python print("2017")
true
ec67d5050211e27b595231fa5f5f3ae31011b821
palaciosdiego/pythoniseasy
/src/fizzBuzzAssignment.py
630
4.15625
4
def isPrime(number): # prime number is always greater than 1 if number > 1: for i in range(2, number): if (number % i) == 0: return False # break else: return True # if the entered number is less than or equal to 1 # then it is not prime number else: return False for num in range(1, 101): if(num % 3 == 0): if(num % 5 == 0): print("FizzBuzz") else: print("Fizz") elif(num % 5 == 0): print("Buzz") else: print(num) if(isPrime(num)): print("Prime")
true
fbfd74756c1efd103b8958b594b2f876f9ed4876
arefrazavi/spark_stack
/spark_sql/select_teenagers_sql.py
1,769
4.15625
4
from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession, Row def convert_to_sql_row(line): row = line.split(',') return Row(id=int(row[0]), name=str(row[1]), age=int(row[2]), friends_count=int(row[3])) if __name__ == '__main__': sc_conf = SparkConf().setMaster('local[*]').setAppName('SelectTeenagers') sc = SparkContext(conf=sc_conf) # Since the dataset file doesn't have a header of columns, # we have to first create an rdd from file and them convert that to a dataframe. dataset_rdd = sc.textFile('dataset/fakefriends.csv') dataset_rows = dataset_rdd.map(convert_to_sql_row) # Create a SparkSQL session. spark = SparkSession.builder.appName('SelectTeenagers').getOrCreate() # Create a dataframe by inferring schema from row objects. dataset_df = spark.createDataFrame(dataset_rows).cache() # Three ways to select teenagers by filtering rows by age column # 1) Use filter function and conditions on dataframe object #teenagers_df = dataset_df.filter(dataset_df.age >= 13).filter(dataset_df.age <= 19).\ # orderBy(dataset_df.friends_count, ascending=False) # 2) Use filter function and sql-like conditions #teenagers_df = dataset_df.filter('age >= 13 AND age <= 19').orderBy('friends_count', ascending=False) # 3) Perform SQL query on the dataframe # 3.1) create a view of dataframe. dataset_df.createOrReplaceTempView('friends') # 3.2) Run SQL query on the view teenagers_df = spark.sql('SELECT * FROM friends WHERE age >= 12 AND age <= 19 ORDER BY friends_count DESC') # Print row objects for row in teenagers_df.collect(): print(row) # Print n rows of dataframe teenagers_df.show(n=20) spark.stop()
true
b3defea1bcb2f421c1d0ba8b54faf7f4a659ea43
EmersonPaul/MIT-OCW-Assignments
/Ps4/ps4a.py
1,929
4.34375
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. ''' if len(sequence) == 1: return [sequence] permutation_list = [] for letter in sequence: index = sequence.index(letter) for char in get_permutations(sequence[:index] + sequence[index + 1:]): permutation_list += [letter + char] return permutation_list def string_permutation(string): if len(string) == 1 or len(string) == 0: return 1 return len(string) * string_permutation(string[1:]) if __name__ == '__main__': # #EXAMPLE # example_input = 'abc' # print('Input:', example_input) # print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) # print('Actual Output:', get_permutations(example_input)) # # Put three example test cases here (for your sanity, limit your inputs # to be three characters or fewer as you will have n! permutations for a # sequence of length n) test_data = ['abc', 'bust', 'cd', 'rusty'] for data in test_data: permutation_list = get_permutations(data) print('The permutations are : ', permutation_list) print('Expected length of list: ', string_permutation(data)) print('Actual length : ', len(permutation_list))
true
ee37314201ebeace70e328eabf38777faedfd212
dairof7/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
641
4.15625
4
#!/usr/bin/python3 """ Module text_indentation module to ident a text print a text """ def text_indentation(text): """this functions print a text insert newline where find a ".", "?", ":" """ if type(text) != str or text is None: raise TypeError("text must be a string") sw = 0 for i in text: if i in [".", "?", ":"]: print(i, end="\n\n") sw = 1 else: if sw == 0: print(i, end="") else: if i == ' ': pass else: print(i, end="") sw = 0
true
e8ac9faefb389204d9bd193a0ba7e54b92498712
shikechen/LearnPython
/01_calculate_exchange_rate/calculate_exchange_rate.py
741
4.125
4
""" Author: shikechen Function: Convert RMB or USD according to a given exchange rate Version: 1.0 Date: 2018/12/24 """ rem_currency = 6.95 input_value = input("Please input money(Exit if input Q):") i = 0 while input_value != 'Q': i = i + 1 unit_value = input_value[-3:] digit_value = input_value[:-3] if unit_value == 'CNY': digit_cny = eval(digit_value) usd_value = digit_cny / rem_currency print(usd_value) elif unit_value == 'USD': digit_usd = eval(digit_value) cny_value = digit_usd * rem_currency print(cny_value) else: print("Input error!") input_value = input("Please input money(Exit if input Q):") print("You are exit!")
false
bb3c1324e8def64fbfddcfcba51d48ce526b40ae
PriyanjaniCh/Python
/henderson_method.py
2,980
4.3125
4
#!/usr/bin/python3 # Purpose: To implement the Henderson method # Execution: One argument for start number can be passed # # William F. Henderson III was a brilliant computer scientist who was taken from us all too soon. He had trouble falling asleep # because there were too many thoughts running through his head. The everyday method of counting sheep didn’t work for him because # it was too easy, leaving him too much time for other thoughts. So he invented the following method which required more calculation. # Start with the number 1000. Subtract 1 from it repeatedly (i.e., 999, 998, etc.) until you get a number ending in 0. (That will happen at 990.) # Then switch to subtracting 2’s, i.e., 988, 986, etc., until you again get a number ending in 0. Then switch to subtracting 3’s. # Every time you get a number ending in 0, increment the number you are subtracting. Stop when the next subtraction would cause the number to go negative. # This program is an implementation of the above method import sys print('\nNumber of arguments: ', len(sys.argv)) print('Argument List: ', str(sys.argv), '\n\n\n') # Validating the arguments passed if len(sys.argv) > 2: print('Wrong number of arguments\n\n') exit() elif len(sys.argv) > 1: if int(sys.argv[1]) < 0: print('Argument passed is Negative \n\n') exit() start_number = int(sys.argv[1]) else: start_number = 1000 count = 0 i = 1 total = 0 # total spoken numbers increment = 0 # total number of increments result = [] # list for the calculated output initial = [] # list for first two rows initial.append(['decrement','current','count','']) initial.append(['',str(start_number),'','']) number = start_number while True: number = number-i count = count+1 if number % 10 == 0 : print_count = '*'*count result.append([i, number, count, print_count]) i = i+1 count = 0 if number-i < 0: print_count = '*'*count if number != 0: result.append([i, number, count, print_count]) break # formats for lists initial and result format1 = '{:>10s}{:>10s}{:>10s}{}{:<14s}' format2 = '{:>10d}{:>10d}{:>10d}{}{:<14s}' for j in range(len(initial)): print(format1.format(initial[j][0],initial[j][1],initial[j][2], ' ',initial[j][3])) for j in range(len(result)): print(format2.format(result[j][0],result[j][1],result[j][2], ' ',result[j][3])) # calculating total spoken words and increment increment = len(result) for j in range(len(result)): total = total + result[j][2] print("\n\nThere were", total,"numbers spoken with", increment,"different increments.") print("Average cycles/incr = {:0.2f}.".format((total/increment))) passed = start_number-number print("\n\nThere were", passed, "numbers passed by with", increment, "different increments.") print("Average numbers/incr = {:0.2f}.".format(passed/increment))
true
7d8c224017d69a62bd0c8183aa8b7dc13c79e211
AlanRdgz/Mision_03
/Boletos.py
1,160
4.125
4
# Autor: Alan Giovanni Rodriguez Camacho A01748185 # Descripcion: Total a pagar de cierto numero de boletos para zonas distintas. def numeroBoletosA(a):#Te da el costo total dependiendo del numero de boletos de etsa zona atotal=a*3250 return atotal def numeroBoletosB(b):#Te da el costo total dependiendo del numero de boletos de etsa zona btotal=b*1730 return btotal def numeroBoletosC(c):#Te da el costo total dependiendo del numero de boletos de etsa zona ctotal=c*850 return ctotal def calcularPago(a,b,c):#Calcula el precio total a pagar entre todos los boletos precioTotal= numeroBoletosA(a)+numeroBoletosB(b)+numeroBoletosC(c) return precioTotal def main(): a= int(input("¿Cuantos boletos quiere de la zona A?: ")) b= int(input("¿Cuantos boletos quiere de la zona B?: ")) c= int(input("¿Cuantos boletos quiere de la zona C?: ")) calcularPago(a,b,c) precioTotal=calcularPago(a,b,c) print("Número de boletos en zona A: {0} ".format(a)) print("Número de boletos en zona B: {0} ".format(b)) print("Número de boletos en zona C: {0} ".format(c)) print("El costo total es: $%.2f"%precioTotal) main()
false
f390a60a44262785efe169930db6f56cba694885
hyperlearningai/introduction-to-python
/examples/my-first-project/myutils/collections/listutils.py
982
4.15625
4
#!/usr/bin/env python3 """Collection of useful tools for working with list objects. This module demonstrates the creation and usage of modules in Python. The documentation standard for modules is to provide a docstring at the top of the module script file. This docstring consists of a one-line summary followed by a more detailed description of the module. Sections may also be included in module docstrings, and are created with a section header and a colon followed by a block of indented text. Refer to https://www.python.org/dev/peps/pep-0008/ for the PEP 8 style guide for Python code for further information. """ def convert_to_dict(my_keys, my_values): """Merge a given list of keys and a list of values into a dictionary. Args: my_keys (list): A list of keys my_values (list): A list corresponding values Returns: Dict: Dictionary of the list of keys mapped to the list of values """ return dict(zip(my_keys, my_values))
true
67b83a8e4af2f594e3f7e1e50f12588fd68ffad2
SuchFNS/kettering
/cs191/dailyThings/ICA_0730_22.py
703
4.4375
4
print('List of months: January, February, March, April, May, June, July, August, September, October, November, December') month = input('Input a month: ') if (month.upper() == 'JANUARY' or month.upper() == 'MARCH' or month.upper() == 'MAY' or month.upper() == 'JULY' or month.upper() == 'AUGUST' or month.upper() == 'OCTOBER' or month.upper() == 'DECEMBER' ): print('There are 31 days this month') elif (month.upper() == 'APRIL' or month.upper() == 'JUNE' or month.upper() == 'SEPTEMBER' or month.upper() == 'NOVEMBER' ): print('There are 30 days this month') elif (month.upper() == 'FEBRUARY'): print('There are 28 days this month') else: print('You input a wrong month, please try again')
false
b752e89398d424ec93433eb14083f898431ce8bd
mcp292/INF502
/src/midterm/2a.py
726
4.4375
4
''' Approach: I knew I had to run a for loop it range of the entered number to print the asterisks. The hard part was converting user input to a list of integers. I found out a good use for list comprehension, which made the code a one liner. ''' nums = input("Enter 5 comma separated numbers between 1 and 20: ").split(",") # convert list of strings to list of ints try: nums = [int(num) for num in nums] # list comprehension except ValueError: print("\nEntry must be a number!\nTerminating program...\n") exit() for num in nums: if (num <= 20): for iter in range(num): print("*", end='') print() else: print("Number out of range! {}".format(num))
true
c7443de044ebc3149c37b398ee230d21ca784bee
johnnymango/IS211_Assignment1
/assignment1_part1.py
1,969
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Assignment 1 - Part 1""" def listDivide(numbers=[], divide=2): """ The function returns the number of elements in the numbers list that are divisible by divide. Args: numbers(list): a list of numbers divide (int, default=2): the number by which numbers in the list will be divided by. Returns: count(int): the count of numbers divisible by divide where remainder = 0. Example: >>> listDivide([2, 4, 6, 8, 10]) 5 """ count=0 for i in numbers: remainder = i % divide if remainder == 0: count=count+1 return count class ListDivideException(Exception): """A custom Exception Class to be raised when errors are created.""" pass def testListDivide(): """A function to test the listDivide function and raise an exception when the test fails. Args: None Returns: An exception when the expected result from the test fails. Example: Traceback (most recent call last): File "C:/Users/Johnny/PyCharmProjects/IS211_Assignment1/assignment1_part1.py", line 62, in <module> testListDivide() File "C:/Users/Johnny/PyCharmProjects/IS211_Assignment1/assignment1_part1.py", line 51, in testListDivide raise ListDivideException("Test 2 Error") __main__.ListDivideException: Test 2 Error """ test1 = listDivide([1, 2, 3, 4, 5]) if test1 != 2: raise ListDivideException("Test 1 Error") test2 = listDivide([2,4,6,8,10]) if test2 != 5: raise ListDivideException("Test 2 Error") test3 = listDivide([30, 54, 63, 98, 100], divide=10) if test3 !=2: raise ListDivideException("Test 3 Error") test4 = listDivide([]) if test4 != 0: raise ListDivideException ("Test 4 Error") test5 = listDivide([1,2,3,4,5], 1) if test5 != 5: raise ListDivideException ("Test 5 Error") testListDivide()
true