blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3c47d535501c877aae1e7c115534d309f9cfac32
indexcardpills/python-labs
/15_generators/15_01_generators.py
237
4.3125
4
''' Demonstrate how to create a generator object. Print the object to the console to see what you get. Then iterate over the generator object and print out each item. ''' daniel = (x+'f' for x in "hello") for x in daniel: print(x)
true
eb2128c3f33e18a27de998a58e00a0c1056d28d3
indexcardpills/python-labs
/04_conditionals_loops/04_07_search.py
575
4.15625
4
''' Receive a number between 0 and 1,000,000,000 from the user. Use while loop to find the number - when the number is found exit the loop and print the number to the console. ''' while True: number = int(input("Enter a number between 0 and 1,000,000,000: ")) x = 7 if number < x: print("no, higher") if number > x: print("no, lower") if number == x: print("correct, the number is 7") break #Is this what I was supposed to do? If not, I don't understand what is meant by "finding the number", if #I'm inputting it myself
true
a4508650196850cea3aecd960dd0e9a06c98cbe3
indexcardpills/python-labs
/10_testing/10_01_unittest.py
690
4.34375
4
''' Demonstrate your knowledge of unittest by first creating a function with input parameters and a return value. Once you have a function, write at least two tests for the function that use various assertions. The test should pass. Also include a test that does not pass. ''' import unittest def multiply(x, y): return x*y-x print(multiply(2, 4)) # import unittest # x=2 # y=3 class Testtimes(unittest.TestCase): def test_times(self): self.assertEqual((multiply(2, 3)), (6)) self.assertEqual(multiply(3, 10), 30) def test_times_two(self): self.assertIs(multiply(5, 9), 45, "this failed") # if __name__ == '__main__': unittest.main()
true
2ca18b8597a9d80d73fd7d1da52f7691664b5bf4
indexcardpills/python-labs
/04_conditionals_loops/04_05_sum.py
791
4.3125
4
''' Take two numbers from the user, one representing the start and one the end of a sequence. Using a loop, sum all numbers from the first number through to the second number. For example, if a user enters 1 and 100, the sequence would be all integer numbers from 1 to 100. The output of your calculation should therefore look like this: The sum is: 5050 ''' sum_number=0 first_number = 5 second_number = 9 range_numbers = range(first_number, second_number+1) for x in range_numbers: print(sum_number+first_number) if sum_number == second_number+1: break # I think I'm getting closer? But now I don't know what else to do. I initialized a variable outside # the for loop, but beyond that, I don't know what to do with it exactly. With this I just get 5 printed # 5 times.
true
0ef559fbb64de7780dda09df151d2e4482bc1410
tonynguyen99/python-stuff
/guess number game/main.py
945
4.25
4
import random def guess(n): random_number = random.randint(1, n) guess = 0 while guess != random_number: guess = int(input(f'Guess a number between 1 and {n}: ')) if guess > random_number: print('Too high!') elif guess < random_number: print('Too low!') print('You got it!') def computer_guess(n): lowestNumber = 1 highestNumber = n feedback = '' while feedback != 'c': if lowestNumber != highestNumber: guess = random.randint(lowestNumber, highestNumber) else: guess = lowestNumber feedback = input(f'Is the computers guess {guess} correct (C), too high (H) or too low (L)? ') if feedback.lower() == 'h': highestNumber = guess - 1 elif feedback.lower() == 'l': lowestNumber = guess + 1 print(f'The computer guessed your number {guess} correctly!') computer_guess(10)
true
b51af61c9960b18b8829708f6a0d3a8f18a5fd2f
sathvikg/if-else-statement-game
/GameWithBasics.py
1,463
4.1875
4
print("Welcome to your Game") name = input("What is your name? ") print("hi ",name) age = int(input("What is your age? ")) #print(age) #print(name,"you are good to go. As you are",age,"years old") health = 10 print("you are starting with ",health,"health") if age > 18: print("you can continue the game.") want_to_play = input("Dow you want to play?") if want_to_play.lower() == 'yes': print("lets play ") choice = input("you wanna go left or right? ") if choice.lower() == "left": ans = input("you came the right way. Now you follow and reach the lake. Do you wanna swim or go around? ") if ans.lower() == "around": print("you went around and reached the other side of the lake.") elif ans.lower() == "across": print("you went around and lost 5 health.") health-=5 ans2 = input("you notice a house and river. where do you go? ") if ans2.lower() == 'house': print("you went to the house and you are safe.") else: print('you couldnt swim now.') health-=5 if health == 0: print("you lose") else: print("you went in the wrong way") else: print("see you then") else: print("you cannot continue the game") #print("The game begins")
true
f642a041bcda31d628b16181016fae4cbb9c128d
nikonoff16/Simple_Number
/simple.py
1,576
4.15625
4
#Создаем переменную quest_number = int(input("Введите число ")) # концепция проекта такая: если число простое, то при делению по модулю всегда будет остаток. Если посчитать эти остатки # и сравнить их с самим числом за вычетом двух из него, то можно понять, простое оно или нет. cycle_th = quest_number - 1 counter = 0 control_number = quest_number - 2 #Проводим базовый отвев числа if quest_number == 2: print('Простое число') elif quest_number % 2 == 0: print("Дурачок чтоли? посмотри на последнюю цифру в том, что ты нарисовал здесь!!!") else: #Проводим дальнейшую провеку на простоту while cycle_th >= 2: module_num = quest_number % cycle_th cycle_th -= 1 if module_num > 0: counter += 1 # if control_number - counter == 0: print("Это элементарно, Ватсон - число простое") else: print("Число не так просто, как кажется") #Проверял таким образом то, какие результаты у меня в переменных хранились. print("Проверка: Счетчик равен " + str(counter) + " итератор - " + str(cycle_th) + " контрольная сумма равна " + str(control_number))
false
d3246fddc314795c42ec10a19be60f2c0e026675
GaborVarga/Exercises_in_Python
/46_exercises/8.py
1,124
4.34375
4
#!/usr/bin/env python ####################### # Author: Gabor Varga # ####################### # Exercise description : # Define a function is_palindrome() that recognizes palindromes # (i.e. words that look the same written backwards). # For example, is_palindrome("radar") should return True. # # http://www.ling.gu.se/~lager/python_exercises.html ########### # imports # ########### from pip._vendor.distlib.compat import raw_input from builtins import int ############### # Function(s) # ############### def ispalindrome(inputstring) : if(len(inputstring)%2==0): return inputstring[:int(len(inputstring)/2)] == \ reverse(inputstring[int(len(inputstring)/2):]) else : return inputstring[:int((len(inputstring)-1)/2)]== \ reverse(inputstring[int(((int(len(inputstring))-1)/2)*-1):]) def reverse(inputstring): result = "" for karakter in inputstring: result = karakter + result return result ########## # Script # ########## inputstring = raw_input("Please enter a string: \n") print("Is it a plaindrome? ",ispalindrome(inputstring))
true
e7e4117d2f583ceedce8c4cdba546523d9532ac8
UCdrdlee/ScientificComputing_HW0
/fibonacci.py
2,824
4.5
4
""" fibonacci functions to compute fibonacci numbers Complete problems 2 and 3 in this file. """ import time # to compute runtimes from tqdm import tqdm # progress bar # Question 2 def fibonacci_recursive(n): if n == 0: return 0 if n == 1: return 1 else: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) pass # Question 2 def fibonacci_iter(n): if n == 0: return 0 a=0 b=1 while n-1>0: a,b = b, a+b n-=1 return b pass print("The first 30 fibonacci numbers using fibonacci_recursive is: ") for i in range(0,30): print(fibonacci_recursive(i)) print("The first 30 fibonacci numbers using fibonacci_iter is: ") for i in range(0,30): print(fibonacci_iter(i)) import numpy as np # Question 3 def fibonacci_power(n): # The matrix A and vector x_1 are given and can be defined in NumPy arrays. A = np.array([[1,1],[1,0]]) x_1 = np.array([1,0]) # We define what F_0 should be, which is 0. if n == 0: return 0 else: def power(mat, i): def isodd(i): """ returns True if n is odd """ return i & 0x1 == 1 if i == 0: # when n=1, the output should be just x_1 return np.identity(2) if isodd(i): return power(mat@mat, i//2)@mat else: return power(mat@mat, i//2) x_n = power(A,n-1)@x_1 # we need just the first element of x_n return int(x_n[0]) for i in range(0,30): print(fibonacci_power(i)) if __name__ == '__main__': """ this section of the code only executes when this file is run as a script. """ def get_runtimes(ns, f): """ get runtimes for fibonacci(n) e.g. trecursive = get_runtimes(range(30), fibonacci_recusive) will get the time to compute each fibonacci number up to 29 using fibonacci_recursive """ ts = [] for n in tqdm(ns): t0 = time.time() fn = f(n) t1 = time.time() ts.append(t1 - t0) return ts nrecursive = range(35) trecursive = get_runtimes(nrecursive, fibonacci_recursive) niter = range(10000) titer = get_runtimes(niter, fibonacci_iter) npower = range(10000) tpower = get_runtimes(npower, fibonacci_power) ## write your code for problem 4 below... import matplotlib.pyplot as plt plt.loglog(nrecursive,trecursive, label=f"Recursive") plt.loglog(niter,titer, label=f"Iteration") plt.loglog(npower,tpower, label=f"Power") plt.legend() plt.xlabel("n") plt.ylabel("run time") plt.title("Fibonacci Algorithm Run Times (log-log)") plt.show() plt.savefig('Fibonacci_runtime.png')
true
837b4fe80020202ed9b37e0ac5dc0f868ec0aa8f
Yagomfh/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
713
4.34375
4
#!/usr/bin/python3 """Module that that adds 2 integers. Raises: TypeError: if a or b are not int or floats """ def add_integer(a, b=98): """Function that adds 2 integers Args: a (int/float): first digit b (int/float): second digit Returns: Int sum of both digits """ if type(a) != int and type(a) != float: raise TypeError('a must be an integer') if type(b) != int and type(b) != float: raise TypeError('b must be an integer') try: a = int(a) except Exception: raise TypeError('a must be an integer') try: b = int(b) except Exception: raise TypeError('b must be an integer') return a + b
true
c0a7efc9d8720a168c1677b413d2a86f8a494fe6
kadahlin/GraphAlgorithms
/disjoint_set.py
1,877
4.15625
4
#Kyle Dahlin #A disjoint set data structure. Support finding the set of a value, testing if #values are of hte same set, merging sets, and how may sets are in the entire #structure. class Disjoint: def __init__(self, value): self.sets = [] self.create_set(value) def create_set(self, value): """ Add a new grouping (set) that only contains this value """ self.sets.append(set(value)) def merge_sets(self, value1, value2): """ Merge the sets containing the two values if they are not already in the same set """ if not self.test_same_set(value1, value2): set1 = self.find_set(value1) set2 = self.find_set(value2) new_set = set1.union(set2); self.sets.remove(set2) self.sets.remove(set1) self.sets.append(new_set) def find_set(self, value): """ Return the set that value belongs to """ for s in self.sets: if value in s: return s def test_same_set(self, value1, value2): """ Return a boolean stating whether or not the two values are in the same set """ return self.find_set(value1) == self.find_set(value2) def size(self): """ Return how many sets are in the structure """ return len(self.sets) if __name__ == '__main__': #Sanity test for myself when making this""" d = Disjoint('A') for char in ['B', 'C', 'D', 'E']: d.create_set(char) assert not d.test_same_set('A', 'B') assert not d.test_same_set('C', 'D') d.merge_sets('A', 'D') d.merge_sets('B', 'C') assert d.test_same_set('A', 'D') assert d.test_same_set('C', 'B') assert not d.test_same_set('A', 'C') d.merge_sets('B', 'D') assert d.test_same_set('A', 'C')
true
fb8318baba89169105e27fdc76b00e80888fb222
Mone12/tictactoe-python
/.vscode/tictactoe.py
1,176
4.1875
4
import random ## Need to establish which player goes first through randomization player = input("Please enter your name:") cpu = "CPU" p_order = [player,cpu] if player: random.shuffle(p_order) if p_order[0] == player: print(f"{player} you are Player 1. You go first!") print(f"{cpu} is Player 2!") elif p_order[0] == cpu: print(f"{cpu} is Player 1. They go first!") print(f"{player} your Player 2!") ## Need to draw board a = [["-","-","-"],["-","-","-"],["-","-","-"]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=" ") print() ## Need to assign X or O to each player ## Randomize who gets X or O ## Need to start game once Players and turns are established ## While loop in game ## Need to assign x and o to area on board player chooses ## CPU chooses randomly ## Game stops when a player gets 3 in a row ## Need to display winner when game is over ## Give score ## Be able to play again ## WHile Loop false ## Game ends when the first player reaches 3 points ## Increment points and display them ## Be able to start whole game over ## Second while loop false
true
7182d6fa3958283a46dfdb5b9f4b6c5eea17055d
kontai/python
/面向對象/運算符重載/classMethod.py
970
4.25
4
# Copyright (c) 2019. # classMethod.py # class FirstClass: def setdata(self, value): self.data = value def display(self): print(self.data) class SecondClass(FirstClass): def display(self): print("Current data is %s" % self.data) class ThirdClass(SecondClass): def __init__(self, value): self.data = value # 重載'+' def __add__(self, other): return ThirdClass(self.data + other) # 重載'str' def __str__(self): return '[ThirdClass: %s]' % self.data # 重載'*' def mul(self, other): self.data *= other if __name__ == '__main__': x = SecondClass() x.setdata("2nd class") x.display() # 覆蓋FirstClass display方法 a = ThirdClass('abc') a.display() # 繼承SecondClass display菲奧法 print(a) # __str__被調用 b = a + 'xyz' # __add__被調用 b.display() print(b) # __str__被調用 a.mul(3) print(a)
false
d867547f67b3c2697fffaabdccd39b4571ee473c
smukh93/Python_MITx
/iter_pow.py
606
4.125
4
def iterPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' # Your code here prod = 1 if exp == 0: return 1 else: for x in range(exp): prod *=base return prod def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' # Your code here if exp == 0: return 1 else: return base * recurPower(base,exp-1) exp = int(input('Enter exp: ')) base = int(input('Enter base: ')) print(iterPower(base,exp))
true
a3a152ffc0a8fb2fe28def7b018ef54f4a65506d
gourav287/Codes
/Codechef-and-Hackerrank/NoOfStepsToReachAGivenNumber.py
1,304
4.15625
4
# -*- coding: utf-8 -*- """ Question Link: https://practice.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1 Given an infinite number line. You start at 0 and can go either to the left or to the right. The condition is that in the ith move, youmust take i steps. Given a destination D , find the minimum number of steps required to reach that destination. """ # Function to calculate minimum no of steps def minSteps(self, D): # Initializing source to track current place source = 0 # i will track the length of next move i = 1 # Keep going forward as it will minimize steps while source < D: source += i i += 1 # Distance remaining to reach diff = source - D # If distance remaining is odd, we need to make it even while diff % 2 != 0: source += i diff = source - D i += 1 # If distance is even, it means altering a few steps taken will # lead us to destination, hence this is the answer return i - 1 # Driver Code if __name__ == '__main__': # No of test cases for _ in range(int(input())): # Destination D = int(input()) #Calling the required function print(minSteps(D))
true
089e2881ecc68c06e9fd9fe958d4ccd1414d55d0
gourav287/Codes
/BinaryTree/TreeCreation/CreateTreeByInorderAndPreorder.py
2,259
4.28125
4
""" Implementation of a python program to create a binary tree when the inOrder and PreOrder traversals of the tree are given. """ # Class to create a tree node class Node: def __init__(self, data): # Contains data and link for both child nodes self.data = data self.left = None self.right = None # Function to print the inorder traversal of a tree, once created def printInorder(start): # if the tree exists if start: # Traverse left subtree printInorder(start.left) # print value print(start.data, end = " ") # Traverse right subtree printInorder(start.right) """ Creation of the Tree from inOrder and preOrder traversals """ def createTree(inOrder, preOrder, left, right): # A global variable to keep track of current preOrder element global cur_ind # If no element in the desired part of list if left > right: return None # Create a tree node from element of preOrder traversal # Increase the global variable's index value tmp = Node(preOrder[cur_ind]) cur_ind += 1 # If left == right then the node is leaf # Else work on to create child nodes as follows if left != right: # Getting the index in inOrder # This tells us about left and right subtree # of the current node ind = inOrder.index(tmp.data) # Recursively run the code for left subtree tmp.left = createTree(inOrder, preOrder, left, ind - 1) # Recursively run the code for right subtree tmp.right = createTree(inOrder, preOrder, ind + 1, right) # Returning the node to be added to the tree return tmp # The driver code if __name__ == '__main__': # inOrder traversal of the tree inOrder = list(map(int, input().split())) #[1, 2, 3, 4, 5, 6, 7] # preOrder traversal of the tree preOrder = list(map(int, input().split())) #[4, 2, 1, 3, 6, 5, 7] # Index to keep track of preOrder elements cur_ind = 0 # Function to create the tree from inOrder and preOrder # traversal given to us start = createTree(inOrder, preOrder, 0, len(inOrder) - 1) # printing the inOrder traversal of the tree created printInorder(start)
true
263b8fdfdc3989979ec92e72110fd79be8ead6fd
gourav287/Codes
/Codechef-and-Hackerrank/Binary_to_decimal_recursive.py
740
4.34375
4
# -*- coding: utf-8 -*- """ Write a recursive code to convert binary string into decimal number """ # The working function def bin2deci(binary, i = 0): # Calculate length of the string n = len(binary) # If string has been traversed entirely, just return if i == n - 1: return int(binary[i]) # Left shifting i-th value to n-i-1 positions will actually multiply # it with 2**(n-i-1) This will then be added to values at other i # and final solution will be returned return ((int(binary[i])<<(n-i-1)) + bin2deci(binary, i + 1)) # The driver code if __name__ == "__main__": # Input the string binary = input() # Print the output print(bin2deci(binary))
true
ed43aa7eacb8f54d80102e3b05a2147451b636a8
januarytw/Python_auto
/class_0605/0605作业.py
1,702
4.15625
4
# 1:创建一个名为 Restaurant 的类,其方法 init ()设置两个属性: restaurant_name 和 cooking_type。 # 创建一个名为 describe_restaurant()的方法和一个名为 open_restaurant()的方法,其中前者打印前述两项信息, # 而后者打印一条消息, 指出餐馆正在营业。 根据这个类创建一个名为 restaurant 的实例,分别打印其两个属性,再调用前述两个方法。 class Restaurant(): def __init__(self,restaurant_name,cooking_type): self.restaurant_name=restaurant_name self.cooking_type=cooking_type def describe_restaurant(self): print("餐厅名字:%s 主营:%s"%(self.restaurant_name,self.cooking_type)) def open_restaurant(self): print("餐厅正在营业!") restaurant=Restaurant("蜀国演义","川菜") restaurant.describe_restaurant() restaurant.open_restaurant() # 2:继承1 这个类,且添加函数:discount 打折扣用的 pay_money 支付餐费用 完成调用 class Restaurant_1(Restaurant): def discount(self,pay_money): print("您将享受8折优惠,优惠后价格:%s"%(int(pay_money)*0.8)) restaurant_1=Restaurant_1("海底捞","火锅") restaurant_1.describe_restaurant() restaurant_1.open_restaurant() restaurant_1.discount(100) # 3:超继承1这个类的open_restaurant方法,多加一个优惠信息宣传。 class Restaurant_2(Restaurant): def open_restaurant(self): super(Restaurant_2,self).open_restaurant() print("餐厅正在营业,消费满100,可以享受8折优惠!") restaurant_2=Restaurant_2("郭林家常菜","东北菜") restaurant_2.describe_restaurant() restaurant_2.open_restaurant()
false
a056d2b012f5d2d3c8b0cb46cd26e5a960550970
HANZ64/Codewars
/Python/8-kyu/07. Return Negative/index.py
1,405
4.15625
4
''' Title: Return Negative Kata Link: https://www.codewars.com/kata/return-negative Instructions: In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? Example: make_negative(1); # return -1 make_negative(-5); # return -5 make_negative(0); # return 0 Notes: • The number can be negative already, in which case no change is required. • Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. Problem: def make_negative( number ): # ... ''' #=============================================# # My solution: def make_negative(number): if (number < 0): return number return -number #=============================================# # 1. Alternative Solution: def make_negative(number): return -abs(number) # 2. Alternative Solution: def make_negative( number ): return (-1) * abs(number) # 3. Alternative Solution: def make_negative( number ): return -number if number>0 else number # 4. Alternative Solution: def make_negative(number): if number >= 0: return (0 - number) else: return number # 5. Alternative Solution: def make_negative( number ): if number < 0: return number else: return number * -1 #=============================================#
true
a93e2fab8fe0972396945484bf75634184a2bf70
albihasani94/PH526x
/week3/word_stats.py
645
4.1875
4
from week3.counting_words import count_words from week3.read_book import read_book def word_stats(word_counts): """Return number of unique words and their frequencies""" num_unique = len(word_counts) counts = word_counts.values() return (num_unique, counts) text = read_book("./resources/English/shakespeare/Romeo and Juliet.txt") word_counts = count_words(text) (num_unique, counts) = word_stats(word_counts) print(num_unique, sum(counts)) text = read_book("./resources/German/shakespeare/Romeo und Julia.txt") word_counts = count_words(text) (num_unique, counts) = word_stats(word_counts) # print(num_unique, sum(counts))
true
be8849979ce06c3cfa24cae9fb933e6673de5a3d
af94080/dailybyte
/next_greater.py
1,066
4.21875
4
""" This question is asked by Amazon. Given two arrays of numbers, where the first array is a subset of the second array, return an array containing all the next greater elements for each element in the first array, in the second array. If there is no greater element for any element, output -1 for that number. Ex: Given the following arrays… nums1 = [4,1,2], nums2 = [1,3,4,2], return [-1, 3, -1] because no element in nums2 is greater than 4, 3 is the first number in nums2 greater than 1, and no element in nums2 is greater than 2. nums1 = [2,4], nums2 = [1,2,3,4], return [3, -1] because 3 is the first greater element that occurs in nums2 after 2 and no element is greater than 4. """ nums1 = [1,2,3,4] nums2 = [2,4] def next_greater_element(n1, n2): if len(n1) < len(n2): smaller, bigger = n1, n2 else: smaller, bigger = n2, n1 out = [] for ele in smaller: right_list = bigger[bigger.index(ele)+1:] next_gt_ele = next((x for x in right_list if x > ele), -1) out.append(next_gt_ele) return out print(next_greater_element(nums1, nums2))
true
3941ff68870c3b573885de1fb512c97953d29dcf
pjm8707/Python_Beginning
/py_basic_datatypes.py
2,077
4.28125
4
import sys print("\npython data types -Numeric") #create a variable with integer value a=100 print("The type of variable having value", a, "is", type(a)) print("The maximum interger value", sys.maxsize) print("The minimum interger value", -sys.maxsize-1) #create a variable with float value b=10.2345 print("The type of variable having value", b, "is", type(b)) #create a variable with complex value c=100+3j print("The type of variable having value", c, "is", type(c)) print("\npython data type - String") d="string in a double quote" e='string in a single quote' print("The type of variable having value", d, "is", type(d)) print("The type of variable having value", e, "is", type(e)) #using ',' to concatenate the two or several strings print(d, "concatenated with", e) print(d+" concatenated with "+e) print("\npython data typed - List") #list of having only integer f=[1,2,3,4,5] print("list f is:",f) #list of having only strings g=["hey", "you", 1,2,3, "go"] print("list g is:",g) #index are 0 based. this will prnt a single character print(g[1]) # this will print "you" in list g print("\npython data type - Tuple") #Tuple is another data type which is a sequence of data similar to list. But it is immutable. #That means data in a tuple is write protected. #Data in a tuple is wrriten using parenthesis and commas. #tuple having only integer type of data h=(1,2,3,4) print("tuple h is:", h) #tuple having multiple type of data i=("hello", 1, 2, 3, "go") print("tuple i is :", i) #index of tuples are also 0 based print("i[4] is ", i[4], "in tuple i") print("\npython data type - Dictionary") #Python Dictionary is an unordered sequence of data of key-value pair form. #It is similar to the hash table type. Dictionaries are written within curly braces in the form key:vale. #It is very useful to retrive data in an optimized way among large amount of data. #a sample dictionary variable j={1:"first name", 2:"second name", "age":3} print(j[1]) print(j[2]) print(j["age"])
true
1f9bd3a166434e6f800e9f01938fd3bf615c5ec9
inesjoly/toucan-data-sdk
/toucan_data_sdk/utils/postprocess/rename.py
976
4.25
4
def rename(df, values=None, columns=None, locale=None): """ Replaces data values and column names according to locale Args: df (pd.DataFrame): DataFrame to transform values (dict): - key (str): term to be replaced - value (dict): - key: locale - value: term's translation columns (dict): - key (str): columns name to be replaced - value (dict): - key: locale - value: column name's translation locale (str): locale """ if values: to_replace = list(values.keys()) value = [values[term][locale] for term in values] df = df.replace(to_replace=to_replace, value=value) if columns: _keys = list(columns.keys()) _values = [column[locale] for column in columns.values()] columns = dict(list(zip(_keys, _values))) df = df.rename(columns=columns) return df
true
6bee3da547307daf0e4245423a159b4196dcd025
Vishal0442/Python-Excercises
/Guess_the_number.py
480
4.21875
4
#User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, #on successful guess, user will get a "Well guessed!" message, and the program will exit import random while True: a = random.randint(1,9) b = int(input("Guess a number : ")) if a == b: print ("Congrats!! Well Guessed...\n") break else: print ("Oops...Wrong Guess!! Try again...\n")
true
3ecfd62848650e4bfe40cb5907d31eb9398e18c5
nikhil-jayswal/6.001
/psets/ps1b.py
1,002
4.21875
4
# Problem Set 1b # Nikhil Jayswal # # Computing sum of logarithms of all primes from 2 to n # from math import * #import math to compute logarithms n = int(raw_input('Enter a number (greater than 2): ')) start = 3 #the second prime; don't need this can do candidate = 3 log_sum = log(2) #sum of logarithms of primes, first prime is 2 candidate = start while (candidate <= n): #upto n divisor = 2 flag = 0 while (divisor < candidate): if (candidate % divisor == 0): #if any number divides candidate, i.e.not prime flag = 1 break divisor = divisor + 1 #else, update divisor if flag == 0: #if prime, update log_sum log_sum += log(candidate) candidate = candidate + 2 #update candidate ratio = log_sum / n #log_sum should be float, hence division should be proper print 'n = ', n print 'Sum of logarithms of primes upto', n, 'is', log_sum print 'Ratio of sum of logarithm of primes to n is', ratio # Code works but results not verified
true
b6ccbbb9ab29a1cbe46ef64731dad597b94c337b
GaneshGoel/Basic-Python-programs
/Grades.py
555
4.125
4
#To print grades x=int(input("Enter the marks of the student:")) if(x<=100 or x>=0): if(x>90 and x<=100): print("O") elif(x>80 and x<=90): print("A+") elif(x>70 and x<=80): print("A") elif(x>60 and x<=70): print("B+") elif(x>50 and x<=60): print("B") elif(x>40 and x<=50): print("C") elif(x>30 and x<=40): print("D") else: print("Fail") else: print("Invalid input")
true
ee5f0793f86f7396d38234c1ac621a387fa768f2
kt00781/Grammarcite
/AddingWords.py
826
4.1875
4
from spellchecker import SpellChecker spell = SpellChecker() print("To exit, hit return without input!") while True: word = input("Input the word that you would like to add to the system: ") if word == '': break word = word.lower() if word in spell: print ("Word ({}) already in Dictionary!".format(word)) else: print ("Word ({}) is not currently in the Dictionary, would you like to add it?".format(word)) new_word = input("Input y if you would like to add this word other wise click return: ") if word == '': break new_word = new_word.lower() if new_word == 'y': spell.word_frequency.add('{}'.format(word)) else: print("Invalid input please click return to exit and rerun the program!") break
true
d03bc8035c16bdef2486f27e59d3e430b178790c
Leofariasrj25/simple-programming-problems
/elementary/python/sum_multiples(ex5).py
258
4.34375
4
print("We're going to print the sum of multiples of 3 and 5 for a provided n") n = int(input("Inform n: ")) sum = 0 # range is 0 based so we add 1 to include n for i in range(3, n + 1): if i % 3 == 0 or i % 5 == 0: sum += i print(sum)
true
3042b228dba1572138e2216bcef1f3dac8f0368b
CTTruong/9-19Assignments
/Palindrome.py
455
4.1875
4
def process_text(text): text = text.lower() forbidden = ("!", "@", "#") for i in forbidden: text = text.replace(i, "") return text def reverse(text): return text[::-1] def is_palindrome(text): new = process_text(text) return process_text(text) == reverse(process_text(text)) something = input("Enter word: ") if (is_palindrome(something)): print("You got a palindrome") else: print("It is not a palindrome")
true
d0c094920da68f24db3d489cab6c1f2e37a17787
yeshwanthmoota/Python_Basics
/lambda_and_map_filter/map_filter.py
1,148
4.3125
4
nums=[1,2,3,4,5,6,7,8,9] def double(n): return n*2 my_list=map(double,nums) print(my_list) def even1(n): return n%2==0 def even2(n): if(n%2==0): return n my_list=map(even2,nums) #This doesn't return a list it returns- #-address of the genrators of the operation performed. print(my_list) my_list=list(map(even2,nums)) print(my_list) # If we don't want to actually define a function just for # single purpose we can use lamda functions. my_list=list(map(lambda n: n*n,nums)) print(my_list) # with map we cannot decide which to choose i mean see below my_list=list(map(lambda n: n%2==0,nums)) print(my_list) # The Output is "[False, True, False, True, False, True, False, True, False]" # But that is not we wanted we wanted to print "[2, 4, 6, 8]" # For this we have to select the elements for which n%2==0 is true for that purpose # We have filter function it appends the element to the list if the # condition in the function section comes out to be true. my_list=list(filter(lambda n: n%2==0,nums)) print(my_list) # Now the Output is "[2, 4, 6, 8]" as we expected. my_list=list(map(lambda n: n*n,nums)) print(my_list)
true
4abe4684d196821bdc39592e31e3b94d21f8e22b
yeshwanthmoota/Python_Basics
/comprehensions/zip_function.py
433
4.125
4
names=["Bruce","Clark","Peter","Logan","Wade"] heroes=["Batman","Superman","Spiderman","Wolverine","Deadpool"] # Now to use the zip function Identity_list=list(zip(names,heroes)) print(Identity_list) Identity_tuple=tuple(zip(names,heroes)) print(Identity_tuple) Identity_dict=dict(zip(names,heroes)) # This is important names goes into key and # Heroes goes into value of each key-value pair in the dictionary. print(Identity_dict)
true
866832f1f7e1429b4462491be12a4891f10934f7
rivergillis/mit-6.00.1x
/midterm/flatten.py
614
4.34375
4
def flatten(aList): ''' aList: a list Returns a copy of aList, which is a flattened version of aList [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5] ''' if aList == []: return [] print(aList) for index,elem in enumerate(aList): print(elem) if type(elem) == list: print("Is a list") return flatten(elem) + flatten(aList[index+1:]) else: print("Is not a list") return [elem] + flatten(aList[index+1:]) print(flatten([[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]))
true
d5dae53d28dc9f6964c7adf0f83a5a5359309792
Gaurav-dawadi/Python-Assignment
/Function/question19.py
226
4.25
4
"""Write a Python program to create Fibonacci series upto n using Lambda.""" fib = lambda n: n if n<=1 else fib(n-1)+fib(n-2) # print(fib(10)) print("The Fibonacci Series is :") for i in range(10): print(fib(i))
false
6406ba8d6fa1df233b6bd4ed010c5061bab39066
Gaurav-dawadi/Python-Assignment
/Data Types/question21.py
909
4.28125
4
"""Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.""" def getListOfTuples(): takeList = [] num = int(input("Enter number of tuples you want in list: ")) for i in range(num): takeTuples = () for j in range(2): inputElement = int(input("Enter an element for a tuple: ")) takeTuples = takeTuples + (inputElement, ) takeList.append(takeTuples) print("---------------------------------------------------") print("The unsorted list of tuples is ",takeList) print("---------------------------------------------------") return takeList def getSortedList(): unsortedList = getListOfTuples() sortedList = sorted(unsortedList, key = lambda tup: tup[1]) return sortedList print("The sorted List is ", getSortedList())
true
79a49b8caf4291c0c762e81a851212cc509e6c6a
Joyce-O/Register
/treehouse_python_basics.py/masterticket.py
1,514
4.125
4
TICKET_PRICE = 10 tickets_remaining = 100 #Run tickets untill its sold out while tickets_remaining >= 1: # Output how many tickets are remaining using the tickets remaining variable print("There are {} tickets remaining.".format(tickets_remaining)) # Gather the user's name and assign it to a new variable name = input("What is your name? ") # Prompt the user by name and ask how many tickets they would loke num_tickets = input("How many tickets would you like, {}? ".format(name)) # Catch error when a non number is inputed try: num_tickets = int(num_tickets) #Coarce it because input() always returns a string print(num_tickets) if num_tickets > tickets_remaining: raise ValueError("There are only {} remaining".format(tickets_remaining)) except ValueError as err: # The as err keywords are used only when you have a raise keyword before the except print("Sorry an error occured") else: # Calculate the price (number of tickets multiplied by the price) and assign it to a variable amount_due = num_tickets * TICKET_PRICE # Output the price in the screen print("The total due is ${}".format(amount_due)) should_proceed = input("Do you want to proceed? Y/N ") if should_proceed.lower == 'y': print('SOLD') tickets_remaining -= num_tickets else: print("Thank you {}".format(name)) print("Sorry tickets are sold out")
true
d5498151efd9677fe5247d12c6b4956822937f60
erin-weeks/hello_world
/8_person.py
777
4.46875
4
#Building more complicated data structures '''This exercise takes various parts of a name and then returns a dicionary.''' def build_person(first_name, last_name, age = ''): '''Return a dictionary of information about a person''' person = {'first': first_name, 'last': last_name} '''Because age is optional, we put it in an if statement just in case.''' if age: person['age'] = age return person musician = build_person('jimi','hendrix') print(musician) '''If we know the keys, can we format better?''' print(musician['first'].title() + " " + musician['last'].title()) '''Testing with age''' musician = build_person('jimi', 'hendrix', 37) print(musician['first'].title() + " " + musician['last'].title() + ", " + str(musician['age']))
true
a2c94ca0ccf5569edfd3637bfeabc22c4ca84940
Nelapati01/321810305034-list
/l1.py
231
4.28125
4
st=[] num=int(input("how many numbers:")) for n in range (num): numbers=int(input("Enter the Number:")) st.append(numbers) print("Maximum elements in the list:",max(st),"\nMinimum element in the list is :",min(st))
true
adfaf200179e8e696cc6f1d74ae475a0beab43c5
slovoshop/LightIT_test_task
/convert_roman_to_arabic.py
1,303
4.34375
4
# -*- coding: utf-8 -*- """ Program in Python 3.6.4 Calculating the numeric value of a Roman numeral. Here is an example of calculating: roman CXLIV values [100, 10, 50, 1, 5] values[:-1] [100, 10, 50, 1] values[1:] [10, 50, 1, 5] zip [(100,10), (10,50), (50,1), (1,5)] sum 100 -10 50 -1 +5 result 144 """ def convert_roman_to_arabic(): roman = input("Enter the roman number: ").upper() """Check valid input""" trans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} invalid = ['IIII', 'VV', 'XXXX', 'LL', 'CCCC', 'DD', 'MMMM'] if (any(sub in roman for sub in invalid) or not any(sign in roman for sign in trans.keys())): print('Invalid input format: {}. Reenter'.format(roman)) convert_roman_to_arabic() return """Calculate the numeric value of a Roman numeral""" values = [trans[sign] for sign in roman] result = sum( val if val >= next_val else -val for val, next_val in zip(values[:-1], values[1:]) ) + values[-1] print('Numeric value of a Roman numeral: {}'.format(result)) convert_roman_to_arabic()
false
e049d49db2e69afaa2795331bdd9500cb0ebc2de
MilesBell/PythonI
/practicep1.py
1,916
4.15625
4
chapter="Introduction to PythonII" print("original chapter name:") print(chapter) print("\nIn uppercase:") print(chapter.upper()) print("\nIn 'swapcase':") print(chapter.swapcase()) print("\nIn title format:") print(chapter.title()) print("\nIn 'strip' format:") print(chapter.strip()) print("\n\nPress the enter key to exit.") print("My expenses are:") car=input("insurance:") gas=input("gas for my car:") rent=input("my rent is:") food=input("groceries and dining out:") shopping=input("my personal shopping:") total=car+gas+food+shopping print("\nGrand total is:", total); #this is good^, but adds the entered values together as a string instead of combining numeric values #int(input( is better because it adds the integers print("My expenses are:") car=int(input("insurance:")) gas=int(input("gas for my car:")) rent=int(input("my rent is:")) food=int(input("groceries and dining out:")) shopping=int(input("my personal shopping:")) total=car+gas+food+shopping print("\nGrand total is:", total); #below adds the entries together as a string, like 5+5+5+5 as 5555 instead of 5+5+5+5 as 20 print("My expenses are:") car=str(input("insurance:")) gas=str(input("gas for my car:")) rent=str(input("my rent is:")) food=str(input("groceries and dining out:")) shopping=str(input("my personal shopping:")) total=car+gas+food+shopping print("\nGrand total is:", total); #also adds together entries as integers, but always returns a decimal; i.e. 5+5+5+5=10.0 print("My expenses are:") car=float(input("insurance:")) gas=float(input("gas for my car:")) rent=float(input("my rent is:")) food=float(input("groceries and dining out:")) shopping=float(input("my personal shopping:")) total=car+gas+food+shopping print("\nGrand total is:", total); #practice01 #gets personal information from the user print("\nUser\'s personal information:") name=input("full name:") age=input("age in years:") weight=input("weight in lbs:")
true
2f32e330a2d5ce49f9687db2f826f1baeaef1089
wkdghdwns199/Python_basic_and_study
/chap_4/22_dic_tion_ary.py
352
4.15625
4
dictionary={ "key1":"ant", "key2":"bee", "key3":"cake" } print("#딕셔너리의 items() 함수") print("items():",dictionary.items()) print() for key,element in dictionary.items(): print("dictionary[{}]= {}".format(key,element)) a_list=["1","2","3"] b_list=["a","b","c"] for i in range(len(a_list)): print(a_list[i],b_list[i])
false
3410fdab20dd9e10e148c29a69b40ef8e10bc160
HaythemBH2003/Object-Oriented-Programming
/OOP tut/Chapter4.py
1,478
4.125
4
######## INTERACTION BETWEEN CLASSES ######## class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade def get_grade(self): return self.grade def get_name(self): return self.name class Course: def __init__(self, name, max_students): self.name = name self.max_students = max_students self.students = [] # students -------> ATTRIBUTE # NOT MENTIONED IN __init__() def get_name(self): return self.name def add_student(self, student): if len(self.students) < self.max_students: self.students.append(student) print(f"Student {student.get_name()} successfully added to the {self.get_name()} course.") return True else: print(f"Maximum number of students reached. Unable to add {student.get_name()} to the {self.get_name()} course.") return False def get_average_grade(self): sum = 0 for student in self.students: sum += student.get_grade() average = sum / len(self.students) return average s1 = Student("Tim", 16, 18) s2 = Student("Bill", 18, 15) s3 = Student("Joe", 19, 14) course = Course("Computer Science", 2) course.add_student(s1) course.add_student(s2) course.add_student(s3) print(course.get_average_grade())
true
9d9e6c968ceabf5bceaeeeb848face6ddf0b24f1
emberenot/pythoncourse
/lab1(py)/lab1_10.py
526
4.28125
4
#Напишите скрипт, позволяющий определить надежность вводимого пользователем пароля. Это задание является творческим: алгоритм #определения надежности разработайте самостоятельно. password = input("Введите пароль: ") if len(password)>8 and not password.isdigit(): print("Пароль надёжный") else: print("Плохой пароль!")
false
59e52bd9931ca75082f8d2504722e8b2bc2c976a
alitsiya/InterviewPrepPreWork
/strings_arrays/maxSubArray.py
670
4.21875
4
# Find the contiguous subarray within an array (containing at least one number) which has the largest sum. # For example: # Given the array [-2,1,-3,4,-1,2,1,-5,4], # the contiguous subarray [4,-1,2,1] has the largest sum = 6. # For this problem, return the maximum sum. def maxSubArray(A): if len(A) == 0: return [] if len(A) == 1: return A start = 0 end = 1 current = 1 max_sum = 0 while current < len(A): cur_sum = sum(A[start:current]) if cur_sum > 0: if cur_sum > max_sum: max_sum = cur_sum end = current else: start = current + 1 end = current + 1 current += 1 print max_sum print maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
true
dea9250a810a2f87be8ee0f6bbf720dfa963d144
nmoore32/coursera-fundamentals-of-computing-work
/2 Principles of Computing/Week 4/dice_analysis.py
1,893
4.21875
4
""" Program to analyze expected value of simple dice game. You pay $10 to play. Roll three dice. You win $200 if you roll triples, get your $10 back if doubles, and lose the $10 otherwise """ def gen_all_sequences(outcomes, length): """ Iterative function that enumerates the set of all sequences of outcomes of given length """ ans = set([()]) for dummy_idx in range(length): temp = set() for seq in ans: for item in outcomes: new_seq = list(seq) new_seq.append(item) temp.add(tuple(new_seq)) ans = temp return ans def max_repeats(seq): """ Determines the maximum number of times any individual item occurs in the sequence """ item_count = [seq.count(item) for item in seq] return max(item_count) def compute_expected_value(): """ Compute the expected value (excluding the initial $10, so an answer of $10 corresponds to breaking even) """ all_rolls = gen_all_sequences([1, 2, 3, 4, 5, 6], 3) results = [max_repeats(roll) for roll in all_rolls] expected_value = 0 for result in results: if result == 2: # The probability for getting any given is 1/216 since there are 216 possible results expected_value += 10 / 216 elif result == 3: expected_value += 200 / 216 return expected_value def run_test(): """ Testing """ outcomes = set([1, 2, 3, 4, 5, 6]) print( f"Number of possible outcomes for rolling three dice: {len(gen_all_sequences(outcomes, 3))}") print(f"Max repeats for (3, 2, 1) is: {max_repeats([3, 2, 1])}") print(f"Max repeats for (3, 3, 1) is: {max_repeats([3, 3, 1])}") print(f"Max repeats for (3, 3, 3) is: {max_repeats([3, 3, 3])}") print(f"Expected value is: {compute_expected_value()}") run_test()
true
bff961baa068c0a52ce669edd31222aa2b45e928
xxw1122/Leetcode-python-xxw
/283 Move Zeroes.py
835
4.15625
4
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ num_zero = 0 while 1: if 0 not in nums: break else: index_0 = nums.index(0) num_zero += 1 del nums[index_0] for i in range(num_zero): nums.append(0)
true
c0a4b16a1d9a2d072892909a4a50def04dc9cb68
masterzht/note
/other/python/code/2_list.py
709
4.3125
4
# this is the code of list word=['a','b','c','d','e','f','g'] a=word[2] print " a is : " +a b=word[1:3] print b # index 1 and 2 elements of word. c=word[:2] print c # index 0 and 1 elements of word. d=word[0:] print "d is " print d # All elements of word. e=word[:2]+word[2:] print "e is :" print e # All elements of word. f=word[-1] print "f is :" print f # the last elements of word. g=word[-4:-2] print " g is :" print g # index 3 and 4 elements of word. h=word[-2:] print " h is :" print h # the last two elements i=word[:-2] print "i is :" print i # Everything except the last two characters l=len(word) print "Length of word is :" + str(l) print " Adds new element ... " word.append('h') print word
false
72c69bbe24970624694106bf99d404fc77b21743
SerioSticks/AprendiendoPython
/Aleatorio.py
1,101
4.1875
4
#Creador Jorge Alberto Flores Sánchez #Matricula: 1622167 Grupo: 22 #Fecha de Creación : 18/09/2019 #En python existen muchas librerias para facilitar la programación, #a estas se les denomina modulos (module). #Para usar un modulo debe importarse y para esto se utiliza la, #instrucción import import random #Definimos nuestra variables, que en esta ocasion sera de tipo, #flotante (float) y le asignamos un valor. numero1=float(10.5) #En python las funciones son instrucciones que hacen una tarea, #específica, como una unidad de ejecución. #Se declaran con def.Y todo el codigo identado a la derecha de la , #definicion forma parte de la misma función. def miFuncion(): #El numero aleatorio se convierte a float, este es generado por #random.randrange() (este solo esta disponible si se importa, # el modulo random) numero2=float(random.randrange(1,10)) #Se utilizan sustituciones para mostrar resultados. mensaje="La suma de {} y {} es {}" print(mensaje.format(numero1,numero2,numero1+numero2)) #Se ejecuta la función definida en el código. miFuncion()
false
7fb3ca8717ca50c532ef518d2569aa39c43afef8
gitjit/ehack
/py/emp.py
993
4.25
4
# This is a sample to demonstrate Python OOP features class Employee(object): raise_amount = 1.04 # class variable num_emps = 0 def __init__(self, first, last, pay): self._first = first self._last = last self._pay = pay self._email = first + '.' + last + '@company.com' Employee.num_emps += 1 def fullname(self): return '{} {}'.format(self._first, self._last) def pay(self): return self.pay * self.raise_amount def main(): emp1 = Employee('Jith', 'Menon', 300000) emp2 = Employee('Ganga', 'Menon', 40000) print(emp1.fullname(), Employee.fullname(emp2)) print(emp1.raise_amount) print(Employee.raise_amount) print (emp2.raise_amount) emp1.raise_amount = 2.0 print(emp1.raise_amount) print(Employee.raise_amount) print (emp2.raise_amount) print(emp1.__dict__) print(Employee.__dict__) print(emp2.__dict__) print(Employee.num_emps) main()
false
602a2952d43b2c43eab807be4a629af2a6fc4849
feladie/info-206
/hw3/BST.py
2,481
4.46875
4
#--------------------------------------------------------- # Anna Cho # anna.cho@ischool.berkeley.edu # Homework #3 # September 20, 2016 # BST.py # BST # --------------------------------------------------------- class Node: #Constructor Node() creates node def __init__(self,word): self.word = word self.right = None self.left = None self.count = 1 class BSTree: #Constructor BSTree() creates empty tree def __init__(self, root=None): self.root = root #These are "external functions" that will be called by your main program - I have given these to you #Find word in tree def find(self, word): return _find(self.root, word) #Add node to tree with word def add(self, word): if not self.root: self.root = Node(word) return _add(self.root, word) #Print in order entire tree def in_order_print(self): _in_order_print(self.root) def size(self): return _size(self.root) def height(self): return _height(self.root) #These are "internal functions" in the BSTree class - You need to create these!!! #Function to add node with word as word attribute def _add(root, word): if root.word == word: root.count +=1 return if root.word > word: if root.left == None: root.left = Node(word) else: _add(root.left, word) else: if root.right == None: root.right = Node(word) else: _add(root.right, word) #Function to find word in tree def _find(root, word): if root is None: # word is not in the tree return 0 if root.word == word: # word has been found return root.count if root.word > word: return _find(root.left, word) if root.word < word: return _find(root.right, word) #Get number of nodes in tree def _size(root): if root is None: # Leaf nodes return 0 else: # Root node and its children return 1 + _size(root.left) + _size(root.right) #Get height of tree def _height(root): if root is None: return 0 # Leaf node else: return max(_height(root.left) + 1, _height(root.right) + 1) # Returns the longest path #Function to print tree in order def _in_order_print(root): if not root: return _in_order_print(root.left) print(root.word) print(root.count) _in_order_print(root.right)
true
9ce73959107cd05593c971af07ac82530e9b6a35
chilango-o/python_learning
/seconds_calculator.py
739
4.34375
4
def calcSec(): """ A function that calculates a given number of seconds (user_seconds) and outputs that value in Hour-minute-second format """ user_seconds = int(input('cuantos segundos? ')) hours = user_seconds // 3600 #integer division between the given seconds and the number of seconds in 1 hour (calculation of the whole hrs in the given seconds) reminder_hours = (user_seconds % 3600) # The remainder of seconds of the hour division (modulus operation) minutes = reminder_hours // 60 # the whole minutes in the seconds given reminder_seconds = reminder_hours % 60 # the number of whole seconds of the total given print('hours:', hours, 'minutes:', minutes, 'seconds:', reminder_seconds) calcSec()
true
21026c68e2fb2a211d72eaf48ab67edc023ffe32
MulengaKangwa/PythonCoreAdvanced_CS-ControlStatements
/53GradingApplication.py
790
4.15625
4
m=int(input("Enter your maths score (as an integer):")) if m >=59: p = int(input("Enter your physics score(as an integer):")) if p >= 59: c = int(input("Enter your chemistry score(as an integer):")) if c >= 59: if (p + m + c) / 3 <= 59: print("You secured a C grade") elif (p + m + c) / 3 <= 69: print("You secured a B grade") elif (p + m + c) / 3 > 69: print("You secured an A grade") else: print("Unfortunately, you have not passed the examination.") else: print("You have not passed the Chemistry examination") else: print("You have not passed the Physics examination") else: print("You have not passed the the Mathematics examination")
true
3b0e84aa74c12e1a1771755e73d37993d27e1ba6
push-95/Project-Euler
/p001.py
279
4.375
4
# Problem 1 - Multiples of 3 and 5 # Pushyami Shandilya # http://github.com/push-95 def calc_sum(N): ''' Function to find the sum of all the multiples of 3 or 5 below a number N. ''' return sum(i for i in range(N) if (i%3==0 or i%5==0)) if __name__ == '__main__': print calc_sum(1000)
false
8d8e09d5241dcf6a3055e72355029a84967aa0af
ellisgeek/linux1
/chapter7/scripts/month.py
332
4.34375
4
#!/usr/bin/env python #define the months of the year months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] print "Traditional order:" for month in months: print month print "\n\nAlphabetical order:" for month in sorted(months): print month
true
eec1de729ffc2a62859746605198505a3f8a994a
tamjidimtiaz/CodeWars
/<8 Kyu> Logical calculator.py
1,216
4.34375
4
''' Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50. Links referring to logical operations: AND, OR and XOR. You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially. First Example: Input: true, true, false, operator: AND Steps: true AND true -> true, true AND false -> false Output: false Second Example: Input: true, true, false, operator: OR Steps: true OR true -> true, true OR false -> true Output: true Third Example: Input: true, true, false, operator: XOR Steps: true XOR true -> false, false XOR false -> false Output: false Input: boolean array, string with operator' s name: 'AND', 'OR', 'XOR'. Output: calculated boolean ''' def logical_calc(array, op): if op=='AND': if False in array: result = False else: result = True elif op=="OR": if True in array: result = True else: result = False else: result = array[0] for i in range(1,len(array)): result = result ^ array[i] #boolean return result
true
80ce0b6a98ffad061eeb45a97c81851afe42a216
Venkatesh123-dev/100-Days-of-code
/Day_06_2.py
1,860
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 13 19:28:24 2020 @author: venky There are two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location and moves at a rate of meters per jump. The second kangaroo starts at location and moves at a rate of meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they’ll ever land at the same location at the same time? Input Format A single line of four space-separated integers denoting the respective values of , , , and . Constraints Output Format Print YES if they can land on the same location at the same time; otherwise, print NO. Note: The two kangaroos must land at the same location after making the same number of jumps. Sample Input 0 0 3 4 2 Sample Output 0 YES Explanation 0 The two kangaroos jump through the following sequence of locations: Thus, the kangaroos meet after jumps and we print YES. Sample Input 1 0 2 5 3 Sample Output 1 NO Explanation 1 The second kangaroo has a starting location that is ahead (further to the right) of the first kangaroo’s starting location (i.e., ). Because the second kangaroo moves at a faster rate (meaning ) and is already ahead of the first kangaroo, the first kangaroo will never be able to catch up. Thus, we print NO. """ #!/bin/python3 import math import os import random import re import sys # Complete the kangaroo function below. def kangaroo(x1, v1, x2, v2): for n in range(10000): if((x1+v1)==(x2+v2)): return "YES" x1+=v1 x2+=v2 return "NO" if __name__ == '__main__': x1, v1, x2, v2 = raw_input().strip().split(' ') x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)] result = kangaroo(x1, v1, x2, v2) print(result)
true
2fc9577d7073827d48449eb4c3988998e55da166
DizzyMelo/python-tutorial
/numbers.py
288
4.25
4
# There are three numeric types in python # int, float and complex import random x = 1 # int y = 2.8 # float z = 1j # complex print(complex(x)) print(int(y)) print(type(z)) # the last number is not included, then, numbers from 1 to 9 will show up print(random.randrange(1, 10))
true
115e1cc9db1fc292b214b1f31ff5b23b62dbd684
DizzyMelo/python-tutorial
/ifelse.py
1,263
4.375
4
# Python Conditions and If statements # Python supports the usual logical conditions from mathematics: # Equals: a == b # Not Equals: a != b # Less than: a < b # Less than or equal to: a <= b # Greater than: a > b # Greater than or equal to: a >= b # These conditions can be used in several ways, most commonly in "if statements" and loops. a = 44 b = 100 if a > b: # Remember that python relies on identation print('a is greater than b') elif a == b: print('a is equals to b') else: print('b is greater than a') if b > a: print('b is greater than a') a = 2 b = 330 print('1') if a > b else print('2') a = 3 b = 4 print('A') if a > b else print('==') if a == b else print('B') # The and logical operator a = 220 b = 33 c = 500 if a > b and c > a: print('both conditions are true') if a > b or a > c: print('at least one of the conditions are true') # Nested If a = 41 if a > 10: print('Above 10') if a > 20: print('Above 20') if a > 40: print('Above 40') else: print('But not above 40') else: print('But not above 20') # Pass statement can be used if for some reason you need an empty if statement, which by default will raise an error if 10 > 5: pass
true
6869f7ccbbe5124779270653201b7bfeb5b12ba5
DizzyMelo/python-tutorial
/trycatch.py
1,830
4.375
4
# The try block lets you test a block of code for errors. # The except block lets you handle the error. # The finally block lets you execute code, regardless of the result of the try- and except blocks. # Exception Handling # When an error occurs, or exception as we call it, Python will normally stop and generate an error message. # These exceptions can be handled using the try statement: # Example # The try block will generate an exception, because x is not defined: try: print('ola') except NameError: print('An exception occured') except: print('Another error') # Else # You can use the else keyword to define a block of code to be executed if no errors were raised: try: print('Hello World') except NameError: print('An exception occured') except: print('Another error') else: print('Everything went OK') # Finally # The finally block, if specified, will be executed regardless if the try block raises an error or not. try: print('asdf') except NameError: print('Name error occured') finally: print('End of try') # This can be useful to close objects and clean up resources: # Example # Try to open and write to a file that is not writable: try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: # f.close() print('close') # Raise an exception # As a Python developer you can choose to throw an exception if a condition occurs. # To throw (or raise) an exception, use the raise keyword. x = -1 # if x < 0: # raise Exception('No numbers below 0 allowed') # The raise keyword is used to raise an exception. # You can define what kind of error to raise, and the text to print to the user. x = 'Hello' if not type(x) is int: raise TypeError('It has to be a number')
true
abbeac5ff24ee0715d8f0e788244239d4740de5a
danieldiniz1/blue
/aula 15 21.05/exercicio 1.py
323
4.15625
4
numeros = [] for nm in range(5): numero = int(input(f"Digite o {nm+1}º número: ")) for chave, valor in enumerate(numeros): if numero < valor: numeros.insert(chave, numero) break else: numeros.append(numero) print("Lista: ", numeros) for nmrs in numeros: print(nmrs)
false
79dd6ddfe911e50f068d60014f5713afd3572345
danieldiniz1/blue
/aula 14.05/aula 14.05.py
515
4.125
4
# exercício de while opc = 1 while opc == 1: numero = float(input("digite um numero: ")) print() if (numero == 0): print(f'o numero digitado é: {numero}') print() elif (numero > 0): print(f'o numero {numero:.2f} é positivo') print() else: print(f'o numero {numero:.2f} é negativo') print() resposta = input("você deseja continuar? (sim/não) ") print() if resposta =="não": opc = 0 print("programa finalizado")
false
0798b0374d82ddc94292b856402b782474d8c891
chaithanyasubramanyam/pythonfiles
/linkedlist.py
992
4.15625
4
class Node: def __init__(self,data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def push(self,new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insert(self,previous_node,new_data): if previous_node == None: print('no') new_node = Node(new_data) new_node.next = previous_node.next previous_node.next = new_node def append(self,new_data): new_node = Node(new_data) if self.head == None: self.head = new_node else: n = self.head while n.next != None: n = n.next n.next = new_node def printlist(self): n = self.head while n != None: print(n.data,end = ' ') n = n.next l = [1,2,3,4] a = Linkedlist() for i in l: a.append(i) a.printlist()
false
16ad2f811290b82e99ad541713ca0b48adc99f87
gauravlahoti80/Project-97-Number-Guessing-Game
/guessing Game/main.py
1,899
4.21875
4
#importing modules import random import pyttsx3 #welcome screen input_speak = pyttsx3.init() input_speak.say("Enter your name: ") input_speak.runAndWait() #taking name input from the user user_name = input("Enter your name: ") #showing hello to the user input_speak.say(f"Hello,{user_name}") input_speak.runAndWait() print(f'Hello , {user_name}.') #chances chances = 5 print(f"You have {chances} chances to win the game.") #random number max_number = 10 min_number = 1 random_number = random.randint(min_number , max_number) #taking input for number input_speak.say("Enter any number from 1 to 10: ") input_speak.runAndWait() guessed_number = int(input("Enter any number from 1 to 10: ")) while True: #checking the numbers if guessed_number == random_number: input_speak.say(f"Congrats, {user_name} you have guessed the number in {chances} chances.") input_speak.runAndWait() print(f"Congrats, {user_name} you have guessed the number in {chances} chances") break #if the user looses elif chances == 1: input_speak.say(f"sorry you were not able to guess the number. The number is {random_number}") input_speak.runAndWait() print(f"sorry you were not able to guess the number. The number is {random_number}") break #checking the numbers for high anf low else: if random_number > guessed_number: input_speak.say("that was too low.") input_speak.runAndWait() print('That was too low.') else: input_speak.say("that was too high.") input_speak.runAndWait() print('That was too high.') #taking the input again on wrong guessed chances -= 1 print(f'You have {chances} chances left.') guessed_number = int(input('Guess again: '))
true
bf5e398738221308a2c5fa8462c32ff1d8de1cbb
emmanuelaboah/Data-Structures-and-Algorithms
/Solved Problems/Data structures/Recursion/String-Permutations.py
1,790
4.125
4
# Problem Statement # Given an input string, return all permutations of the string in an array. # Example 1: # string = 'ab' # output = ['ab', 'ba'] # Example 2: # string = 'abc' # output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] # Note - Strings are Immutable # Recursive Solution """ Param - input string Return - compound object: list of all permutations of the input string """ def permutations(string): return return_permutations(string, 0) def return_permutations(string, index): # output to be returned output = list() # Terminaiton / Base condition if index >= len(string): return [""] # Recursive function call small_output = return_permutations(string, index + 1) # Pick a character current_char = string[index] # Iterate over each sub-string available in the list returned from previous call for subString in small_output: # place the current character at different indices of the sub-string for index in range(len(small_output[0]) + 1): # Make use of the sub-string of previous output, to create a new sub-string. new_subString = subString[0: index] + current_char + subString[index:] output.append(new_subString) return output # Test - function def test_function(test_case): string = test_case[0] solution = test_case[1] output = permutations(string) output.sort() solution.sort() if output == solution: print("Pass") else: print("Fail") string = 'ab' solution = ['ab', 'ba'] test_case = [string, solution] test_function(test_case) string = 'abc' output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] test_case = [string, output] test_function(test_case)
true
2eff58b50c69128a2999948651acc3cb11701e98
emmanuelaboah/Data-Structures-and-Algorithms
/Solved Problems/Data structures/Recursion/Reverse _string_input.py
1,389
4.53125
5
def reverse_string(input): """ Return reversed input string Examples: reverse_string("abc") returns "cba" Args: input(str): string to be reversed Returns: a string that is the reverse of input """ # (Recursion) Termination condition / Base condition if len(input) == 0: return "" else: first_char = input[0] the_rest = slice(1, None) # `the_rest` is an object of type 'slice' class sub_string = input[the_rest] # convert the `slice` object into a list # Recursive call reversed_substring = reverse_string(sub_string) return reversed_substring + first_char # Test Cases print ("Pass" if ("" == reverse_string("")) else "Fail") print ("Pass" if ("cba" == reverse_string("abc")) else "Fail") #-------------------------------------------------# ''' **Time and Space Complexity Analysis** Each recursive call to the `reverse_string()` function will create a new set of local variables - first_char, the_rest, sub_string, and reversed_substring. Therefore, the space complexity of a recursive function would always be proportional to the maximum depth of recursion stack. The time complexity for this function will be O(k*n), where k is a constant and n is the number of characters in the string (depth of recursion stack). '''
true
f10c03cbd6d9a175258290a51135d1ab0609281b
ParthRoot/Basic-Python-Programms
/list Python program to print even numbers in a list.py
444
4.15625
4
# Programme by parth.py # Python program to print even numbers in a list def even(lst): for i in lst: if i % 2 == 0: print(i, end=" ") def odd(lst): for i in lst: if i % 2 != 0: print(i, end=" ") print("Even Number is-:") even([1,2,3,4,5,6,7,8,9]) print("\nodd Number is:-") odd([1,2,3,4,5,6,7,8,9]) """ output: Even Number is-: 2 4 6 8 odd Number is:- 1 3 5 7 9 """
false
0424290f9aa1009976c74c19bfc41f65da59146e
ParthRoot/Basic-Python-Programms
/Fectorial.py
285
4.1875
4
num=int(input("enter the num")) factorial=1 if num < 0: print("sorry factorial doesnot exit negative num") elif num == 0: print("factorial always start 1") else: for i in range(1,num+1): factorial = factorial * i print("the factorial of",num,factorial)
true
bb328aa070b6889b12d9dac1b3508801da268fd6
daniel-laurival-comp19/slider-game-1o-bimestre
/getStartingBoard.py
574
4.25
4
def getStartingBoard(): ''' Return a board data structure with tiles in the solved state. For example, if BOARDWIDTH and BOARDHEIGHT are both 3, this function returns [[1, 4, 7], [2, 5, 8], [3, 6, BLANK]]''' counter = 1 board = [] for x in range(BOARDWIDTH): column = [] for y in range(BOARDHEIGHT): column.append(counter) counter += BOARDWIDTH board.append(column) counter -= BOARDWIDTH * (BOARDHEIGHT - 1) + BOARDWIDTH - 1 board[BOARDWIDTH-1][BOARDHEIGHT-1] = BLANK return board
true
d3911c904e2e9cae6da70563f707270a07aae8f6
jnegro/knockout
/knockout_steps/knockout_step3.py
2,339
4.46875
4
#!/usr/bin/python # STEP 3 - Code the 'main' function to play the game # In this step we replace the 'main' function with code that runs the game from __future__ import print_function # We need to import the 'random' Python library in order to generate random numbers import random class Boxer(object): """ An Object to describe a Boxer and the actions he/she takes """ def __init__(self, name): """Create a new boxer with a name and set starting health""" self.name = name self.health = 100 @property def standing(self): """A property we can check at any time to see if the boxer is still standing""" if self.health > 0: return True else: return False def punch(self): """Boxer throws a punch. We randomly choose damage between 1 and 10""" damage = random.randint(1, 10) return damage def punched(self, damage): """Boxer gets punched and receives damage""" self.health = self.health - damage def main(): """This function starts the program""" # Ask the player for their name name = raw_input("Please enter your name: ") # Create the player as a new Boxer player = Boxer(name) # Create the Computer boxer computer = Boxer("Computer") # Print out the initial health stats print("{0}: {1}".format(player.name, player.health)) print("{0}: {1}".format(computer.name, computer.health)) print("") # Start our game loop and keep repeating until someone falls down while player.standing and computer.standing: # Pause and wait for the player to hit enter to punch raw_input("Press enter to punch") # Computer punches the player player.punched(computer.punch()) # Player punches the computer computer.punched(player.punch()) # Print out the stats after they punch each other print("{0}: {1}".format(player.name, player.health)) print("{0}: {1}".format(computer.name, computer.health)) print("") # Once someone falls down the loop stops if player.standing: print("KNOCKOUT! YOU WON!") print("") else: print("You lost. Too bad") print("") if __name__ == "__main__": # run the main function main()
true
0ae1e723b9a16cd4c9a5bad9d756158888ccfe27
SabiqulHassan13/python3-programiz-try
/NumberIsOddOrEven.py
290
4.46875
4
# python program to check a number is even or odd #take input a number to check from the user num = float(input("Enter a number: ")) # checking a number is odd or even if num % 2 == 0: print("{} is even number".format(num)) elif num % 2 == 1: print("{} is odd number".format(num))
true
886979bbd25e5a15e02eef4cad6519d56f710c6c
SabiqulHassan13/python3-programiz-try
/FindFactorsOfANumber.py
251
4.4375
4
# python program to find the factors of a number # take input a number num = int(input("Enter a positive integer: ")) # print the factors print("The factors of {} are: ".format(num)) for i in range(1, num + 1): if num % i == 0: print(i)
true
56353728f6e3f62a021e580e8e73cb4231c5e41a
Sohan11Sarkar/Basic-Calculator.github.io-
/main.py
1,011
4.1875
4
print('*********** WELCOME TO MY CALCULATOR ************') while True: print() print("Please select the operation you want to perform : \n\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit\n") option = int(input("Enter pption here -> ")) if option==1: no1=int(input("Enter First Number -> ")) no2=int(input("Enter Second Number -> ")) print(no1,' + ',no2,' = ',no1+no2) elif option==2: no1=int(input("Enter First Number -> ")) no2=int(input("Enter Second Number -> ")) print(no1,' - ',no2,' = ',no1-no2) elif option==3: no1=int(input("Enter First Number -> ")) no2=int(input("Enter Second Number -> ")) print(no1,' * ',no2,' = ',no1*no2) elif option==4: no1=int(input("Enter First Number -> ")) no2=int(input("Enter Second Number -> ")) print(no1,' / ',no2,' = ',no1/no2) elif option==5: print("Thanks for using my calculator!") break else: print("""Operation is not available....Try something else!""")
false
ed5cd23e31fcabc16b3ec9a5822e666bfa66b667
utolee90/Python3_Jupyter
/workspace2/10-collection/exam1_.py
730
4.1875
4
# 문자열 여러개 한꺼번에 저장 str_list = ['국어', '영어', '수학', '사회', '한국사'] print(str_list) # 인덱싱 : 데이터 1개 처리 print(str_list[0]) print(str_list[3]) # 슬라이싱 : 데이터 여러개 처리 print(str_list[1:4]) print(str_list[:4]) print(str_list[1:]) print(str_list[:]) print(str_list[::2]) print(str_list[::-1]) print('-' * 30) # 정수 저장 num_list = [1, 2, 3, 4, 5] print(num_list) print('-' * 30) # 실수 저장 float_list = [5.5, 3.14, 7.7] print(float_list) print('-' * 30) # boolean값 저장 bool_list = [True, False, False] print(bool_list) print('-' * 30) # 여러 데이터 저장 list1 = [5, 7.7, True, "Hello"] print(list1) print('-' * 30)
false
a59bc8107619ffaa5468ee7d5df1e9cf6cc3ebee
utolee90/Python3_Jupyter
/workspace2/06-operator/exam6.py
646
4.25
4
''' 논리 연산자 : 수학의 집합 기호를 명령어로 만들어 놓은 것 => boolean 연산 <진리표> x y x and y x or y not x true true true true false true false false true false false true false true true false false false false true ''' a = 100 b = 200 x = 5 y = 3 r1 = a >= b r2 = x >= y print(r1, r2) print('=' * 30) result = r1 and r2 print(result) print('=' * 30) result = r1 or r2 print(result) print('=' * 30) result = not r1 print(result) print('=' * 30)
false
55d460794565caf77b2f5c357a550f86049a7c9e
gawalivaibhav/Vg-python
/08-usefull datastructures/07-sets.py
370
4.15625
4
#Sets :- collection of uniqu elements #Union "|" #intersection "^" #diffrence "-" my_set = set(['one','two','three','one']) #print(my_set) my_set1 = set(['two','three','four']) a = my_set - my_set1 print(a <= my_set) #subset my_set1.add('five') print(my_set1) #print(my_set|my_set1) #Union #print(my_set ^ my_set1) #intersection #print(my_set - my_set1) #Diffrence
false
2a14971a28aee88ed93ee3aefb06dc1ec2fc0151
rickyqiao/data-structure-sample
/binary_tree.py
1,401
4.125
4
class Node: def __init__(self, data): self.left = None self.right = None self.parent = None self.data = data self.height = 0 class BinaryTree: def __init__(self): self.root = None def __str__(self, node = 0, depth = 0, direction_label = ""): "The tree structure in string form, to be used in str(my_node) or print(my_node)." if node == 0: node = self.root if node: height_info = "(H"+str(node.height)+")" if node.height > 0 else "" return depth * "\t" + direction_label + height_info + str(node.data) + "\n" + \ self.__str__(node.left, depth+1, "L:") + self.__str__(node.right, depth+1, "R:") else: return "" def inorder(self, node = 0, result = None): if result is None: result = [] if node == 0: node = self.root if node: self.inorder(node.left, result) result.append(node.data) self.inorder(node.right, result) return result if __name__ == "__main__": tree = BinaryTree() tree.root = Node("0") tree.root.left = Node("1") tree.root.right = Node("2") tree.root.left.right = Node("3") print(tree) print(tree.inorder()) tree = BinaryTree() tree.root = Node("0") print(tree) print(tree.inorder())
true
9670dc0c87a0205c248e98154aa92186b48addba
arinmsn/My-Lab
/Books/PythonCrashCourse/Ch8/8-6_CityNames.py
720
4.53125
5
# Write a function called city_country() that takes in the name # of a city and its country. The function should return a string formatted like this: # "Santiago, Chile" # Call your function with at least three city-country pairs, and print the value # that’s returned. def city_country(city, country): message = city + ', ' + country return message while True: print("Type 'q' at any time to quit ") city_name = input("Enter a city name: ") if city_name == 'q': break country_name = input("Enter name of that city's country: ") if country_name == 'q': break formatted_message = city_country(city_name, country_name) print(f'{formatted_message}') city_country()
true
de0f6049fdf79eddf97e30129d1c449999dc4cab
slayer96/codewars_tasks
/pattern_craft_decorator.py
1,691
4.5
4
""" The Decorator Design Pattern can be used, for example, in the StarCraft game to manage upgrades. The pattern consists in "incrementing" your base class with extra functionality. A decorator will receive an instance of the base class and use it to create a new instance with the new things you want "added on it". Your Task Complete the code so that when a Marine gets a WeaponUpgrade it increases the damage by 1, and if it is a ArmorUpgrade then increase the armor by 1. You have 3 classes: Marine: has a damage and an armor properties MarineWeaponUpgrade and MarineArmorUpgrade: upgrades to apply on marine. Accepts a Marine in the constructor and has the same properties as the Marine """ import test_framework as Test class Marine: def __init__(self, damage, armor): self.damage = damage self.armor = armor class Marine_weapon_upgrade: def __init__(self, marine): self.damage = marine.damage + 1 self.armor = marine.armor class Marine_armor_upgrade: def __init__(self, marine): self.damage = marine.damage self.armor = marine.armor + 1 Test.describe('Basic tests') Test.it('Single upgrade') marine = Marine(10, 1) Test.assert_equals(Marine_weapon_upgrade(marine).damage, 11) Test.assert_equals(Marine_weapon_upgrade(marine).damage, 11) Test.it('Double upgrade') marine = Marine(15, 1) marine = Marine_weapon_upgrade(marine) marine = Marine_weapon_upgrade(marine) Test.assert_equals(marine.damage, 17) Test.it('Triple upgrade') marine = Marine(20, 1) marine = Marine_weapon_upgrade(marine) marine = Marine_weapon_upgrade(marine) marine = Marine_weapon_upgrade(marine) Test.assert_equals(marine.damage, 23)
true
5a31b5a75acc5bba977ad3117973e674063ffcc8
joseph-guidry/dot
/mywork/ch5_ex/ex7.py
636
4.125
4
#! /usr/bin/env python3 def update_value(dictionary, num): """Take a dictionary and number to add values. Returns an updated dictionary""" for key in dictionary: dictionary[key] += num #with no return dict_value = {"cats":0, "dogs":0} #get input and convert to int number = int(input("What value do you want to increase by?\n>")) update_value(dict_value, number) #no need to use a return of function() #dict_value is updated in place. animal = list(dict_value.keys()) for thing in animal: print("there are " + str(dict_value[thing]) + " " + thing +" in the zoo")
true
5380d9d84232b3c71cac9aa3e622a86d34dd1939
dayna-j/Python
/codingbat/not_string.py
238
4.375
4
# Given a string, return a new string where "not " has been added # to the front. However, if the string already begins with "not", return the string unchanged. def not_string(str): if str[0:3]=='not': return str return 'not '+str
true
aa5611dd17a02c0642afabcb5d37e5816079631d
deepakgd/python-exercises
/class7.py
719
4.1875
4
# multiple inheritance init call analysis class A: def __init__(self): print("init of A") def feature1(self): print("Feature 1-A") def featurea(self): print("Feature A") class B: def __init__(self): print("init of B") def feature1(self): print("Feature 1-B") def featureb(self): print("Feature B") class C(A, B): # what happen if there is no init in sub class. it will call super call init but here we have # two super class. it will call A because it is in first. Left to right order # check class8.py def feature1(self): print("Feature 1-C") def featureb(self): print("Feature C") c = C()
true
f0c63a412162c445546ebdb2b5f12239f85e2212
pxblx/programacionPython
/practica03/E01Cuadrado.py
925
4.15625
4
""" Ejercicio 1 de clases Implementa en Python las clases GatoSimple, Cubo y Cuadrado vistas en el libro "Aprende Java con Ejercicios" y sus respectivos programas de prueba. """ class Cuadrado: def __init__(self, lado): self.__lado = lado def __str__(self): resultado = "" c = 0 while c < self.__lado: resultado += "##" c += 1 resultado += "\n" c = 1 while c < self.__lado - 1: resultado += "##" espacios = 1 while espacios < self.__lado - 1: resultado += " " espacios += 1 resultado += "##\n" c += 1 c = 0 while c < self.__lado: resultado += "##" c += 1 resultado += "\n" return resultado # Principal if __name__ == "__main__": miCuadradito = Cuadrado(5) print(miCuadradito)
false
db71200cb44b9a230d57338187a30ad8045b7912
pxblx/programacionPython
/practica05/E10HashMap.py
1,025
4.1875
4
""" Ejercicio 10 de POO4 Crea un mini-diccionario español-inglés que contenga, al menos, 20 palabras (con su correspondiente traducción). Utiliza un objeto de la clase HashMap para almacenar las parejas de palabras. El programa pedirá una palabra en español y dará la correspondiente traducción en inglés. """ diccionario = { "hola": "hello", "adiós": "goodbye", "por favor": "please", "nombre": "name", "hoy": "today", "ayer": "yesterday", "semana": "week", "día": "day", "mes": "month", "lunes": "monday", "martes": "tuesday", "miércoles": "wednesday", "jueves": "thursday", "viernes": "friday", "sábado": "satuday", "domingo": "sunday", "enero": "january", "febrero": "february", "marzo": "march", "abril": "april" } palabra = input("Introduce una palabra en español: ") if palabra in diccionario: print("La traducción en inglés es: " + diccionario.get(palabra)) else: print("La palabra no está en el diccionario.")
false
6d51a33cce5ed2c713c298e7a0ae483a3c8ebedf
pxblx/programacionPython
/practica01/repetitivas/E05Repetitivas.py
1,166
4.25
4
""" Ejercicio 5 de repetitivas Escribe un programa que pida el limite inferior y superior de un intervalo. Si el limite inferior es mayor que el superior lo tiene que volver a pedir. A continuacion se van introduciendo numeros hasta que introduzcamos el 0. Cuando termine el programa dara las siguientes informaciones: - La suma de los numeros que estan dentro del intervalo (intervalo abierto). - Cuantos numeros estan fuera del intervalo. - Informa si hemos introducido algun numero igual a los limites del intervalo. """ # Pedir valores while True: desde = int(input("Desde: ")) hasta = int(input("Hasta: ")) if desde < hasta: break numero = int(input("Introduce un numero: ")) # Resultado suma = 0 fuera = 0 igual = 0 while True: suma = suma + numero if numero < desde or numero > hasta: fuera += 1 if numero == desde or numero == hasta: igual += 1 numero = int(input("Introduce un numero: ")) if numero == 0: break print("Has introducido " + str(fuera) + " numeros fuera del rango, " + str(igual) + " numeros iguales a los limites y la suma de todos es igual a " + str(suma) + ".")
false
3cf82f53cf591934fb01755beabf9904c3c1ffdf
Aobie/Project-Euler
/Euler9.py
1,170
4.1875
4
#Euler 9 #Pythagorean triplet is a set of 3 natural numbers which can define a right triangle #a ** 2 + b ** 2 = c ** 2, where a < b < c import math import time def find_product(): # since a, b, and c are natural numbers and a < b < c # the smallest set possible is a = 1, b = 2, c = 3 # this also means that the largest a is 1000 / 3 - 1 = 332 # since this would lead to a = 332, b = 333, c = 334 for a in range(1, 332): # since b > a, start the inner loop at a + 1 # since b < c, and a + b + c = 1000, set a = 1 to find largest b # leads to b + c = 999, so largest b = floor (999 / 2) for b in range (a + 1, 499): if (math.sqrt (a ** 2 + b ** 2)).is_integer(): c = int(math.sqrt(a ** 2 + b ** 2)) #print ("A: ", a, "B: ", b, "C: ", c) if a + b + c == 1000: return a * b * c if __name__ == "__main__": print("Problem 9") print("Find the product of the one Pythagorean triplet for which a + b + c = 1000.") t1 = time.time() answer = find_product() t2 = time.time() print((t2-t1)*1000.0, " ms") print(answer)
false
f87730c01046eddf792665e051463ff59fde7aa0
LilMelt/Python-Codes
/Rock_Paper_Scissors.py
1,880
4.1875
4
import random def opponent(): choice = random.choice(["rock", "paper", "scissors"]) print("Your opponent chose " + choice) return choice def main(): game = True score = 0 opponent_score = 0 while game: # input user move user_move = input("Type \"rock\", \"paper\" or \"scissors\" then press enter: ") # check attack is valid while user_move != 'rock' and user_move != 'paper' and user_move != 'scissors': print("Please enter a valid move") user_move = input("Type \"rock\", \"paper\" or \"scissors\" then press enter: ") opponent_move = opponent() if user_move == 'rock' and opponent_move == 'scissors': score += 1 print("You won! Nice job!") elif user_move == 'paper' and opponent_move == 'rock': score += 1 print("You won! Nice job!") elif user_move == 'scissors' and opponent_move == 'paper': score += 1 print("You won! Nice job!") elif user_move == opponent_move: print("You tied!") else: opponent_score += 1 print("You lose!") # ask user if they want to play again play = input("The score is [" + str(score) + "," + str(opponent_score) + "]. Do you want to play another " "game? Type \"yes\" or \"no\": ") # ensure this is a valid input while play != 'yes' and play != 'no': print("Please enter a valid answer") play = input("Do you want to play another game? Type \"yes\" or \"no\": ") if play == 'no': print("Ok, lets play again soon!") game = False else: print("Ok, lets play another game!") if __name__ == "__main__": main()
true
0a749ccfccd2d7b18168455fca9c7701f26177fd
Pankhuriumich/EECS-182-System-folder
/Homeworks/HW5/printmovie.py
994
4.25
4
'''TASK: Fill in the code to generate the HTML-formatted string from the fields of a movie. See the README.txt for the format ''' def print_movie_in_html(movieid, movie_title, moviedate, movieurl): '''STUB code. Needs to change so that the return value contains HTML tags, as explained in README.txt.''' resulthtml = movieid + " " + movie_title + " " + moviedate + " " + movieurl + "\n"; # Output resulthtml to a file print_to_file(movieid + ".html", resulthtml); return resulthtml; ''' You do not have to change this function. It writes the string s to the specified filename. In this program, s will be a raw HTML string. By writing the HTML to a file, you can view the HTML file in a browser. This is called from main.cpp. ''' def print_to_file(filename, s): f = open(filename, "w"); f.write(s); f.close(); def main(): result = print_movie_in_html("1", "Sample movie", "1-1-2005", "http://imdb.com"); print result; main();
true
30e6b14d953e87fb0f37066e53f5222755743ddb
Pankhuriumich/EECS-182-System-folder
/Lecture_Code/Recursion/stone_to_dust_simulation/stonetodust.py
797
4.21875
4
def turn_stone_into_dust(stone): if (isdust(stone)): print "We got a dust piece! Nothing more to do on the piece!"; return; else: (piece1, piece2) = strike_hammer(stone); turn_stone_into_dust(piece1); turn_stone_into_dust(piece2); def isdust(stone): # Stones of size 1 or smaller are considered to be dust if (stone <= 1): return True; else: return False; def strike_hammer(stone): print "Striking hammer on a stone of size:", stone; # Divide stone into two smaller pieces. piece1 = stone / 2; piece2 = stone - piece1; print "Created stones of size:", piece1, "and", piece2; return (piece1, piece2); def main(): # Turn a stone of volume 7 units into dust. turn_stone_into_dust(7); main();
true
92d1c7f8015d4d552bb11fa8c818f81840d49646
lavenderLatte/89926_py
/homework/helperfunctions.py
536
4.34375
4
""" Create a python module helperfunctions.py with the following functions. add - returns the sum of two numbers diff - returns the difference between two numbers product - returns the product of two numbers greatest - returns the greatest of two numbers. Import this module in your python program and use the functions your created on any two numbers and print the result. """ def add(a, b): return a + b def diff(a, b): return a - b def product(a, b): return a * b def greatest(a, b): if a >= b: return a else: return b
true
54bc71f87b9de5e9956881744c63d1501c24ddd4
saragregory/hear-me-code
/pbj_while.py
1,801
4.28125
4
# Difficulty level: Beginner # Goal #1: Write a new version of the PB&J program that uses a while loop. Print "Making sandwich #" and the number of the sandwich until you are out of bread, peanut butter, or jelly. # Example: # bread = 4 # peanut_butter = 3 # jelly = 10 # Output: # Making sandwich #1 # Making sandwich #2 # All done; only had enough bread for 2 sandwiches. bread = 6 pb = 4 jelly = 10 sandwiches = 0 while bread >= 2 and pb > 0 and jelly > 0: bread = bread - 2 pb = pb - 1 jelly = jelly - 1 sandwiches = sandwiches + 1 print "I just made sandwich #{0}.".format(sandwiches) # print "I have enough bread for {0} more sandwiches, enough peanut butter for {1} more and enough jelly for {2} more".format(bread/2,pb,jelly) # Goal #2: Modify that program to say how many sandwiches-worth of each ingredient remains. # Example 2: # bread = 10 # peanut_butter = 10 # jelly = 4 # Output: # Making sandwich #1 # I have enough bread for 4 more sandwiches, enough peanut butter for 9 more, and enough jelly for 3 more. # Making sandwich #2 # I have enough bread for 3 more sandwiches, enough peanut butter for 8 more, and enough jelly for 2 more. # Making sandwich #3 # I have enough bread for 2 more sandwiches, enough peanut butter for 7 more, and enough jelly for 1 more. # Making sandwich #4 # All done; I ran out of jelly. if bread == 0 and pb == 0 and jelly == 0: print "All done, I ran out of ingredients." elif bread <= 1 and pb >= 1 and jelly >= 1: print "All done, I ran out of bread." elif pb <= 1 and bread >= 2 and jelly >= 1: print "All done, I ran out of peanut butter." elif jelly <= 1 and bread >= 2 and pb >= 1: print "I ran out of jelly but I can make a peanut butter sandwich." print "I had enough ingredients to make {0} sandwiches.".format(sandwiches)
true
a9d2ac3204cf92eb968c39fcc51ba887805b9645
coolguy-kr/questions
/py-multiple_inheritance.py
826
4.4375
4
# The following code is an example. The tree structure of class inheritance relationships is displayed as a list on the console. class X: pass class Y: pass class Z: pass class A(X, Y): pass class B(Y, Z): pass class M(B, A, Z): pass print(M.mro()) # So, It displays a result as a list. """ Console Output [<class '__main__.M'>, <class '__main__.B'>, <class '__main__.A'>, <class '__main__.X'>, <class '__main__.Y'>, <class '__main__.Z'>, <class 'object'>] """ # However, I expected a result of below to be printed. """ The result that I expected [<class '__main__.M'>, <class '__main__.B'>, <class '__main__.Y'>, <class '__main__.Z'>, <class '__main__.A'>, <class '__main__.X'>, <class 'object'>] """ # Q. If we look at them in order, the expected result should be output. Shouldn't it?
true
87bf49b4a94a28bd4ae46e00b09ef44e3ddfa977
the-brainiac/twoc-problems
/day6/program_14.py
699
4.15625
4
#to solve this question i used geeksforgeeks{in anticlockwise} as a reference # https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/ # N = 4 def rotateMatrix(mat): for x in range(0, int(N / 2)): for y in range(x, N-x-1): temp = mat[N-1-y][x] mat[N-1-y][x]=mat[N-1-x][N-1-y] mat[N-1-x][N-1-y]=mat[y][N-1-x] mat[y][N-1-x]=mat[x][y] mat[x][y]=temp # Function to print the matrix def displayMatrix( mat ): for i in range(0, N): for j in range(0, N): print (mat[i][j], end = ' ') print ("") mat = [ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ] rotateMatrix(mat) displayMatrix(mat)
false
8d37ab6a0ee58ee4f45551e06ac99603c239f64b
suboqi/-python
/ex3.py
794
4.53125
5
#现在数一数我的鸡 print("I will now count my chickens:") #hens有30只鸡,打印出来 print("Hens",25+30/6) #roosters有97只鸡,打印出来 print("Roosters",100-25*3%4) #现在数一数我的蛋 print("Now i will count the eggs:") #一共有以下几只蛋,并打印出来 num1=print(3+2+1-5+4%2-1/4+6) #这是一个判断 print("Is it true that 3 + 2 <5 - 7?") #判断真假 print(3+2<5-7) #这是一个判断 print("What is 3 + 2?",3+2) #这是一个判断 print("What is 5 - 7?",5-7) #哦!为什么它是假的 print("oh!,thst's why it's False") #要不,再点一点例子 print("How about some more") #判断是否为真 print("Is it greater?",5 > 2) #判断是否为真 print("Is it greater or equal?",5 >= -2) #判断是否为假 print("Is it less or equal?",5 <= -2)
false
511f378d45e5474c7a7eb679a78a14af4bac5cbf
asikurr/Python-learning-And-Problem-Solving
/3.Chapter three/elseif_stste.py
350
4.125
4
age = input("Input Your Age : ") age = int(age) if 0<age<=3: print("Ticket is free for you. ") elif 3<age<=10: print("Ticket price is 150 tk.") elif 10<age<=20: print("Ticket price is 250 tk.") elif 20<age<=150: print("Ticket Price is 350 tk.") elif age == 0 or 0>age or age>150: print("Sorry... You are not exist in the World")
true
1ba6cdf92840fef7f2deef408520de98826d61e9
asikurr/Python-learning-And-Problem-Solving
/8.Chapter eight SET/set.py
499
4.28125
4
# Set is unordered collection of unique data item # why we user set method # Because it contain unique data #but we cannot user 'list' and 'dictionary' in set # what is we do by set functon # list data unique and tuple data unique s = {1,2,3} # print(s) list1 = [6,3,4,5,4,3,5,4,4,3,3,4,6,8] l = list(set(list1)) # Removed Duplicate data from list using set method # print(l) s.add(4)# add data in set #s.remove(2)# Remove dat from set #s.discard(4) # s.clear() s1 = s.copy()#copy set print(s)
true
34585338db8d706740fe31e9c42ba2dd934580e6
asikurr/Python-learning-And-Problem-Solving
/2.Chapter two/exercise3.py
517
4.21875
4
#String case insensetive name , char = input("Enter a Name and a character separate by coma : ").split(",") print(f"the length of your name : {len(name)}") print(f"Number of Character in your name case sensetive: {name.count(char)}")#case sensetive print(f"Number of Character in your name case insensetive: {name.lower().count(char)}") #remove spacese # name.strip().lower().count(char.strip().lower()) print(f"Number of Character in your name case insensetive: {name.strip().lower().count(char.strip().lower())}")
false
832e49a939e333b9d95193acd6aae656167855df
asikurr/Python-learning-And-Problem-Solving
/6.Chapter six/about_tuple.py
667
4.34375
4
#looping in tuple #tuple in one element # tuploe without paranthesis # tuple unpacking # list inside tuple # some function that you can use tuple mix = (2,1,4,1,4,5,6,32) # i = 0 # while i<len(mix): # print(mix[i]) # i+=1 # for i in mix: # print(i) #Single element with tuple n = (1,) s = ('asikur',) # print(type(n)) # print(type(s)) #Tuple without paranthesis name = 'asikur', 'rahaman asikur', 'rahaman' # print(type(name)) #Tuple upaking n1,n2,n3 = (name) # print(n1) #List inside tuple nam = ('asikur','rahaman asikur',['rahaman','fayez']) # nam[2].pop() nam[2].append("Abdur Rahaman") # print(nam) # some function using tuple max-min-sum-len-count print(sum(mix))
false
6e632c820c3eda237542b2035be429ead1069019
asikurr/Python-learning-And-Problem-Solving
/8.Chapter eight SET/more_set.py
343
4.125
4
# more about set method # Union and Intersection methode s = {'a','b','v', 'd'} # if 'as' in s: # print('Present') # else: # print('Not present') # for i in s: # print(i) # Union operation s1 = {1,2,3,3,4} s2 = s | s1 # print(s2) #Intersection s3 = {1,2,3,4,5,6,7,8,9} s4 = {1,2,3,45,6,7,8,9,10,11,12} s5 = s3 & s4 print(s5)
false
674fb6ebc81e0fca4a75301afcd0ec17922d5051
chamzheng/python-cookbook
/c01_data_structures_algorithms/p09_find_commonalities_in_dicts.py
1,943
4.1875
4
# -*- coding:utf-8 -*- # 问题 # 怎样在两个字典中寻寻找相同点(比如相同的键、相同的值等等)? # 解决方案 # 考虑下面两个字典: a = { 'x': 1, 'y': 2, 'z': 3 } b = { 'w': 10, 'x': 11, 'y': 2 } # 为了寻找两个字典的相同点,可以简单的在两字典的 keys() 或者 items() 方法返回结果上执行集合操作。比如: # Find keys in common print(a.keys() & b.keys()) # {'y', 'x'} # Find keys in a that are not in b print(a.keys() - b.keys()) # {'z'} # Find (key, value) pairs in common print(a.items() & b.items()) # {('y', 2)} # 这些操作也可以用于修改或者过滤字典元素。 比如,假如你想以现有字典构造一个排除几个指定键的新字典。 # 下面利用字典推导来实现这样的需求: # Make a new dictionary with certain keys removed c = {key: a[key] for key in a.keys() - {'z', 'w'}} print(c) # {'x': 1, 'y': 2} # 讨论 # 一个字典就是一个键集合与值集合的映射关系。 # 字典的 keys() 方法返回一个展现键集合的键视图对象。 # 键视图的一个很少被了解的特性就是它们也支持集合操作,比如集合并、交、差运算。 # 所以,如果你想对集合的键执行一些普通的集合操作,可以直接使用键视图对象而不用先将它们转换成一个set。 # 字典的 items() 方法返回一个包含(键,值)对的元素视图对象。 # 这个对象同样也支持集合操作,并且可以被用来查找两个字典有哪些相同的键值对。 # 尽管字典的 values() 方法也是类似,但是它并不支持这里介绍的集合操作。 # 某种程度上是因为值视图不能保证所有的值互不相同,这样会导致某些集合操作会出现问题。 # 不过,如果你硬要在值上面执行这些集合操作的话,你可以先将值集合转换成set,然后再执行集合运算就行了。
false
edb125836089b25155cd4c46222393d502e7881e
wangmengyu/pythontutorial27
/ch04/unchangeable.py
625
4.125
4
# -*- coding: utf-8 -* # 参数默认值 i = 5 def my_fun(num=i): """默认值只被赋值一次,传递了不可变的对象""" print num i = 6 my_fun() def append_list(a, l=[]): """默认值只被赋值一次,传递了可变的对象""" l.append(a) return l print append_list(1) print append_list(2) print append_list(3) def append_list_2(a, l=None): """将传递的可变的对象换成NOne,函数内部进行初始化,可避免每次调用会影响该对象""" if l is None: l = [] l.append(a) return l print append_list_2(1) print append_list_2(2) print append_list_2(3)
false
e433f895bb2fc8d0cf6607b9e5801bd8f61f57c4
erikaosgue/python_challenges
/easy_challenges/7-write_a_function.py
349
4.1875
4
#!/usr/bin/python3 def is_leap(year): leap = False # leap year have to be divided by 4 and not by 100, or # leap year have to be divided by 400 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap = True return leap if __name__ == "__main__": year = int(input()) print(is_leap(year))
false