blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b50a873c8d0d45fd4ebac22fdeaa92097cdea731
rakshithsingh55/Clg_project
/FoodSearch/webapp/test.py
550
4.5
4
# Python3 code to demonstrate working of # Common words among tuple strings # Using join() + set() + & operator + split() # Initializing tuple test_tup = ('gfg is best', 'gfg is for geeks', 'gfg is for all') # printing original tuple print("The original tuple is : " + str(test_tup)) # Common words among tuple strings # Using join() + set() + & operator + split() res = ", ".join(sorted(set(test_tup[0].split()) & set(test_tup[1].split()) & set(test_tup[2].split()))) # printing result print("Common words among tuple are : " + res)
true
20ce051e440910c78ca5b3c409ff8ebb566520c0
am3030/IPT
/data/HW5/hw5_182.py
1,171
4.28125
4
def main(): num1 = int(input("Please enter the width of the box: ")) num2 = int(input("Please enter the height of the box: ")) symbol1 = input("Please enter a symbol for the box outline: ") symbol2 = input("Please enter a symbol for the box fill: ") boxTop = "" insideBox = "" for i in range(num1): # This loop constructs the top and bottom of the box boxTop = boxTop + symbol1 for n in range(num2 + 1): # This loop ensures the box does not exceed if n == 1 or n == num2: # This if statement prints out the top and print(boxTop) elif n < num2 and n > 1: # This if statement defines how and when the insideBox = "" # Resets the inside of the box so that the length is for j in range(num1 + 1): # This loop creates the inside of the box if j == 1 or j == num1: # This if statement sets when the insideBox = insideBox + symbol1 elif j < num1 and j > 1: # This if statement sets when the insideBox = insideBox + symbol2 print(insideBox) # prints the inside of the box for the user main()
true
5de5d8d3bedb628d5dfd81a6d4f1df396678c98c
am3030/IPT
/data/HW5/hw5_453.py
747
4.3125
4
def main(): width = int(input("Please enter the width of the box: ")) # Prompt user for the width of the box height = int(input("Please enter the height of the box: ")) # Prompt user for the height of the box outline = input("Please enter a symbol for the box outline: ") # Prompt user for the symbol that will make up the box's outline fill = input("Please enter a symbol for the box fill: ") # Prompt user for the content that will fill the interior of the box BUFFER = 2 # When creating the fill for the box, set this much aside for the border for i in range(height): print((outline + fill * (width-BUFFER) + (outline if width > 1 else "")) if i not in [0, height-1] else outline * width) # Print the box main()
true
7c2eb614d8ed545815425e6181dc9b77cd285d16
am3030/IPT
/data/HW4/hw4_340.py
451
4.21875
4
flavorText = "Hail is currently at height" def main(): height = 0 # 0 is not a valid input because it is not "positive" while height < 1: height = int(input("Please enter the starting height of the hailstone: ")) while height != 1: print(flavorText, height) if (height % 2) == 0: height //= 2 else: height = (height * 3) + 1 print("Hail stopped at height", height) main()
true
853882de1ef0c0ac6ddc0c41cbfd480fdcaabfef
agatakaraskiewicz/magic-pencil
/eveningsWithPython/stonePaperScissorsGame.py
1,229
4.1875
4
from random import randint """ 1 - Paper 2 - Stone 3 - Scissors 1 beats 2 2 beats 3 3 beats 1 """ points = 0 userPoints = 0 howManyWins = int(input('How many wins?')) def userWins(currentUserScore): print(f'You won!') return currentUserScore + 1 def compWins(currentCompScore): print(f'You loose!') return currentCompScore + 1 #1. Create some randomized number (1,3), which will be the comp attack #3. Compare the created values and decide, who won while points < howManyWins and userPoints < howManyWins: userAttack = int(input('What is your attack? Input 1 for Paper, 2 for Stone or 3 for Scissors')) attack = randint(1,3) if userAttack == attack: print (f'Tie! No one gets the point!') continue elif userAttack == 1: if attack == 2: userPoints = userWins(userPoints) else: points = compWins(points) elif userAttack == 2: if attack == 3: userPoints = userWins(userPoints) else: points = compWins(points) elif userAttack == 3: if attack == 1: userPoints = userWins(userPoints) else: points = compWins(points) else: print('You were supposed to provide 1-3 number... Try again') if points > userPoints: print('Computer won the battle!') else: print('You won the battle!')
true
1fe6cd8e407ae44133b561e4c885bc0ef4904560
kaceyabbott/intro-python
/while_loop.py
489
4.28125
4
""" Learn conditional repetition two loops: for loops and while loops """ counter = 5 while counter != 0: print(counter) # augmented operators counter -= 1 print("outside while loop") counter = 5 while counter: print(counter) counter -= 1 print("outside while loop") # run forever while True: print("enter a number") response = input() #take user input if int(response) % 7 == 0: break #exit loop print("outside while loop")
true
b5efc5698eac40c55d378f100337a8e52f9936fa
Nihadkp/python
/co1/16_swap_charecter.py
396
4.1875
4
# create a single string seperated with space from two strings by swapping the charecter at position 1 str1 = "apple" str2 = "orange" str1_list = list(str1) str2_list = list(str2) temp = str1_list[1] str1_list[1] = str2_list[1] str2_list[1] = temp print("Before exchanging elements:", str1, str2) print("string after exchanging charecter at position 1:", "".join(str1_list), "".join(str2_list))
true
65efd951f0153acbaee277e256b3e891376ab64a
Nihadkp/python
/co1/4_occurance_of_words.py
211
4.3125
4
#Count the occurrences of each word in a line of text. text=input("Enter the line : ") for i in text.strip().split(): print("Number of occurence of word ","\"",i,"\""," is :",text.strip().split().count(i))
true
97b16a9798970f1f2d734ed16a60187ae7f3f7e1
sudhanthiran/Python_Practice
/Competitive Coding/RegEx matching.py
1,621
4.5625
5
""" Given a pattern string and a test string, Your task is to implement RegEx substring matching. If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with the starting position of the text string. Similarly, if it is preceded by a $, the pattern(excluding the ^) will be matched with the ending position of the text string. If no such markers are present, it will be checked whether pattern is a substring of test. Example : ^coal coaltar Result : 1 tar$ coaltar Result : 1 rat algorate Result: 1 abcd efgh Result :0 Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The first line of each test case contains a pattern string. The second line of each test case consists of a text string. Output: Corresponding to every test case, print 1 or 0 in a new line. Constrains: 1<=T<=100 1<=length of the string<=1000 """ def isSubString(test_string,base_string): flag = base_string.find(test_string) if(flag == -1): return False else: return True def test_for_regex(): test_string = str(input()) base_string = str(input()) flag=False if (test_string.startswith('^')): flag = (test_string[1:] == base_string[:len(test_string)-1]) elif(test_string.endswith('$')): flag = (test_string[:len(test_string)-1] == base_string[(len(test_string)-1)*-1:]) else: flag = (isSubString(test_string, base_string)) if(flag==True): print("1") else: print("0") t = int(input()) for i in range(t): test_for_regex()
true
dd5e52323d02710e902a1bb7ca8615a18ecfb258
RockMurdock/Python-Book-1-Tuples
/zoo.py
1,703
4.46875
4
# Create a tuple named zoo that contains 10 of your favorite animals. zoo = ( "elephant", "giraffe", "hippopotamus", "monkey", "otter", "peacock", "panther", "rhino", "alligator", "lama" ) # Find one of your animals using the tuple.index(value) syntax on the tuple. print(zoo.index("hippopotamus")) # Determine if an animal is in your tuple by using value in tuple syntax. animal_to_find = "hippopotamus" if animal_to_find in zoo: print(f"We found the {animal_to_find}") # You can reverse engineer (unpack) a tuple into another tuple with the following syntax. """ children = ("Sally", "Hansel", "Gretel", "Svetlana") (first_child, second_child, third_child, fourth_child) = children print(first_child) # Output is "Sally" print(second_child) # Output is "Hansel" print(third_child) # Output is "Gretel" print(fourth_child) # Output is "Svetlana" """ # Create a variable for the animals in your zoo tuple, and print them to the console. ( first_animal, second_animal, third_animal, fourth_animal, fifth_animal, sixth_animal, seventh_animal, eighth_animal, ninth_animal, tenth_animal ) = zoo print(first_animal) print(second_animal) print(third_animal) print(fourth_animal) print(fifth_animal) print(sixth_animal) print(seventh_animal) print(eighth_animal) print(ninth_animal) print(tenth_animal) # Convert your tuple into a list. zooList = list(zoo) print(zooList) # Use extend() to add three more animals to your zoo. three_animals = ["zebra", "jellyfish", "antelope"] zooList.extend(three_animals) print(zooList) # Convert the list back into a tuple. zooListToTuple = tuple(zooList) print(zooListToTuple)
true
c95d54e49c03fc707c8081fb3fa6f67bb27a8046
kmollee/2014_fall_cp
/7/other/quiz/McNuggets.py
1,336
4.34375
4
''' McDonald’s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 McNuggets, since no non- negative integer combination of 6's, 9's and 20's add up to 16. To determine if it is possible to buy exactly n McNuggets, one has to find non-negative integer (can be 0) values of a, b, and c such that 6a+9b+20c=n Write a function, called McNuggets that takes one argument, n, and returns True if it is possible to buy a combination of 6, 9 and 20 pack units such that the total number of McNuggets equals n, and otherwise returns False. Hint: use a guess and check approach. ''' def McNuggets(n): """ n is an int Returns True if some integer combination of 6, 9 and 20 equals n Otherwise returns False. """ # Your Code Here a = 6 b = 9 c = 20 aRange, bRange, cRange = int(n / a), int(n / b), int(n / b) isPossible = False for _a in range(aRange + 1): for _b in range(bRange + 1): for _c in range(cRange + 1): if n == _a * a + _b * b + _c * c: return True return isPossible assert McNuggets(15) == True assert McNuggets(16) == False assert McNuggets(32) == True
true
deaaf816ff3deab54b62b699d53b417ad3cbb3f1
MehdiNV/programming-challenges
/challenges/Staircase
1,216
4.34375
4
#!/bin/python3 """ Problem: Consider a staircase of size (n=4): # ## ### #### Observe that its base and height are both equal to n and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n """ import math import os import random import re import sys # Complete the staircase function below. # Solution for the Staircase problem # Author: Mehdi Naderi Varandi def staircase(n): stringOutput="#" #String variable used later on to output the # character spaceCharacters=" " spacePosition=1 stringOutput=((spaceCharacters*(n-spacePosition)) + "#") initialCharacter="#" stringHorziontal=2 spacePosition+=1 for i in range(1,n): #Goes from each level to N e.g. from 1 to 5 (maximum level) stringOutput += ("\n" + (spaceCharacters*(n-spacePosition))+ (stringHorziontal*initialCharacter)) #Outputs line/# elements equal to the relevant number needed at that specific position stringHorziontal+=1 spacePosition+=1 print(stringOutput) #Return answer #End of submission if __name__ == '__main__': n = int(input()) staircase(n)
true
c957f654ddb5d6c2fa6353ad749a7dbbb151bc44
MehdiNV/programming-challenges
/challenges/Diagonal Difference
1,576
4.5
4
#!/bin/python3 """ Problem: Given a square matrix, calculate the absolute difference between the sums of its diagonals. For example, the square matrix (arr) is shown below: 1 2 3 4 5 6 9 8 9 Looking at the above, you can see that... The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17 . Their absolute difference is |15-17| = 2 The aim is to complete the function 'diagonalDifference', which returns an integer representing the absolute diagonal difference (when inputted the parameter arr) """ import math import os import random import re import sys # Complete the diagonalDifference function below. # Author: Mehdi Naderi Varandi def diagonalDifference(arr): #Start of code submission columnAndRow=arr[0] leftDiag=0 rightDiag=0 leftPointer=0 rightPointer=(len(arr[0])-1) for i in range(0,len(arr[0])): for j in range(0,len(arr[0])): if (j==leftPointer): leftDiag+=arr[i][j] if(j==rightPointer): rightDiag+=arr[i][j] leftPointer+=1 rightPointer-=1 return (abs(rightDiag-leftDiag)) #Return absolute difference (irregardless of whether its + or -) #End of code submission if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) fptr.write(str(result) + '\n') fptr.close()
true
586bd4a6b6ec0a7d844531448285fab1499f10bd
NontandoMathebula/AI-futuristic
/Python functions.py
1,492
4.53125
5
import math #define a basic function #def function1(): # print("I am a cute function") #function that takes arguments #def function2(arg1, arg2): #print(arg1, " ", arg2) #funcion that returns a value #def cube(x): #return x*x*x #function with default value for an argument def power(num, x = 1): result = 1 for i in range(x): result = result * num #it takes a number and raises it to the given power return result #function with variable number of arguments #def multi_add(*args): #the star character means I can pass a variable number of arguments #result = 0 #for x in args: # result = result + x #the function loops over each argument and adds them all to a running total, which is then returned #return result #"Parameter values" of the above functions #function1() #functions are objects that can be passed around to other pieces of Python code #print(function1()) #here the function is called inside the print statement the output should be "I am a cute function" #print(function1) #this function doesn't return a value, therefore, the output is set to "None" meaning it is not executed because there are no parathesis #function2(10,20) #print(function2(10,20)) #print(cube(3)) print(power(2, 1)) print(power(2, 3)) print(power(x=3, num=2))#function can be called in no particular order, if you supply the names along with the values print(math.pow(2,3)) #print(multi_add(30, 5, 10, 4))
true
cf8e3546673231056cd11c663e0dfde3b158fb9c
albertisfu/devz-community
/stacks-queues/stacks-queues-2.py
2,013
4.21875
4
#Node Class class Node: def __init__(self, data): self.data = data self.next_node = None #LinkedList Class class Stack: def __init__(self): self.head = None #append new elements to linked list method def push(self, data): new_node = Node(data) if self.head == None: self.head = new_node else: prev_head = self.head self.head = new_node new_node.next_node = prev_head def peek(self): if self.head != None: #print(self.head.data) return self.head.data else: #print('None') return None def pop(self): if self.head != None: last_node = self.head #print(last_node.data) self.head = last_node.next_node return last_node.data else: #print('None') return None #print elements of linked list def print_list(self): if self.head != None: current_node = self.head while current_node != None: print(current_node.data) current_node = current_node.next_node class StackQueue: def __init__(self): self.in_stack = Stack() self.out_stack = Stack() def push(self, data): self.in_stack.push(data) def pop(self): while self.in_stack.peek() != None: value = self.in_stack.pop() self.out_stack.push(value) return self.out_stack.pop() def peek(self): while self.in_stack.peek() != None: value = self.in_stack.pop() self.out_stack.push(value) return self.out_stack.peek() new_stack = StackQueue() new_stack.push(1) new_stack.push(2) new_stack.push(3) new_stack.push(4) new_stack.push(5) print('peek: ', new_stack.peek() ) print('pop: ', new_stack.pop() ) print('peek: ', new_stack.peek() )
true
796196c624f370d5237a3f5102e900e534adc4e7
sandeepmendiratta/python-stuff
/pi_value_to_digit.py
1,004
4.28125
4
#!/usr/bin/env python3 """"Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go.""" import math def getValueOfPi(k): return '%.*f' % (k, math.pi) def main(): """ Console Function to create the interactive Shell. Runs only when __name__ == __main__ that is when the script is being called directly No return value and Parameters """ print("Welcome to Pi Calculator. In the shell below Enter the number of digits upto which the value of Pi should be calculated or enter quit to exit") while True: try: entry = int(input("How many spaces? ")) if entry > 50: print("Number to large") # elif str(entry) == "quit": # break else: print(getValueOfPi(int(entry))) except: print("You did not enter an integer") if __name__ == '__main__': main()
true
092a3fd97569804c742af907c3279274384885fa
333TRS-CWO/scripting_challenge_questions
/draw_box.py
545
4.25
4
from typing import List ''' Complete the draw_box function so that given a non-negative integer that represents the height and width of a box, the function should create an ASCII art box for returning a list of strings. Then wall of the box should be made up of the "X" character The interior of the box should be made up of the " "(space) character Don't try to stack the box, just ensure you return the appropriate strings that could be stacked vertically, given proper formatting. ''' def draw_box(box_size: int) -> List[str]: pass
true
4698e65f6b47edcf78afa0b583ccc0bb873df5a3
shouryaraj/Artificial_Intelligence
/uniformed_search_technique/uniform-cost-search.py
1,787
4.21875
4
""" Implementation of the uniform cost search, better version of the BFS. Instead of expanding the shallowest node, uniform-cost search expands the node n with the lowest path cost """ from queue import PriorityQueue # Graph function implementation class Graph: def __init__(self): self.edges = {} self.weights = {} def neighbors(self, node): return self.edges[node] def get_cost(self, from_node, to_node): return self.weights[(from_node + to_node)] def uniform_cost_search(graph, start_node, goal): """ :param graph: The simple directed graph with the weight as string :param start_node: start node is the starting point :param goal: The end point to reach, that is goal state :return: nothing to return, prints the total cost """ path = set() explored = set() if start_node == goal: return path, explored path.add(start_node) path_cost = 0 frontier = PriorityQueue() frontier.put((path_cost, start_node)) while frontier: cost, node = frontier.get() if node not in explored: explored.add(node) if node == goal: print("all good") print("At the cost of " + str(cost)) return for neighbor in graph.neighbors(node): if neighbor not in explored: total_cost = cost + graph.get_cost(node, neighbor) frontier.put((total_cost, neighbor)) # Driver Function edges = { 'S': ['R', 'F'], 'R': ['P'], 'F': ['B'], 'P': ['B'] } weigth = { 'SR': 80, 'SF': 99, 'RP': 97, 'PB': 101, 'FB': 211 } simple_graph = Graph() simple_graph.edges = edges simple_graph.weights = weigth uniform_cost_search(simple_graph, 'S', 'B')
true
5f40dec210d36c3114c1d66a8c2c63371e93fa88
Pavithralakshmi/corekata
/m7.py
356
4.1875
4
print("cheack the given input is mulitiple by 7"); y=0 while y==0: num=int(input("enter ur first input")) if num>1: for i in range(1,num): if num%7==0: print (num,"this number is multiple by 7") break else: print(num,"this number is not multiple by 7") y=int(input("ënter 0 to continue else press 1"))
true
581c8b441de9dcafd76d98cfc6841f3b95bdf2c2
Pavithralakshmi/corekata
/sec.py
290
4.1875
4
print("calculate amounts of seconds ") days =int(input("Inputdays: ")) * 3600* 24 hours = int(input("Input hours: ")) * 3600 minutes = int(input("Input minutes: ")) * 60 seconds = int(input("Input seconds: ")) time = days + hours + minutes + seconds print("The amounts of seconds ", time)
true
da849e60a9415fcab68301964185eec25d87a179
ExerciseAndrew/Algorithms
/python/Stack.py
1,271
4.25
4
### Implementation of a stack using python list class Stack: def __init__(self, items): #creates empty stack self._theItems = list() def isEmpty(self) #returns True if stack is empty return len(self) == 0 def __len__(self): #returns number of items in the stack return len( self._theItems ) def peek(self): #returns top item of stack without removing it assert not self.isEmpty(), "cannot peek at an empty stack" return self._theItems[-1] def pop(self): #removes and returns the top item of the stack assert not self.isEmpty(), "cannot pop an empty stack" return self._theItems.pop() def push(self, itema): return self._theItems.append( item ) #Push an item to the top of the stack def is_balanced(self): #determines if stack is balanced or not for char in _theItems: if char in ['(', '[']: stack.push(char) else: if isEmpty(): return False stack.pop() if (top == '[' and char != ']') or (top == '(' and char != ')'): return False return
true
eea7f7d0ba7898a1710816682b1aa4fad7ca2731
Surfsol/Intro-Python-I
/src/12_scopes.py
1,019
4.375
4
# Experiment with scopes in Python. # Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables # When you use a variable in a function, it's local in scope to the function. x = 12 def change_x(): x = 99 change_x() x = 99 # This prints 12. What do we have to modify in change_x() to get it to print 99? print(x) # This nested function has a similar problem. def outer(): y = 120 def inner(): y = 999 inner() # This prints 120. What do we have to change in inner() to get it to print # 999? # Note: Google "python nested function scope". print(y) outer() #local, enclosing, global, built in #local x = 1 y = 2 def mmm(x): y = 3 print(x, y) mmm(10) print(x, y) x = 100 def my_outer(x): y = 50 def inner(): print(x,y) inner() my_outer(75) #last scope to be searched Builtin print(pow(2, 3)) #see builtin variables #puts a variable in global scope def vus(): global x x = 100 vus() print(x)
true
beaeb644f8fe8229b68743dd33a8c898fa70a701
Nathiington/COMP322
/Lab03/greatest.py
279
4.1875
4
num1 = int(input('Enter the first number: ')) num2 = int(input('Enter the second number: ')) if num1 > num2: print('{0} is greater than {1}'.format(num1,num2)) if num2 > num1: print('{0} is greater than {1}'.format(num2, num1)) else: print('Both numbers are equal')
true
15c333a2098d819b9a27780609d683801c0e8643
Btrenary/Module6
/basic_function_assignment.py
737
4.15625
4
""" Author: Brady Trenary Program: basic_function_assignment.py Program takes an employee's name, hours worked, hourly wage and prints them. """ def hourly_employee_input(): try: name = input('Enter employee name: ') hours_worked = int(input('Enter hours worked: ')) hourly_pay_rate = float(input('Enter hourly pay rate: ')) result = f'{name}, {hours_worked} hours worked, {hourly_pay_rate}/hr.' if name.isdigit(): print('Invalid name input') elif hours_worked < 0 or hourly_pay_rate < 0: print("Invalid input") else: print(result) except ValueError: print('Invalid input') if __name__ == '__main__': hourly_employee_input()
true
b247074ec75f920382e80eeae0f68a123d8e15d0
mathe-codecian/Collatz-Conjecture-check
/Collatz Conjecture.py
743
4.3125
4
""" The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. """ x = int(input("Enter a Number:\n")) step = 0 '''' Comment - (Loop for Finding The Whole sequence leading to 1 and number of steps involved)''' while x != 1: if x%2 == 0: x= x/2 else: x = 3*x +1 print(x) step +=1 print("Number of steps involved are " + str(step))
true
1f77b65cded382e0c1c0b149edf94e02c67f5bb5
farremireia/len-slice
/script.py
375
4.15625
4
toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms'] prices = [2,6,1,3,2,7,2] num_pizzas = len(toppings) print('We sell ' + str(num_pizzas) + ' different kinds of pizzas!') pizzas = list(zip(prices, toppings)) print(pizzas) pizzas.sort() print(pizzas) cheapest_pizza = pizzas[0] priciest_pizza = pizzas[-1] print(priciest_pizza)
true
87d31fe1d670b7c6dc43441b6eefc8f578cadc52
truevines/GenericExercise
/isomorphic_strings.py
1,115
4.1875
4
''' Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. For example, Given "egg", "add", return true. Given "foo", "bar", return false. Given "paper", "title", return true. Note: You may assume both s and t have the same length. ''' def isomorph(s, t): #boundary case if (len(s)!=len(t)): return False dic={} # s as the key; t as the value i=0 while (i<len(s)): # i-th character: #if s is in key, value must match if (s[i] in dic) and (dic[s[i]]!=t[i]): return False #if s is not in key, t must not in value if (s[i] not in dic) and (t[i] in iter(dic.values())): return False #if s is not in key, t not in value -> never appear #add relationship if (s[i] not in dic) and (t[i] not in iter(dic.values())): dic[s[i]]=t[i] i+=1 return True
true
2087c9753aaa8e60bd2add3256f03431a538d185
HarleyRogers51295/PYTHON-LEARNING
/1.1 PYTHON/1.4 pythong-numbers.py
1,445
4.21875
4
import math import random print("-------------BASICS & MATH--------------") #integer is a whole number ex. 4, 500, 67, 2........ no decimals #float has a decimal point ex. 1.521346584 ..... #python auto changes these for you if you do 1 + 1.5 it will be 2.5. #you can use +, -, /, *, %, **(to the power of!) print(abs(-50)) #returns the positive of the number entered print(abs(50)) print(10 + 5) print(10 - 5) print(10 * 5) print(10 / 5) print(10 % 5) print(10 ** 5) print(math.pow(10, 5)) print(math.log2(100000000)) #this will come up in the algo area print(random.randint(0, 1000)) #random number generator print("--------------TYPE CASTING-------------") result = "10" + "10" print(result) #type cast as such! result = int("10") + int("10") ##typically used with variuables. look below. print(result) print(type("10")) num_1 = "20" num_2 = "14" result = int(num_1) + int(num_2) # change to int print(result) print(type(result)) num_3 = 10 num_4 = 45 result_2 = num_3 + num_4 result_2= str(result_2) #chamge to string print(result_2) print(type(result_2)) ####CANNOT CONVERT things that are not numbers to an int! ex, harley cannot be a number.#### print("--------------INPUT FROM USER-------------") print("Welcome here! PLease enter yur numbers to be multiplied!") print("-" * 30) num_5 = input("Enter Your first number here: ") num_6 = input("Enter Your second number here: ") result_3 = int(num_5) * int(num_6) print(result_3)
true
ade8f044c63fbfac40e25b851ded70da30ab1533
the-potato-man/lc
/2018/21-merge-two-sorted-lists.py
776
4.125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Creating pointers so the original lists aren't modified p1 = l1 p2 = l2 dummy = p3 = ListNode(0) while p1 and p2: if p1.val < p2.val: p3.next = ListNode(p1.val) p1 = p1.next else: p3.next = ListNode(p2.val) p2 = p2.next p3 = p3.next if p1: p3.next = p1 else: p3.next = p2 return dummy.next
true
87cee9d43718c10c989e16c6c993abd82d40d4ef
uit-inf-1400-2017/uit-inf-1400-2017.github.io
/lectures/05-summary-and-examples/code/PointRobust.py
1,947
4.34375
4
# Program: RobustPoint.py # Authors: Michael H. Goldwasser # David Letscher # # This example is discussed in Chapter 6 of the book # Object-Oriented Programming in Python # from math import sqrt # needed for computing distances class Point: def __init__(self, initialX=0, initialY=0): self._x = initialX self._y = initialY def getX(self): return self._x def setX(self, val): self._x = val def getY(self): return self._y def setY(self, val): self._y = val def scale(self, factor): self._x *= factor self._y *= factor def distance(self, other): dx = self._x - other._x dy = self._y - other._y return sqrt(dx * dx + dy * dy) # imported from math module def normalize(self): mag = self.distance( Point() ) if mag > 0: self.scale(1/mag) def __str__(self): return '<' + str(self._x) + ',' + str(self._y) + '>' def __add__(self, other): return Point(self._x + other._x, self._y + other._y) def __mul__(self, operand): if isinstance(operand, (int,float)): # multiply by constant return Point(self._x * operand, self._y * operand) elif isinstance(operand, Point): # dot product return self._x * operand._x + self._y * operand._y def __rmul__(self, operand): return self * operand if __name__ == '__main__': a = Point() a.setX(-5) a.setY(7) print('a is', a) # demonstrates __str__ b = Point(8, 6) print('b is', b) print('distance between is', a.distance(b)) print(' should be same as', b.distance(a)) c = a + b print('c = a + b results in', c) print('magnitude of b is', b.distance(Point())) b.normalize() print('normalized b is', b) print('magnitude of b is', b.distance(Point())) print('a * b =', a * b) print('a * 3 =', a * 3) print('3 * a =', 3 * a)
true
afec1e0f73187993bcccc19b708eca0234b959f1
merileewheelock/python-basics
/objects/Person.py
1,904
4.21875
4
class Person(object): #have to pass the object right away in Python def __init__(self, name, gender, number_of_arms, cell): #always pass self, name is optional self.name = name self.gender = gender #these don't have to be the same but often make the same self.species = "Human" #all Persons are automatically set to human self.number_of_arms = number_of_arms self.phone = { "cell": cell, "home": "Who has a home phone anymore?" } def greet(self, other_person): print "Hello %s, I am %s!" % (other_person, self.name) def print_contact_info(self): if (self.phone["cell"] != ""): print "%s's number is %s" % (self.name, self.phone["cell"]) marissa = Person("Marissa", "female", 3, "770-777-7777") #self is always implied, don't pass self print marissa.name, marissa.gender, marissa.species, marissa.number_of_arms merilee = Person("Merilee", "female", 2, "770-555-5555") print merilee.species #this will return Human merilee.species = "Robot" print merilee.species #this will return Robot due to reassigning .species to robot print merilee.number_of_arms print marissa.phone["cell"] print marissa.phone["home"] marissa.greet("Rob") marissa.print_contact_info() #This will run the code print merilee.print_contact_info #This will not error but will print the actual method class Vehicle(object): def __init__(self, make2, model2, year2): self.make = make2 #2 added to make clearer self.model = model2 self.year = year2 def print_info(self): print self.year, self.model, self.make def change_year(self, new_year): self.year = new_year def get_year(self): return self.year david_cummings_car = Vehicle("Mcclaren", "Mp4-12c", 2013) david_cummings_car.print_info() david_cummings_car.change_year(2015) #These two are the same david_cummings_car.year = 2015 print david_cummings_car.year #These two are the same print david_cummings_car.get_year()
true
9a16c86ce7f42e1d826b67de35c866885e79c9b6
merileewheelock/python-basics
/dc_challenge.py
2,153
4.5
4
# 1) Declare two variables, a strig and an integer # named "fullName" and "age". Set them equal to your name and age. full_name = "Merilee Wheelock" age = 27 #There are no arrays, but there are lists. Not push, append. my_array = [] my_array.append(full_name) my_array.append(age) print my_array def say_hello(): print "Hello!" say_hello() # 4) Declare a variable named splitName and set it equal to # fullName split into two seperate objects in an array. # (In other words, if the variable fullName is equal to "John Smith", then splitName should # equal ["John", "Smith"].) # Print splitName to the console. # HINT: Remember to research the methods and concepts listed in the instructions PDF. split_name = full_name.split() print split_name # 5) Write another simple function that takes no parameters called "sayName". # When called, this function should print "Hello, ____!" to the console, where the blank is # equal to the first value in the splitName array from #4. # Call the function. (In our example, "Hello, John!" would be printed to the console.) def say_name(): print ("Hello, " + split_name[0]) say_name() # 6) Write another function named myAge. This function should take one parameter: the year you # were born, and it should print the implied age to the console. # Call the function, passing the year you were born as the argument/parameter. # HINT: http://www.w3schools.com/js/js_functions.asp def my_age(birthyear): print (2017 - birthyear) my_age(1989) # 7) Using the basic function given below, add code so that sum_odd_numbers will print to the console the sum of all the odd numbers from 1 to 5000. Don't forget to call the function! # HINT: Consider using a 'for loop'. def sum_odd_numbers(): sum = 0 for i in range(1,5001,2): #2 is the step (increases by 2) sum += i return sum print sum_odd_numbers() # def sum_odd_numbers(): # sum = 0 # for i in range(1,5001): # if (i % 2 == 1): #This uses the modulus instead of the step # sum += i # return sum # print sum_odd_numbers() i = 0 while 1: #this alone will run forever i += 1 print i if (i ==10): break print "We broke out of the loop!"
true
737f4b4ac58e7c1cd65b096b1f93db0fccfdfaa6
Zubair-Ali61997/learnOOPspring2020
/main1.py
1,752
4.3125
4
#Taking the range of number from the user to find even and odd using for loop startNum = int(input("Enter starting value: ")) endNum = int(input("Enter end value: ")) for eachNumber in range(startNum,endNum+1): modeValue = eachNumber % 2 if modeValue == 0: print(eachNumber, "is an even") else: print(eachNumber, "is an odd") #Taking the range of number from the user to find even and odd using while loop # taking_a_value = int(input("Enter a value: ")) startNum = int(input("Enter starting value: ")) endNum = int(input("Enter end value: ")) while (startNum >= endNum): modeValue = endNum % 2 if modeValue == 0: print(endNum, "is an even") else: print(endNum, "is an odd") endNum=endNum+1 #Finding totel number of odd and even in a range using for loop startNum = int(input("Enter starting value: ")) endNum = int(input("Enter end value: ")) evenNumber = 0 oddNumber = 0 for eachNumber in range (startNum, endNum+1): modeValue = eachNumber % 2 if modeValue == 0: evenNumber = evenNumber + 1 else: oddNumber = oddNumber + 1 print ("Total number of even number is = ",evenNumber) print ("Total number of odd number is = ",oddNumber) # Finding totel number of odd and even in a range using while loop startNum = int(input("Enter starting value: ")) endNum = int(input("Enter end value: ")) evenNumber = 0 oddNumber = 0 while (startNum >= endNum): modeValue = endNum % 2 if modeValue== 0: evenNumber = evenNumber + 1 else: oddNumber = oddNumber + 1 endNum = endNum + 1 print ("Total number of even number is = ",evenNumber) print ("Total number of odd number is = ",oddNumber)
true
6e892b4f6d70d5c79be4b157697d474eb6ebd5cb
G00387847/Bonny2020
/second_string.py
279
4.25
4
# Bonny Nwosu # This program takes asks a user to input a string # And output every second letter in reverse order. # Using Loop num1 = input("Please enter a sentence") def reverse(num1): str = "" for i in num1: str = i + str return str print(end="") print(num1[::-2])
true
fb2bb0a3eaab6f9cdc2cc9d35b0d23b992d21e41
skolte/python
/python2.7/largest.py
825
4.1875
4
# Write a program that repeatedly prompts a user for integer numbers until # the user enters 'done'. Once 'done' is entered, print out the largest and # smallest of the numbers. If the user enters anything other than a valid number # catch it with a try/except and put out an appropriate message and ignore the number. # Enter the numbers from the book for problem 5.1 and Match the desired output as shown. # Uses Python 2.7 largest = None smallest = None while True: num = raw_input("Enter a number: ") if num == "done" : break try: int(num) if (num > largest or largest is None): largest = num if (num < smallest or smallest is None): smallest = num except ValueError: print "Invalid input" print "Maximum is", largest print "Minimum is", smallest
true
d0e11c937aed44b865d184c98db570bfb5d522d5
jegarciaor/Python-Object-Oriented-Programming---4th-edition
/ch_14/src/threads_1.py
587
4.1875
4
""" Python 3 Object-Oriented Programming Chapter 14. Concurrency """ from threading import Thread class InputReader(Thread): def run(self) -> None: self.line_of_text = input() if __name__ == "__main__": print("Enter some text and press enter: ") thread = InputReader() # thread.start() # Concurrent thread.run() # Sequential count = result = 1 while thread.is_alive(): result = count * count count += 1 print(f"calculated squares up to {count} * {count} = {result}") print(f"while you typed {thread.line_of_text!r}")
true
0c98aecf543889b9c73f73b014508a184b0507e2
Tower5954/Instagram-higher-lower-game
/main.py
1,790
4.21875
4
# Display art # Generate a random account from the game data. # Format account data into printable format. # Ask user for a guess. # Check if user is correct. ## Get follower count. ## If Statement # Feedback. # Score Keeping. # Make game repeatable. # Make B become the next A. # Add art. # Clear screen between rounds. from game_data import data import random from art import logo, vs from replit import clear def format_account(account): """Format the data values into an account""" account_name = account["name"] account_descr = account["description"] account_country = account["country"] return f"{account_name}, a {account_descr}, from {account_country}" def check_answer(guess, a_followers, b_followers): """Take the users guess and compares with followers then returns if correct """ if a_followers > b_followers: return guess == "a" else: return guess == "b" print(logo) score = 0 game_continues = True account_b = random.choice(data) while game_continues: account_a = account_b account_b = random.choice(data) if account_a == account_b: account_b = random.choice(data) print(f"Compare A: {format_account(account_a)}") print(vs) print("") print(f"Against B: {format_account(account_b)}") print("") guess = input("Who has more instagram followers? Type 'A' or 'B' ").lower() a_follower_account = account_a["follower_count"] b_follower_account = account_b["follower_count"] is_correct = check_answer(guess, a_follower_account, b_follower_account) clear() print(logo) if is_correct: score += 1 print(f"Well done, you're correct! You're score is {score}") else: game_continues = False print(f"Who would have thought it, however Unfortunately you're wrong this time. You're final score is {score}")
true
80ac17949c445619dda20aa217ae6a7158b014ce
wz33/MagicNumber
/magic_number.py
1,761
4.3125
4
from builtins import input # for handling user input gracefully in Python 2 & 3 #!/usr/bin/env Python3 # Python 2 & 3 """ Program generates a random number between 1 and 100, inclusive. User has five attempts to correctly guess the number. """ # Import Python module import random # for "magic" number generation # Define variable MAX_ATTEMPTS = 5 # maximum number of guesses # Define functions def num_gen(): """ Return random number between 1 and 100, inclusive. """ return random.randint(1, 100) def user_guess(): """ Prompt player for guess. Return integer. """ while True: try: return int(input('Enter a guess: ')) except ValueError: print('Sorry, try again.') def play_again(): """ Prompt user for Y/N input. Return y or n. """ while True: again = input('Play again? Y/N: ').lower() if again == 'y' or again == 'n': return again def guessing_game(): """ Compare user guess to magic number. Provide user feedback. """ magic_number = num_gen() for attempt in range(MAX_ATTEMPTS): guess = user_guess() if guess < magic_number: print('Higher...') elif guess > magic_number: print('Lower...') else: print('That\'s right!') break if guess != magic_number: print('Out of guesses! The magic number was: %s.' % magic_number) def game_play(): """ Play game. Allow user to play multiple rounds or resign. """ while True: play = guessing_game() another_round = play_again() if another_round == 'y': continue else: break if __name__ == '__main__': print("\nWelcome to the magic number guessing game!\nSee if you can guess the magic number (1-100) in 5 attempts or less.\n") game_play()
true
8d56284d45480737b0b2cd79d8c2358355828f8b
zahidkhawaja/cs-module-project-iterative-sorting
/src/iterative_sorting/iterative_sorting.py
1,989
4.375
4
# Runtime complexity: O(n ^ 2) - Quadratic # Nested for-loop def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for x in range(cur_index, len(arr)): if arr[x] < arr[smallest_index]: smallest_index = x # Swapping the values arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index] return arr # Runtime complexity: O(n ^ 2) - Quadratic def bubble_sort(arr): needs_swapping = True while needs_swapping: # Change to false and change back to true only if a swap occurs # If a swap doesn't occur, it stays on false and the loop ends needs_swapping = False for x in range(len(arr) - 1): # If the current value is greater than the next value, swap the values if arr[x] > arr[x + 1]: arr[x], arr[x + 1] = arr[x + 1], arr[x] needs_swapping = True return arr ''' STRETCH: implement the Counting Sort function below Counting sort is a sorting algorithm that works on a set of data where we specifically know the maximum value that can exist in that set of data. The idea behind this algorithm then is that we can create "buckets" from 0 up to the max value. This is most easily done by initializing an array of 0s whose length is the max value + 1 (why do we need this "+ 1"?). Each buckets[i] then is responsible for keeping track of how many times we've seen `i` in the input set of data as we iterate through it. Once we know exactly how many times each piece of data in the input set showed up, we can construct a sorted set of the input data from the buckets. What is the time and space complexity of the counting sort algorithm? ''' def counting_sort(arr, maximum=None): # Your code here return arr
true
54dde7561bb2c3ef7fab4db446088c997c168037
ZhaohanJackWang/me
/week3/exercise3.py
2,448
4.40625
4
"""Week 3, Exercise 3. Steps on the way to making your own guessing game. """ import random def check_number(number): while True: try: number = int(number) return number except Exception: number = input("it is not number plz enter again: ") def check_upper(upper, low): upper = check_number(upper) print(type(upper)) while True: if upper > low: return upper else: upper = check_number(input("upper should bigger than low, plz enter again: ")) def advancedGuessingGame(): """Play a guessing game with a user. The exercise here is to rewrite the exampleGuessingGame() function from exercise 3, but to allow for: * a lower bound to be entered, e.g. guess numbers between 10 and 20 * ask for a better input if the user gives a non integer value anywhere. I.e. throw away inputs like "ten" or "8!" but instead of crashing ask for another value. * chastise them if they pick a number outside the bounds. * see if you can find the other failure modes. There are three that I can think of. (They are tested for.) NOTE: whilst you CAN write this from scratch, and it'd be good for you to be able to eventually, it'd be better to take the code from exercise 2 and merge it with code from excercise 1. Remember to think modular. Try to keep your functions small and single purpose if you can! """ lowBound = input("Enter an low bound: ") lowBound = check_number(lowBound) upperBound = input("Enter an upper bound: ") upperBound = check_upper(upperBound, lowBound) actualNumber = random.randint(lowBound, upperBound) guessed = -1 while guessed != actualNumber: guessedNumber = input("Guess a number: ") guessedNumber = check_number(guessedNumber) print("You guessed {},".format(guessedNumber),) if guessedNumber == actualNumber: print("You got it!! It was {}".format(actualNumber)) guessed = actualNumber elif guessedNumber > upperBound or guessedNumber < lowBound: print("outside of bounds") elif guessedNumber < actualNumber: print("Too small, try again :'(") else: print("Too big, try again :'(") return "You got it!" # the tests are looking for the exact string "You got it!". Don't modify that! if __name__ == "__main__": print(advancedGuessingGame())
true
69d705b017380b3127c4c7cfda8636c3d8c16e3d
SOURADEEP-DONNY/PYTHON-3-PROGRAMMING
/week 4/ALIASING.py
636
4.21875
4
list1=[10,20,30] list2=[10,20,30] #CHECKING WHETHER THE TWO LISTS ARE SAME OR NOT. print(list1 is list2) #CHECKING THE IDS OF THE TWO LISTS. print('THE ID OF list1 is',id(list1)) print('THE ID OF list2 is',id(list2)) #CHECKING WHETHER THE LISTS ARE EQUIVALENT OR NOT. print(list1==list2) #--------ALIASING---------- list1=list2 #AGAIN CHECKING THE IDS OF THE TWO LISTS. print('THE ID OF list1 is',id(list1)) print('THE ID OF list2 is',id(list2)) #AGAIN CHECKING WHETHER THE TWO LISTS ARE SAME OR NOT. print(list1 is list2) #AGAIN CHECKING WHETHER THE LISTS ARE EQUIVALENT OR NOT. print(list1==list2)
true
b259e685aef03dabe48233184d84bd228beac2a9
SOURADEEP-DONNY/PYTHON-3-PROGRAMMING
/PYTHON FUNCTIONS FILES AND DICTIONARIES/week 4/ADDITION OF AS MANY NUMBERS AS POSSIBLE.py
263
4.5
4
#PROGRAM TO ADD AS MANY NUMBERS AS POSSIBLE. TO STOP THE ADDITION ENTER ZERO. #THIS KIND OF LOOP IS ALSO KNOWN AS LISTENER'S LOOP. SUM=0 number=1 while number!=0: number=int(input('Enter a number to add-')) SUM=SUM+number print('The sum =',SUM)
true
53d6f8a3a438037857021c5d2264c6817c7406a1
olgarozhdestvina/pands-problems-2020
/Labs/Topic09-errors/check_input.py
417
4.28125
4
# Olga Rozhdestvina # a program that takes in a number as an input and subtracts 10% # prints the result, # the program should throw a value error of the input is less than 0 # input number num = int(input("Please enter a number: ")) # calculate 90% percent = 0.90 # (1- 0.10) ans = num * percent if num < 0: raise ValueError("input should be greater than 0: {}".format(num)) print("{} minus 10% is {}".format(num, ans))
true
524e98dfa7805b3c42ff0c3c021510afdabeaf0a
SirMatix/Python
/MITx 6.00.1x Introduction to Computer Science using Python/week 1/Problem set 1/Problem 3.py
1,413
4.15625
4
""" Problem 3 15.0/15.0 points (graded) Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head. """ # tracking variables initialization maxLen=0 current=s[0] longest=s[0] # program loop # iterating through letters of string s for letter in range(len(s) - 1): #if letter ahead current letter is 'bigger' add to current sequence if s[letter + 1] >= s[letter]: current += s[letter + 1] # if lenght of the current sequence is longer than maxLen update it # and current becomes longest if len(current) > maxLen: maxLen = len(current) longest = current else: current=s[letter + 1] # prints out the longest substring print ('Longest substring in alphabetical order is: ' + longest)
true
2cddfcca5ba5885135c7cf4271166db2a18b12a3
weishanlee/6.00.1x
/PS01/1_3.py
2,047
4.28125
4
# create random letter lists to test PS1 import random import string def test(tests,a,b): ''' tests: int, the number of tests to perform a: int, the length of the shortest string allowed b: int, the length of the maximum string allowed ''' n = 0 while n < tests: s = generate_string(a,b) word = longest_string(s) print s print 'Longest substring in alphabetical order is: ' + str(word) n += 1 return def generate_string(a,b): ''' total: int, the maximum number of letters in the string new_string: string, will hold the new string for testing n: int: ''' new_string = '' n = 0 total = random.randrange(a,b) #print 'the total number of letters are: ' + str(total) if total == 26: new_string = 'abcdefghijklmnopqrstuvwxyz' elif total == 5: new_string = 'zyxwvutsrqponmlkjihgfedcba' else: while n < total: letter = random.choice(string.letters) new_string += letter n += 1 #print new_string.lower() return new_string.lower() def longest_string(s): ''' current longest: string testing: char the_longest: string ''' n = 0 current_longest = '' testing = s[n] the_longest = s[n] while n < len(s) - 1: if s[n] <= s[n+1]: testing += s[n+1] #print testing elif s[n] > s[n+1]: #print 'current: ' + str(current_longest) #print 'longest: ' + str(the_longest) if len(current_longest) > len(the_longest): the_longest = current_longest current_longest = testing testing = s[n+1] if len(testing) > len(the_longest): the_longest = testing n += 1 #print 'Longest substring in alphabetical order is: ' + str(the_longest) return the_longest test(5,5,26)
true
0b204934269b03e929537727a134c4e5685a964f
weishanlee/6.00.1x
/PS03/3_3.py
1,389
4.21875
4
secretWord = 'apple' lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. It starts by converying the secretword to a list and by creating an empty list with underscores for the word that they are trying to find. Then it loops through for each element in the lettersGuessed list looking to see if it is in each of the positions of the secret list. each time it finds a letter that is in both it updates the guess with the letter in the correct position it then returns the clue with spaces between each letter to make it more readabile. ''' # FILL IN YOUR CODE HERE... secret = list(secretWord) guess = [] for letter in secret: guess.append('_') for element in lettersGuessed: n = 0 while n < len(secret): if element == secret[n]: guess[n] = element n += 1 clue = '' for each in guess: clue += each clue += ' ' return clue print getGuessedWord(secretWord, lettersGuessed)
true
3b5db557711710d79a80e3c008ab4b04fe29e1aa
josephantony8/GraduateTrainingProgram2018
/Python/Day5/Listcommand.py
1,828
4.5
4
Consider a list (list = []). You can perform the following commands: insert i e: Insert integer e at position i. print: Print the list. remove e: Delete the first occurrence of integer e. append e: Insert integer e at the end of the list. sort: Sort the list. pop: Pop the last element from the list. reverse: Reverse the list. Initialize your list and read in the value of followed by lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list. comlist=[] comcount=int(raw_input("Enter the number of commands")) for i in range(comcount): cmd=raw_input("enter the command and values") ins=cmd.split(' ') if(ins[0]=='insert'): try: if(ins[1].isdigit()==True and ins[2].isdigit()==True and len(ins)==3): comlist.insert(int(ins[1]),int(ins[2])) else: print("Enter proper integer values") except Exception as error: print(error) elif(ins[0]=='print'): print(comlist) elif(ins[0]=='remove' and len(ins)==2): try: comlist.remove(int(ins[1])) except Exception as error: print(error) elif(ins[0]=='append' ): if(ins[1].isdigit()==True and len(ins)==2): comlist.append(int(ins[1])) else: print("Enter proper integer values") elif(ins[0]=='sort'): if(len(ins)==1): comlist.sort() else: comlist.sort() print("Sort doesn't need any arguments") elif(ins[0]=='pop'): try: if(len(ins)==1 and ins[1].isdigit()==True): comlist.pop() elif(len(ins)==2 and ins[1].isdigit()==True): comlist.pop(int(ins[1])) elif(len(ins)>2): comlist.pop(int(ins[1]),int(ins[2])) except Exception as error: print(error) elif(ins[0]=='reverse'): if(len(ins)==1): comlist.reverse() else: comlist.sort() print("reverse doesn't need any arguments")
true
954fbd695169cf5ca915f4afa14673647e4a77b4
olzama/Ling471
/demos/May13.py
1,688
4.15625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression # Linear regression demo X = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] # Want: y = 2x + 0 (m = 2, b = 0) Y = [2*x for x in X] # list comprehension Y_2 = [x*x for x in X] Y_3 = [x*x*x for x in X] # for x in X: # Y.append(2*x) # plt.plot(X,Y,color="red") # plt.plot(X,Y_2,color="blue") # plt.plot(X,Y_3,color="green") # plt.show() # The data: Distance needed for cars at different speeds to stop data_url = 'https://raw.githubusercontent.com/cmdlinetips/data/master/cars.tsv' cars = pd.read_csv(data_url, sep="\t") print(cars.head()) print(cars.shape) # cars['dist'] X = cars.dist.values Y = cars.speed.values plt.scatter(X, Y) plt.xlabel('Distance to stop (ft)') plt.ylabel('Speed (mph)') # plt.show() lr = LinearRegression() X_matrix = [[x] for x in X] lm = lr.fit(X_matrix, Y) predictions = lm.predict(X_matrix) plt.plot(X, predictions) # plt.show() # By the way, that's how you could do it without any package: # Create a matrix where first column is all 1s and second column is our X data # To use the linear algebra package, need to use the numpy, # because the linear algebra backage expects a proper matrix. # Could use pandas objects as well. #X_matrix = np.vstack((np.ones(len(X)), X)).T # Find our A matrix (the vector of parameters) by solving a matrix equation: #best_parameters_for_regression = np.linalg.inv(X_matrix.T.dot(X_matrix)).dot(X_matrix.T).dot(Y) # Prediction line: Multiply X by A, now that we know A: #predictions = X_matrix.dot(best_parameters_for_regression) #plt.plot(X, predictions) # plt.show()
true
8fa9a8bf7fe98cf7785f5a40d0dc19b0173cfa9d
nbackas/dsp
/python/q8_parsing.py
678
4.125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled Goals and Goals Allowed contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in for and against goals. # The below skeleton is optional. You can use it or you can write the script with an approach of your choice. import pandas epl = pandas.read_csv("football.csv") diff = epl["Goals"]-epl["Goals Allowed"] min_ind = diff.idxmin() print epl["Team"][19]
true
8c1ce3b11bdaee1a2cea312cdd71334fd944ca25
Manpreet-Bhatti/WordCounter
/word_counter.py
1,477
4.28125
4
import sys # Importing the ability to use the command line to input text files import string # Imported to use the punctuation feature def count_the_words(file_new): # Counts the total amount of words bunch_of_words = file_new.split(" ") amount_of_words = len(bunch_of_words) return amount_of_words def most_common(file_new): # Counts and prints the most common words in (word, count) format for p in string.punctuation: # Cleans the punctuation file_new = file_new.replace(p, " ") new_words = file_new.lower().split() lone = set() # Set of unique words for w in new_words: lone.add(w) pairs = [] # List of (count, unique) tuples for l in lone: count = 0 for w in new_words: if w == l: count += 1 pairs.append((count, l)) pairs.sort() # Sort the list pairs.reverse() # Reverse it, making highest count first for i in range(min(10, len(pairs))): # Print the ten most frequent words count, word = pairs[i] print("%s: %d" %(word, count)) if __name__ == "__main__": # Run code below if a text file is inputted if len(sys.argv) < 2: print("Usage: python word_count.py <file name>.txt") exit(1) filename = sys.argv[1] f = open(filename, "r") file_data = f.read() f.close() most_common(file_data) num_of_words = count_the_words(file_data) print("The total number of words are: %d" %(num_of_words))
true
25cfb5db84e817269183a1686d9f4ff72edaaae4
gcd0318/pe
/l5/pe102.py
1,454
4.125
4
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ def oriIsSameSide(x1, y1, x2, y2, x3, y3): return (y1*(x2-x1)-x1*(y2-y1))*((x3-x1)*(y2-y1)-(x2-x1)*(y3-y1)) > 0 def oriIsIn(x1, y1, x2, y2, x3, y3): res = True i = 0 while(res and(i < 3)): res = res and oriIsSameSide(x1, y1, x2, y2, x3, y3) tx = x1 ty = y1 x1 = x2 y1 = y2 x2 = x3 y2 = y3 x3 = tx y3 = ty i = i + 1 return res f = open('triangles.txt', 'r') ls = f.readlines() f.close() i = 0 for l in ls: sx1, sy1, sx2, sy2, sx3, sy3 = l.strip().split(',') x1 = int(sx1) y1 = int(sy1) x2 = int(sx2) y2 = int(sy2) x3 = int(sx3) y3 = int(sy3) if oriIsIn(x1, y1, x2, y2, x3, y3): i = i + 1 print(i)
true
9010ea2d997ec82fcd62f887802e1dc6f599f70f
edward408/bicycleproject
/bikeclasses.py
1,717
4.25
4
#Modeling the bicycle industry #Classes layout #Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. #Methods are essential in encapsulation concept of the OOP paradigm class Bicycle(object): def __init__(self,model,weight,production_cost): self.model = model self.weight = weight self.production_cost = production_cost self.retail_cost = self.production_cost * 1.20 class Bike_Shop(object): """Defines the bike shop with its respective inventory""" def __init__(self,store_name): self.store_name = store_name self.store_inventory = [] self.affordable_bikes = [] def display_bikes(self): print "The store is called %s and it has %s" % (self.store_name,self.bikes) def bikes_under(self, budget): for bike in self.store_inventory: if bike.retail_cost <= budget: self.affordable_bikes.append(bike) def getAffordableBikes(self): return self.affordable_bikes class Customers(Bike_Shop): def __init__(self,name,budget): self.name = name self.budget = budget self.shopping_cart ={} def purchase(self,store_inventory,affordable): for bike in store_inventory: if bike in affordable: self.shopping_cart[bike.model]=bike.retail_cost self.budget -=bike.retail_cost store_inventory.remove(bike) def display_customers(self): print "Customer is %s and with a budget of %s dollars" % (self.name, self.budget)
true
93fe3bdc09d05d492d4752b3d3300120e9c6b902
pratik-iiitkalyani/Data_Structure_and_Algo-Python-
/interview_problem/reverse_sentance.py
576
4.375
4
# Write a program to print the words of a string in reverse order. # Sample Test Cases: # INPUT: Hi I am example for this program # OUTPUT: Program this for example am I Hi def revrseSentanse(str): # spilt all the word present in the sentance sentance = str.split(" ") # the first letter of last word of sentance will be capital sentance[-1] = sentance[-1].title() # reverse the sentance input = sentance[::-1] # join the words output = ' '.join(input) return output str = "Hi I am example for this program" print(revrseSentanse(str))
true
6d6c68769059fc9e98f45d934c014ca7d1d5c47d
bretuobay/fileutils
/exercises5.py
684
4.1875
4
''' Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon". ''' def translate(str_input): vowel_list = ['A', 'E', 'I', 'O', 'U'] temp = str_output = '' # TODO: remove when there are spaces for char in str_input: if char.upper() not in vowel_list or char.isspace() == True : temp = char + 'o' + char else: temp = char str_output += temp return str_output print (translate("this is fun"))
true
d857a6d39e3b537539c9e5f74e45a11c78d1545f
bretuobay/fileutils
/exercises7.py
440
4.59375
5
''' Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I". ''' # this works by slicing from the end #This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string. def reverse(input_str): return input_str[::-1] print(reverse("I am testing"))
true
35b40ee37d55f57f862dd0d76bdf73ce42bf1c92
rozeachus/Python.py
/NumberGuess.py
1,035
4.40625
4
""" This program will allow a user to guess a number that the dice will roll. If they guess higher than the dice, they'll get a message to tell them they've won. If its lower than the dice roll, they'll lose. """ from random import randint from time import sleep def get_user_guess(): guess = int(input("Guess a number.... ")) return guess def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sides) max_val = number_of_sides * 2 print ("The maximum possible value is: %d" % max_val) guess = get_user_guess() if guess > max_val: print ("This value is higher than the value allowed") else: print ("Rolling...") sleep(2) print ("The first roll is: %d" % first_roll) sleep(1) print ("The second roll is: %d" % second_roll) sleep(1) total_roll = first_roll + second_roll print ("The result is....") sleep(1) if guess > total_roll: print ("You've won!") else: print ("Sorry, you lost") roll_dice(6)
true
a5a954481f937f566af621b3071afb1e90783ab3
guti7/hacker-rank
/30DaysOfCode/Day08/phone_book.py
1,020
4.3125
4
# Day 8: Dictionaries and Maps # Learn about key-value pair mappings using Map or a Dicitionary structure # Given n names and phone numbers, assemble a phone book that maps # friend's names to their respective phone numbers # Query for names and print "name=phoneNumber" for each line, if not found # print "Not found" # Note: Continues to read lines until EOF. import sys n = int(raw_input().strip()) phone_book = {} for i in range(n): # range max in not inclusive info_array = list(raw_input().strip().split()) # Build dictionary structure phone_book[info_array[0]] = info_array[1] print info_array print phone_book # for line in sys.stdin: # name = line.strip() # if name in phone_book: # print '%s=%s' % (name, phone_book[name]) # else: # print "Not found" while True: try: name = raw_input() if name in phone_book: print "%s=%s" % (name, phone_book[name]) else: print 'Not Found' except: break
true
aeea679670645912d34b278ae177905d59c87bed
par1321633/problems
/leetcode_october_challenge/minimum-domino-rotations-for-equal-row.py
2,457
4.375
4
""" In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Example 1: Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. """ from typing import List class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: # print (A) # print (B) a_hash = {} b_hash = {} max_val_a = 0 max_val_b = 0 for i in range(len(A)): # print (A[i], B[i]) if A[i] not in a_hash: a = self.check_swap_numbers(A, B, A[i]) if a != -1: a_hash[A[i]] = a if B[i] not in b_hash: b = self.check_swap_numbers(B, A, B[i]) if b != -1: b_hash[B[i]] = b # print (a_hash, b_hash) if len(a_hash) == 0 and len(b_hash) == 0: return -1 a_min = min([val for i, val in a_hash.items()]) b_min = min([val for i, val in b_hash.items()]) return min(a_min, b_min) def check_swap_numbers(self, A, B, val): # print (A, B, val) swap_num = 0 for i in range(len(A)): # print (A[i], B[i], val) if A[i] != val and B[i] != val: return -1 elif A[i] != val and B[i] == val: swap_num = swap_num + 1 return swap_num if __name__ == '__main__': A = [2,1,2,4,2,2] B = [5,2,6,2,3,2] print ("Case 1 : A {}, B {}".format(A, B)) sol = Solution().minDominoRotations(A, B) print ("Solution : {}".format(sol)) A = [3,5,1,2,3] B = [3,6,3,3,4] print("Case 2 : A {}, B {}".format(A, B)) sol = Solution().minDominoRotations(A, B) print("Solution : {}".format(sol))
true
1cd2a64be451bc3b5375777c203dca390eb4b1cc
Deepak-Deepu/Thinkpython
/chapter-5/exercise5.4.py
350
4.125
4
a = int(raw_input('What is the length of the first side?\n')) b = int(raw_input('What is the length of the first side?\n')) c = int(raw_input('What is the length of the first side?\n')) def is_triangle(a, b,c): if a > (b+c): print('No') elif b>(a+c): print('No') elif c > (a+b): print('No') else: print('Yes') print is_triangle(a, b,c)
true
88350f210e517a64996c1b7a382a93447fda8792
emilywitt/HW06
/HW06_ex09_06.py
951
4.3125
4
#!/usr/bin/env python # HW06_ex09_05.py # (1) # Write a function called is_abecedarian that returns True if the letters in a # word appear in alphabetical order (double letters are ok). # - write is_abecedarian # (2) # How many abecedarian words are there? # - write function(s) to assist you # - number of abecedarian words: ############################################################################## # Imports # Body def is_abecedarian(word): if len(word) <= 1: return True if word[0] > word[1]: return False return is_abecedarian(word[1:]) ############################################################################## def main(): with open("words.txt", "r") as fin: count_abc = 0 total_words = 0 for line in fin: total_words += 1 word = line.strip() if is_abecedarian(word): count_abc+= 1 print count_abc # print is_abecedarian('best') if __name__ == '__main__': main()
true
9d9206ef57e6dfb7444b1eb1391f5d705fb3c929
singhsukhendra/Data-Structures-and-algorithms-in-Python
/Chapter#02/ex_R_2_9.py
2,612
4.34375
4
class Vector: """ Represent a vector in a multidimensional space.""" def __init__(self, d): """ Create d-dimensional vector of zeros. """ self._coords = [0] * d def __len__(self): # This special method allows finding length of class instance using len(inst) style . """ Return the dimension of the vector. """ return len(self._coords) def __getitem__(self, j): ## This special method let you get the value using square bracket notation. like inst[j] """ Return jth coordinate of vector.""" return self._coords[j] def __setitem__(self, j, val): ## This special method let you set the value using square bracket notation. like inst[j] = 10 """ Set jth coordinate of vector to given value.""" self._coords[j] = val def __add__(self, other): ## lets you use + operator """ Return sum of two vectors.""" if len(self) != len(other): # relies on len method raise ValueError("dimensions must agree") result = Vector(len(self)) # start with vector of zeros for j in range(len(self)): result[j] = self[j] + other[j] return result def __eq__(self, other): ## lets you use == operator """Return True if vector has same coordinates as other.""" return self._coords == other._coords def __sub__(self, other): ## lets you use == operator if len(self) != len(other): # relies on len method raise ValueError("dimensions must agree") """Return True if vector has same coordinates as other.""" result = Vector(len(self)) for i in range(len(self)): result[i] = self._coords[i] - other._coords[i] return result def __neg__(self): ## This special method let you use -inst """Produce string representation of vector.""" result = Vector(len(self)) for i in range(len(self)): result[i] = - self._coords[i] return result def __ne__(self, other): ## lets you use != operator """ Return True if vector differs from other.""" return not self == other # rely on existing eq definition def __str__(self): ## This special method let you use print() function to print a representation of the class instance. """Produce string representation of vector.""" return '<' + str(self._coords)[1:-1] + '>' # adapt list representation if __name__ == '__main__': vec1 = Vector(3) vec1[0] = 10 vec2 = Vector(3) vec2[1] = 10 print(vec2) print(-vec2)
true
381fe255c58115bb31ccba6a94d3f69216367d9f
fredzhangziji/myPython100Days
/Day3_BranchStructure/practice1_cmToinch.py
740
4.5
4
''' Convert between cm and inch 12/17/2019 written by Fred Zhang ''' while True: print("\n\n-------Welcome to cm/inch Converter Version 1.0-------") print("Enter 'cm' for converting inch to cm;") print("Enter 'inch for converting cm to inch;") print("Enter 'e' for exiting the program.") print("Select option: ") selection = input() if selection == 'cm': inch = float(input('Enter inch: ')) cm = inch * 2.54 print("%.2f inches = %.2f cm" % (inch, cm)) elif selection == 'inch': cm = float(input("Enter cm: ")) inch = cm / 2.54 print('%.2f cm = %.2f inch' % (cm, inch)) elif selection == 'e': break else: print("Invalid input.")
true
4db295d5fb56f4a6779bffc189e483f6fe58dfb0
fredzhangziji/myPython100Days
/Day3_BranchStructure/practice2_pointToGrade.py
678
4.15625
4
''' Convert 100-point scale to grade scale 12/17/2019 written by Fred Zhang ''' print('\n\nYo this is a grade converter you sucker!\n') point = int(input('put in your stupid-ass points here: ')) print() if point <= 100 and point >= 90: print('You got a fucking A. Greate fucking job!') elif point < 90 and point >= 80: print("B. Hmm. Can't you fucking do a lil better than dat?") elif point < 80 and point >= 70: print("You got a C. Did you take Dr. Canas' class?") elif point <70 and point >= 60: print("D. Noob.") elif point < 60: print("Go home kid. You fucking failed.") else: print("How'd fuck you get over 100 points? Reported.") print()
true
28df5a8ca0c2ed5bf2bdbc571844a352d9266fd8
fredzhangziji/myPython100Days
/Day2_Variable_Operator/practice1_FahrenheitToCelsius.py
1,227
4.53125
5
''' A simple program to convert between Fahrenheit and Celsius degrees. 12/17/2019 written by Fred Zhang ''' while True: print('**************************************************') print('**************************************************') print('Welcome to Fahrenheit and Celsius degree converter') print('Enter the option:') print('c for Fahrenheit to Celsius degree;') print('f for Celsius to Fahrenheit degree;') print('e for exiting the program.') print('**************************************************') print('**************************************************') userInput = input() if userInput == 'c': DegreeF = float(input('Enter the Fahrenheit degree: ')) DegreeC = (DegreeF - 32) / 1.8 print('The Celsius degree is: ', DegreeC) if userInput == 'f': DegreeC = float(input('Enter the Celsius degree: ')) DegreeF = 1.8 * DegreeC + 32 print('The Fahrenheit degree is: ', DegreeF) if userInput == 'e': break if userInput != 'c' and userInput != 'f' and userInput != 'e': print('userInput at this point is: ', userInput) print("Invalid input. Please enter a valid input.")
true
6ff06eb58bc0deca7987c036855822e85e368745
shivamsood/Python
/factorial.py
267
4.46875
4
#Code to calculate Factorial of the user entered integer factorial_input = input("Please enter the number to calculate Factorial\n\n") output = 1 while factorial_input >= 1: output *= factorial_input factorial_input -=1 print "The Factorial is {}".format(output)
true
be172b3b278c917d476ef101884bf526e6997862
youth-for-you/Natural-Language-Processing-with-Python
/CH-1/Exercises/10.py
680
4.125
4
#Define a variable my_sent to be a list of words,using the syntax my_sent = ["My", "sent"] # (but with your own words, or a favorite saying). #Use ' '.join(my_sent) to convert this into a string. #Use split() to split the string back into the list form you had to start with. if __name__ == '__main__': my_sent = ['I', 'Love', 'Python', '!'] # join():连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 str_my_sent = ' '.join(my_sent) print(str_my_sent) #输出I Love Python ! list_my_sent = str_my_sent.split() print(list_my_sent) #输出['I', 'Love', 'Python', '!']
true
11ff73edd6eb7d4142a374916bfcf13662ee83ff
poojatathod/Python_Practice
/max_of_list.py
556
4.375
4
#que 13: The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one. def max_of_list(list1): return max(list1) inpt=input("enter a list of element: ") list1=inpt.split() list1=[int(a) for a in list1] output=max_of_list(list1) print("maximum no from a list is: ",output)
true
e3d61428e98c35ba2812b991330964bc362a0f6c
poojatathod/Python_Practice
/translate.py
1,023
4.15625
4
#que 5: Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon". def translate(string): c=0 list1=[] for x in string: for y in string1: if(x==y): c+=1 if(c==0): list1.append(x) list1.append("o") list1.append(x) else: list1.append(x) c=0 return ''.join(list1) def translate1(string): list1=[] for x in string: if x not in string1: list1.append(x) list1.append("o") list1.append(x) else: list1.append(x) return ''.join(list1) string=(input("enter a string: ")) string1="aeiouAEIOU " output=translate1(string) print(output) #alternative function for translate is translate1 both gives same output
true
ecc17cab948c55d4262611b10b8cf6152c5297d3
poojatathod/Python_Practice
/longest_world.py
401
4.34375
4
#que 15: Write a function find_longest_word() that takes a list of words and returns the length of the longest one. def longest_word(string): list1=[] for x in string: list1.append=len(x) outpt=max(list1) outpt1=list1.index(outpt) outpt2=string[outpt1] return outpt2 string=input("enter a string: ") string=string.split() output=longest_word(string) print(output)
true
8e8d9b4f6cca0fba2c9b14d044ae44aa017529d5
GucciGerm/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
589
4.28125
4
#!/usr/bin/python3 class MyList(list): """ MyList - Created this class to inherit components from list Args: list - This is the list that we will be inheriting from Return: None, will print the sorted inherited list """ def print_sorted(self): """ print_sorted - This will print the list, but sorted (ascending sort) Args: self - defining that we will just refer to itself Return: None """ print(sorted(self)) """ The function will print the list in sorted (ascending sort) """
true
04e3213d38a169dee4919acce36d7537edcfd27f
GucciGerm/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
590
4.46875
4
#!/usr/bin/python3 """ say my name module """ def say_my_name(first_name, last_name=""): """ say_my_name - This function will print "My name is <first><last>" Args: first_name - is the users first name last_name - is the users last name Return: None """ def say_my_name(first_name="", last_name=""): if type(first_name) != str: raise TypeError("first_name must be a string") if type(last_name) != str: raise TypeError("last_name must be a string") else: print("My name is {} {}".format(first_name, last_name))
true
8b06343d1d12cd050ae44928ebcc321809abb08f
GucciGerm/holbertonschool-higher_level_programming
/0x0B-python-input_output/11-student.py
772
4.21875
4
#!/usr/bin/python3 class Student: """ Creating a class named Student """ def __init__(self, first_name, last_name, age): """ __init__ - Initializing attibutes Args: first_name - This is the first name passed last_name - This is the last name passed age - This is the age passed Return: Here we want to return the dictionary representation of student instances """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self): """ to_json - This will retrieve the dictionary representation of Student instance Return: The dictionary """ return (self.__dict__)
true
3c403aebce458271cc65041f15a420abb8f010b3
Cipher-007/Python-Program
/Convert_miles_to_Km.py
237
4.375
4
#Converting Miles to Kilometers miles = float(input("Enter Miles to be converted into Kilometers: ")) #Conversion factor conversion_factor = 1.609 #Conversion kilometers = miles * conversion_factor print(f"{miles}mi is {kilometers}Km")
true
13c88ffd58b096511ee71e2752e0dc588c71cfed
lchoe20/lchoe20.github.io
/challenge1.py
806
4.21875
4
#challenge 1 prompt: create a guess the number uding a while loop from random import * #import * is a wild card that says import all information aRandomNumber = randint(1,20) #inclsuive #generates a randominteger guess = input("Guess a number between 1 and 20 inclusive: ") #assume user's guess is equal to 5 if not guess.isnumeric(): #checks to see if users guess is a real number print("That's not a positive whole number, try again!") else: guess = int(guess) #converts a string to an integer if guess < 1 or guess > 20: print("That's not a positive whole number, try again!") elif(guess > aRandomNumber): print("Pick a smaller number") elif(guess < aRandomNumber): print("Pick a smaller number") else: print("You win!") print("game over")
true
278597b789075960afb774815cf487ca6fc22cff
appledora/SecurityLab_2_3
/Task_2/CeaserCipher.py
1,575
4.1875
4
import string import time alpha = string.ascii_letters def ceaser_decrypt_without_key(target): print("DECRYPTING....") key = 0 while key <= 26: temp = "" for char in target: if char.isalpha(): temp += alpha[(alpha.index(char)-int(key)) % 26] else: temp += char print(temp + " ........... key: ", key) key = key + 1 def ceaser_decrypt(target, shift): print("DECRYPTING....") temp = "" temp = "" for char in target: if char.isalpha(): temp += alpha[(alpha.index(char)-int(shift)) % 26] else: temp += char print(temp) def main(): objType = input( "type 1 if you want to decrypt a string with a key and 2 if you want to decrypt in Brute-force... \n") if (int(objType) == 1): target = input( "Type the string you want to DECRYPT with a known KEY : \n") shift = input("Enter the shift key : \n") start_time = time.time() ceaser_decrypt(target, shift) print("--- %s seconds ---" % (time.time() - start_time)) elif (int(objType) == 2): target = input("Type the string you want to brute-force DECRYPT : \n") start_time = time.time() ceaser_decrypt_without_key(target) print("--- %s seconds ---" % (time.time() - start_time)) else: print("Only select 1 or 2") main() print("Congratulations!") if __name__ == "__main__": main()
true
9603b36b1bba94a0929fb0c2d436e6257184fef8
elizabethdaly/collatz
/collatz.py
519
4.3125
4
# 16 sept 2019 collatz.py # n is the number we will perform Collatz on. # n = 20 # Request user input. n = int(input("Please enter an integer n: ")) # Keep looping until n = 1. # Note: Assumes Collatz conjecture is true. while n != 1: # Print the current value of n. print(n) # Check if n is even. if n % 2 == 0: # If n is even, divide n by 2. n = n / 2 else: # If n is odd, multiply n by 3 and add 1. n = (3 * n) + 1 # Finally, print the current value of n. print(n)
true
2d0da772303ac46285ea43b6283a17c4823e52f3
Noah-Huppert/ksp-sandbox
/src/lib/velocity.py
1,716
4.53125
5
""" calc_energy calculates the kinetic energy for a given body traveling in 1D Arguments: - m (float): Mass of body - v (float): Velocity of body Returns: - float: Kinetic energy of body """ def calc_energy(m, v): # Ensure kinetic energy is negative if velocity is negative # (Separate logic necessary because velocity looses its sign in the eq due # to being raised to the power of 2) dir = 1 if v < 0: dir = -1 # Kinetic energy eq: (1/2) * m * v^2 return dir * (m * (v ** 2)) / 2 """ calc_acceleration calculates the acceleration needed to accelerate from an initial to final velocity in a specified length of time. Arguments: - vi (float): Initial velocity - vf (float): Final velocity - dt (float): Time Returns: - float: Acceleration """ def calc_acceleration(vi, vf, dt): # Derived from formula: vf = vi + (a * t) return (vf - vi) / dt """ calc_delta_distance calculates the 1D distance travelled at a specific velocity in a certain time. Arguments: - vi (float): Initial velocity - vf (float): Final velocity - dt (float): Time duration Returns: - float: Distance covered """ def calc_delta_distance(vi, vf, dt): # Formula: d = (vi * t) + ((1/2) * a * t^2) a = calc_acceleration(vi, vf, dt) return (vi * dt) + (0.5 * a * (dt ** 2)) """ calc_force calculates the force needed to add the specified kinetic energy to a body in a certain distance. Arguments: - delta_energy (float): Energy to add to the body - delta_distance (float): Distance to add energy to body in Returns: - float: Force """ def calc_force(delta_energy, delta_distance): return delta_energy / delta_distance
true
2801333709f62497a68f7925030ddbe55a0397b6
MrZebarth/PythonCheatSheet2019
/Conditionals.py
977
4.40625
4
# Conditionals # We want to be able to make decisions based on our variables # We use the "if" statment with a condition to check for a result num1 = int(input("Enter a first number: ")) num2 = int(input("Enter a second number: ")) if num1 > num2: print(num1, "is greater than", num2) elif num1 < num2: print(num1, "is less than", num2) else: print(num1, "is the same as", num2) # You can have as many "elif" statements as you want. Each one must have a different condition # The "else" statement always goes last. This is run if none of the other conditions are met. # We can also use this with words and letters password = input("Enter the password: ") realPassword = "Pa$$w0rd" if password == realPassword: print("You got it!") else: print("Wrong password") # Possible comparisons # == equal # != not equal # > greater than # < less than # >= greater than equal # <= less than equal # and combine two conditions # or one or the other condition
true
e957cb1c881194614a3d58e36d953c14a59da8b7
sidamarnath/CSE-231-Labs
/lab12.py
2,876
4.25
4
######################################### # lab12.py # ALgorithm # Create a vector class # Have program do calculations ######################################### class Vector(): def __init__(self, x = 0, y = 0): self.__x = x self.__y = y #self.__valid = self.__validate() def __str__(self): ''' returns a string as formal representation of vector''' out_str = "(" + str(round(self.__x ,2)) + "," + str(round(self.__y,2)) + ")" return out_str def __repr__(self): ''' returns representation of vector''' out_str = "({:02d},{:02d})".format(self.__x, self.__y) return out_str def __add__(self, v): ''' returns addition of vectors in Vector format''' return Vector(self.__x + v.__x, self.__y + v.__y) def __sub__(self, v): ''' returns subtraction of vectors in Vector format''' return Vector(self.__x - v.__x, self.__y - v.__y) def __mul__(self,v): ''' returns multiplication of vectors in Vector format''' return Vector(self.__x * v.__x, self.__y * v.__y) def magnitude(self): ''' returns magnitude of given vector''' from math import sqrt return sqrt(self.__x**2 + self.__y**2) def __eq__(self, v): ''' returns true/false if vectors are equal ''' return self.__x == v.__x and self.__y == v.__y def __rmul__(self, v): ''' returns multiplication but not in Vector format''' return self.__x * v.__x + self.__y * v.__y def unit(self): ''' function returns ValueError if magnitude = 0''' result = self.magnitude() if result == 0: raise ValueError("Cannot convert zero vector to a unit vector") def main(): ''' function used for testing previous functions''' # testing __inti__ and __str__ v1 = Vector(1,2) v2 = Vector(3,4) print(v1) print(v2) # testing __add__ v_ret = v1.__add__(v2) print(v_ret) v3 = Vector(5,-2) v_ret = v1.__add__(v3) print(v_ret) v4 = Vector(-3,-3) v_ret = v1.__add__(v4) print(v_ret) # testing __sub__ v_ret = v1.__sub__(v2) print(v_ret) v_ret = v1.__sub__(v4) print(v_ret) # testing __mul__ v_ret = v1.__mul__(v4) print(v_ret) v_ret = v1.__mul__(v2) print(v_ret) # testing __rmul__ v_ret = v1.__rmul__(v4) print(v_ret) # testing __eq__ v5 = Vector(3,4) v_ret = v2.__eq__(v5) print(v_ret) v6 = Vector(0,0) v_ret = v1.unit() print(v_ret) # testing unit function v_ret = v6.unit() print(v_ret) main()
true
adbe15cb36083194aa46ab708ce15c24a07628d6
sidamarnath/CSE-231-Labs
/lab08b.py
1,648
4.15625
4
############################### # lab08b.py # Algorithm # Prints out student scores alphabetically # If name appears more than once in file, add scores together ############################### # read file function to open and read file # takes in dictionary and filename as argument def read_file(dictionary, filename): # opens file and reads the lines fp = open(filename, "r") reader = fp.readlines() # ignores the first line of the file for line in reader[1:]: #splits line into list line_list = line.split() name = line_list[0] score = int(line_list[1]) # checks for name in dictionary if name not in dictionary: dictionary[name] = score else: # find the dublicate name in dictionary and combine scores dictionary[name] += score # display function displays results from read_file function def display(dictionary): # set to an empty list display_list = list() # adds name and scores into display list for name, score in dictionary.items(): display_list.append((name, score)) # sorts list alphabetically # formats results display_list.sort() print("{:10s} {:<10s}".format("Name", "Total")) for item in display_list: print( "{:10s} {:<10d}".format(item[0], item[1])) def main(): dictionary = {} read_file(dictionary, "data1.txt") read_file(dictionary, "data2.txt") display(dictionary) main()
true
3bb6d95502446c35cdbfed74b9067dc54d6d165f
0rps/lab_from_Alex
/school_42/d02/ex04_ft_print_comb.py
579
4.1875
4
# Create a function on display all different combination of three different digits in ascending order, # listed by ascending order - yes, repetition is voluntary. def print_comb(): number = '' flag = False for i in range(10): for k in range(i+1, 10): for l in range(k+1, 10): number = str(i) + str(k) + str(l) if flag: print(', ' + number, end = "") else: print(number, end = '') flag = True if __name__ == "__main__": print_comb()
true
20cc7f1c4ff34b334763271c8ea7ccd73071786f
vlvanchin/learn
/learn_python/others/ver3/isOddOrEven.py
259
4.46875
4
#!/usr/bin/env python3 def even_or_odd(number): '''determines if number is odd or even''' if number % 2 == 0: return 'Even'; else: return 'Odd'; userinput = input("enter a number to check odd or even:"); print (even_or_odd(int(userinput)));
true
d46d6e0a8e63ca3ae1f83ecb50707a4f3fa48538
grrtvnlw/grrtvnlw-python-103-medium
/tip_calculator2.py
991
4.25
4
# write a tip calculator based off user input and quality of service and divide bill in equal parts # get user input for total bill amount, quality of service, how many ways to split, and tip amount total_bill = float(input("Total bill amount? ")) service_level = input("Level of service - good, fair, or bad? ") split = float(input("Split how many ways? ")) tip = 0 # calculate tip based off user input if service_level == "good": tip = total_bill * .20 elif service_level == "fair": tip = total_bill * .15 elif service_level == "bad": tip = total_bill * .10 # format tip, bill, and split bill to dollar amount and calculate total bill and split including tip total_bill += tip split_bill = total_bill / split format_tip = '%.2f' % tip format_total_bill = '%.2f' % total_bill format_split_bill = '%.2f' % split_bill # display formatted output print(f"Tip amount: ${format_tip}") print(f"Total amount: ${format_total_bill}") print(f"Amount per person: ${format_split_bill}")
true
c4aaaaa193fb7ee3b670371978dcea295c908fbe
mtj6/class_project
/users.py
1,199
4.125
4
"""A class related to users.""" class User(): """Describe some users.""" def __init__(self, first_name, last_name, age, sex, race, username): """initialize user attributes""" self.first_name = first_name self.last_name = last_name self.age = age self.sex = sex self.race = race self.username = username self.login_attempts = 0 def describe_user(self): """describe the user""" print('\nName: ' + self.first_name.title() + ' ' + self.last_name.title()) print('Age: ' + str(self.age)) print('Sex: ' + self.sex) print('Race: ' + self.race) print('Username: ' + self.username) print("Number of login attempts: " + str(self.login_attempts)) def increment_login_attempts(self): """increase number of login attempts""" self.login_attempts += 1 def greet_user(self): """greet the user""" print('Hello ' + self.first_name.title() + ' ' + self.last_name.title() + '!') def reset_login_attempts(self): """reset the number of login attempts""" self.login_attempts = 0
true
32197a9d260623de1d6b2b98e3c1930f8a35115e
amarmulyak/Python-Core-for-TA
/hw06/uhavir/hw06_task1.py
902
4.5625
5
# Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence # n - length of Fibonacci sequence. # NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements # --> 1, 1, 2, 3, 5, 8, 13, 21, 34,... # EXAMPLE OF Inputs/Ouputs when using this function: # ``` # >>> print fibo(6) # [1, 1, 2, 3, 5, 8] # ``` def fibonacci(n_terms): # check if the number of terms is valid n1 = 0 n2 = 1 # count = 0 if n_terms <= 0: print("Please enter a positive integer") elif n_terms == 1: print("Fibonacci sequence upto", n_terms, ":") print(n1) else: l = [] while len(l) < n_terms: nth = n1 + n2 # update values n1 = n2 n2 = nth # count += 1 l.append(n1) return l print(fibonacci(6))
true
f7fa1e213ddd43ea879957bc309c5026addb905e
amarmulyak/Python-Core-for-TA
/hw06/amarm/task1.py
634
4.375
4
""" Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence n - length of Fibonacci sequence. NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,... EXAMPLE OF Inputs/Ouputs when using this function: print fibo(6) [1, 1, 2, 3, 5, 8] """ def fibo(n): """This function returns n-first numbers from the Fibonacci list""" a = 0 b = 1 fibonacci_list = [a, b] for i in range(n): a, b = b, a + b fibonacci_list.append(b) return fibonacci_list[0:n] print(fibo(10))
true
17e555d24c9b10c7748c183a1ac62960f9328ba5
amarmulyak/Python-Core-for-TA
/hw03/pnago/task_2.py
777
4.1875
4
year = int(input("Enter a year: ")) month = int(input("Enter a month: ")) day = int(input("Enter a day: ")) short_months = [4, 6, 9, 11] # Check if it is a leap year is_leap = False if year % 4 != 0: is_leap elif year % 100 != 0: is_leap = True elif year % 400 != 0: is_leap else: is_leap = True # Date validation if year < 0 or month < 1 or month > 12 or day > 31: print("The date you have entered is invalid!") elif month in short_months and day > 30: print("The date you have entered is invalid!") elif month == 2: if day > 29: print("The date you have entered is invalid!") elif day == 29 and not is_leap: print("The date you have entered is invalid!") else: print("year:", year, "month:", month, "day:", day)
true
b08dfa9c61ea32b40594f424dfb140002764f5a5
amarmulyak/Python-Core-for-TA
/hw06/arus/fibo_func.py
583
4.4375
4
"""Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence n - length of Fibonacci sequence. NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,... """ def fibo_func(n): i = 1 i1 = 1 list_value = 1 fibo_list = [list_value] while n > len(fibo_list): fibo_list.append(list_value) i = i1 i1 = list_value list_value = i + i1 print(fibo_list) n = int(input("Enter any value ")) print(fibo_func(n))
true
11479ff5ed3027796c3c54b35c4edbc9609ffeac
amarmulyak/Python-Core-for-TA
/hw03/amarm/task1.py
310
4.28125
4
from calendar import monthrange var_year = int(input("Type the year to found out if it's leap year: ")) february = monthrange(var_year, 2) # Here 2 means second month in the year february_days = february[1] if february_days == 29: print("It's a leap year!") else: print("This is not a leap year!")
true
8c9320a9c918a667a1e308dc73b7cda9d1b7aa0b
amarmulyak/Python-Core-for-TA
/hw06/yvasya/hw06_01.py
673
4.28125
4
""" Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence n - length of Fibonacci sequence. NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,... EXAMPLE OF Inputs/Ouputs when using this function: print fibo(6) [1, 1, 2, 3, 5, 8] """ fib_sequence = [] def fibo(n): elem1 = 1 elem2 = elem1 + 0 fib_sequence.append(elem1) fib_sequence.append(elem2) for i in range(n-2): elem_next = elem1 + elem2 elem1, elem2 = elem2, elem_next fib_sequence.append(elem_next) return fib_sequence print(fibo(6))
true
c4cc1df080077fd565d9afbbb3a6c1129a00501c
aiqbal-hhs/python-programming-91896-JoshuaPaterson15
/print_statement.py
384
4.21875
4
print("Hello and Welcome to this Digital 200 print statement.") print("Here is string one." + "Here is string two.") print("Here is string one times 5." * 5) name = input("What is your name? ") print("Welcome to Digital 200 {}.".format(name)) print("Line one \nLine two \nLine three") print("""This is line one this is line two this is line three""")
true
1658511ddf06d9124b17445af3164864cdd45c39
nilearn/nilearn
/examples/05_glm_second_level/plot_second_level_design_matrix.py
1,994
4.34375
4
""" Example of second level design matrix ===================================== This example shows how a second-level design matrix is specified: assuming that the data refer to a group of individuals, with one image per subject, the design matrix typically holds the characteristics of each individual. This is used in a second-level analysis to assess the impact of these characteristics on brain signals. This example requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError("This script needs the matplotlib library") ######################################################################### # Create a simple experimental paradigm # ------------------------------------- # We want to get the group result of a contrast for 20 subjects. n_subjects = 20 subjects_label = [f"sub-{int(i):02}" for i in range(1, n_subjects + 1)] ############################################################################## # Next, we specify extra information about the subjects to create confounders. # Without confounders the design matrix would correspond to a one sample test. import pandas as pd extra_info_subjects = pd.DataFrame( { "subject_label": subjects_label, "age": range(15, 15 + n_subjects), "sex": [0, 1] * (n_subjects // 2), } ) ######################################################################### # Create a second level design matrix # ----------------------------------- # With that information we can create the second level design matrix. from nilearn.glm.second_level import make_second_level_design_matrix design_matrix = make_second_level_design_matrix( subjects_label, extra_info_subjects ) ######################################################################### # Let's plot it. from nilearn.plotting import plot_design_matrix ax = plot_design_matrix(design_matrix) ax.set_title("Second level design matrix", fontsize=12) ax.set_ylabel("maps") plt.tight_layout() plt.show()
true
a19ab2d3920ca3f956ca83719af3124ff6b9b073
lberge17/learning_python
/strings.py
368
4.5
4
my_string = "Hello world! I'm learning Python." print("Hello") print(my_string) # using square brackets to access a range of characters print(my_string[26:30]) # prints "Pyth" # using commas to print two items print("My message is:", my_string[13:33]) # prints "My message is: I'm learning Python." # using string interpolation print(f'My message is: {my_string}')
true
ec39e9b0fffa050ae20a40a3a73bb23cbc5f606b
manisha-jaiswal/Division-of-apples
/problem19.py
1,258
4.25
4
""" -------------------------------------Problem Statement:-------------------------- Harry potter has got n number of apples. Harry has some students among whom, he wants to distribute the apples. These n number of apples are provided to harry by his friends and he can request for few more or few less apples. You need to print whether a number in range mn to mx is a divisor of n or not. Input: Take input n, mn and mx from the user Output: Print whether the numbers between mn and mx are divisor of n or not. If mn = mx, show that this is not a range and mn is equal to mx. Show the result for that number Example: If n is 20 and mn=2 and mx = 5 2 is a divisor of 20 3 is not a divisor of 20 … 5 is a divisor of 20 """ try: apples = int(input("Enter the number of apples\n")) mn = int(input("Enter the minimum number to check\n")) mx = int(input("Enter the maximum number to check\n")) except ValueError: print('Enter integers only ') exit() if mn>=mx: print('This can not be the range as the min should be less than max') for i in range(mn, mx+1): if apples%i == 0: print(f"{i} is a divisor of {apples}") else: print(f"{i} is not a divisor of {apples}")
true
296fb4507878591bdde602c63284b9785971509d
hungd25/projects
/CS6390/HW2_P3.py
2,213
4.59375
5
""" """ def get_input(): """ # Get height and weight from the user and validate. If inputs are (negative numbers or strings), the program should throw an error message. : return: height, weight """ try: # get user input and convert to type float height_input = float(input("Enter the person's height: ")) weight_input = float(input("Enter the person's weight: ")) # check for negative numbers if height_input > 0.0 and weight_input > 0.0: return height_input, weight_input # return height and weight else: print("Negative values are not allowed.") exit() # exit program # if string values, then throw error message except ValueError: # throw exception for float function during version of a non digit print("Please enter only numbers.") # inform user of string input exit() # exit program def calculate_bmi(height_in, weight_in): """ This function calculates the body mass index : param h: height : param w: weight : return: bmi: body mass index """ try: bmi = (weight_in * 703) / (height_in ** 2) # calculate bmi return bmi # return bmi except Exception as error: # throws error when problem with calculation print("There was error calculating BMI, message: %s" % error) # print error message exit() # exit program def calculate_weight_category(bmi): """ This function to compute one of the three weight categories : param bmi: : return: weight_category """ if 18.5 < bmi < 25: # if bmi is between 18.5 and 25 weight_category = 'optimal' # set category to optimal elif bmi < 18.5: # if bmi is less than 18.5 weight_category = 'underweight' # set category to underweight else: # bmi > 25 weight_category = 'overweight' # set category to overweight return weight_category # return weight_cat # get input height, weight = get_input() # get BMI BMI = calculate_bmi(height, weight) # get weight category and print it print('Based on your BMI of %s . You are %s' % (round(BMI, 2), calculate_weight_category(BMI))) # End of script
true
d4a8e2b76d5cce35ebceb4df5064a07886a2d14f
halysl/python_module_study_code
/src/study_checkio/Fizz buzz.py
768
4.5
4
''' https://py.checkio.org/mission/fizz-buzz/ "Fizz buzz" is a word game we will use to teach the robots about division. Let's learn computers. You should write a function that will receive a positive integer and return: "Fizz Buzz" if the number is divisible by 3 and by 5; "Fizz" if the number is divisible by 3; "Buzz" if the number is divisible by 5; The number as a string for other cases. Input: A number as an integer. Output: The answer as a string. ''' def checkio(number): if number%3 == 0 and number%5 == 0: return("Fizz Buzz") elif number%3 == 0 and number%5 != 0: return ("Fizz") elif number%3 != 0 and number%5 == 0: return ("Buzz") else: return (str(number)) print(checkio(7))
true
12ab232125ed90cbb8c19aa08924a027f36a3146
halysl/python_module_study_code
/src/study_checkio/Second Index.py
1,015
4.28125
4
''' https://py.checkio.org/mission/second-index/ You are given two strings and you have to find an index of the second occurrence of the second string in the first one. Let's go through the first example where you need to find the second occurrence of "s" in a word "sims". It’s easy to find its first occurrence with a function index or find which will point out that "s" is the first symbol in a word "sims" and therefore the index of the first occurrence is 0. But we have to find the second "s" which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 3. Input: Two strings. Output: Int or None ''' import re def second_index(text: str, symbol: str): try: a = re.search(symbol,text).span() a = list(a) a = text[:a[0]]+text[a[1]:] a = re.search(symbol, a).span() a = list(a) print(a) return a[1] except: return None second_index("find the river", "e")
true
47d0464a02a778306eb170b12bd379fdfee93af4
gramanicu/labASC
/lab02/task2.py
1,164
4.25
4
""" Basic thread handling exercise: Use the Thread class to create and run more than 10 threads which print their name and a random number they receive as argument. The number of threads must be received from the command line. e.g. Hello, I'm Thread-96 and I received the number 42 """ from random import randint, seed from threading import Semaphore, Thread import threading # Thread Class class SimpleThread(Thread): # Constructor def __init__(self, nr): Thread.__init__(self) self.nr = nr # Main Thread Code def run(self): print ("Hello, I'm Thread-", threading.get_ident(), " and I received the number ", self.nr, sep='') def main(): # The list of threads thread_list = [] # Initialise the rng seed() num_of_threads = int(input("How many threads? ")) # Create and start the threads for i in range(num_of_threads): t = SimpleThread(randint(1, 100)) thread_list.append(t) thread_list[i].start() # Wait for the threads to finish for i in range(len(thread_list)): thread_list[i].join() if __name__ == "__main__": main()
true
c12079a7505f4a68a30fa8369852f79b52a6d51a
ssahai/python
/if.py
331
4.15625
4
#!/usr/bin/python # To check whether the guessed number is correct (as per our fixed number) num = 15 guess = int (raw_input ("Enter you guess : ")) if guess == num: print 'You guessed it right!' elif guess > num: print 'Your guesses a larger number' else: print 'You guessed a smaller number' print 'Program exits'
true
3ad3977085f0aa26d5674c2cb73bbdf592a9ec8e
Aniketa1986/pythonExercises
/fortuneSim.py
962
4.4375
4
# chapter 3, exercise 1 # Fortune Cookie # Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run. import random #generate random number between 1 and 5 randomNum = random.randint(1,5) #Unique fortune messages fortune1 = "Some days you are pigeon, some days you are statue. Today, bring umbrella." fortune2 = "Wise husband is one who thinks twice before saying nothing." fortune3 = "Dijon vu -- the same mustard as before." fortune4 = "The fortune you seek is in another cookie." fortune5 = "A day without sunshine is like night." print("Welcome to the fortune cookie simulator.\nHere you will get motivated like never. \n") if randomNum == 1: print(fortune1) elif randomNum == 2: print(fortune2) elif randomNum == 3: print(fortune3) elif randomNum == 4: print(fortune4) else: print(fortune5) print("Now get back to your work!")
true