blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3b922b231dd58ac97104bb606bd44afae63e2393
noozip2241993/homework4
/task1.py
671
4.34375
4
import random def generating_defining_prime_number(): """Checking whether the argument is a prime number or not""" for j in range(6): #generating six random numbers num = random.randrange(1,101) if num > 1: #prime numbers are greater than 1 for i in range(2,num): #check for factors if(num%i)== 0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number") #if input is less than or equal to 1, it is not a prime number generating_defining_prime_number()
true
ab4612f127ea1205fddf615ea520a2dbab9821dc
cishocksr/cs-module-project-algorithms-cspt9
/moving_zeroes/moving_zeroes.py
566
4.1875
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): positive = [] negative = [] zero = [] for i in range(len(arr)): if arr[i] > 0: positive.append(arr[i]) elif arr[i] < 0: negative.append(arr[i]) else: zero.append(arr[i]) return positive + negative + zero if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
true
29da3a12725b989dea553c04e0493371cdbc57ff
strivehub/conventional-algorithm-
/quick_sort.py
861
4.34375
4
#这是一个利用python实现的快速排序算法 def quick_sort(arr): if len(arr)<2: #判断数组长度,如果数组里面只有一个元素,则不需要排序,直接返回 return arr else: #如果长度大于2个及以上,则需要排序 value = arr[0] #设定一个基准值,这里我们每次都取数组第一个,也阔以取数组其他值 min_value = [i for i in arr[1:] if i <=value] #将数组中小于等于基准值放在这个数组中 max_value = [i for i in arr[1:] if i>value] #将数组中大于基准值的放在这里 return quick_sort(min_value)+[value]+quick_sort(max_value) #循环以上步骤,数组将被我们分的越来越小,最后只剩下一个的时候就结束了 if __name__ == "__main__": arr = [3,5,1,7,9,0] #定义数组 print(quick_sort(arr)) #调用排序函数
false
1a7a5c3a0b5b5cd2858ce8c186ff63af040ed238
ashnashahgrover/CodeWarsSolutions
/practiceForPythonInterview/pythonEx6.py
519
4.34375
4
# Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. # # Examples # pig_it('Pig latin is cool') # igPay atinlay siay oolcay # pig_it('Hello world !') # elloHay orldway ! def pig_it(text): text = text.split(" ") new_text = [] for i in text: if (i=="!" or i=="?"): new_text.append(i) else: i = i+i[0]+"ay" i = i[1:] new_text.append(i) return " ".join(new_text)
true
7f238c4217229748ef202dc4361832fa3211f331
ThapaKazii/Myproject
/test19.py
416
4.1875
4
# From a list separate the integers, stings and floats elements into three different lists. list=["bibek",44,'puri',288.8,'gaida',33,12.0,] list2=[] list3=[] list4=[] for x in list: if type(x)==int: list2.append(x) elif type(x)==float: list3.append(x) elif type(x)==str: list4.append(x) else: print("Sorry, Undetermined one..") print(list2) print(list3) print(list4)
true
c449b076d13c203c8b3012cdc2909eac3008662b
nerugattiraju/interview-questions
/generator.py
277
4.40625
4
#generators are used to creating the iterators with the different approches from time import sleep n=int(input("enter the number")) print("contdown start") def countdown(n): while n>0: yield n n=n-1 sleep(0.3) x=countdown(n) for i in x: print(i)
true
7939224df96eb3ca863d0a6372dabed86ee25436
nerugattiraju/interview-questions
/class functions.py
448
4.125
4
class Employee: def __init__(self,name,id,age): self.name=name self.id=id self.age=age x=Employee("raju",100,24) print(getattr(x,'name'))#get the attribute of the object. setattr(x,'age',34)#set the perticular attribute of the object. print(getattr(x,'age')) #delattr(x,'id')#delete the pericular attribute of the object. print(getattr(x,'id')) print(hasattr(x,'ide'))#it returns the true if object contain the attribute
true
808e78714e7cafbc102de51be052bd3d737c20e8
avi202020/sailpointbank
/Bank.py
358
4.125
4
from typing import Dict import Account """ Bank keeps track of users by keeping a map of user name to Account instance. Every time a new Account is created, it will add it to its map. """ class Bank: def __init__(self): self.accounts: Dict[str, Account] = {} def add_account(self, name, account): self.accounts[name] = account
true
e1a8475f8e89deecb8de69b1fc8205635c08cbdf
lamessk/CPSC-217
/Assignment2/Assignment2.py
2,143
4.25
4
#Lamess Kharfan, Student Number: 10150607. CPSC 217. #Draw a climograph displaying temperature and precipitation data for all #12 months of the year using 24 input statements, 12 for temperature and 12 for #precipitation. Line graph will be repersenative of temperature data and Bar #graph is representative of the precipitation data. from SimpleGraphics import* background("white") #draw outer lines of graph line(50, 500, 720, 500) line(50, 100, 50, 500) line(720, 100, 720, 500) #Labels on axises text(20, 270, "Temp.") text(20, 285, "(°C)") text(775, 280, "Precip.") text(775, 295, "(mm)") #ticks and numbers along the left side x = 0 numT = 30 for x in range (5): x = (x * 100) numT = numT - 10 line(40, x + 100, 50, x + 100) text(30, x + 100, numT) #ticks and numbers along the right side x = 0 precY = 220 for x in range (11): x = (x * 40) precY = precY - 20 line(720, x + 100, 730, x + 100) text(740, x + 100, precY) #list months along the bottom wordsX = 40 months = ['Jan', 'Feb' , 'March' , 'April' , 'May' , 'June' , 'July' , 'Aug' , 'Sept' , 'Oct' , 'Nov' , 'Dec'] for i in range(0, 12): wordsX = (i * 55) text(80 + wordsX, 520, (months[i])) #recieve input from the user for precipitation, draw a bar on the graph #according to month and precipitation value mon = 1 xPos = 0 yPos = 500 scale = -2 while mon <= 12: prec = float(input("Enter a precipitation value for month number " + str(mon) + ": ")) mon = mon + 1 xPos = (xPos + 55) setFill("light blue") rect(xPos, 500, 50, prec * scale) #recieve input from user for temperature and draw a dot where the the user #specifies, according to month and temperature value mon = 1 xPos = 20 yPos = 295 scalingF = -10 while mon <= 12: temp = float(input("Enter a temperature value for month number " + str(mon) + ": ")) mon = mon + 1 xPos = (xPos + 55) setOutline("red") setFill("red") ellipse(xPos - 4, temp * scalingF + yPos - 4 , 10, 10) #connect dots with a line if mon > 2: line(xPos - 55, prevY * scalingF + yPos , xPos, temp * scalingF + yPos) prevY = temp
true
206225b6030be7c606ca115d31b0b4e8804fa4b4
asen1995/Python-Learning
/basic/dataStructures.py
2,604
4.28125
4
import collections # list example from basic.Stack import Stack def list(): list = ["apple", "banana", "cherry"] print(list) print("len is ", len(list)) print(type(list)) list.append("orange") print(list) list.insert(0, "Asen") print(list) list.remove("Asen") print(list) del list # tuple example def tulpe(): # A tuple is a collection which is ordered and unchangeable. mytuple = ("apple", "banana", "cherry") print(mytuple) print(type(mytuple)) for x in mytuple: print(x) del mytuple # simple example def array(): cars = ["Ford", "Volvo", "BMW"] for x in cars: print(x) cars[1] = "Mazda" for x in cars: print(x) del cars # two dimensional array example def twoDimensionalarray(): numbers = [1, 2, 3], [4, 5, 6], [7, 8, 9] print(numbers[1], [2]) del numbers # map example def map(): dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) print('Keys = {}', res.keys()) print('Values = {}', res.values()) print(res.get("day3")) res['day6'] = "saturday" print(res.get("day6")) # update value res.update({'day2': 'Tuesday'}) print(res.get("day2")) # delete print('before delete day6') print(res) del res['day6'] print(res) del res def setExperience(): Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]) Days.remove("Tue") Months = {"Jan", "Feb", "Mar"} Months.remove("Mar") Dates = {21, 22, 17} Dates.add(21) Dates.add(55) # print(Days) # print(Months) # print(Dates) Days.discard("Sun") # other way of delete # for d in Days: # print(d) # Intersection of Sets DaysA = set(["Mon", "Tue", "Wed"]) DaysB = set(["Wed", "Thu", "Fri", "Sat", "Sun"]) AllDays = DaysA & DaysB print(AllDays) def stack(): stack = Stack() stack.add("Mon") stack.add("Tue") stack.peek() print(stack.peek()) print(stack.size()) stack.add("Wed") stack.add("Thu") print(stack.peek()) print(stack.size()) def deque(): DoubleEnded = collections.deque(["Mon", "Tue", "Wed"]) DoubleEnded.append("Thu") print("Appended at right - ") print(DoubleEnded) DoubleEnded.appendleft("Sun") print("Appended at right at left is - ") print(DoubleEnded) DoubleEnded.pop() print("Deleting from right - ") print(DoubleEnded) DoubleEnded.popleft() print("Deleting from left - ") print(DoubleEnded)
false
2bf5f4ead2ab7718b6849f03e90f852e462d8e74
pi6220na/CapLab1
/guess.py
596
4.125
4
#Lab1 Jeremy Wolfe # Guess a number import random random_pick = random.randint(1,10) print('computer random number is : ' + str(random_pick)) guessed_number = input('Guess a number between 1 and 10: ') guessed_number = int(guessed_number) while True: if random_pick == guessed_number: print('You got it!') break elif random_pick < guessed_number: print('Your guess is high') elif random_pick > guessed_number: print('Your guess is low') guessed_number = input('Guess again ') guessed_number = int(guessed_number)
true
ac72560db9c6fb4aa2861c059245eeaa979b6808
jpchato/a-common-sense-guide-to-data-structures-and-algorithms
/binary_search.py
1,471
4.375
4
def binary_search(arr, val): # first , we establish the lower and upper bounds of where the value we're searching for can be. To start, the lower boudn is the first value in the array, while the upper bound is the last value lower_bound_index = 0 upper_bound_index = len(arr) - 1 # we begin a loop in which we keep inspecting the middlemost value between the upper and lower bounds: while lower_bound_index <= upper_bound_index: # find the middlepoitn between the upper and lower bounds: midpoint_index = (upper_bound_index + lower_bound_index)//2 # we inspect the value at the midpoint value_at_midpoint = arr[midpoint_index] # If the value at the midpoint is the one we're looking for, we're done. If not, we change the lower or upper bound based on whether we need to guess higher or lwoer: if val < value_at_midpoint: upper_bound_index = midpoint_index - 1 elif val > value_at_midpoint: lower_bound_index = midpoint_index + 1 elif val == value_at_midpoint: print(f'midpoint index: {midpoint_index}, midpoint value: {value_at_midpoint}') return midpoint_index # If we've narrowed the bounds until they've reached each other, that means that the value we're searching for is not in the array return None # binary_search([1,2,3,4,5,6,7,8,9], 5) if __name__ == '__main__': binary_search([1,2,3,4,5,6,7,8,9], 5)
true
1e46263668a98a2dceeb41f653dc22354597e323
manojkotte/gunturClasses
/classTenOnline.py
2,303
4.3125
4
Derived data types ------------------- collections ------------ lists tuples dictionaries -------------------------------------- Lists [ ] ----- --> MUTABLE objects --> Iterable objects --> collection --> stores heterogenous elements --> indexed --> sliced --> concatenated --> operated by using functions --> Nested lists are also possible ------------------------- SYNTAX ------ nameOfList = [ <elements> ] names = ["khan" , "suma" , "surya" , "asif"] name of list ---> names elements of list ---> "khan" , "suma" , "surya" , "asif" nums = [1,2,3,4,5,6] name of list ---> nums elements of list ---> 1,2,3,4,5,6 store loads of data --> collective data ( names , salaries) heterogenous list ----------------- numsNames = ["khan" , 1 , 2 ,4 , "suma" , 7 , "asif" , 40] nested lists ------------ listInList = [1 ,2 ,5, [3,4,7,8] , 9 ,10] lsit = [[[[[2]]]]] Type --> < class list > print(type(nums)) --> < class list > MUTABLE --> open for change , modification -------------------------------------------- Indexing and slicing of list ----------------------------- names = ["khan" , "suma" , "surya" , "asif"] 0 1 2 3 names[0] --> "khan" names[3] --> "asif" names[5] --> error names[0:2] --> "khan" , "suma" names[1:3] --> "suma" , "surya" ----------------------------------- Iterable -------- for <dummy variable> in listName: -- implementation -- i names[0] names[1] names[2] names[3] for i in range(0,4): print(names[i]) for i in names: print(i) for i in "khan": print(i) i/p nums = [1,2,3,4,5,6] o/p 1 3 5 0. 1. 2. 3. 4. 5 listInList = [1 ,2 ,5, [3,4,7,8] , 9 ,10] listInList[0] --> 1 listInList[5] --> 10 listInList[4] --> [3,4,7,8] listInList[4][0] --> 3 listInList[4][1] --> 4 listInList[4][2] --> 7 listInList[4][3] --> 8 i/p vs o/p =========== lsit = [[[[[[3,4]]]]]] >>> lsit[0][0][0][0][0] [3, 4] >>> lsit[0][0][0][0][0][0] 3 >>> lsit[0][0][0][0][0][1] 4 ---------------------------------- concatenation of lists ---------------------- l1= [1,2,3,4,5] l2= [4,5,7,8,9,10] l1 + l2 [1,2,3,4,5,4,5,7,8,9,10] l3 = l1 + l2 l3 ==> [1,2,3,4,5,4,5,7,8,9,10] -------------------------------- operations on lists --> 7/6/18 ------------------- c:/>python listtask.py enter a list [1,2,3,4,5] 19 listofnums = [1,1,1,1,1,1]
false
34555e8f777b09f08c25d1b4e13f693010b41064
lcsm29/MIT6.0001
/lecture_code/in_class_questions/lec2_in-class.questions.py
1,165
4.15625
4
# 1. Strings # What is the value of variable `u` from the code below? once = "umbr" repeat = "ella" u = once + (repeat+" ")*4 #umbrella ella ella ella # 2. Comparisons # What does the code below print? pset_time = 15 sleep_time = 8 print(sleep_time > pset_time) # False derive = True drink = False both = drink and derive # False print(both) # 3. Branching # What's printed when x = 0 and y = 5? x = float(input("Enter a number for x: ")) y = float(input("Enter a number for y: ")) if x == y: if y != 0: print("x / y is", x/y) elif x < y: # this one print("x is smaller") else: print("y is smaller") # 4. While Loops # In the code below from Lecture 2, what is printed when you type "Right"? n = input("You're in the Lost Forest. Go left or right? ") while n == "right": n = input("You're in the Lost Forest. Go left or right? ") print("You got out of the Lost Forest!") # this one # 5. For Loops # What is printed when the below code is run? mysum = 0 for i in range(5, 11, 2): #5 7 9 mysum += i if mysum == 5: #stop right up at 5 break mysum += 1 print(mysum) #5
true
9704dbce6358c457c123d424f1b11b89cad08452
zois-tasoulas/ThinkPython
/chapter8/exercise8_4.py
849
4.1875
4
#This will return True for the first lower case character of s def any_lowercase1(s): for c in s: if c.islower(): return True else: return False #This will alsways return True as islower() is invoked on the character 'c' def any_lowercase2(s): for c in s: if 'c'.islower(): return 'True' else: return 'False' #This function will return True is the last character of the string is lower case, otherwise it will return false def any_lowercase3(s): for c in s: flag = c.islower() return flag #This function will return True if at least one character of s is lower case def any_lowercase4(s): flag = False for c in s: flag = flag or c.islower() return flag #This function will return True if all the characters of s are lower case def any_lowercase5(s): for c in s: if not c.islower(): return False return True
true
32c9dd2e13bf06dfc108a5cbd9d3b874f6ad54d8
zois-tasoulas/ThinkPython
/chapter6/exercise6_3.py
434
4.125
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(word): if len(word) == 0 or len(word) == 1: return True elif len(word) == 2: return first(word) == last(word) else: return first(word) == last(word) and is_palindrome(middle(word)) return None msg = 'Give a string to check if it is a palindrome:\n' string = input(msg) print(is_palindrome(string))
true
5a49c755e899791e44508020c26bd00dd37f299c
drewvlaz/CODE2RACE
/SOLUTIONS/reverse_aword.py
301
4.125
4
from __future__ import print_function try: raw_input # Python 2 except NameError: raw_input = input # Python 3 def reverse_string(string): return " ".join(string.split(" ")[::-1]) string = raw_input('Enter a string containing multiple words:') print(reverse_string(string))
false
04d85f17c4b854dc6822b1f33ea7993daceb38b4
drewvlaz/CODE2RACE
/SOLUTIONS/reverse-Word-Python.py
212
4.40625
4
#Get User word user_input= raw_input("Please input your word ") #reverse the user input reverse_user_input =user_input[::-1] #Print the reverse word print ("This is reverse of your word : " + reverse_user_input)
true
21663c061e8a16c3c9e56129ed778358c7625f00
annieshenca/LeetCode
/98. Validate Binary Search Tree.py
947
4.125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ # Set upper bound to infinite and lower bound to negative infinite. return self.checkBST(root, float("-inf"), float("inf")) def checkBST(self, node, left, right): # Know when you reach the end leafs with no children. if not node: return True # If node has any children that violates the binary tree rule. if not (left < node.val < right): return False # Recurse through the whole tree, checking all left and right nodes. return ( self.checkBST(node.left, left, node.val) and self.checkBST(node.right, node.val, right) )
true
47598a547fe44cea7968834b2d4c110a99cd96d8
prachichikshe12/HelloWorld
/Arithmatic.py
348
4.375
4
print(10 + 3) print(10 - 3) print(10 * 3) print(10 / 3) print(10 // 3) # print division calculation ans in Integer print(10 % 3) # prints remainder print(10 ** 3) # 10 to the power 3 #Augmented Assignment Operator x = 10 #x = x +3 #x +=3 x -= 3 print(x) # operator precedence #x= (2+3)* 10 -3 x = 2+6*2*2 print(x) #Python 3 module functions
true
2fe7e7a8758a9a89632d255c8813a2eb2e128125
Shariarbup/Shariar_Python_Algorithm
/find_a_first_uppercase_character/find_a_first_uppercase_character.py
921
4.15625
4
#Given a String, find a first uppercase character #Solve both an iterative and recursive solution input_str_1 = 'lucidProgramming' input_str_2 = 'LucidProgramming' input_str_3 = 'lucidprogramming' def find_uppercase_iterative(input_str): for i in range(len(input_str)): if input_str[i].isupper(): return input_str[i] return 'No uppercase character found' def find_recursive_recursion(input_str, idx = 0): if input_str[idx].isupper(): return input_str[idx] if idx == len(input_str) - 1: return 'No uppercase letter found.' return find_recursive_recursion(input_str, idx + 1) print(find_uppercase_iterative(input_str_1)) print(find_uppercase_iterative(input_str_2)) print(find_uppercase_iterative(input_str_3)) print('\n') print(find_recursive_recursion(input_str_1)) print(find_recursive_recursion(input_str_2)) print(find_recursive_recursion(input_str_3))
true
e68d56d6766a20bfec980011ce9619996315c089
AbdelOuaffar/python_work
/November_11/convert_binary.py
774
4.15625
4
def break_binary_single_digit(string): list_binary_digits = [] for char in string: list_binary_digits.append(int(char)) return list_binary_digits def convert_binary_decimal(binary_list): decimal = 0 rev_list = [] rev_list += reversed(binary_list) for i in range(len(binary_list)): decimal += rev_list[i]*pow(2, i) return decimal def main(): binary_string = input("enter a binary number") binary_list = break_binary_single_digit(binary_string) result = convert_binary_decimal(binary_list) print(f"decimal number of {int(binary_string)} = {result} ") if __name__=="__main__": main() #enter a binary number>? 1000 #decimal number of 1000 = 8 #enter a binary number>? 10001 #decimal number of 10001 = 17
false
a2073aece1c27ba4c3e57612ac3fe1ab9a5913b8
shimoleejhaveri/Solutions
/solution16.py
1,475
4.4375
4
""" Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 1. Any left parenthesis '(' must have a corresponding right parenthesis ')'. 2. Any right parenthesis ')' must have a corresponding left parenthesis '('. 3. Left parenthesis '(' must go before the corresponding right parenthesis ')'. 4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 5. An empty string is also valid. Example 1: Input: "()" Output: True Example 2: Input: "(*)" Output: True Example 3: Input: "(*))" Output: True Note: The string size will be in the range [1, 100]. """ class Solution: def checkValidString(self, s: str) -> bool: if not s: return True s1 = [] s2 = [] for i in range(len(s)): if s[i] == "(": s1.append(i) elif s[i] == "*": s2.append(i) elif s[i] == ")": if s1: s1.pop(-1) else: if s2: s2.pop(-1) else: return False while s1: if not s2: return False else: if s1.pop(-1) > s2.pop(-1): return False return True
true
8f45b136ac4be56e56f786576ad8151c1856925b
giladse19-meet/meet2017y1lab4
/fruit_sorter.py
206
4.1875
4
fruit = 'water' if fruit == 'apples': print('go to bin 1') elif fruit == 'oranges': print('go to bin 2') elif fruit == 'olives': print('go to bin 3') else : print('what is this fruit')
false
0aedbb6c0ea2871be312b08786599e814757f6c5
AdenRao3/Unit-6-03-Python
/movie.py
533
4.1875
4
# Created by: Aden Rao # Created on: April 7, 2019 # This program lets the user enter age and based on that it tells them what movies they can see. # imports math function import math #Input fot the user to enter their age and it tells them to myAge = int(input("Type your age: ")) # If statment to determine what movies they can see if myAge >= (17): print("You can watch R Rated Movies") elif myAge >= (13): print("You can watch PG-13 Rated Movies") elif myAge >= (1): print("You can watch G Rated Movies")
true
12d562efccfa120bf7658aa958d8d23b8e56cc44
Nate2019/python-basics
/camel.py
2,427
4.375
4
import random #Camel BASIC Game in python from 'Program Arcade Games with Python' Chapter 4: Lab exercise! #Written by Iago Augusto - plunter.com print """ Welcome to camel! You have stolen a camel to make your way across the great Mobi desert. The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.""" #VARIABLES miles_traveled = 0 thirst = 0 camel_tied = 0 natives_travel = -20 canteen = 5 natives_up = random.randrange(0, 10) full_speed = random.randrange(10, 20) moderate_speed = random.randrange(5, 12) ##### done = False while not done: print """ A. Drink from your canteen. B. Ahead moderate speed. C. Ahead full speed. D. Stop for the night. E. Status check. Q. Quit.\n""" choice = raw_input("What do you want to do? ") if choice.upper() == "Q": done = True #STATUS CHECK elif choice.upper() == "E": print "\nMiles traveled: %s\nDrinks in canteen: %s\nThe natives are %s behind you." % (miles_traveled, canteen, natives_travel) #STOP FOR THE NIGHT elif choice.upper() == "D": camel_tied = 0 print "The camel is happy! The natives are %s miles" % natives_up #AHEAD FULL SPEED elif choice.upper() == "C": print "You walked %s miles" % full_speed miles_traveled = miles_traveled + full_speed natives_travel = natives_travel + natives_up thirst = thirst + 1 camel_tied = camel_tied + random.randrange(1,3) #AHEAD MODERATE SPEED elif choice.upper() == "B": print "You walked %s miles" % moderate_speed miles_traveled += full_speed natives_travel += natives_up thirst += 1 camel_tied = camel_tied + random.randrange(1,3) #DRINK FROM YOUR CANTEEN elif choice.upper() == "A": print "You drink from your canteen." canteen = canteen - 1 thirst = 0 #PRINT THIRSTY IF THIRST >= 4 if thirst >= 4: print "You are thirsty." #DYING OF THIRSTY if thirst >= 6: print "You died of thirsty." done = True #PRINT IF CAMEL IS GETTING TIRED if camel_tied >= 5: print "Your camel is getting tired." #CAMEL IS DEAD if camel_tied >= 8: print "Your camel is dead." done = True #IF NATIVES CAUGHT if natives_travel >= 0: print "The natives caught you." done = True #NATIVES WALKING elif: natives_travel >= -10 print "Natives are getting close." if miles_traveled == 200: print "You won, you got the camel and across the Mobi Desert." done = True else: print "Something is wrong!"
true
85ab9c2e85e5830c1671f481f828a0ab5daf1909
sneakyweasel/DNA
/FIB/FIB.py
1,049
4.15625
4
import os import sys file = open(os.path.join(os.path.dirname(sys.argv[0]), 'rosalind_fib.txt')) dna = file.read() print(dna) # dna = "5 3" n = int(dna.split(' ')[0]) k = int(dna.split(' ')[1]) population = [1, 1] def next_generation(population, k): current = population[-1] # reproductor_pairs = (population - (population % 2)) / 2 offsprings = population[-2] * k result = current + offsprings return result for i in range(0, n - 2): population.append(next_generation(population, k)) print(population[-1]) # Any given month will contain the rabbits that were alive the previous month, plus any new offspring. # A key observation is that the number of offspring in any month is equal to the number of rabbits that were alive two months prior. # The total number of rabbit pairs that will be present after n months, if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of k rabbit pairs (instead of only 1 pair). # start = 1 # current = alive(prevmonth) + offsprings
true
b65a3596d0a9ab4e62564e25ce0d7e6e7debc54e
jfcarocota/python-course
/Strings.py
1,604
4.28125
4
myStr = 'Hi Friend' # restusn all options for string object #print(dir(myStr)) print(myStr) # converts strings in uppercase print(myStr.upper()) #converts string in lowercase print(myStr.lower()) #change lower to upper an viceverse print(myStr.swapcase()) # convert the first character in strings to uppercase and the rest to lowercase print(myStr.capitalize()) # replace a selected characfter or chain inside string by another chain or character print(myStr.replace("Hi", "Bye")) #you can make chain methods print(myStr.replace("Hi", "Bye").swapcase()) #counts a character or chain of it print(myStr.count('i')) #checks if string starts with a character or a chain. Is case sensitive print(myStr.startswith("Hi")) print(myStr.startswith("hi")) #the same as start width but in the end print(myStr.endswith("friend")) print(myStr.endswith("Friend")) #sepataes a string base on spaces or characters print(myStr.split()) myStr2 = 'Hi,Friend' print(myStr2.split(',')) print(myStr2.split('i')) #returns the index of character finded print(myStr2.find('e')) #returns the lenght of something print(len(myStr)) #gets the index of the first character or a chain of it finded print(myStr.index('Fr')) print(myStr.index('i')) print(myStr.index('d')) print(myStr.index('Hi')) #check if string ir character is numeric print(myStr.isnumeric()) myStr3 = '789' myStr4 = 'sdassdgfwerdf' print(myStr3.isnumeric()) #check is is alphanumeric print(myStr4.isalpha()) #pritns the character based on index print(myStr[0]) print(myStr[-1]) #concatenation print('message: ' + myStr) print(f'message: {myStr}')
true
2c33a2630ab625d76ac59e7a2c376c1c76f80ca6
NyntoFive/Python-Is-Easy
/03_main.py
1,197
4.34375
4
""" Homework Assignment #3: "If" Statements Details: Create a function that accepts 3 parameters and checks for equality between any two of them. Your function should return True if 2 or more of the parameters are equal, and false is none of them are equal to any of the others. Extra Credit: Modify your function so that strings can be compared to integers if they are equivalent. For example, if the following values are passed to your function: 6,5,"5" You should modify it so that it returns true instead of false. Hint: there's a built in Python function called "int" that will help you convert strings to Integers. """ def equalCheck(a, b, c): # convert arguments to ints a = int(a) b = int(b) c = int(c) # compare all pairs if a == b or a == c or b == c: return True else: return False # Testing print(equalCheck(1, 2, 3), "Result: False") print(equalCheck(1, 1, 3), "Result: True") print(equalCheck(1, 2, 1), "Result: True") print(equalCheck(1, 2, 2), "Result: True") print(equalCheck('1', '2', '3')) print(equalCheck(1, '1', 3)) print(equalCheck(1, 2, '1')) print(equalCheck(1, '2', 2))
true
2ac7a2f65c84ed64006361e1b6c3d92bd9acb2fc
shaheryarshaikh1011/HacktoberFest2020
/Algorithms/Python/sorting/bubble sort.py
406
4.375
4
#Python Implementation of bubble Sort Algorithm #Using data available in Python List temperature=[45,10,14,77,-3,22,0] #ascending Order Sort def bubble(data): n=len(data) for i in range(n-1): for j in range(i+1,n): if data[i]>data[j]: temp=data[j] data[j]=data[i] data[i]=temp print("Data Before Sort") print(temperature) bubble(temperature) print("Data After Sort") print(temperature)
true
7bada2bc40f499a7e4df7809b9f5e01844224af3
rishabhnagraj02/rishabh
/PEP8.PY
458
4.125
4
#Program to show use of constuctor and destructor class Person: def __init__(self,fname,lname): self.fname=fname self.lname=lname def getFullName(self): print(fname,lname) def __del__(self): print("Destroying instance of person class") p1=Person("Emraan","Hashmi") p1.getFullName() p2=Person("Rohit","Sharma") p2.getFullName() #p1 None #p2 None p1.__del__() p2.__del__()
true
a2bf5e8dea0ba645dba3f1b4425eaf2b6af7279b
vdonoladev/aprendendo-programacao
/Python/Programação_em_Python_Essencial/5- Coleções/counter.py
1,817
4.1875
4
""" Módulo Collections - Counter (Contador) https://docs.python.org/3/library/collections.html#collections.Counter Collections -> High-performance Container Datetypes Counter -> Recebe um interável como parâmetro e cria um objeto do tipo Collection Counter que é parecido com um dicionário, contendo como chave o elemento da lista passada como parâmetro e como valor a quantidade de ocorrências desse elemento. # Realizando o import from collections import Counter # Exemplo 1 # Podemos utilizar qualquer iterável, aqui usamos uma lista lista = [1, 1, 1, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 5, 3, 45, 45, 66, 66, 43, 34] # Utilizando o Counter res = Counter(lista) print(type(res)) print(res) # Counter({1: 5, 3: 5, 2: 4, 5: 4, 4: 3, 45: 2, 66: 2, 43: 1, 34: 1}) # Veja que, para cada elemento da lista, o Counter criou uma chave e colocou como valor a quantidade de ocorrências. # Exemplo 2 print(Counter('Geek University')) # Counter({'e': 3, 'i': 2, 'G': 1, 'k': 1, ' ': 1, 'U': 1, 'n': 1, 'v': 1, 'r': 1, 's': 1, 't': 1, 'y': 1}) """ from collections import Counter # Exemplo 3 texto = """A Wikipédia é um projeto de enciclopédia colaborativa, universal e multilíngue estabelecido na internet sob o princípio wiki. Tem como propósito fornecer um conteúdo livre, objetivo e verificável​​, que todos possam editar e melhorar. O projeto é definido pelos princípios fundadores. O conteúdo é disponibilizado sob a licença Creative Commons BY-SA e pode ser copiado e reutilizado sob a mesma licença — mesmo para fins comerciais — desde que respeitando os termos e condições de uso.""" palavras = texto.split() # print(palavras) res = Counter(palavras) print(res) # Encontrando as 5 palavras com mais ocorrência no texto print(res.most_common(5))
false
45076d538b6ef92f733093861d65cc159abefbac
davidevaleriani/python
/ball.py
1,925
4.15625
4
####################################################################### # Bouncing ball v1.0 # # This program is a first introduction to PyGame library, adapted # from the PyGame first tutorial. # It simply draw a ball on the screen and move it around. # If the ball bounce to the border, the background change color # # Author: Davide Valeriani # University of Essex # ####################################################################### # Import libraries import sys, pygame # Init all PyGame modules statements pygame.init() # Size of the window size = width, height = 640, 480 # Set linear speed (x, y) speed = [1, 2] # Background color list (RGB) colors = [[0, 0, 0], [255, 0, 0], [255, 255, 0], [255, 0, 255], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 255, 255]] # Background color index colorIndex = 0 # Create a graphical window screen = pygame.display.set_mode(size) # Load an image from file ball = pygame.image.load("ball.gif") # Get bounding box of the image ballrect = ball.get_rect() while 1: # Check if a key is pressed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: sys.exit() # Apply a speed to the bounding box of the image ballrect = ballrect.move(speed) # If the ball is out of the screen if ballrect.left < 0 or ballrect.right > width: # reverse the speed speed[0] = -speed[0] # change the background color colorIndex = (colorIndex + 1) % len(colors) if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] colorIndex = (colorIndex + 1) % len(colors) # Erase the screen to prepare printing the next frame screen.fill(colors[colorIndex]) # Copy pixels from ball image to ballrect surface that will be drawn on the screen screen.blit(ball, ballrect) # Update the visible display pygame.display.flip() # Make it slower pygame.time.delay(10)
true
34e5e6e7d7f787c615ef1f7ceb9a72a5c3d39d0d
LorienOlive/python-fundamentals
/paper-rock-scissors.py
1,205
4.21875
4
import random choices = ['paper', 'rock', 'scissors'] computer_score = 0 player_score = 0 while computer_score < 2 and player_score < 2: computer_choice = random.choice(choices) player_choice = input('What do you choose: paper, rock, or scissors? ') if computer_choice == player_choice: print('Tie game! Try again!') elif computer_choice == 'paper' and player_choice == 'rock': print('The computer scores!') computer_score += 1 elif computer_choice == 'rock' and player_choice == 'scissors': print('The computer scores!') computer_score +=1 elif computer_choice == 'scissors' and player_choice == 'paper': print('The computer scores!') computer_score += 1 elif player_choice == 'paper' and computer_choice == 'rock': print('You score!') player_score += 1 elif player_choice == 'rock' and computer_choice == 'scissors': print('You score!') player_score += 1 elif player_choice == 'scissors' and computer_choice == 'paper': print('You score!') player_score += 1 if computer_score == 2: print('The computer wins!') elif player_score == 2: print('You win!')
true
d7cf2b029976585f7be464cf911046e1946e9fc0
Aditya8821/Python
/Python/Daily Challenges/Searching And Sorting/Bubble_Sort.py
365
4.15625
4
def BubbleSort(arr): n=len(arr) for i in range(n): for j in range(n-i-1): #Here n-i-1 Bcoz largest element is reached to its pos(top) previous pass if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] arr=[64,34,25,12,22,11,90] BubbleSort(arr) print("Sorted Array: "+str(arr))
false
7d0c08ca7c6e4e45ccf852bda6db201391a71f92
Aditya8821/Python
/Python/Daily Challenges/Searching And Sorting/Insertion_Sort.py
278
4.25
4
def InsertionSort(arr): for i in range(1,len(arr)): key=arr[i] j=i-1 while j>=0 and key<arr[j]: arr[j+1]=arr[j] j-=1 arr[j+1]=key arr = [12, 11, 13, 5, 6] InsertionSort(arr) print("Sorted Array: "+str(arr))
false
22b4c505efcf84030192e3f6708d68c823fce03b
Ashish313/Python-Programs
/algorithms/Sorting/mergesort.py
1,074
4.1875
4
def mergesort(arr): if len(arr) > 1: # find the middle point and divide the array into two parts mid = len(arr)//2 L = arr[:mid] R = arr[mid:] # repeat the same procedure for left array and right array mergesort(L) mergesort(R) i = j = k = 0 # compare the elements of left and right array while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # check for remaining elements of left array if any while i < len(L): arr[k] = L[i] i += 1 k += 1 # check for remaining elements of right array if any while j < len(R): arr[k] = R[j] j += 1 k += 1 return arr # driver code if __name__ == '__main__': arr = [91,12,11,87,28,13,5,33,63,7,13] print(f'Given array: {arr}') mergesort(arr) print(f'Sorted array: {arr}')
false
07d3ce76ec05f6b1bfc4d1bdee287552e0c06aab
ledurks/my-first-portfolio
/shpurtle.py
604
4.15625
4
from turtle import * import math # Name your Turtle. t = Turtle() t.pencolor("white") # Set Up your screen and starting position. penup() setup(500,300) x_pos = -250 y_pos = -150 t.setposition(x_pos, y_pos) ### Write your code below: t.goto(500,600) pendown() begin_fill() fillcolor("LightSalmon") for sides in range(4): pendown() forward(100) left(90) penup() end_fill() import sys print (sys.argv) input_var = int(input("enter something: ")) t.goto(500,300) pendown() for shape in range(input_var): forward(100) left(360/input_var) # Close window on click. exitonclick()
true
a4b554f80bca1935d4685c39c1222d486f23ddbb
aniketguptaa/python
/Strings.py
1,493
4.375
4
#strings are immutable # Different method of writing string x = "Hello My name is Carry" y = 'Hello My name is Carry' z = '''Hello My name is carry and i read in class 10 and I am smart''' print(type(x)) # TypeViewing print(type(y)) # TypeViewing print(type(z)) # TypeViewing print(x) print(y) print(z) # Indexing of string str = "spamming" print(str[4]) # print 'm' # Negative indexing of string print(str[-1]) # print 'g' # Slicing in string print(str[0:8]) # spamming # Negative slicing print(str[:-4]) # Changing a string str2 = "C++" # str[1] = "Spam" Error text ommited print(str2) str2 = 'Python' # Replacing C++ with Python print(str2) # Del function in string del str2 # print(str2) # error text ommited # Concatenation and repeating in string str3 = "Hello " str4 = "World" str5 = str3 + str4 # print(str3+str4) print(str5) print(str5 * 2) # Iterating through a string count = 0 str6 = "pooling" for letters in str6: if (letters == 'l'): count+=1 print(count ," letters found", str6 ) # More complex iteration count = 0 word = "engineering" for letters in word: if(letters == 'e'): count+= 1 print(count," letters founded in", word) # Membership test str7 = 'spam' print('a' in str7) #True print('g' in str7) #False # Using Built-in functions # Enumerate function str8 = 'commerce' enum_str8 = list(enumerate(str8)) print(enum_str8) len_str8 = len(str8) print(len_str8)
true
e5c6517652c80dd958f26cb072055e255ce1967a
aniketguptaa/python
/Dictionary.py
966
4.1875
4
dict = {1 : "spam", 2: "spamming"} print(dict) dict1= {'name': 'Carry', 'age': 26} print(dict1['name']) print(dict1['age']) # Adding keys and value in preesxising dictionary dict1['address'] = 'Silicon valley' print(dict1['address']) print(dict1) squares = {1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81, 10:100} print(squares.pop(4)) # pop up value of key print(squares) # Methods in dictionary marks = {}.fromkeys(['Maths','English','Science'], "very good") # marks = {}.fromkeys(['Maths','English','Science'], 99) print(marks) for item in marks.items(): print(item) print(list(sorted(marks.keys()))) # name = {"name":"carry", "age":14} # print(list(name.keys())) # print(list(sorted(name.keys()))) it will print sorted values # Python dictionary comprehension square = {x : x * x for x in range(6)} print(square) # Alternative Methods # squares = {} # for x in range(6): # squares[x] = x*x # print(squares)
true
677d3f159cff2060f8116447d319ffe0ff39e3a4
duncanmurray/Python2-Training-Practicals
/takepin.py
659
4.3125
4
#!/usr/local/bin/python # Page 13 of exercise quide # Emulate a bank machine # Set the correct pin correct_pin = "1234" # Set number of chances and counter chances = 3 counter = 0 # While counter is less than chances keep going while counter < chances: # Ask for user input supplied_pin = raw_input("Please enter your pin: ") # Compare supplied pin to correct one and break if correct if supplied_pin == correct_pin: print "Very Good!!" break # If pin is incorrect loop back up if supplied_pin != correct_pin: print "You have 3 chances to get it right" counter += 1 # Say goodbye print "Goodbye"
true
355e20ddaff58320b195720f29272a5c093b66ca
swachchand/Py_exercise
/python_small_examples/pythonSnippets/frontThreeCharacters.py
700
4.1875
4
''' Given a string, we'll say that the front is the first 3 chars of the string. . If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. front3('Java') 'JavJavJav' front3('Chocolate') 'ChoChoCho' front3('abc') -- 'abcabcabc' front3('abcXYZ') 'abcabcabc' front3('ab') 'ababab' front3('a') 'aaa' front3('') '' ''' def front3(strChars): if len(strChars) == 3: return strChars * 3 else: mkList = list(strChars) tmpList = mkList[:3] strChars =''.join(tmpList) return strChars * 3 inpt1 = input('Enter word:') print(front3(inpt1))
true
886bdc4ecade0c75feae27d9205511a5377818c2
swachchand/Py_exercise
/python_small_examples/pythonSnippets/revStringSimple.py
362
4.40625
4
''' Print entire character stream in reverse without ---> List Comprehension Technique (simple traditional for loop) example: hello world olleh dlrow ''' word = input('Enter: ') ##The split() method splits a string into a list. w = word.split(' ') re =[] for i in w: re=i[::-1] #re.append() print(re, end=' ') #print(re)
true
5e63cb5efb36f2a1765446b6f9591594bf45cd4c
kevinsjung/mixAndMatchSentence
/mixAndMatchSentence.py
1,389
4.125
4
def mixAndMatchSentences(sentence): """ Given a sentence (sequence of words), return a list of all "mix and matched" sentences. We define these sentences to: - have the same number of words, and - each pair of adjacent words in the new sentence also occurs in the original sentence Example: - Input: 'the house and the car' - Output: ['and the house and the', 'house and the house and', 'the house and the house', 'the house and the car'] """ # make a list of the individual words wordlist = str.split(sentence) graph = {} # Create a graph with words and their adjacent words for i in xrange(0, len(wordlist)-1): if wordlist[i] in graph: if wordlist[i+1] not in graph[wordlist[i]]: graph[wordlist[i]].append(wordlist[i+1]) else: graph[wordlist[i]] = [] graph[wordlist[i]].append(wordlist[i+1]) sentencelist = [] # Recursive function to make sentences def recurse(curr, k): if len(curr.split()) == len(wordlist): sentencelist.append(curr) else: if k in graph: for v in graph[k]: recurse(curr + ' ' + v, v) for k in graph: curr = k recurse(curr, k) return sentencelist print mixAndMatchSentences('the house and the car')
true
84a5cf98811446097102aa2f93bdb0ee5b1afe2d
ReginaAkhm/Python-Adv
/day_4/anagrams.py
731
4.1875
4
# Анаграммы* # Задается словарь (список слов). # Найти в нем все анаграммы (слова, составленные из одних и тех же букв). # Пример: 'hello' <-> 'ollhe' import itertools from pprint import pprint def make_anagram_dict(line): d = {} for word in line: word = word.lower() key = ''.join(sorted(word)) anagram_temp = list(itertools.permutations(key)) anagram = [] for i in anagram_temp: i = ''.join(i) anagram.append(i) d[key] = anagram return d if __name__ == '__main__': my_list = ['hello', 'table', 'count'] pprint(make_anagram_dict(my_list))
false
09696fc8ccfcfad1e74b6dea56b5a067770f2549
jermailiff/python
/ex37.py
1,573
4.15625
4
import os # from math import sqrt # # # print "Hello World" # # while True: # # feelings = input("How are you feeling this morning on a scale of 1 - 10?") # # if feelings in range(1,5): # print "Pretty shitty then!" # break # elif feelings in range(6,10): # print "Pretty damn good eh" # break # else: # print "You're confusing as fuck" # # secondary = input("How did you feel yesterday on that same scale?") # try: # val = int(secondary) # except ValueError: # print "[You stooopid, clearly that means you need to enter a number!]" # # # if feelings % 2 == 0 and secondary % 2 == 0: # print feelings % 2 == 0 and secondary % 2 == 0 # print "You've been feeling pretty even of late pal." # else: # print "You odd bastard." # # print max(sqrt(feelings), sqrt(secondary)) # # print "Your secondary feeling isn't important as today is a new day, so let's fuck it off." # # del secondary # # if feelings%2 == 0 or sqrt(feelings) > 1.5: # print True # else: # print "I'm just being random" # # def location(): # loaction = raw_input("What's your current location trooper? ") # pass # return location # # location() # # locations = [location, 2, 'uk', 'germany', 4] # # print "What are the odds you pick a location?" # pick = input("Choose a number? ") # # if pick != int(pick): # raise TypeError("Only intergers accepted") # # # resolve # print location[pick] # # with # assert # yield # class # exec # finally os.chdir(r 'C:\users\jermaine\documents') enter = open('test1.rtf') for line in enter: print line close()
true
0cc636d346719e4c433d91254f053d451c52d9c2
ljyadbefgh/python_test
/test2/test2_1_lambda.py
1,621
4.3125
4
'''lambda函数的练习 lambda表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。 lambda所表示的匿名函数的内容应该是很简单的,如果复杂的话,干脆就重新定义一个函数了,使用lambda就有点过于执拗了。 lambda就是用来定义一个匿名函数的,如果还要给他绑定一个名字的话,就会显得有点画蛇添足,通常是直接使用lambda函数。 如下所示: add = lambda x, y : x+y add(1,2) # 结果为3 ''' ''' 练习1: 1.以下lambda等同于以下函数 def func(x): return(x+1) ''' func1=lambda x:x+1 print(func1(1)) ''' 2.配合其他函数使用 filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 说明:关于filter()方法, python3和python2有一点不同。Python2.x 中返回的是过滤后的列表, 而 Python3 中返回到是一个 filter 类。 题目:将列表中的所有奇数显示出 以下代码等价于下面的代码 #定义一个函数,当是奇数时返回true,否则返回false def count(x): return x % 2 == 1 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print(list(filter(count,foo))) ''' foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print(list(filter(lambda x:x%2==1,foo))) # list=[1,2,3,4,5] # func2=lambda list:[i for i in list] # print(func2)
false
0090d97141e758c65615795888ee1b999d28431c
iiit-nirmal/pyhton_prac
/loops/loopControl.py
458
4.15625
4
## continue returns control the begining of loop for letteres in 'geeksgeeks': if letteres == "e" or letteres == "s": continue print('character:',letteres) ## break returns control to the end of loop for letteres in 'geeksforgkees': if letteres == "e" or letteres == "s": break print('character:', letteres) ## pass is used to write emplty loops print("pass...") for letteres in 'geekdsadsasd': pass print(letteres)
true
da2d37c8ceebc6e7ac03eb30f5d472d0e7c7e1f3
joshmreesjones/algorithms
/interviews/n-possible-balanced-parentheses.py
755
4.21875
4
""" Print all possible n pairs of balanced parentheses. For example, for n = 2: (()) ()() """ def balanced_parentheses(n): if n == 0: return [""] elif n == 1: return ["()"] else: previous = balanced_parentheses(n - 1) result = [] for i in range(len(previous)): result.append("()" + previous[i]) result.append("(" + previous[i] + ")") result.append(previous[i] + "()") return result def print_all(list_of_strings): for string in list_of_strings: print(string) print_all(balanced_parentheses(1)) print("\n") print_all(balanced_parentheses(2)) print("\n") print_all(balanced_parentheses(3)) print("\n") print_all(balanced_parentheses(4))
true
e9b507e0c053a2990f82f4a9fecc0b63d17349e1
gmn7/aep2
/TrabalhoPilha/main.py
766
4.125
4
from pilha import Pilha def menu(): print ('Entre com a opcao: \n', \ '1 para inserir na pilha \n', \ '2 para retirar na pilha\n', \ '3 para mostra o proximo valor a ser retirado da pilha \n', \ '4 verificar se esta vazia \n', \ '5 para finalizar o programa \n') pilha = Pilha() menu() contro = input("informe uma opcao: ") while contro !=5: if contro =='1': pilha.push(input('Qual o valor ?')) elif contro =='2': pilha.pop() elif contro =='3': pilha.peek() elif contro =='4': pilha.empty() break else: print ('Opcao invalida', contro) menu() contro=input('\n') print ('Programa finalizado')
false
3e331573d4214f4302f4124c42e74dd8f6d2c691
glennandreph/learnpython
/thirtysix.py
213
4.15625
4
name = "Glenn" age = 24 if name == "Glenn" and age == 24: print("Your name is Glenn, and you are 24 years old.") if name == "Glenn" or name == "Rick": print("Your name is either Glenn or Rick.")
true
b0edb28c2f7c9c69361b8d5121d0e7372c50f93e
savadev/Leetcode-practice
/122 Sum and average.py
501
4.1875
4
Sum and Average from a List Given a list of integers, write a method that returns the sum and average of only the 1st, 3rd, 5th, 7th etc, element. For example, [1, 2, 3] should return 4 and 2. The average returned should always be an integer number, rounded to the floor. (3.6 becomes 3.) def sumavg(arr): sum = 0 n =0 for i,j in enumerate(arr[::2]): sum += j n +=1 print(sum) print(sum//n) Used enumerate to find out the indices while finding out the sum.
true
9d6d5ac4882ae9213f56d729cf98c531f3a0f180
jc328/CodeWars-1
/7kyu_MostCommonFirst.py
1,192
4.25
4
// 7kyu - Most Common First // Given a string, s, return a new string that orders the characters in order of // frequency. // The returned string should have the same number of characters as the original // string. // Make your transformation stable, meaning characters that compare equal should // stay in their original order in the string s. // most_common("Hello world") => "lllooHe wrd" // most_common("Hello He worldwrd") => "lllHeo He wordwrd" // Explanation: // In the hello world example, there are 3 'l'characters, 2 'o'characters, and one // each of 'H', 'e', ' ', 'w', 'r', and 'd'characters. Since 'He wrd'are all tied, // they occur in the same relative order that they do in the original string, // 'Hello world'. // Note that ties don't just happen in the case of characters occuring once in a // string. See the second example, most_common("Hello He worldwrd")should return // 'lllHeo He wordwrd', not 'lllHHeeoo wwrrdd'. This is a key behavior if this // method were to be used to transform a string on multiple passes. from collections import Counter def most_common(s): count=Counter(s) return ''.join(sorted(s, key=lambda x: count[x], reverse=1))
true
46fae30e099f6a6047c7628e24b03b0157946a1e
chronosvv/pythonAdvanced
/myiterable.py
1,072
4.3125
4
# 1.可迭代对象 # 以直接作用于for循环的数据类型有以下几种: # 一类是集合数据类型,如list,tuple,dict,set,str等; # 一类是generator,包括生成器和带yield的generator function。 # 这些可以直接作用于for循环的对象统称为可迭代队象:Iterable # 2.判断是否可以迭代 from collections import Iterable print(isinstance([], Iterable)) #列表是不是Iterable的实例 print(isinstance(100, Iterable)) # 3.迭代器 # 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 # 可以使用isinstance()判断一个对象是否是Iterator对象: from collections import Iterator print(isinstance([], Iterator)) print(isinstance((x for x in range(10)), Iterator)) # 4.iter()函数 # 生成器都是Iterator对象,但是list,dict,str虽然是Iterable,却不是Iterator。 # 把list,dict,str等Iterable变成Iterator可以使用iter()函数: print(isinstance(iter([]), Iterator)) # 迭代器仅仅只是一个地址,比可迭代对象省内存
false
f0cb0daab6662ac4862f4ce2b06b4976cced1e45
youngcardinal/MFTI-Labs
/002_grafik.py
801
4.34375
4
# Каскадные условные функции: # по данным ненулевым числам x и y определяет, # в какой из четвертей координатной плоскости находится точка (x,y) print("Задача:\nОпределить какой четверти принадлежит точка с введенными координатами\nВведите число x:") x = int(input()) print("Введите число y:") y = int(input()) if x > 0 and y > 0: print('Первая четверть графика') elif y < 0: print('Четвертая четверть графика') elif y > 0: print('Вторая четверть графика') else: print('Третья четверть графика')
false
30ad4e8bf69f6407bd388987245d39c368ee0bed
lavisha752/Python-
/LCM.py
889
4.125
4
# User input and storing data in variables var1=int(input("Enter the first number:")) var2=int(input("Enter the second number:")) # Using an if statement to find the smallest number and storing in a variable called smallest if(var1 > var2): smallest=var1 else: smallest=var2 # A while loop is used to test if the condition is true and the loop continues while the condition is true else it breaks while(1): # An if statement is used to check the smallest number and # if it is divisible by the two digit and check for remainder when smallest divide by var2 if(smallest % var1 ==0 and smallest % var2 ==0): #while the condition is true , the output is displayed print("LCM is:",smallest) # If the value is divisible , it breaks and moves out of the loop break # Else there is an increment to continue the loop smallest=smallest+1
true
373d68168b0589221d4e0548104c737bd52ecf4d
mrech/LearnPython_TheHardWay
/shark.py
741
4.15625
4
#define a class with is methods (functions) class Shark: def swim(self): print("The shark is swimming.") def be_awesome(self): print("The shark is being awesome.") # function object # create a variable called main that point the function object def main(): sammy = Shark() # Initialize the object sammy.swim() # use the mothod of the class sammy.be_awesome() if __name__ == "__main__": main() # module as part of a program # if Py interpreter is running that module (source file) as the main program, # it sets the special __name__ variable to have a value "__main__". # If this file is being imported from another module, __name__ # will be set to the module's name.
true
05ed02a2c46f709e7769d0eec1333fbcec83c517
Sever80/Zadachi
/11.py
455
4.34375
4
# Даны два списка одинаковой длины. # Необходимо создать из них словарь таким образом, # чтобы элементы первого списка были ключами, # а элементы второго — соответственно значениями нашего словаря. a=[1,2,3,4,5] b=['one','two','three','four','five'] my_dict=dict(zip(a,b)) print(my_dict)
false
ba0a8b6acbfcc9f03f99db2f0d7ac145a5090f68
madhav9691/python
/matrix_mul.py
1,148
4.34375
4
def create_matrix(m,row,col): for i in range(row): m.append([]) # adding rows for i in range(row): for j in range(col): m[i].append(0) #adding columns to each row def enter_elements(n,r1,c1): for i in range(r1): for j in range(c1): n[i][j]=int(input()) a=[] b=[] c=[] r1=int(input("enter no of rows of matrix a: ")) c1=int(input("enter no of columns of matrix a: ")) r2=int(input("enter no of rows of matrix b: ")) c2=int(input("enter no of columns of matrix b: ")) if c1!=r2: print("matrix multiplication is not possible") else: create_matrix(a,r1,c1) create_matrix(b,r2,c2) create_matrix(c,r1,c2) print("enter elements of matrix a") enter_elements(a,r1,c1) print("enter elements of matrix b") enter_elements(b,r2,c2) #multiplication for i in range(r1): for j in range(c2): for k in range(c1): c[i][j]+=a[i][k]*b[k][j] print("Multiplication of two matrices") for i in range(r1): for j in range(c2): print(c[i][j], end=" ") print()
false
e427482ec1b80a52fc2919c61d32fb16d8c4e794
xKolodziej/02
/06/Zad11.py
473
4.125
4
array1=["water","book","sky"] array2=["water","book","sky"] def compare(array1,array2): print("Array1: ", end="") for i in array1: print(i, end=" ") print() print("Array2: ", end="") for j in array2: print(j, end=" ") print() if array1==array2: print("Arrays are the same") return True else: print("Arrays are not the same") return False print(compare(array1,array2))
false
f2bd85b263adf608ccda9023189d9a0b84f3f1ae
raonineri/curso_em_video_python
/ex008.py
451
4.21875
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. distancia_m = float(input("Digite uma distância em metros: ")) print('-=' * 10) print(f'{distancia_m}m corresponde a:') print('-=' * 10) print(f'{distancia_m/1000} Km\n' f'{distancia_m/100} Hm\n' f'{distancia_m/10} Dam\n' f'{distancia_m*10} Dm\n' f'{distancia_m*100} Cm\n' f'{distancia_m*1000} mm') print('-=' * 10)
false
904a4c613bb872548cfcb721e3c4453c4758076f
TheBlocks-CN/PoHaiFriends
/PoHai (Version 1.2).py
1,258
4.125
4
Language = input("What language r u use?zh-CN(zh-SG) , zh-TW(zh-HK,zh-MO) or en-UK (en-US)?If u use Chinese(Simplified) type 1,use Chinese(Tranditional) type 2, use English type 3.") Language = int(Language) if Language == 1: digital = input("Please type the digital") digital = int(digital) if digital == 9979: print("恭喜你!你成功输入了密码!") print("9979的意思是:小猪是屑!(9键拼音输入法)") else: print("你输入的数字错误!请再次输入!") if Language == 2: digital = input("Please type the digital") digital = int(digital) if digital == 9979: print("恭喜你!你成功輸入了密碼!") print("9979的意思是:小豬是屑!(9键中國大陸拼音输入法)") else: print("你輸入的数字錯誤!請重新輸入!") if Language == 3: digital = input("Please type the digital") digital = int(digital) if digital == 9979: print("Congratulations!You type Digital is right!") print("The Digital '9979' mean:xiaozhu_zty is xie!") else: print("The digital you entered is incorrect! Please enter again!") #此版本新增English(英语),并将变量详细化。"SCorTC -> Language" "password -> digital"
false
f6bc7d44457f10f177f97fd6fba284923262ab3d
MTset/Python-Programming-Coursework
/Python 01: Beginning Python/Lesson 11: Defining and Calling Your Own Functions/three_param.py
640
4.1875
4
#!/usr/local/bin/python3 def my_func(a, b="b was not entered", c="c was not entered" ): """ right triangle check """ result = "Values entered: a - {0}, b - {1}, c - {2}\n".format(a, b, c) if type(c) is int: d = sorted([a, b, c]) if abs(complex(d[0], d[1])) == d[2]: result += "You have a right triangle!\n" elif type(b) is int: d = abs(complex(a, b)) result += "With c = {0} you could have a right triangle.\n".format(d) else: result += "Don't abuse the hypotenuse.\n" return result print(my_func(3)) print(my_func(3,4)) print(my_func(3,4,5)) print(my_func)
true
427ab151f21bdd3fbd09e2fce7dddcdbdac5eb5d
purcellconsult/jsr-training
/day_2_files/secret_number_game.py
1,014
4.25
4
# Secret Number Game # ------------------- # A text based game written in python. # The user gets to take an arbitrary number of guesse. # They will be provided feedback on if their guess # is less than, greater than, or equal to the secret num. # If equal, the secret number should be revealed, and # then the loop terminates. # ########################################### from random import randint secret_number = randint(1, 100) print("The secret is {}. Don't tell anyone!".format(secret_number)) while True: user_guess = int(input("Enter in your guess ")) if user_guess < 0 or user_guess > 100: print("Enter in a number within the range of 1-100") elif user_guess == secret_number: print("{} is the secret number. You win!".format(secret_number)) break elif user_guess > secret_number: print("{} is greater than the secret number".format(user_guess)) else: print("{} is less than the secret number".format(user_guess))
true
bd1c05cbe4e34d9a8b3f5d9f65d0ac89ec5145a6
zxcv-zxcv-zxcv/python_mega_course
/textpro_mysolution.py
875
4.21875
4
# 1. Output "Say Something" # 2. take an input, store it into a list # 3. end if user inputs /end # 4. Capitalise first letter. End in a question mark if it starts with who, # what , when, where, why, how # 5. Print out each input. inputs = [] word = '' fullstop = '.' sentence = '' while True: if word != "\end.": word = input("Say something: ") word = str(word) word = word.capitalize() if (word.startswith('Who') or word.startswith('What') or word.startswith('When') or word.startswith('Why') or word.startswith('How')): word = word + '?' else: word = word + '.' inputs.append(word) continue else: inputs.remove('\end.') print(' '.join(inputs)) break
true
74df3681854c0447bd341b5cb42ae5f2fcbfe544
min0201ji/Pyhthon_Programming_Basic
/Exam2/2_5.py
615
4.5625
5
""" 이름 : 박민지 날짜 : 2021/04/15 내용 : 파이썬 클래쓰 연습문제 """ class King: def __init__(self,#name(M) #name=태조, #year(M) #year=1392): self.name = name self.year = year def show(self): print('-------------') print('name :', self.name) print('year :', self.year) if __name__ == '__main__': King1 = King() King2 = King#('태종') 뒤에 1392 써도 되고 안써도 됨! 왜냐면 위에 값이 있음 이미 King3 = King#('세종대왕', 1418) King1.show() King2.show() King3.show()
false
cf5f292acb3d3bfd6f306cb80d49a31b9a194533
nankyoku/nankyokusPython
/ex6.py
1,262
4.375
4
# Exercise 6: Strings and Text # The below 4 statements set up variables and their values x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) # The below 2 statements print out the values of the variables x and y. print x print y # The statement below prints a string and variable x, note that we're using type %r. print "I said: %r." % x # The statement below prints a string and variable y, note that we're using type %s, and it is in between ' ' which seems to make no difference for the string that was defined with " ". print "I also said: '%s'." % y # Setting up variables as well in the following 2 statements. hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" # printing two variables, this is interesting because the first variable is a string, and it is using %r. It seems there are subtleties as how to use these. Will keep on studying. print joke_evaluation % hilarious # Setting up two variables and their values. w = "This is the left side of..." e = "a string with a right side." # Printing the two variables above, which were strings. print w + e # %r is useful for debugging, since it displays the raw value of the variable!
true
698a372fd9c7e4b717d593c2d5f9196f320d89d1
PET-Comp-UFMA/Monitoria_Alg1_Python
/03 - Laços de repetição/q13.py
1,411
4.1875
4
""" Faça um programa que funcione como uma loja. Esse programa deverá mostrar os itens que estão a venda e o preço de cada um e então receberá como entrada o item a ser comprado e a quantidade, ele deverá então perguntar se o usuário deseja continuar comprando ou encerrar a compra. Ao final, o programa deverá mostrar quanto será o total a ser pago pelo usuário. Exemplo: Entrada Saída O que desea comprar? item 1 Qtd:5 Deseja continuar? sim O que deseja comprar? item 2 Qtd:5 Deseja continuar? não Sua conta foi de xxx gold. """ #Solução x=1 carrinho=0 print("1- Poção de vida: 50g") print("2- Éter: 100g") print("3- Elixir: 500g") print("4- Antídoto: 75g") while x!=0: item=int(input("O que você gostaria de comprar? ")) quantidade=int(input("Quantos você gostaria? ")) if item==1: carrinho+=quantidade*50 elif item==2: carrinho+=quantidade*100 elif item==3: carrinho+=quantidade*500 elif item==4: carrinho+=quantidade*75 x=int(input("Você gostaria de continuar comprando? Digite 0 para encerrar a compra e qualquer outra coisa para continuar: ")) print("O total da sua compra foi de: "+ str(carrinho) + "g.")
false
808a95bb776910cbb22c0baeb85c30a83a5e08ec
PET-Comp-UFMA/Monitoria_Alg1_Python
/04 - Strings/q04.py
515
4.21875
4
#Leia uma String e retorne na tela mostrando se é uma palíndroma. #Um palíndromo é uma palavra ou frase que pode ser lida no seu sentido normal, da esquerda para a direita, bem como no sentido contrário, da direita para a esquerda, sem que haja mudança nas palavras que a formam e no seu significado. palavra = input() palavra = palavra.lower() palavra = palavra.replace(" ", "") palavraInvertida = palavra[::-1] if palavra == palavraInvertida: print("Palíndromo") else : print("Não Palíndromo")
false
8505e1201ac2c84644d9546bc8fee4c1489b9fb9
PET-Comp-UFMA/Monitoria_Alg1_Python
/03 - Laços de repetição/q15.py
550
4.40625
4
""" Faça um programa que receba uma string e imprima ela de volta com a formatação trocada, ou seja, todas as letras que estiverem em minúsculo serão imprimidas em maiúsculo e todas as letras em maiúsculo serão impressas em minúsculo. Exemplo: Entrada Saída Sino sINO InVeJa iNvEjA SABONETE sabonete """ #Solução string=str(input()) for i in string: if i.isupper(): print(i.lower(), end="") elif i.islower(): print(i.upper(), end="")
false
45a868005faa26f5eaaee0eda5f2fa03926ca8ea
PET-Comp-UFMA/Monitoria_Alg1_Python
/03 - Laços de repetição/q10.py
309
4.1875
4
#Questão 10 #Faça um código que peça um número natural N ao usuário e printe um triângulo de #asteriscos de N linhas na tela. Exemplo: #N = 5 #* #** #*** #**** #***** n = int(input("Digite um número natural: ")) for i in range(n): for j in range(i+1): print("*", end = "") print("")
false
551c8929a594c2eea91e8dac5f2ef39bb359106f
PET-Comp-UFMA/Monitoria_Alg1_Python
/01 - Variáveis/q06.py
604
4.1875
4
#Questão 6 #Dado uma variável A que receba qualquer informação de entrada do usuário, escreva um programa #que imprima em tela o tipo de dado dessa variável, seguindo o formato: “O tipo da variável é TIPO.”, #onde TIPO é um dos tipos de variáveis definidos na linguagem utilizada. #(ex: em linguagens da família C, temos int, float, double, char, etc…, já em Lua, temos string, #number, boolean, nil, etc...). Não use estruturas IF. Bibliotecas nativas são permitidas. variavel = input('Digite a informação de entrada: ') tipo = type(variavel) print("A variável é do tipo", tipo)
false
8b1c96315b8a255f0902b513ac699bf2bc973288
Anishukla/50-Days-of-Code
/Day-14/HackerRank/Recursion: Davis' Staircase.py
435
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 25 23:59:26 2020 @author: anishukla """ #Level: Medium # Complete the stepPerms function below. def stepPerms(n): A = [1, 2, 4] for i in range(3, n): A.append(A[i-3]+A[i-2]+A[i-1]) return A[n-1] if __name__ == '__main__': s = int(input()) for s_itr in range(s): n = int(input()) res = stepPerms(n) print(res)
false
b6ce6f9b3a313926e6cc0e1e38cdf78c4c133456
linneakarlstrom/Notes
/Notes/something.py
2,847
4.15625
4
# anteckningar # en operator är + - osv. Det finns olika sorters operatorer. # Aritmetiska (arithmetic) + - / % // * ** # Jämförelse (comparision) == (ifall de är lika) < > <= => != (ej lika med) # logiska (logical) and, or , not # if, else är villkorsatser. När ett villkor ska avögra (conditional statement - villkor sats) # Ditt quiz ska ha alternativa frågor (A,B,C, osv.). Det ska vara med if. # ifall du vill ha resultat av quiz skriv score = 0 questions = 0 # questions = questions + 1 # print("A. Dessert topping") # print("B. Desert topping") # user_input = input("A cherry is a: ") # if user_input.upper() == "A": # print("Correct!") # else: # print("Incorrect.") # my_list = [5] #for i in range(5): # my_list.append(i) den lägger till 0,1,2,3,4 för att for i in range(5)betyder att den ska printa ut 0,1,2,3,4 #print(my_list) # du får ej ändra på en tuple men med en lista får du #print("Simpson" + "College") printar ihop så simpsoncollege #print("Simpson" + "College"[1]) printar simpsono för att den tar simpson + andra bokstaven i college #print( ("Simpson" + "College")[1] ) printar i för att det är andra elementet i det. #word = "Simpson" #for i in range(3): # word += "College" #print(word) printar simpsoncollegecollegecollege för att den printar ut college 3 gånger + simpson #my_list = [] #for i in range(5): # question = input("Skriv en siffra") # my_list.append(question) #print() # tom dictonary "variabel" = {} # ta bort värde = del # två key_value par = {"title" : "något"} # "variabel".keys() får man ut alla 'nycklar' i dictionary # iterera betyder repetera # foo = dict(first_name='Einar') #print(foo) # to add a key-value in python --> "variabel"[""Key""] = ""Value"" # Copy of the array to sum #my_list = [5,76,8,5,3,3,56,5,23] # Initial sum should be zero #list_total = 0 # Loop from 0 up to the number of elements # in the array: #for i in range(len(my_list)): # len(my_list) för att annars förstår den inte hur den ska göra. listan kan inte göras till en integer. # Visst listan är 9 lång men då måste du isåfall lägga till saker. # Add element 0, next 1, then 2, etc. # list_total += my_list[i] # Print the result #print(list_total) #my_list = [5, 76, 8, 5, 3, 3, 56, 5, 23] # Initial sum should be zero #list_total = 0 # Loop through array, copying each item in the array into # the variable named item. #for item in my_list: # Add each item # list_total += item # Print the result #print(list_total) #def a(x): # x = x + 1 #x = 3 #a(x) #print(x) This will only print 3 because here we have 2 different variables. X inside the function and x outside. #it would be the same as long as the function does not change the value def minlista(list): output = "" for item in list: output += str(item) return output
false
a925aacc4744ec91d54bdd345e471dc9af142bf2
Eqliphex/python-crash-course
/chapter08 - Functions/exercise8.8_user_albums.py
1,269
4.375
4
def make_album(album_artist, album_title, album_song_num=None): """Creates an album. Args: album_artist (str): Name of the artist. album_title (str): Title of the album. album_song_num (:obj:`str`, optional): The second parameter. Defaults to None. Returns: bool: The return value. True for success, False otherwise. """ if album_song_num: return {'artist': album_artist, 'title': album_title, 'song_num': album_song_num} else: return {'artist': album_artist, 'title': album_title} def create_albums(): """Enteres a loop for generating albums. Returns: dict: returns a dictionary with albums and artists """ albums = [] while True: print("Please enter album information") print("(type 'quit' for exiting program!)") artist = input("Album artist: ") if artist == 'quit': break title = input("Album title: ") if title == 'quit': break track_num = input("Album track numbers: (leave blank if unknown)") if track_num == 'quit': break albums.append(make_album(artist, title, track_num)) return albums print(create_albums())
true
11a0b9c55f4e24347745c648bd8ca2ccc8f34e97
omkar-21/Python_Programs
/Que_34.py
645
4.1875
4
""" Write a procedure char_freq_table() that, when run in a terminal, accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen. """ from collections import Counter import os def main(): try: with open(input("Enter the file path to read\n>>"),'r') as input_file: dic=Counter(input_file.read()) print("Count of Character using Inbuilt Function:",sorted(dic.items())) except FileNotFoundError: print("File or File Path not Found") if __name__ == "__main__": main()
true
04e02bb6cbe311c3ad31150ad5816489651edcf3
omkar-21/Python_Programs
/Que_37.py
836
4.34375
4
""" Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n (where n is the number of lines in the file). """ import os def number_lines(file_path, path_for_new_file): try: with open(file_path,'r') as input_file, open(path_for_new_file,"w+") as output_file: lines=input_file.readlines() for no,line in enumerate(lines,1): output_file.write("%d) %s" %(no,line) ) return except FileNotFoundError: print("File or File Path not Found") def main(): file_path=input("Enter the file path:\n>> ") path_for_new_file=input("Enter the File Path with File Name for New File:\n>> ") number_lines(file_path,path_for_new_file) if __name__ == "__main__": main()
true
1cb69c0e9b56b34d446dd27338c94dbb8d424439
omkar-21/Python_Programs
/Que_36.py
888
4.1875
4
""" A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a language, the works of an author, or in a single text. Define a function that given the file name of a text will return all its hapaxes. Make sure your program ignores capitalization. """ import os import re def hapax(file_path): try: with open(file_path,'r') as inputed_file: file_to_read=inputed_file.readlines() words=[word for line in file_to_read for word in re.sub('[^\w\s]','',line).strip().split(" ")] result = filter(lambda word: words.count(word) == 1, words) print(list(result)) return except FileNotFoundError: print("File or File Path not Found") def main(): file_path=input("Enter the file path:\n>> ") hapax(file_path) if __name__ == "__main__": main()
true
7fd8a9449de8ae605918a93e43925901f0794604
omkar-21/Python_Programs
/Que_3.py
425
4.125
4
''' Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) ''' def findLen(str1): counter = 0 for i in str1: counter += 1 print("Length of string is",counter) def main(): str1=input("Enter the string: ") findLen(str1) if __name__=='__main__': main()
true
d6171f54ce5fade36bd8eddf7ca3e20f270016ff
omkar-21/Python_Programs
/Que_32.py
658
4.28125
4
""" Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome. """ import re import os def main(): try: with open(input("Enter the file path to read\n>>"),'r') as input_file: lines=input_file.readlines() print("Palindromic lines are: ") for line in lines: pal=re.sub('[^a-zA-Z0-9]','',line).strip() if pal==pal[::-1]: print(line) except FileNotFoundError: print("File or File Path not Found") if __name__ == "__main__": main()
true
8f5b0188b57f4db2e84ebc8d798465340f299e5a
omkar-21/Python_Programs
/Que_27.py
871
4.46875
4
""" Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions. """ def lengths_using_loop(words): lengths = [] for word in words: lengths.append(len(word)) return lengths def lengths_using_map(words): return map(len, words) def lengths_using_list_comp(words): return [len(word) for word in words] def main(): m=int(input("Enter the size of List:\n>>")) words=[input("Enter the word: ") for i in range(m)] print("List Using Loop:",lengths_using_loop(words)) print("List Using Map:",list(lengths_using_map(words))) print("List Using List Comperihension:",lengths_using_list_comp(words)) if __name__ == "__main__": main()
true
c1f275be9c454a9542991878f85be18a0b03e516
apoorvakashi/launchpad-Assignments
/problem3.py
230
4.125
4
numbers = [1, 3, 4, 6, 4, 35, 5, 43, 3, 4, 18, 3, 1, 1] numlist= [] element = int(input("Enter a number: ")) for index, value in enumerate(numbers): if value==element: numlist.append(index) print(numlist)
true
ba0f7783481d57ca633b50240f40f0fc2a6516cc
raulzc3/MastermindPython
/primerPrograma/primerPrograma.py
603
4.25
4
# Mi primer programa en Python! # Este programa recibe tres números como input por parte del usuario e indica los números mayor y menor num1 = int(input("Introduce un número: ")) num2 = int(input("Introduce otro número: ")) num3 = int(input("Introduce otro número (este será el último): ")) maxNum = max(num1, num2, num3) minNum = min(num1, num2, num3) ''' Solución concatenando usando comas: print("El número mayor es ", maxNum, " y el menor es ", minNum) ''' # Solución con función format print("El número mayor es {max} y el menor es {min}".format(max=maxNum, min=minNum))
false
4ae99f08a25243205420fc508e86b53a86d2d032
roger-mayer/python-practice
/crash_course/input_and_while_loops/greeter.py
580
4.28125
4
# # single line # name = input("please enter your name: ") # print(f"Hello, {name}!") # # # multi line prompt # prompt = "If you tell us you name, we can personalize messages." # prompt += "\nWhat is your name? " # # name = input(prompt) # print(f"\nHello, {name}!") # using int to accept numerical input age = input("How old are you? ") age = int(age) if age >= 18: print("You are an adult") else: print("You are a baby") # even or odd num = input("Please enter a number: ") num = int(num) if num % 2 == 0: print(f"{num} is even") else: print(f"{num} is odd")
true
348d80458e3fa747a0693fc3aa826a5fbf8c3ff7
roger-mayer/python-practice
/crash_course/dictionaries/many_users.py
566
4.28125
4
# dictionary in a dictionary users = { 'rmayer': { 'first': 'roger', 'last': 'mayer', 'age': 35 }, 'kwest': { 'first': 'katie', 'last': 'west', 'age': 28 }, 'amayer': { 'first': 'asher', 'last': 'mayer', 'age': 1 } } for username, user_info in users.items(): print(f"\nusername: {username}") full_name = f"{user_info['first']} {user_info['last']}" user_age = user_info['age'] print(f"Full Name: {full_name.title()}") print(f"Age: {user_age}")
false
5d7d95edc99927d94276b4c44b0904fed9f9b5af
iam-abbas/cs-algorithms
/Searching and Sorting/Selection Sort/PYTHON/SelectionSort.py
945
4.28125
4
#Call 'main()' in the terminal/console to run Selection Sort on desired unsorted sequence. #This algorithm returns the sorted sequence of the unsorted one and works for positive values. def SelectionSort(arr): pos = 0 min_num = 0 for i in range(0, len(arr)): min_num = arr[i] pos = i for j in range(i+1, len(arr)): if min_num > arr[j]: min_num = arr[j] pos = j if pos != i: arr[i], arr[pos] = arr[pos], arr[i] return arr def main(): arr = list() print("Enter the elements of array to be sorted.\ Type 'x' (along with inverted commas) for termination") while True: el = input() if el is 'x' or el is 'X': break else: arr.append(int(el)) arr = SelectionSort(arr) print("Sorted array is : {}", arr) return 0 if __name__ == "__main__": main()
true
b7d9ab7dd8f30d06e51e1f8c9e73c797e5d62aa3
iam-abbas/cs-algorithms
/Searching and Sorting/Linear Search/Python/linear search.py
460
4.125
4
# Python3 code to linearly search x in arr[]. # If x is present then return its location, # otherwise return -1 def search(arr, n, x): for i in range (0, n): if (arr[i] == x): return i; return -1; # Driver Code arr = [ 2, 3, 4, 10, 40 ]; x = 10; n = len(arr); result = search(arr, n, x) if(result == -1): print("Element is not present in array") else: print("Element is present at index", result);
true
10219c8538c18b8955068ffb124244e2990603f0
iam-abbas/cs-algorithms
/Floyd Cycle Loop Detection/floyd_cycle_loop_detection.py
1,272
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Push value to the end of the list def push(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: temp = self.head while temp.next is not None: temp = temp.next temp.next = new_node # Floyd Cycle Loop Detection def detect_loop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: print("Found loop at value: ", slow_p.data) return def print_list(self): node = self.head while(node): print(node.data) node = node.next linked_list = LinkedList() linked_list.push(1) linked_list.push(2) linked_list.push(3) linked_list.push(4) linked_list.push(5) linked_list.push(6) linked_list.push(7) linked_list.print_list() linked_list.head.next.next.next.next = linked_list.head.next.next linked_list.detect_loop()
true
aa94cde42819d8cbbf072da6da479e0312534a25
santibaamonde/prueba
/juego_adivinar.py
321
4.15625
4
numero_adivinar = int(input("Dime un numero que quieras que otro trate de adinivar: ")) numero_adivinador = int(input("Intenta adivinar el numero que ha pensado la otra persona: ")) while numero_adivinar != numero_adivinador: numero_adivinador = int(input("Has fallado, prueba otro numero: ")) print("Has ganado")
false
eb62010da78c62f30e81952970bb2d33f62db4b6
santibaamonde/prueba
/clase10_parte3_ej3.py
1,303
4.15625
4
""" Crear un programa que guarde e imprima varias listas con todos los números que estén dentro de una lista proporcionada por el usuario y sean múltiplos de 2, de 3, de 5 y de 7. Ejemplo: input = [1, 10, 70, 30, 50, 55] multiplos_dos = [10, 70, 30, 50] multiplos_tres = [30] multiplos_cinco = [10, 70, 30, 60, 55] multiplos_siete = [70] """ lista_usuario = [] input_usuario = input("Dime un número para añadir a la lista o escribe FIN para terminar: ") while input_usuario != "FIN": lista_usuario.append(int(input_usuario)) input_usuario = input("Dime un número para añadir a la lista o escribe FIN para terminar: ") print("Tu lista es {}".format(lista_usuario)) multiplos_dos = [] multiplos_tres = [] multiplos_cinco = [] multiplos_siete = [] for numero in lista_usuario: if numero % 2 == 0: multiplos_dos.append(numero) if numero % 3 == 0: multiplos_tres.append(numero) if numero % 5 == 0: multiplos_cinco.append(numero) if numero % 7 == 0: multiplos_siete.append(numero) print("Los múltiplos de dos son: {}".format(multiplos_dos)) print("Los múltiplos de dos tres: {}".format(multiplos_tres)) print("Los múltiplos de dos cinco: {}".format(multiplos_cinco)) print("Los múltiplos de dos siete: {}".format(multiplos_siete))
false
96da3374de0f73da3bc5de499917b3f0427e4f80
wandeg/fun
/pascals.py
2,117
4.28125
4
from utils import func_timer import math @func_timer def factorial_loop(n, until=1): """Get the nth factorial using a loop""" fact = 1 i = until while i<=n: fact *= i i+=1 return fact @func_timer def factorial_rec(n): """Returns the nth factorial using recursion""" if n == 1 or n == 0: return 1 else : return n*factorial_rec(n-1) @func_timer def n_choose_k_naive(n,k): """ Returns the number of ways you can choose k items from n items in any order """ return factorial_loop(n)/(factorial_loop(k)*factorial_loop(n-k)) # @func_timer def n_choose_k_improved(n,k): """ Returns the number of ways you can choose k items from n items in any order Faster especially if k is close to n """ return factorial_loop(n,k+1)/(factorial_loop(n-k)) @func_timer def pascals_triangle_naive(n): """ Returns the nth row of pascals triangle the naive way by starting from the first row """ arr = [1] if n == 0: return arr for i in xrange(0,n): arr.insert(0,0) arr.append(0) nu_arr = [] for i in xrange(len(arr)-1): nu_arr.append(arr[i]+arr[i+1]) arr = nu_arr return nu_arr @func_timer def pascals_triangle_binomial(n): """Uses binomial coefficients to generate pascals triangle's nth row""" triangle_row = [] for i in range(n+1): triangle_row.append(n_choose_k_improved(n,i)) return triangle_row @func_timer def pascals_triangle_binomial_improved(n): """Uses binomial coefficients to generate pascals triangle's nth row""" triangle_row = [] top = (n/2) + 1 for i in range(top): triangle_row.append(n_choose_k_improved(n,i)) if n %2 == 0: triangle_row.extend(triangle_row[:-1][::-1]) else: triangle_row.extend(triangle_row[::-1]) return triangle_row @func_timer def fact_memo(n): mem = {} mem[1] = 1 if n > 2: for i in range(2,n+1): mem[i] = i * mem[i-1] return mem @func_timer def get_fact_as_facts(top = 30): mem = fact_memo(top) mem_inv = {v:k for k,v in mem.iteritems()} mapper = {} for i in range(2,top+1): for j in range(2,i): val = mem[i]/mem[j] if val in mem_inv: mapper[i]= (j, mem_inv[val]) return mapper \
false
7359a38cffa8a37405a0f7be60eefdae3685436a
TimTheFiend/Automate-the-Boring-Stuff-with-Python
/_Finished/Ch15/time_module.py
1,489
4.1875
4
import time def intro(): print(time.time()) # 1574066563.5332215 """Explanation: Here I'm calling time.time() on 18th of November, 09:43. The value is how many seconds have passed between the Unix epoch and the moment time.time() was called. Epoch timestamps can be used to profile code, that is, to measure how long a piece of code takes to run. If you call time.time() at the beginning of the code block you want to measure and again at the end, you can subtract the first timestamp from the secnod to find the elapsed time between those two calls. For example, (continued in calc_prod()) """ def how_get_time_func_takes(): def calc_prod(): # Calculate the product of the first 100.000 numbers. product = 1 for i in range(1, 100000): product = product * i return product start_time = time.time() prod = calc_prod() end_time = time.time() print(f"The result is {len(str(prod))} digits long.") # The result is 456569 digits long. print(f"Took {end_time - start_time} seconds to calculate.") # Took 2.092365264892578 seconds to calculate. def time_dot_sleep_func(): for i in range(3): print("Tick") time.sleep(1) print("Tock") time.sleep(1) def rounding_numbers(): now = time.time() print(now) # 1574070708.6545494 print(round(now, 2)) # 1574070708.65 print(round(now, 4)) # 1574070708.6545 print(round(now)) # 1574070709
true
0e9c5822ad15fa0fe196d6a7c1f072720e8c9c0f
JKam123/homework1
/PrimeNumbersCode.py
394
4.1875
4
# Check if the number is a prime number Int = 5 IsPrime = True if Int != 0: for x in range(2, Int / 2): if Int%x == 0: IsPrime = False break if IsPrime: print "Its a prime number" else: print "Its not a prime number" else: print "0 is an invalid number! Please try again with a different number."
true
890e202babb89001a51ad8f813e708fbaffc2c55
yushenshashen/hello-python
/classic-100-scripts/JCP017.py
666
4.1875
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- #题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 #程序分析:利用while语句,条件为输入的字符不为'\n'。 import string #text = raw_input('please input a string: ') text = '34fdgds hrd77&*' letters = 0 space = 0 digits = 0 others = 0 #for i in range(len(text)): for i in text: if i.isalpha(): letters += 1 elif i.isspace(): space += 1 elif i.isdigit(): digits += 1 else: others += 1 print '''letters is %d space is %d digits is %d others is %d ''' % (letters,space,digits,others)
false
e4d7f983cdcf0101b5e9d0a382c12ec23e48d74a
aaron-goshine/python-scratch-pad
/workout/note_11.7.py
468
4.15625
4
## # Compute the greatest common divisor of two # positive integer using a while loop # # Read two positive from the user n = int(input("Enter a positive integer: ")) m = int(input("Enter a positive integer: ")) # Initialize d to the smaller of n and m d = min(n, m) # Use a while loop to find the greatest common divisor # of n and m while n % d != 0 or m % d != 0: d = d - 1 # Report the result print("The greatest common divisor of" , n, "and", m, "is", d)
false
9ddb24b957201560c1491cf5333e453280648689
aaron-goshine/python-scratch-pad
/workout/note_11.5.py
648
4.46875
4
## # Determine whether or not a string is a palindrome. # # Read the input from the user line = raw_input("Enter a string: ") # Assume that the string is a palindrome until # we can prove otherwise is_palindrome = True # Check the characters, starting from the end until # the middle is reached for i in range(0, len(line) // 2): # If the characters don't match then mark # the string as not a palindrome if line[i] != line[len(line) - i - 1]: is_palindrome = False # Display a meaningful out put message if is_palindrome: print(line, "is a palindrome") else: print(line, "is not a palindrome")
true
3e2f558efe5f67fcf73a15fa759c3d488e074062
aaron-goshine/python-scratch-pad
/workout/note_11.1.py
1,394
4.5
4
## # Compute the perimeter of a polygon. # The user will enter a blank line for the x-coordinates # that all of the points have been entered. # from math import sqrt # Store the perimeter of the polygon perimeter = 0 # Read the coordinates of the first point first_x = float(raw_input("Enter the x part of the coordinates: ")) first_y = float(raw_input("Enter the y part of the coordinates: ")) # Provide initial values for prev_x and prev_y prev_x = first_x prev_y = first_y # Read the remaining coordinates line = raw_input("Enter the x part of the coordinate (blank to quit): ") while line != "": # Convert the x part to number and read the y part x = float(line) y = float(raw_input("Enter the y part of the coordinate")) # Compute the distance to the previous point # and add it to the perimeter dist = sqrt((prev_x - x) ** 2 + (prev_y - y) ** 2) perimeter = perimeter + dist # Set up prev_x and prev_y for the next loop iteration prev_x = x prev_y = y # Read the x part of the next coordinate line = raw_input("Enter the x part of the coordinate (blank to quit): ") # Compute the distance from the last point to the first # point to the first point and add it to the perimeter dist = sqrt((first_x - x) ** 2 + (first_y) ** 2) perimeter = perimeter + dist # Display the result print("The perimeter of that polygon is", perimeter)
true
4507f6384a59dd92167050449c52ba68e0c9f624
aaron-goshine/python-scratch-pad
/workout/shuffle_deck.py
1,341
4.1875
4
## # Create deck for cards and shuffle it # from random import randrange # Construct a standard deck of cards with 4 # suits and 13 value per suit # @return a list of card, with each represented by two characters def createDeck (): # Create a list to store the card in cards = [] # For each suit and each value for suit in ["s", "h", "d", "c"]: for value in ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]: # Construct the card and add in to the list cards.append(value + suit) # Return the complete deck of cards return cards # Shuffle a deck of cards, modifying the deck of # cards passed as a parameter # @param cards the list of cards to shuffle def shuffle (cards): # For each card for i in range(0, len(cards)): # Pick a random index other_pos = randrange(0, len(cards)) # Swap the current card with the one at the random position temp = cards[i] cards[i] = cards[other_pos] cards[other_pos] = temp # Display a deck of cards before and after it has been shuffled def main (): cards = createDeck() print("The original deck of cards is: ") print(cards) print() shuffle(cards) print("The shuffled deck of cards is: ") print(cards) print() if __name__ == "__main__": main()
true
a88d040a8ffb05efeefc349a1dd1d8dc54187075
aaron-goshine/python-scratch-pad
/workout/reduce_measure.py
2,453
4.34375
4
## # Reduce an imperial measurement so that it is expressed using # the largest possible unit of measure. For example, 59 teaspoon # to 1 cup... # TSP_PER_TBSP = 3 TSP_PER_CUP = 48 ## Reduce an imperial measurement to that it is expressed using # the largest unit of measure. # @param num the number of units that need to be reduced # @param unit the unit of measure (cup, tablespoon or teaspoon) # @return a string representing the measurement in reduce form def reduceMeasure (num, unit): # Compute the number of teaspoons that the parameters represent unit = unit.lower() if unit == "teaspoon" or unit == "teaspoons": teaspoons = num elif unit == "tablespoon" or unit == "tablespoons": teaspoons = num * TSP_PER_TBSP elif unit == "cup" or unit == "cups": teaspoons = num * TSP_PER_CUP # Convert the number of teaspoon to largest possible units of measure cups = teaspoons // TSP_PER_CUP teaspoons = teaspoons - cups * TSP_PER_TBSP tablespoons = teaspoons // TSP_PER_TBSP teaspoons = teaspoons - tablespoons * TSP_PER_TBSP # Generate the result string result = "" # Add the number of cups to the result string (if any) if cups > 0 : result = result + str(cups) + " cup" # Make cup plural if there is more that one if cups > 1: result = result + "s " # Add the number of tablespoon to the result sting (if any) if tablespoons > 0: if result != "": result = result + "s " result = result + str(tablespoons) + " tablespoon" # Make tablespoon plural if there is more than one if tablespoons > 1: result = result + "s " # Add the number of teaspoon to the result sting (if any) if teaspoons > 0: if result != "": result = result + "s " result = result + str(teaspoons) + " teaspoon" # Make teaspoon plural if there is more than one if teaspoons > 1: result = result + "s " # Handle the case where the number of units was 0 if result == "": result = "0 teaspoon " return result # Demonstrate the reduce measure function by preforming several reductions def main (): print("59 teaspoons is %s." % reduceMeasure(59, "teaspoon")) print("59 tablespoons is %s." % reduceMeasure(59, "tablespoon")) print("99 teaspoons is %s." % reduceMeasure(99, "teaspoon")) main()
true
abbfbf2e681ac34c9d6c666a1ae5d11c2a83b19f
AnilSonix/CSPySolutions
/sol2.py
727
4.46875
4
# bubble sort numbers = [] def bubble_sort(numbers): n = len(numbers) # Traverse through all array elements for i in range(n - 1): # range(n) also work but outer loop will repeat one time more than needed. # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] for i in range(7): numbers.append(int(input("Enter number : "))) bubble_sort(numbers) print("after sorting") for number in numbers: print(number)
true