blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c545ac91b38825b2e124b5d76180536faf48f1a2
mreboland/pythonTestingCode
/cityFunctions.py
1,572
4.3125
4
# 11-1. City, Country: Write a function that accepts two parameters: a city name # and a country name. The function should return a single string of the form # City, Country, such as Santiago, Chile. Store the function in a module called # city_functions.py. # Create a file called test_cities.py that tests the function you just wrote # (remember that you need to import unittest and the function you want to test). # Write a method called test_city_country() to verify that calling your function # with values such as 'santiago' and 'chile' results in the correct string. Run # test_cities.py, and make sure test_city_country() passes. # 11-2. Population: Modify your function so it requires a third parameter, # population. It should now return a single string of the form City, Country – # population xxx, such as Santiago, Chile – population 5000000. Run test # _cities.py again. Make sure test_city_country() fails this time. # Modify the function so the population parameter is optional. Run test # _cities.py again, and make sure test_city_country() passes again. # Write a second test called test_city_country_population() that verifies # you can call your function with the values 'santiago', 'chile', and # 'population=5000000'. Run test_cities.py again, and make sure this new test # passes. def cityInfo(city, country, population=""): if population: formattedCityInfo = f"{city.title()}, {country.title()} - population {population}" else: formattedCityInfo = f"{city.title()}, {country.title()}" return formattedCityInfo
true
bf8a9d807a536330f68fa44f78589909b04f3e83
Yannyezixin/python-study-trip
/stack-qa/string/check_contains.py
258
4.375
4
str = 'This is my name!' if 'is' not in str: print 'is not found in the str' else: print 'is found in the str' if str.find('is') == -1: print 'is not found in the str by the method find' else: print 'is found in the str by the mothod find'
true
27319b104dd88c23d0e3fff012b5a248db79dad8
akejen01/adventOfCode
/2018/OppositesAttract.py
1,158
4.28125
4
# BitCounting # coding=utf-8 """ 8 kyu Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love. Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't. """ import unittest class TestMethod(unittest.TestCase): def test_1(self): self.assertEqual(lovefunc(1,4), True) def test_2(self): self.assertEqual(lovefunc(2,2), False) def test_3(self): self.assertEqual(lovefunc(0,1), True) def test_4(self): self.assertEqual(lovefunc(0,0), False) def test_5(self): self.assertEqual(lovefunc(639, 945), False) # def lovefunc(flower1, flower2): # petals1 = flower1 % 2 == 0 # petals2 = flower2 % 2 == 0 # if ((petals1 == petals2) ): # return False # else: # return True lovefunc=lambda a,b:(a+b)%2 def main(): print("Text") if __name__ == "__main__": unittest.main() #main()
true
68cc358c308ad75b1357fff5fdccea584cac46e3
FullBinaryAlchemist/algo-practice
/Search/3.Search in sorted matrix.py
1,704
4.125
4
###Problem Statement: # We're given a 2D array that consists of elements sorted row wise as well the elements of the sorted column wise #Given an element , we need to find whether it exists in the matrix and return the index if it does exist #I/p: # [1,2,3,4,10] # [4,5,6,7,11] # [8,9,11,12,13] # Target: 12 #O/p : [2,3] ###Naive approach: # Iterate all the row and for each row iterate all the elements # Time:O(N*M) # ###Better approach: # For each row, apply binary search # Time: O(n*log(m)) as we are travesing through all n rows and performing binary search with time Complexity of O(log a) # Therefore O(n*logm) ####Solution: 1. Compare with the last element of the first row 2. If greater then eliminate the elements preceding it and increment the row to as it is in sorted order Else decrement the column index and compare with it 3. Repeat 2 till column<0 or row>n #Complexity Analysis: # # Space Complexity: O(1) as no inplace searching with no variable space that depends on the size of the input # # Time Complexity: O(N+M) where N is the no of rows and M is the no of column # Explanation: We re moving either downwards or leftwards . Therefore in worst case scenario we'll move down # the entire column and leftwards movements would at most sum to the number of elements in a row def searchSortedMatrix(matrix,target): '''Arguments: matrix: 2-D array(list) of sorted integers target: int to be searched Return: Either list of length=2 or None in case the element is not found ''' row=0 col=len(row[0])-1 while(row<n and col>=0): if matrix[row][col]<target: row+=1 elif matrix[row][col]>target: col-=1 else: return [row,col] return None
true
541189ece5958548f8a693b46030bff8b5a5b763
ayoubc/competitive-programming
/datastructure/heap/min_heap.py
1,856
4.1875
4
class MinHeap: def __init__(self): self.heap = [0] self.size = 0 def bubble_up(self, i): """complexity: O(log(n))""" # we swap current element with it's parent if the value in the parent is greater the its vallue while i // 2 > 0: if self.heap[i] < self.heap[i // 2]: self.heap[i], self.heap[i // 2] = self.heap[i // 2], self.heap[i] i = i // 2 def push(self, val): """complexity: O(log(n))""" self.heap.append(val) self.size += 1 self.bubble_up(self.size) def min_child(self, i): if i * 2 + 1 > self.size: return i * 2 else: if self.heap[i * 2] < self.heap[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def bubble_down(self, i): """complexity: O(log(n))""" while (2 * i) <= self.size: mc = self.min_child(i) if self.heap[i] > self.heap[mc]: self.heap[i], self.heap[mc] = self.heap[mc], self.heap[i] i = mc def is_empty(self): return self.size == 0 def pop(self): """complexity: O(log(n))""" if self.is_empty(): raise "Can not pop from an empty heap!" min_val = self.heap[1] self.heap[1] = self.heap[self.size] self.size -= 1 self.heap.pop() self.bubble_down(1) return min_val # We still need to understand why this method works in O(n) ! # sample solution to build is to insert each item from the list, but this will work in O(nlog(n)) # def build_heap(self, alist): # i = len(alist) // 2 # self.current_size = len(alist) # self.heap = [0] + alist[:] # while (i > 0): # self.perc_down(i) # i = i - 1
false
255905d67c4ee9aba6e3e8d71e7a23fc814baa81
nguyntyler/DigitalCrafts-Class
/Programming102/keyValueEx.py
234
4.21875
4
# Create a program that starts with an empty dictionary. # Add 3 different key value pairs to the empty dictionary. empty = { } empty.update({"color": "White"}) empty.update({"size": "big"}) empty["smell"] = "stinky" print(empty)
true
b059db3d3a55148901ce2da4140f92c34569be75
samdenlama/pythonproject
/ITS320_CTA3_Option1.py
1,228
4.125
4
year = int(input('Enter year:\n')) if year <1962: print ('Car did not exist yet!') elif year <= 1964: print('$',18500) year = int(input('Enter year:\n')) if year <1965: print('Car did not exist yet!') elif year <= 1968: print ('$',6000) year = int(input('Enter year:\n')) if year <1969: print('Car did not exist yet!') elif year <= 1971: print('$',12000) year =int(input('Enter year:\n')) if year <1972: print ('Car did not exist yet!') elif year <=1975: print ('$',48000) year =int(input('Enter year:\n')) if year <1976: print('Car did not exist yet!') elif year <=1980: print ('$',200000) year = int(input('Enter year:\n')) if year <1981: print('Car did not exist yet!') elif year <=1985: print ('$',650000) year = int(input('Enter year:\n')) if year <1986: print('Car did not exist yet!') elif year <=2012: print ('$',35000000) year = int(input('Enter year:\n')) if year <2013: print('Car did not exist yet!') elif year <=2014: print ('$',52000000) #Result #Enter year: #1962 #$ 18500 #Enter year: #1965 #$ 6000 #Enter year: #1969 #$ 12000 #Enter year: #1972 #$ 48000 #Enter year: #1976 #$ 200000 #Enter year: #1981 #$ 650000 #Enter year: #1986 #$ 35000000 #Enter year: #2013 #$ 52000000
false
f937d345d0aff94b223c37b72c4df376056458bd
Rigo-Hernandez/Python
/Python work/stringexercise.py
1,253
4.375
4
# Q1 # name = "the dog is running in the field. " # print (name.title()) # Q2 # name = "the dog" # print (name.upper()) # Q3 # sentence= "The cat in the hat" # backwards = sentence [::-1] # print (backwards) # Q4 # paragraph = "A paragraph is a series of sentences that are organized and coherent, and are all related to a single topic. Almost every piece of writing you do that is longer than a few sentences should be organized into paragraphs. This is because paragraphs show a reader where the subdivisions of an essay begin and end, and thus help the reader see the organization of the essay and grasp its main points.".upper() # paragraph = paragraph.replace('A','4') # paragraph = paragraph.replace('E','3') # paragraph = paragraph.replace('G','6') # paragraph = paragraph.replace('I','1') # paragraph = paragraph.replace('O','0') # paragraph = paragraph.replace('S','5') # paragraph = paragraph.replace('T','7') # print (paragraph) #Q5 # word = "cheese" # word = word.replace("a","aaaaa") # word = word.replace("e","eeeee") # word = word.replace("i","iiiii") # word = word.replace("o","ooooo") # word = word.replace("u","uuuuu") # print (word) #Q6 # word = "lbh zhfg hayrnea jung lbh unir yrnearq" # alphabet = "abcdefghijklmnopqrstuvwxyz"
true
8d12a996c4076159bfdfeef83fbd08e19960b30d
JaydeepKachare/Python-Assignment
/Assignment6/Assignment6_1.py
787
4.125
4
# create class accept value from user and store it in object class Demo : def __init__(self,num1,num2): print("Inside constructor") self.no1 = num1 self.no2 = num2 def Fun(self) : print("no1 : {} for {} ".format(self.no1 , type(self))) def Gun(self) : print("no2 : {} for {} ".format(self.no2 , type(self))) def main() : num1 = int(input("Enter value for no1 : ")) num2 = int(input("Enter value for no2 : ")) Obj1 = Demo(num1,num2) num1 = int(input("Enter value for no1 : ")) num2 = int(input("Enter value for no2 : ")) Obj2 = Demo(num1,num2) Obj1.Fun() Obj2.Fun() Obj1.Gun() Obj2.Gun() if __name__ == "__main__" : main()
false
632087967cba32490e57cab841eb9fb229c45c11
binaythapamagar/insights-workshop-assignment
/py-assignment-I/datatypes/5makeing.py
468
4.28125
4
class MakeIng: def makeIng(self,word): """ @argument word string @retuns string """ if len(word) < 3: return "length of string must be greater than 3." if word.endswith('ing'): return f"{word}ly" else: return f"{word}ing" if __name__ == "__main__": word = input('Enter a word: ') makeing = MakeIng() print(makeing.makeIng(word))
true
d2f7afae4fd6f462f87003f63835d564dcb3a6e3
RUC-CompThinking18/exploratory-programming-3-Cintronny
/regex.py
521
4.125
4
import re hammon = open("Scarletletter.txt", "r") sendo = hammon.read() def finder(word): if type(word) != str: raise TypeError("this is not a string") #this catches if the argument is a string and raises a TypeError if it is not matches = re.findall(r"\w*at\b", sendo) findings = [] for word in matches: if len(word) > 3: #this searches through the list and removes the words that are 3 letters or less findings.append(word) print findings finder(sendo)
true
adac79c130cab8d03123c3dbb7d6cf10e6627671
TylerBromley/fullstack_python_codeguild
/lab3-grading_v2.py
871
4.15625
4
# lab3-grading_v2.py # get the letter grade for the number def letter_grade(grade): if grade >= 90: return 'A' elif grade >= 80: return 'B' elif grade >= 70: return 'C' elif grade >= 60: return 'D' else: return 'F' # find whether the grade has a qualifier def plus_or_minus(number): digit = number % 10 if digit < 3: return '-' elif digit > 7: return '+' else: return '' # append any qualifiers to grade, unless grade is 'F' def final_grade(number): letter = letter_grade(number) modifier = plus_or_minus(number) if number > 100 or number < 0: print("That's impossible!") if letter == 'F': return letter else: return letter + modifier user_input = int(input("Please enter your grade: ")) print(final_grade(user_input))
true
5732bef8816b2effaaf449212390f02123a53940
TylerBromley/fullstack_python_codeguild
/lab12-guess-the-number_v1.py
503
4.1875
4
# lab12-guess-the-number_v1.py import random # create a count of triess and set it to 0 tries = 0 # get a random number between 1 and 10 number = random.randint(1, 10) # give the use 10 tries to guess the number while tries < 10: # get user guess user_num = int(input("Please guess a number between 1 and 10: ")) # check if user guessed right if user_num == number: print("You win!") break # if not, and tries are not 10, let the user guess again else: print("Try again!") tries += 1
true
5b85fb3ca8b74cc4831da7517792c622c6a67903
TylerBromley/fullstack_python_codeguild
/lab12-guess-the-number_v4.py
1,045
4.125
4
# lab12-guess-the-number_v4.py import random # get a random number number = random.randint(1, 10) # store the previous guess last_guess = 0 # let the user guess until they get it right # give them hints if they are getting warmer or colder while True: user_num = int(input("Please guess a number between 1 and 10: ")) print(last_guess) if user_num == number: print("You win!") break elif user_num < number: print("Too low!") if abs(user_num - number) == abs(last_guess - number): print("Keep going!") elif abs(user_num - number) < abs(last_guess - number): print("You are getting warmer.") elif abs(user_num - number) > abs(last_guess - number): print("You're getting colder.") last_guess = user_num else: print("Too high!") if abs(user_num - number) == abs(last_guess - number): print("Keep going!") elif (user_num - number) < (last_guess - number): print("You are getting warmer.") elif (user_num - number) > (last_guess - number) : print("You're getting colder.") \ last_guess = user_num
true
e69a42eaf91cc882c8619d8d9d06b84ef44bc887
TylerBromley/fullstack_python_codeguild
/lab7-rockpaperscissors_v1.py
797
4.25
4
# lab7-rockpaperscissors_v1.py import random # get the player's choice and create a random choice for the # computer player_choice = input("Please choose rock, paper or scissors: ") computer_choice = random.choice(("rock", "paper", "scissors")) # test whether the player won, lost or tied if player_choice == computer_choice: print("It's a tie!") elif player_choice == "rock": if computer_choice == "paper": print("Computer chose paper. You lose!") else: print("Computer chose scissors. You win!") elif player_choice == "paper": if computer_choice == "scissors": print("Computer chose scissors. You lose!") else: print("Computer chose rock. You win!") else: if computer_choice == "rock": print("Computer chose rock. You lose!") else: print("Computer chose paper. You win!")
true
a75f823300cba31305c35faae73bfcb3a56155e6
yehonadav/python_course
/lessons/advanced_concepts/map_filter_reduce.py
1,382
4.25
4
"""Map""" def length(n): return len(n) fruits = ('apple', 'banana', 'cherry') fruits_length = map(length, fruits) print(fruits_length) def combo(a, b): return a + b more_fruits = map(combo, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple')) print(len(fruits)) """Filter""" ages = [5, 12, 17, 18, 24, 32] def kid_filter(age): if age < 18: return False else: return True adults = filter(kid_filter, ages) for age in adults: print(age) """Reduce""" from functools import reduce number_list = [1, 3, 5, 6, 2, ] # using reduce to compute sum of list print("The sum of the list elements is : ", end="") print(reduce(lambda a, b: a + b, number_list)) # using reduce to compute maximum element from list print("The maximum element of the list is : ", end="") print(reduce(lambda a, b: a if a > b else b, number_list)) # importing operator for operator functions import operator # using reduce to compute sum of list # using operator functions print("The sum of the list elements is : ", end="") print(reduce(operator.add, number_list)) # using reduce to compute product # using operator functions print("The product of list elements is : ", end="") print(reduce(operator.mul, number_list)) # using reduce to concatenate string print("The concatenated product is : ", end="") print(reduce(operator.add, ["geeks", "for", "geeks"]))
true
36d8f90c9b21fa8a450ea7e6af295592ceb49add
yehonadav/python_course
/lessons/advanced_concepts/lambdas.py
2,434
4.375
4
""" what are python lambdas ? A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. The expression is executed and the result is returned Syntax lambda arguments : expression examples: """ compute1 = lambda x: x**x print(compute1(5)) # add 10 to the number passed in as an argument, and print the result: compute2 = lambda a : a + 10 print(compute2(5)) # Lambda functions can take any number of arguments # multiply argument 'a' with argument 'b' and print the result compute3 = lambda a, b : a * b print(compute3(10, 10)) # sum arguments a, b, and c and print the result compute4 = lambda a, b, c : a + b + c print(compute4(5, 6, 2)) """ Why are Python lambdas useful? https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. The power of lambda is better shown when you use them as an anonymous function inside another function. """ # Say you have a function definition that takes one argument, # and that argument will be multiplied with an unknown number: def multiply_by(n): return lambda a: a * n double_trouble = multiply_by(2) triple_trouble = multiply_by(3) print(double_trouble(2)) print(triple_trouble(3)) # This is often used to create function wrappers, such as Python's decorators. print(multiply_by(4)(4)) # we can use lambdas on filters evens = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) odds = filter(lambda x: x % 2 != 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print(evens) print(odds) # VS def evens_filter(x): return x % 2 == 0 def odds_filter(x): return x % 2 != 0 evens = filter(evens_filter, [1, 2, 3, 4, 5, 6, 7, 8, 9]) odds = filter(odds_filter, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # VS evens = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 2 == 0] odds = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 2 != 0] # VS evens = [x for x in range(0,10,2)] odds = [x for x in range(1,10,2)] # lambdas with reduce() from functools import reduce combo1 = reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9]) combo2 = reduce(lambda a, b: a+b, [1, 2, 3, 4]) print(combo1) print(combo2) # Sorting by an alternate key cool_sort = sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x)) # closest to 5 print(cool_sort)
true
29c5e56f270eb7805575cedb839abb9a7a468d97
mlsmall/Python-scripts
/fibonacci sequence.py
242
4.15625
4
# This function will calculate the fibonacci sequence for any given number. def fib(n): if n < 1: return None if n < 3: return 1 return fib(n - 1) + fib(n - 2) for n in range(1, 11): print(n, "->", fib(n))
true
65ab4ac4e49117f66fce376e27ad5876f60c7315
lxy1218/python_automation
/homework/find_function.py
590
4.15625
4
#!/usr/bin/python3.6 # -*- coding=utf-8 -*- #作业//Python基础 第八天作业-第二题(用函数方法) #找到两个清单中相同的内容 #方案一:不用函数解决 #方案二:修改为函数的更加通用的方案 def find(list1,list2): for a in list2: #print(a) for b in list1: #print(b) if a == b: print(str(b) +" in list1 and list2") list1.remove(b) for c in list1: print(str(c) +" only in list1") list1 = ['aaa', 222, (4, 5), 2.01] list2 = ['bbb', 222, 111, 3.14, (4, 5)] find(list1,list2)
false
86f6f6f9087a8a251ae0e81da307f3ed58bf7664
harshitakedia/fibonacci-seies
/Untitled.py
444
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #Function for fibonacci series def fibo(n) : #check if n is valid if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return (fibo(n-1) + fibo(n-2)) # In[4]: #driver program to print fibonacci series n = int(input("enter a value : ")) print("fibonacci series: ", end = ' ') for n in range(0,n): print(fibo(n),end = ' ') # In[ ]:
false
c3ee0cc45f35a96eb7c2ce443239db4cf0ff1716
SivaBackendDeveloper/Python-Assessments
/12.Constructors/2qs.py
774
4.5
4
#2. Call the constructors(both default and argument constructors) of super class from a child class """ When you define another constructor in your class, you do not get the "usual" default constructor (public and without arguments) anymore. Of course, when creating an object instance using new you have to choose which one to call (you cannot have both) """ class Person: def __init__(self): # Default constructor print("HI") def __init__(self, n): # argument constructor self.name = n class Employee(Person): def __init__(self, i, n): #super().__init__() super().__init__(n) # same as Person.__init__(self, n) self.id = i emp = Employee(99, 'SIVA') print(f'Employee ID is {emp.id} and Name is {emp.name}')
true
e076f60cc803789fc51457fb1a4e64ce9862c19c
SivaBackendDeveloper/Python-Assessments
/12.Constructors/4qs.py
1,092
4.46875
4
#4. Write a program which illustrates the concept of attributes of a constructor # super class class Student: # protected data members _name = None _roll = None _branch = None # constructor def __init__(self, name, roll, branch): self._name = name self._roll = roll self._branch = branch # protected member function def _displayRollAndBranch(self): # accessing protected data members print("Roll: ", self._roll) print("Branch: ", self._branch) # derived class class Details(Student): # constructor def __init__(self, name, roll, branch): Student.__init__(self, name, roll, branch) # public member function def displayDetails(self): # accessing protected data members of super class print("Name: ", self._name) # accessing protected member functions of super class self._displayRollAndBranch() # creating objects of the derived class obj = Details("SIVA", 1706318, "MECHANICAL") # calling public member functions of the class obj.displayDetails()
true
369b080934ba60112f40f8900bc1672cea7f5ed0
SivaBackendDeveloper/Python-Assessments
/3.Loops/4qs.py
326
4.375
4
#Write a program to print the odd and even numbers. def evennumbers(x): while x<=10:# it will print even numbers before 1000 we can change the value it will increase or decrease print(x) x+=2 evennumbers(2) def oddnumbers(x): while x<=10: print(x) x+=2 oddnumbers(1)
true
23f7d8469fdf3b4d124cfa956d965e87e1d400e4
neasatang/Python
/numberGuesser.py
883
4.34375
4
import random while True: print("Welcome to Guessing the number!") try: answer = int(input ("The number is between 1 - 10. What do you think the number is?")) except ValueError: print("Sorry but you must enter an integer to play!") else: break random = random.randint(1, 10) print(random) playing = True; while playing: print("You think the number is " + str(answer)) if int(answer) > random: answer = input("The number is lower than you think. Guess again!") elif int(answer) < random: answer = input("The number is higher than you think. Guess again!") else: playing = input( "You got it correct! The number was " + str(answer) + ". Would you like you play again? Type 'y/n'") == 'y' or 'Y' if playing == 'n' or 'N': playing = False print("Thank you for playing!")
true
8d188f38f1bd5c87edb19d46f7d00791d9516e46
jpsalviano/uri-online-judge
/1020.py
875
4.25
4
# 1020 - Age in Days ''' Read an integer value corresponding to a person's age (in days) and print it in years, months and days, followed by its respective message “ano(s)”, “mes(es)”, “dia(s)”. Note: only to facilitate the calculation, consider the whole year with 365 days and 30 days every month. In the cases of test there will never be a situation that allows 12 months and some days, like 360, 363 or 364. This is just an exercise for the purpose of testing simple mathematical reasoning. Input The input file contains 1 integer value. Output Print the output, like the following example. ''' days = int(input()) def ageInDays(days): years = days // 365 daysLeft = days % 365 months = daysLeft // 30 daysLeft = daysLeft % 30 print(str(years) + ' ano(s)\n' + str(months) + ' mes(es)\n' + str(daysLeft) + ' dia(s)') ageInDays(days)
true
0e6f3a3833691c0680ef84fff58077de7df315fb
slavaprotogor/python_base
/homeworks/lesson2/task2.py
1,419
4.40625
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ # version 1 elements = [] while True: element = input('Введите элемент (q - выход): ') if element == 'q': break elements.append(element) elements_len = len(elements) index = 1 while index < elements_len: elements[index - 1], elements[index] = elements[index], elements[index - 1] index += 2 print('Результат: ', elements) # version 2 elements = [] while True: element = input('Введите элемент (q - выход): ') if element == 'q': break elements.append(element) elements_odd = elements[::2] elements_odd_len = len(elements_odd) elements_even = elements[1::2] elements_even_len = len(elements_even) elements_new = [] for index in range(elements_odd_len): if index < elements_even_len: elements_new.append(elements_even[index]) elements_new.append(elements_odd[index]) print('Результат: ', elements_new)
false
d4e43dd5fa18429f9cd4b7f0405fa8cf0a7a99e0
markyashar/Learn_Python_The_Hard_Way
/ex5.py
2,249
4.3125
4
# -*- coding: utf-8 -*- # Exercise 5: More Variables and Printing name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches height_cm = 74*2.54 # there are 2.54 cm in an inch weight = 180 # lbs weight_kg = 180 * 0.453 # there are 0.453 kg in a lb eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name print "He's %d inches tall." % height print "He's %d centimeters tall." % height_cm print "He's %d pounds heavy." % weight print "He's %d kilograms heavy." % weight_kg print "Acually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth print "His teeth are usually %r depending on the coffee." % teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight) print "If I add %r, %r, and %r I get %r." % (age, height, weight, age + height + weight) """ EXAMPLE OUTPUT: bash-3.2$ python ex5.py Let's talk about Zed A. Shaw. He's 74 inches tall. He's 187 centimeters tall. He's 180 pounds heavy. He's 81 kilograms heavy. Acually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. His teeth are usually 'White' depending on the coffee. If I add 35, 74, and 180 I get 289. If I add 35, 74, and 180 I get 289. STUDY DRILL: 1. Change all the variables so there is no my_ in front of each one. Make sure you change the name everywhere, not just where you used = to set them. 2. Try to write some variables that convert the inches and pounds to centimeters and kilograms. Do not just type in the measurements. Work out the math in Python. 3. Search online for all of the Python format characters. 4. Try more format characters. %r is a very useful one. It's like saying "print this no matter what." ADDITIONAL COMMENTS: %s, %r, and %d are formatters. They tell Python to take the variable on the right and put it in to replace the %s with its value. You can round a floating point number by using the round() like this: round(1.7333) If you get this error: "TypeError: 'str' object is not callable.", it probaby means that you forgot the % between the string and the list of variables. """
true
86f57b23ac3a63255c847e58713cf139991d9701
markyashar/Learn_Python_The_Hard_Way
/ex3.py
1,574
4.53125
5
print "I will now count my chickens:" print "Hens", 25 +30 / 6 # I'm counting how many hens I have: 25+5 =30 hens print "Roosters", 100 - 25 * 3 % 4 # I'm counting the number of roosters print "now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # 5 % 2 - 1/4 + 6 print "Is it true that 3 + 2 < 5 - 7?" # It's not true that 5 < -2 print 3 + 2 < 5 - 7 # False: 5 is greater tha -2 print "What is 3 + 2?", 3 + 2 # 3 + 2 = 5 print "What is 5 - 7?", 5 -7 # 5-7 = -2 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 # TRUE print "Is it greater or equal?", 5 >= -2 # TRUE print "Is it less or equal?", 5 <= -2 # FALSE """ EXAMPLE OUTPUT: bash-3.2$ python ex3.py I will now count my chickens: Hens 30 Roosters 97 now I will count the eggs: 7 Is it true that 3 + 2 < 5 - 7? False What is 3 + 2? 5 What is 5 - 7? -2 Oh, that's why it's False. How about some more. Is it greater? True Is it greater or equal? True Is it less or equal? False """ """ ADDITIONAL NOTES: The modulus operation (%) is a way of saying "X divided by Y with J remaining." For example, "100 divided by 16 with 4 remaining." The result of % is the J part, or the remaining part. In the United States we use an acronym called PEMDAS which stands for Parentheses Exponents Multiplication Division Addition Subtraction, to determine the order of operations. That's the order Python follows as well. The / (division) operator drops the fractional part of the decimal For example, 7/4=1 and 7.0/4.0=1.75 """
true
5ed4e5201a06c474ba984a274a7ab131d509105e
fizalihsan/py101
/src/a_datatypes/d_List.py
2,314
4.40625
4
# definition list0 = [] print list0 list0 = list() print list0 list1 = [1, 2.0, 'c', 2, 3, 4, 5] print list1 # [1, 2.0, 'c'] # setters list1.append("d") print list1 # prints [1, 2.0, 'c', 'd'] print list1 + ["e"] # + operator creates a new list and leaves the original list unchanged list1.insert(0, "apple") print list1 # prints ['apple', 1, 2.0, 'c', 'd'] list1.extend(["apple", "orange"]) # like appendAll print list1 # getters # Subscripting is the term for describing when you access an element in a list or a tuple as well as a dictionary list2 = [1, 2, 3, 4, 5] print list2.pop(0) # element at index 0 is popped print list2.pop() # last element is popped print list2 # [2, 3, 4] # deletion del list2[0] print list2 # converting print tuple(list1) t = (1, 2, 3, 4) print list(t) # sorting list3 = [2, 3, 5, 6] list3.reverse() print list3 # [6, 5, 3, 2] # ------------------------List comprehension------------------------ # bracket [] operator indicates that we are constructing a new list. This is called list comprehension list4 = list('fizal') # without condition print [c.capitalize() for c in list4] # ['F', 'I', 'Z', 'A', 'L'] # with condition print [c.capitalize() for c in list4 if c in ('a', 'e', 'i', 'o', 'u')] # ['I', 'A'] # nested list comprehension nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print [[x + 1 for x in sub_list] for sub_list in nested_list] # ------------------------Generator expressions------------------------ # Generator expressions are similar to list comprehensions, but with parentheses instead of square brackets. # The result is a generator object that knows how to iterate through a sequence of values. # But unlike a list comprehension, it does not compute the values all at once; it waits to be asked. # The built-in function next gets the next value from the generator. g = (x ** 2 for x in range(5)) # The generator object keeps track of where it is in the sequence, so the for loop picks up # where next left off. Once the generator is exhausted, it continues to raise StopException print next(g) # 0 print next(g) # 1 print next(g) # 4 print next(g) # 9 print next(g) # 16 # print next(g) # 16 # StopIteration exception is thrown g = (x ** 2 for x in range(5)) # looping through the generator expression for val in g: print val
true
852923cf24e7e5745670b7d0b84c8083aa28532d
fizalihsan/py101
/src/a_datatypes/i_CollectionUtils.py
688
4.1875
4
from collections import Counter from collections import namedtuple # ------------------Zip------------------ # zip takes in iterables as input and returns list of tuples s = 'abc' l = [1, 2, 3] print zip(s, l) # [('a', 1), ('b', 2), ('c', 3)] s = 'abc' l = [1, 2] print zip(s, l) # [('a', 1), ('b', 2)] s = 'abc' l = [1, 2, 3] t = (4, 5, 6) print zip(s, l, t) # [('a', 1, 4), ('b', 2, 5), ('c', 3, 6)] # ------------------Counter------------------ count = Counter('parrot') print count # Counter({'r': 2, 'a': 1, 'p': 1, 't': 1, 'o': 1}) # ------------------Named tuple------------------ Point = namedtuple('Point', ['x', 'y']) p = Point(x=10, y=20) print p # Point(x=10, y=20)
false
e7e20e88d1bbc4f77a509ba814cfd6f3042e7cb0
gitter-badger/survival-python
/06 Functions/arguments_1.py
407
4.25
4
def first_last(full_name): first_name = '' last_name = '' has_been_a_space = False for letter in full_name: if letter == ' ': has_been_a_space = True elif has_been_a_space: last_name = last_name + letter else: first_name = first_name + letter print('First: ', first_name) print('Last: ', last_name) first_last('Tony Macaroni')
true
8f2fcaacb38ca2e933be1f4e1299c59277d32bb4
xiexiaop/Head-First-Python
/Chapter2_处理有序数据/P56_寻找原音.py
803
4.15625
4
# 在一个英文单词中寻找包含原音的英文字母 # 步骤一:找到即输出所有原音 # vowels = ['a','e','i','o','u'] # word = "Milliways" # for letter in word: # if letter in vowels: # print(letter) # # 步骤二:找到即输出所有原音[不重复] # vowels = ['a','e','i','o','u'] # found = [] # word = "Milliways" # for letter in word: # if letter in vowels and letter not in found: # found.append(letter) # for vowel in found: # print(vowel) # 步骤三:提供前台用户输入英文字符 vowels = ['a','e','i','o','u'] found = [] word = input("Provide a word to search for vowels") for letter in word: if letter in vowels and letter not in found: found.append(letter) for vowel in found: print(vowel)
false
800616439764eb99dee18eed395c5a2ab15e679f
ynvtlmr/Fundamentals
/day_05/users/app.py
1,215
4.15625
4
def get_user_name(): # prompt a user to give their name. name = input("What is your name? ") return name def save(name): # write the name to a file names = open('names', 'a') names.write(name + '\n') def show_names(): names = open('names', 'r') names_list = names.readlines() for name in names_list: print("{} {}".format(names_list.index(name), name), end='') def update_name(): print("TODO: Implement me!") def remove_name(name_index): print("TODO: Implement me!") options = ''' NAMES ===== Help Menu q quit v view names a add name e edit name r remove name ''' def get_user_input(): return input("Enter an option: ").lower() while True: print(options) user_input = get_user_input() if user_input == "q": break elif user_input == "v": show_names() elif user_input == "a": name = get_user_name() save(name) elif user_input == "e": update_name() elif user_input == "r": name_index = int(input("Enter the number of the name to remove: ")) remove_name(name_index)
true
a82cf141a35735ab5434245cf3398d3b6d2f3a9b
LopeAriyo/python_sandbox
/python_sandbox_starter/variables.py
925
4.125
4
# A variable is a container for a value, which can be of various types ''' This is a multiline comment or docstring (used to define a functions purpose) can be single or double quotes ''' """ VARIABLE RULES: - Variable names are case sensitive (name and NAME are different variables) - Must start with a letter or an underscore - Can have numbers but can not start with one """ x = 1 # * This is an integer y = 2.6 # * This is a float name = "Lope" # * This is a string is_savage = True # * This is a boolean, booleans in python start with a capital letter # Multiple Assignments a, b, surname, is_wizard = (5, 6.5, "Ariyo", False) print(type(a)) print(type(b)) print(type(surname)) print(type(is_wizard)) # Casting print(x, type(x)) x = str(x) # change a integer to a string print(x, type(x)) print(y, type(y)) y = int(y) # change a float to an integer print(y, type(y)) z = float(y) print(z, type(z))
true
281db0400c5818980b264e15ef071e49afc60149
HigorSenna/python-study
/guppe/lambdas_e_funcoes_integradas/sorted.py
1,155
4.625
5
""" Sorted OBS: Não confunda com a função sort de list, pois o sort() so funciona com list, porém o sorted() funciona com qualquer iterável. list.sort() -> modifica a propria lista sorted(iterável) -> retorna a lista ordenada OBS: Independente do iretavel passado em sorted(), o retorno é SEMPRE do tipo list. """ numeros = [6, 1, 8, 2] print(numeros) print(sorted(numeros)) # Orderna em ordem CRESCENTE # Adicionando parâmetros print(sorted(numeros, reverse=True)) # Ordena em ordem DECRESCENTE usuarios = [ {"username": "samuel", "tweets": ["Eu adoro bolos", "Eu adoro pizzas"]}, {"username": "carla", "tweets": ["Eu amo meu gato"]}, {"username": "jeff", "tweets": []}, {"username": "bob123", "tweets": []}, {"username": "doggo", "tweets": ["Eu gosto de cachorros", "Vou sair hoje"]}, {"username": "gal", "tweets": [], "cor": "amarelo", "musica": "rock"} ] print(usuarios) # Ordenando pelo username - Ordem alfabética print(sorted(usuarios, key=lambda usuario: usuario.get('username'))) # Ordenando pelo numero de tweets - Crescente print(sorted(usuarios, key=lambda usuario: len(usuario.get('tweets'))))
false
be15cad5130c606da8d456947620db659ecbe621
HigorSenna/python-study
/guppe/lambdas_e_funcoes_integradas/reversed.py
589
4.53125
5
""" Reversed OBS: nao confunda com a funcao reverse() que utilizamos na lista A funcao .reverse() so funciona em listas, ja a funcao em reversed() funciona com qualquer iteravel, sua funcao é inverter o iteravel A funcao reversed() retorna um iteravel chamado List Reverse Iterator """ lista = [1, 2, 3, 4, 5] res = reversed(lista) print(type(res)) print(list(res)) tupla = 1, 2, 3, 4, 5 res = reversed(tupla) print(type(res)) print(list(res)) set1 = {1, 2, 3, 4, 5} # res = reversed(set1)c # Nao funciona pois o set nao tem ordwem for n in reversed(range(0, 10)): print(n)
false
2d964efcff3ee03a7706837e65d7d6ffbb09e9d9
HigorSenna/python-study
/guppe/loops/loop_for.py
1,175
4.40625
4
""" Estrutura de repeticao 'For' Exemplos de itaraveis - String nome = 'Teste' - Lista lista = [1, 2, 3] - Range numeros = range(1, 10) """ nome = 'Teste' lista = [1, 2, 3] numeros = range(1, 3) # temos que transformar em uma lista for letra in nome: print(letra) for numero in lista: print(numero) """ range(valo_inicial, valor_final) OBS: O valor final não é inclusive. range(1, 3) 1 2 3 - Não """ for numero in numeros: print(numero) """ Enumerate, retorna um indice,valor de cada elemento """ for indice, letra in enumerate(nome): print(nome[indice]) """ No python quando eu tenho dois parâmetros e vou usar só um, posso user o _ (underline) para descartar o parâmetro """ for _, letra in enumerate(nome): print(letra) for enumerated in enumerate(nome): print(enumerated) quantidade = int(input('Quantars vezes o loop deve rodar?')) for n in range(1, quantidade + 1): print(f'Imprimindo {n}') # Imprimir sem pular linha for n in range(1, quantidade + 1): print(f' Imprimindo {n}', end='') # No python é possivel multiplicar strings nome = 'Teste ' print(nome * 5, end='') emoji = '\U0001F60D' print(emoji)
false
bc05229130c7a77228cb0399015e1d3392ba9242
crissebasbol/Python_course
/a_introduction/9_Strings.py
725
4.28125
4
word = "hola" print("Word: "+word) print(word[1:3]) print(word[::2]) print(word[::-1]) print(word[::-2]) print(len(word)) print(word) print(word.islower()) print(word.upper()) print(word.isupper()) print(word.upper().isupper()) word = "Hola" print(word) print(word.isupper()) print(word.lower()) print(word.islower()) print(word.find("la")) print(word.find("la",1)) print(word.find("la",3)) print(word.find("pl")) print(word.isdigit()) print(word.endswith("a")) print(word.endswith("o", 0, 2)) print(word.startswith("h")) print(word.startswith("H")) words = "Hola amigos, cómo están?" print(words.split()) print(words.split(" ", 2)) print(" ".split("a")) myTuple = ("John", "Peter", "Vicky") x = " ".join(myTuple) print(x)
false
2e9037078d5bc58cf011f15d16974ca80e10f99c
crissebasbol/Python_course
/a_introduction/17_Dictionaries.py
871
4.3125
4
my_dictionary1 = { "first_element": "1", "second_element": "2" } print(my_dictionary1) my_dictionary2 = dict() my_dictionary2["first_element"] = "Hello" my_dictionary2["second_element"] = "Bye" print(my_dictionary2) print(my_dictionary2["first_element"]) my_dictionary3 = dict([ ("first_element", "primer elemento"), ("second_element", "Segundo elemento") ]) print(my_dictionary3) # Iteration notes = {} pass notes["math"] = 4.6 notes["science"] = 5 notes["biology"] = 3 notes["apps"] = 4 print(notes) for value in notes.values(): print(value) for key in notes.keys(): print(key) for key, value in notes.items(): print("key: {}, value: {}".format(key, value)) # Notes average sum_notes = 0 for value in notes.values(): sum_notes += value average = sum_notes / len(notes) print("The notes average is: {}".format(average))
true
b0ede6988ece1feafa845e0850b5d30ce8fc44bb
cuiminghao8/Python-100-Days
/Day16-20/thief.py
1,853
4.1875
4
""" 贪婪法例子:假设小偷有一个背包,最多能装20公斤赃物,他闯入一户人家,发现如下表所示的物品。很显然,他不能把所有物品都装进背包,所以必须确定拿走哪些物品,留下哪些物品。 | 名称 | 价格(美元) | 重量(kg) | | :----: | :----------: | :--------: | 电脑 200 20 收音机 20 4 钟 175 10 花瓶 50 2 书 10 1 油画 90 9 | """ class Thing(object): """物品""" def __init__(self, name, price, weight): self._name = name self._price = price self._weight = weight @property def name(self): return self._name @property def price(self): return self._price @property def weight(self): return self._price @property def value(self): return self._price / self._weight def input_thing(): """输入物品信息""" print('请输入物品信息: ') name_str , price_str , weight_str = input().split() return name_str, int(price_str) , int(weight_str) True def main(): """主函数""" print('请输入最大重量,物品数量') max_weight , num_of_things = map(int, input().split()) all_things = [] for _ in range(num_of_things): all_things.append(Thing(*input_thing())) all_things.sort(key=lambda x : x.value , reverse = False) for thing in all_things: print(thing.name) total_weight = 0 total_price = 0 for thing in all_things: if total_weight + thing.weight <= max_weight: print(f'小偷拿走了{thing.name}') total_weight += thing.weight total_price += thing.price print(f'总价值: {total_price}美元') if __name__ == '__main__': main()
false
27b666b95f8e612b29fd2ef6072fee2846493eb7
Kgothatso-katshedi/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
575
4.28125
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): """ adds the first two elements of two tuples together and returns the result """ ta_len = len(tuple_a) tb_len = len(tuple_b) new_tup = () for i in range(2): if i >= ta_len: val_a = 0 else: val_a = tuple_a[i] if i >= tb_len: val_b = 0 else: val_b = tuple_b[i] if (i == 0): new_tup = (val_a + val_b) else: new_tup = (new_tup, val_a + val_b) return (new_tup)
false
0407ee506c18e997441da5cf781733a760bd5cc9
rufengchen/games
/5217/5312tutwk5.py
1,809
4.15625
4
# Exercise 1: list sorting # create one state a line and only contain the first 13 states statefile = open("States.txt","r") # you get Str statesstr = statefile.read() # read all the content # Use split turn the Str into List, create a list of states using split() statelist = statesstr.split('\n') #\n mean the seperator # sort the 13 states in alphabetical order, extract the first 13 states new_list = statelist[0:13] new_list.sort() print(new_list) # display the 13 states one in one line for i in range (0,len(new_list)): print(new_list[i]) statefile.close() # Exercise 1: list sorting (another version) # create one state a line and only contain the first 13 states statefile1 = open("States.txt","r") # you get Str statelist1 =[line for line in statefile1]# read lines, list comprehension statelist1 = statelist1[0:13] statelist1.sort() for i in range(0,len(statelist1)): statelist1[i].replace('\n','') print(statelist1[i]) statefile1.close() # Exercise 2: list comprehension and sorting with lambda function names = ['Yuqi Lan','Marilyn Leung','Chenyu Zhang','Wing Sze Wong'] setLN =set() for name in names: setLN.add(name.split()[-1]) print(setLN) # Exercise 2: list comprehension and sorting with lambda function # 2.1 use list comprehesion names1 = ['Yuqi Lan','Marilyn Leung','Chenyu Zhang','Wing Sze Wong'] setLN1 = [lname1.split()[-1] for lname1 in names1] print(setLN1) # Exercise 2: list comprehension and sorting with lambda function # 2.2 use lambda sort the name by last name names2 = ['Yuqi Lan','Marilyn Leung','Chenyu Zhang','Wing Sze Wong'] setLN2 = [lname.split()[-1] for lname in names2] names2.sort(key=lambda x: x.split()[-1]) print(names2) # Another method: def y(x): return x.split()[-1] names3 = ['Yuqi Lan','Marilyn Leung','Chenyu Zhang','Wing Sze Wong'] names3.sort(key=y)# the key is the function name(no need parameters) print(names3)
true
0793403e9170663eb9e96f4433fa6fc9f94e5bab
ashvinipadekar/my-django-app
/pythonfull/dictionaries program.py
980
4.40625
4
""" d1={"name":"ash","middle":"datta","lastname":"padekar"} print(d1) # To print the your choice values by using key print(d1["middle"]) print(d1.get("name")) ### MOdify the values d1["middle"]="popat" print(d1) ### TO use for loop for showing the keys and values for i in d1: print(i) ### To print values using for loop for i in d1: print(d1[i]) ### To print keys and values from the dictionaries for x,y in d1.items(): print(x,y) ### To check whether the key present or not if "name" in d1: print("yes") #### To add items to dictionary d1["son"]="rihu" print(d1) #### To remove items from dictionary d1.pop("name") print(d1) """ ### To print dictionaries within dictionaries mydic={ "child1":{"name":"A","age ":20}, "child2":{"name":"B","age":30}, "child3":{"name":"c","age":40} } print(mydic) c1={"name ":"ash","age":56} c2={"name":"sucheta","age":60} c3={"name":"sonia","age":65} mychild={"childs1":c1,"child2":c2,"child3":c3} print(mychild)
false
f69fed093055a812752b471c52e448672388c862
ashvinipadekar/my-django-app
/HelloWord/app1.py
735
4.15625
4
# name = input("what is your name") # color = input("what is your favourite color is") # print(name + "likes" + color) # birth_year=input("enter your birth year: ") # age=2019-int(birth_year) # print(age) # weight_l = input("weight in lbs:") # weight_k = float(weight_l) * 0.45 # print(weight_k) ###course = ''' # hi ashvini # how are you # whats going on # ib am fine # take care yourself # ''' # print(course) # course = "ahvini" # print(course[-2]) # print(course[:5]) # print(course[0:3]) first = "smith" last = "john" message = first + '[' + last + '] is a coder' print(message) print(len(first)) print(first.upper()) print(first.find('m')) #print(first.replace('smith', 'ash')) print('smith' in first) print('Smith'in first)
true
278bb64a6893089a5cb8e05881d7348463a51432
Xenomorphims/Python3-examples
/new folder/if_else.py
221
4.1875
4
countrys = ['usa', 'china', 'sudan', 'brazil', 'france'] if 'zambia' == countrys: print('It is in the list') elif 'zambia' != countrys: print('Yep, it is in there') else: print('It is not in the list')
false
03b14ee3c3685dc11120d003b64660cc885621b4
athiyamaanb/py_challenge
/scripts/reverse_string.py
680
4.4375
4
# Write a function that reverses a string. The input string is given as an array of characters char[]. # # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # # You may assume all the characters consist of printable ascii characters. def reverse_string(input_s): i = 0 length = len(input_s) while i < length: input_s.append(input_s[length -1 -i]) input_s.pop(length -1 -i) i += 1 return input_s if __name__ == '__main__': input_s = ['a','b','c','d'] print('Input List: ') print(input_s) print('Reversed List: ') print(reverse_string(input_s))
true
24eb680800ad4d2c3f299e7b2b690857a797b5b4
nimowairimu/Password-Locker
/user.py
1,255
4.25
4
class User(): """ Class for user log in """ user_list = []# empty list of logged in users def __init__(self,name, password): """ method that defines the properties of a user. """ self.name = name self.password = password def add_user(name,password): """ method to add the user into the system """ User.user_list.append(self) def login(name,password):# login functions to the password locker """ method to log in user """ print("Please enter your login details") name = input("Enter your username: ") password = input("Enter your password : ") print("Welcome") def register(): """ method to register a new user """ print("Enter your name and password ") name = input("Enter your username: ") password = input("Enter your password : ") login() def enter(): """ method to check if a user is a returning user or a new one """ print ("Stressing about your passwords? Don't worry , Password Locker got you!") ask = input("Do you have an accout ? y/n: ") if ask == "y".lower(): login() elif ask == "n".lower(): register() else: enter() enter()
true
58eccf7be8c628ba0146e90b897a1dac927a49bf
gadkaria/python_excercises
/Regression.py
823
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt # set up the data X = np.array([0,1,2,3,4,5,6,7,8,9]) Y = np.array([1,3,2,5,7,8,8,9,10,12]) # In[5]: # calculate the bars x_mean = np.mean(X) y_mean = np.mean(Y) # In[7]: # calculating cross-deviation and deviation about x n = np.size(X) SS_xy = np.sum(X*Y) - n*x_mean*y_mean SS_xx = np.sum(X*X) - n*x_mean*x_mean b_1 = SS_xy / SS_xx b_0 = y_mean - b_1*x_mean # In[8]: # plotting the actual points as scatter plot plt.scatter(X, Y, color = "m", marker = "o", s = 30) # predicted response vector y_pred = b_0 + b_1*X # plotting the regression line plt.plot(X, y_pred, color = "g") # putting labels plt.xlabel('x') plt.ylabel('y') # function to show plot plt.show() # In[ ]:
false
79dc41c13693a4dfc10e1bff678dd981c964d720
161299/CodiGo---Tecsup
/Backend/Semana4/Dia4/03-funcion-new.py
922
4.15625
4
# METODOS MAGICOS class Empleado(object): def __new__(cls): print("El metodo magico __new__ ha sido invocado") instancia = object.__new__(cls) print(instancia) return instancia def __init__(self): print("El metodo magico __init__ ha sido invocado") def __str__(self): """metodo magico que podemos sobreescribir (Override) para devolver lo que nosotros deseamos """ return "Yo soy la nueva definicion de la clase" empleado1 = Empleado() print(type(empleado1)) print(hex(id(empleado1))) print(empleado1) class Punto: def __init__(self,x=0, y=0): self.x = x self.y = y def __add__(self,otro): """ Metodo magico que sirve para incrementar el mismo objeto con otro""" x = self.x + otro.x y = self.y + otro.y return x, y punto1 = Punto(4,8) punto2 = Punto(-2,2) punto3 = punto1 + punto2 print(punto3)
false
5a0f28894e48ed06adca6ed854845f7cb10cf86d
CReesman/Python_Crash_Course
/Python_Crash_Course_Book/CH5/hello_admin_5_8.py
713
4.46875
4
''' 5-8. Hello Admin: Make a list of five or more usernames, including the name 'admin'. Imagine you are writing code that will print a greeting to each user after they log in to a website. Loop through the list, and print a greeting to each user: If the username is 'admin', print a special greeting, such as Hello admin, would you like to see a status report? Otherwise, print a generic greeting, such as Hello Jaden, thank you for logging in again. Christopher Reesman 5/7/20 ''' usernames = ['admin','auditor','analyst','developer','manager'] for name in usernames: if name == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello Jaden, thank you for logging in again.")
true
781bacad1b2d1741da4841dd4c10be45341d4b2e
CReesman/Python_Crash_Course
/Python_Crash_Course_Book/CH8/cities_8_5.py
566
4.4375
4
''' 8-5. Cities: Write a function called describe_city() that accepts the name of a city and its country. The function should print a simple sentence, such as Reykjavik is in Iceland. Give the parameter for the country a default value. Call your function for three different cities, at least one of which is not in the default country. Christopher Reesman 5/11/20 ''' def describe_city(city, country='the united states of america'): print(f"{city.title()} is in {country.title()}") describe_city('San Antonio') describe_city('Philadelphia') describe_city('London', 'England')
true
892fb2d2619a3bb0eb7dc6f8732dd783363ea292
CReesman/Python_Crash_Course
/Python_Crash_Course_Book/CH5/conditional_tests.py
991
4.1875
4
''' 5-1. Conditional Tests: Write a series of conditional tests. Print a statement describing each test and your prediction for the results of each test. Your code should look something like this: car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') print("\nIs car == 'audi'? I predict False.") print(car == 'audi') Look closely at your results, and make sure you understand why each line evaluates to True or False. Create at least ten tests. Have at least five tests evaluate to True and another five tests evaluate to False. Christopher Reesman 5/6/20 ''' car = 'ford' print("Is car == 'Ford'? I predict False.") print(car == 'Ford') car = 'Chevrolet' print("Is car == 'Chevrolet?' I predict True.") print(car == 'Chevrolet') car = 'dodge' print("Is car == 'Dodge'? I predict False.") print(car == 'Dodge') car = 'Honda' print("Is car == 'Honda'? I predict True.") print(car == 'Honda') car = 'BMW' print("Is car == 'bmw'? I predict False.") print(car == 'bmw')
true
2bb3f8285572e49a89614c685c2c66b73905abc5
matthewj1561/cse210-tc06
/mastermind/game/console.py
2,141
4.28125
4
import time class Console: """A code template for a computer console. The responsibility of this class of objects is to get text or numerical input and display text output. Stereotype: Service Provider, Interfacer Attributes: prompt (string): The prompt to display on each line. """ def __init__(self) -> None: self._answer = '99999' self._countdown = 4 def read(self, prompt): """Gets text input from the user through the Console. Args: self (Console): An instance of Console. prompt (string): The prompt to display to the user. Returns: string: The user's input as text. """ self._answer = '99999' self._answer = input(prompt) return self._answer def read_for_turn(self): """Allows input for the player's guess Args: self (Console): An instance of Console. Returns: str: user inputted answer """ self._answer = '99999' self._answer = input() return self._answer def timer_for_turn(self): """Creates timed turns for game. Args: self: instance of Console Returns: str: answer that will never be true """ time.sleep(self._countdown) if self._answer != '99999': return print("Gotta be faster than that!") self._answer = 'zzzz' return self._answer def read_number(self, prompt): """Gets numerical input from the user through the Console. Args: self (Console): An instance of Console. prompt (string): The prompt to display to the user. Returns: integer: The user's input as an integer. """ return int(input(prompt)) def write(self, text): """Displays the given text on the Console. Args: self (Console): An instance of Console. text (string): The text to display. """ print(text)
true
640192570c353d40b467f543f093e15db290f4fc
PyPiTeam/GraphImplementation
/main.py
2,699
4.1875
4
# The main purpose of this application is to take in a graph, and to find a shortest path from one node to another node # This program uses the pseudocode from this video: https://www.youtube.com/watch?v=oDqjPvD54Ss # Had to make a few changes from the pseudocode since I am using an object here # Instead of enqueue, it is put # Instead of dequeue, it is get # Instead of isEmpty, it is empty from queue import Queue class graphImp() : def __init__(self, graph, numNodes) : self.graph = graph self.numNodes = numNodes self.toTraverse = Queue(maxsize=numNodes) def listAllNodes(self): for node in self.graph: print(node, end = " ") print() def listAllNodesAndConnections(self): for node in self.graph: print("%s ->" % (node), end=" ") for adjacents in self.graph[node]: print("%s" % (adjacents), end=" ") print() def addNode(self, nodeName, nodeAdjacents): self.graph[nodeName] = nodeAdjacents for node in nodeAdjacents: self.graph[node].append(nodeName) def removeNode(self, nodeName): del self.graph[nodeName] for node in self.graph: if nodeName in self.graph[node]: self.graph[node].remove(nodeName) def shortestPath(self, startNode, endNode): def solve(self, startNode): self.toTraverse.put(startNode) visited = {} for node in self.graph: visited[node] = False visited[startNode] = True prev = {} for node in self.graph: prev[node] = None while(not self.toTraverse.empty()): node = self.toTraverse.get() neighbors = self.graph[node] for nextt in neighbors: if not visited[nextt]: self.toTraverse.put(nextt) visited[nextt] = True prev[nextt] = node return prev def reconstructPath(self, startNode, endNode, prev): path = [] at = endNode while at != None: path.append(at) at = prev[at] path.reverse() if path[0] == startNode: return path return [] prev = solve(self, startNode) path = reconstructPath(self, startNode, endNode, prev) return path def shortestPathLen(self, startNode, endNode): dist = len(self.shortestPath(startNode, endNode)) - 1 print(dist) return dist #print(toBeTraversed) graph = {"A": ["B", "C", "F"], "B": ["A", "D"], "C": ["A", "E", "F"], "D": ["B", "E"], "E": ["C", "D"], "F": ["A", "C"]} numNodes = 6 graphObject = graphImp(graph, numNodes) graphObject.listAllNodesAndConnections() print(graphObject.shortestPath("A", "E")) graphObject.shortestPathLen("A", "E")
true
0c4dd4d82f715320997cd91bfd2a87de843fdfec
Saeed-Jalal/ifprogramflow
/ifprogramflow.py
549
4.15625
4
age = int(input("How old you are? ")) if age >=18 and age<=60: print("You can vote.") else: print("You are not in that age group.") parrot = "A bird Name" letter = input("Enter a letter.") if letter in parrot: print("Reward me an {},with money".format(letter)) else: print("I don't deserve reward. ") name = input("Please enter your name: ") age = int(input("How old you are,{0}? ".format(name))) if age>=18 and age<40: print("Welcome to the Summer holiday club.") else: print("We are sorry you are not in this age group.")
true
2bd6f2403b60851b83a7cc79ed946bedacdc1c16
kibol/USF-Repo
/Python/ch09e02.py
1,757
4.1875
4
##2 my_list = ['spam!', 'one', ['Brie', 'Roquefort', 'Pol le Veq'],[1,2,3]] ## Received the following error with 1 as part the list ##TypeError: object of type 'int' has no len() for elem in my_list: print len(elem) # Received the follwing error message: TypeError: object of type 'int' has no len() ##my_list[1:1]= ["one"] ##print len(elem) ##4 a = [1,2,3] b = a[:] print a print b # a=[1,2,3] # b= [1,2,3] b[0] = 5 # a= [1,2,3] # b= [5,2,3] print a print b ###17 ##string.split and string.join have an inverse relationship. string.split ##change a string of characters into its indidual compoment. string.join will ##take a list and reverse it into into string. Used togetther as in string.split(string.join()) ##there is no effect because the original string is reverted to what it was before applying the ##module.##By default both of these modules will split or join at white spaces. However, they could be ##be set to split or join at a specified location inside a string or a list, making them ideal for inserting ## substrings. ##18 import string def replace(s, old, new): """ >>> replace('Mississippi', 'i', 'I') 'MIssIssIppI' >>> s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!' >>> replace(s, 'om', 'am') 'I love spam! Spam is my favorite food. Spam, spam, spam, yum!' >>> replace(s, 'o', 'a') 'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!' """ split_list =string.split(s, old) result=string.join(split_list, new) return result s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!' print replace(s, 'om', 'am') if __name__ == '__main__': import doctest doctest.testmod()
true
dd30bce0852d51df453f2285e084ec2eadb70ebe
Boggavarapuvenkatasaichakravarthi/python
/5_array_rotation.py
485
4.125
4
arr = [4,1,3,2,5]; n = 3; print("Original array: ") for i in range(0, len(arr)): print(arr[i]), for i in range(0, n): first = arr[0]; for j in range(0, len(arr)-1): arr[j] = arr[j+1]; arr[len(arr)-1] = first; print(); print("Array after left rotation: "); for i in range(0, len(arr)): print(arr[i]),
false
cca94054971b252a79fddbe41cd1ff37779ea0bd
rutikamandape01/Codewayy_python_series
/Python-Task3/Ques3.py
364
4.21875
4
#printing numbers from 1 to 10 except 3 and 7 using for loop for number in range(1,11): if(number==3 or number==7): continue else: print(number) #printing numbers from 1 to 10 except 3 and 7 using while loop num=1 while(num<11): if(num==3 or num==7): num+=1 else: print(num) num+=1
true
51bb39ffc72ad46846db30caca8cdeed992721d4
rutikamandape01/Codewayy_python_series
/Python_Task2/Dictionaries.py
661
4.46875
4
#dictionaries methods #get method gives the value of the specific item dict1={"name":"Rutika","Age":"20","city":"Nagpur","state":"Maharashtra"} print(dict1.get("name")) #item method items=dict1.items() print(items) #value method use to give all values in the dictionary values=dict1.values() print(values) #pop method used to remove specific item from dictionary pop=dict1.pop("Age") print(dict1) #popitem method use to remove last item from dictionary popItem=dict1.popitem() print(dict1) #update method is use to add item into dictionary updateDict=dict1.update({"country" : "India"}) print(dict1) #clear method clearDict=dict1.clear() print(dict1)
true
4b1a8dcb0f15cd9983231017c6faea3a18982e02
ZachDunn8/Pygame
/pygamenotes.py
1,266
4.125
4
#include pygame import pygame #init game #in order to use pygame, we have to run the init method pygame.init() #create screen with a particular size #screen size must be a tuple screen_size = (512, 480) #Actually tell pygame to set screen up and store it pygame_screen = pygame = pygame.display.set_mode(screen_size) #set up a pointless caption pygame.display.set_caption("Goblin Chase") #set up a var with our image background_image = pygame.image.load('background.png') hero_image = pygame.image.load('hero.png') #set up hero location hero = { 'x':100, 'y':100, 'speed':20 } #create a game loop (while) # create boolean for whether the game should be going or not game_on = True while game_on: #we are inside the main game loop. #it will keep running as long as bool is true #add a quit event (python needs an escape) # pygame comes with an event loop! (sort of like JS) for event in pygame.event.get(): if (event.type == pygame.QUIT): #the user clicked the red x in the top left game_on = False #fill in screen with a color (or image) # ACTUALLY RENDER SOMETHING #blit takes 2 arguments #1. What do you want to draw? #2. Where do you want to draw it? pygame_screen.blit(background_image, [0,0]) #repeat 6 over and over..... pygame.display.flip()
true
3f68c4e9c5ca7d839ca6a790838c620efd065a27
ddp-d/Coursera_phyton_assesment
/Assessment_Files_and_CSV.py
2,687
4.53125
5
# 1. The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. # Find the total number of characters in the file and save to the variable num. # Output: 316 file_obj = open("travel_plans.txt", 'r') num = 0 data = file_obj.read() num = len(data) print(num) file_obj.close() # 2. We have provided a file called emotion_words.txt that contains lines of words that describe emotions. # Find the total number of words in the file and assign this value to the variable num_words. # Output: 48 file_obj = open("emotion_words.txt", 'r') num_words = 0 for word in file_obj.readlines(): values = word.split() for i in values: num_words += 1 print(num_words) file_obj.close() # 3. Assign to the variable num_lines the number of lines in the file school_prompt.txt. # Output: 10 file_obj = open("school_prompt.txt", 'r') num_lines = 0 for lines in file_obj.readlines(): num_lines += 1 print(num_lines ) file_obj.close() # 4. Assign the first 30 characters of school_prompt.txt as a string to the variable beginning_chars. # Output: Writing essays for school can file_obj = open("school_prompt.txt", 'r') beginning_chars = "" beginning_chars = file_obj.read()[:30] print(beginning_chars) file_obj.close() # 5. Challenge: Using the file school_prompt.txt, assign the third word of every line to a list called three. # Output: ['for', 'find', 'to', 'many', 'they', 'solid', 'for', 'have', 'some', 'ups,'] file_obj = open("school_prompt.txt", 'r') three = [] for word in file_obj.readlines(): values = word.split() three.append(values[2]) print(three) file_obj.close() # 6. Challenge: Create a list called emotions that contains the first word of every line in emotion_words.txt. # Output: ['Sad', 'Angry', 'Happy', 'Confused', 'Excited', 'Scared', 'Nervous'] file_obj = open("emotion_words.txt", 'r') emotions = [] for first in file_obj.readlines(): values = first.split() emotions.append(values[0]) print(emotions) file_obj.close() # 7. Assign the first 33 characters from the textfile, travel_plans.txt to the variable first_chars. # Output: This summer I will be travelling. file_obj = open("travel_plans.txt", 'r') first_chars = file_obj.read(33) print(first_chars) file_obj.close() # 8. Challenge: Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called p_words. # Oupput: ['topic', 'point', 'papers,', 'ups,', 'scripts.'] file_obj = open("school_prompt.txt", 'r') words = file_obj.read().split() p_words = [] for w in words: if 'p' in w: p_words.append(w) print(p_words) file_obj.close()
true
3b5a307c029cd62f7d453269c4f286ed00ceed5d
MichaelTrotterPersonal/PythonClub
/24042020_StupidAddition.py
1,420
4.1875
4
# Problem Wk 20/04: Stupid Addition # Given 2 parameters, if: # both are strings, then add them as if they were integers # if both are integers, then concatenate them # if they have different data types then return None # Examples: # if param1=1, param2=2, then concatenate them to give the result="12" # if param1="1", param2="2", then add them as integers to give the result=3 # if param1="1", param2=2, then these have different datatypes and the result=None # Extension: # write a function to do this. #Over-riding the + operator using a class class o: def __init__(self, i): self.var = i def __add__(self, other): if type(self.var) == str and type(other.var) == str: return int(self.var) + int(other.var) elif type(self.var) == int and type(other.var) == int: return str(self.var) + str(other.var) else: return None print('string addition:', o('1') + o('2') ) print('int addition:', o(1) + o(2) ) print('mixed addition:', o(1) + o('1') ) #The function version def stupid_addition(p1, p2): if type(p1) == str and type(p2) == str: return int(p1) + int(p2) elif type(p1) == int and type(p2) == int: return str(p1) + str(p2) else: return None print('String addition:', stupid_addition('1','2')) print('Int addition:',stupid_addition(1,2)) print('Mixed addition:', stupid_addition('1',2))
true
d5c28f22d06468c8a633594af00b24e0f0b21b0f
surinder1/Assignment
/assignment no.11.py
2,962
4.3125
4
#Q.1- Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is inheriting Animal and access the base class method. class animal: def __init__(self,no_of_legs): self.no_of_legs=no_of_legs def display(self): print("it has",self.no_of_legs,"legs") class tiger(animal): def show(self): print("tiger is a carnivorous animal") a=tiger(int(input("enter no_of_legs of tiger:"))) a.show() a.display() #Q.2- What will be the output of following code. class A: def f(self): return self.g() def g(self): return 'A' class B(A): def g(self): return 'B' a = A() b = B() print(a.f(), b.f()) print(a.g(), b.g()) # output:- # A B # A B #Q.3- Create a class Cop. Initialize its name, age , work experience and designation. # Define methods to add, display and update the following details. Create another class # Mission which extends the class Cop. Define method add_mission _details. Select an # object of Cop and access methods of base class to get information for a particular cop # and make it available for mission. class cop: def __init__(self,name,age,work_experience,designation): self.name=name self.age=age self.work_experience=work_experience self.designation=designation def display(self): print("your name:",self.name) print("your age:",self.age) print("your work_experience:",self.work_experience) print("your designation:",self.designation) def update(self,name,age,work_experience,designation): self.name=name self.age=age self.work_experience=work_experience self.designation=designation class mission(cop): def add_mission_details(self): print("for murder mystery:") print("this cop is suitable") m=mission(input("enter your name:"),int(input("enter your age:")),int(input("enter your work experience:")),input("enter your designation:")) m.add_mission_details() m.display() m.update(input("enter your name:"),int(input("enter your age:")),int(input("enter your work experience:")),input("enter your designation:")) m.add_mission_details() m.display() #Q.4- Create a class Shape.Initialize it with length and breadth Create the method Area. #Create class rectangle and square which inherits shape and access the method Area. class shape: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): self.result=self.length*self.breadth class rectangle(shape): def rectarea(self): print("area of rectangle is",self.result) class square(shape): def sqarea(self): print("area of square is",self.result) s=square(int(input("enter length of square:")),int(input("enter breadth of square:"))) s.area() s.sqarea() r=rectangle(int(input("enter length of rectangle:")),int(input("enter breadth of rectangle:"))) r.area() r.rectarea()
true
e86fe3500ea5be98d54af0c870ce2d0d349f3f92
xxx58/Heap
/heap.py
2,086
4.1875
4
#making max heap class heap(object): def __init__(self,l): self.heap=[0]*len(l) self.index=0 self.heap[0]=l[0] self.insert(l) def insert(self,l): for i in l[1:]: self.index=self.index+1 self.heap[self.index]=i self.heapify_up(self.index) def heapify_up(self,index): parent_index=(index-1)//2 while (parent_index>=0) and (self.heap[index]>self.heap[parent_index]): temp=self.heap[parent_index] self.heap[parent_index]=self.heap[index] self.heap[index]=temp index=parent_index parent_index=(index-1)//2 def show_heap(self): print(self.heap) def max_element(self): print(self.heap[0]) #pop always take place from top_most element of heap(ie max element if heap) def pop(self): self.heap[0]=self.heap[self.index] del self.heap[self.index] self.index=self.index-1 print(self.index) left_child_index=1 right_child_index=2 while(left_child_index<=self.index): if(left_child_index<=self.index): swap_with=0 if(right_child_index > self.index): swap_with=left_child_index else: if self.heap[right_child_index]>self.heap[left_child_index] and self.heap[right_child_index]>self.heap[swap_with] : swap_with=right_child_index elif self.heap[right_child_index]<self.heap[left_child_index] and self.heap[left_child_index]>self.heap[swap_with] : swap_with=left_child_index else: swap_with=swap_with break temp=self.heap[swap_with] self.heap[swap_with]=self.heap[0] self.heap[0]=temp print(self.heap) left_child_index=2*swap_with+1 right_child_index=2*swap_with+2
false
04d9ec0bd59f04fd165dd5da0aae69b092aca558
Alkantou/PythonClass
/15_GuessingGameChallenge.py
1,618
4.25
4
# # Guessing Game Challenge # # Let's use `while` loops to create a guessing game. # # The Challenge: # # Write a program that picks a random integer from 1 to 100, and # has players guess the number. The rules are: # # 1. If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS" # 2. On a player's first turn, if their guess is # * within 10 of the number, return "WARM!" # * further than 10 away from the number, return "COLD!" # 3. On all subsequent turns, if a guess is # * closer to the number than the previous guess return "WARMER!" # * farther from the number than the previous guess, return "COLDER!" # 4. When the player's guess equals the number, tell them they've guessed # correctly *and* how many guesses it took! # # You can try this from scratch, or follow the steps outlined below. A separate Solution # notebook has been provided. Good luck! import random x = int(random.randint(1, 100)) print(x) guesses = [0] input_number = int(input('Enter A number between 1 and 100: ')) difference = int(abs(input_number - x)) guesses.append(input_number) first_try = True while difference != 0: if not first_try: if difference < abs(int(x) - int(guesses[-2])): print('Warmer!') else: print('Colder!') if first_try: if difference <= 10: print('Warm!') else: print('Cold!') first_try = False input_number = int(input('Enter A number between 1 and 100: ')) guesses.append(input_number) difference = abs(input_number - x) print(f'You guessed it in {len(guesses)} tries')
true
e88859be8f74d0392325bdb7d6f38abdbf005439
Anjalkhadka/lab3
/qn2.py
545
4.25
4
'''Write a function calledfizz_buzzthat takes a number. If the number is divisible by 3, it should return “Fizz”. If it is divisible by 5, it should return “Buzz”. If it is divisible by both 3 and 5, it should return “FizzBuzz”. Otherwise, it should return the same number.''' def calledfizz(num): if num%3==0: print('fizz') elif num%5==0: print(' buzz') elif num%3==0 and num%5==0: print('fizzbuzz') else: print("not divisible by the 5&3") num=int(input('enter a number : ')) calledfizz(num)
true
f4b8aa3b0001d27326ee5a6fba4e011a940a5f98
dvihaan/Python-Beginners
/Math/Polygon/Polygon.py
1,323
4.4375
4
import math ''' This is a function to get the points that you are supposed to plot, given a certain side length and amount of sides. This function and code only prints the points you would need to plot the shape that you have decided on. ''' #The inputs, in order from left to right are: number of sides, side length, centre x position, centre y position, and the angle the shape is rotated #By default, the shape is centered at the origin and has no rotation from its original shape def GetPoints(n, a, cx = 0, cy = 0, theta = 0): #the list of tuples that will contain the points points = [] # r = the distance from the centre to any vertex r = a*math.sin(math.radians(90-180/n))/math.sin(math.radians(360/n)) #creating the tuples containing the points for i in range(n+1): Vix = r*math.cos(math.radians(i*360/n+theta)) + cx Viy = r*math.sin(math.radians(i*360/n+theta)) + cy points.append((Vix,Viy)) return points #printing the points that should be connected in a drawing def Draw(points): for p in range(len(points)-1): print("({:.2f},{:.2f}) ---------- ({:.2f},{:.2f})".format(points[p][0],points[p][1],points[p+1][0],points[p+1][1])) #running the program def main(): points = GetPoints(8,1) Draw(points) if __name__ == '__main__': main()
true
046c44799d50b6cc950fafad28968479951d517e
alicavdar91/ASSIGMENTS
/Assignment 7 - 2 (Covid 19).py
1,226
4.34375
4
#!/usr/bin/env python # coding: utf-8 # # Assignment 7- 2 (Covid-19) # Problem : # # Task : Estimating the risk of death from coronavirus. Write a program that; # # Takes "Yes" or "No" from the user as an answer to the following questions : # # Are you a cigarette addict older than 75 years old? Variable → age # # Do you have a severe chronic disease? Variable → chronic # # Is your immune system too weak? Variable → immune # # Set a logical algorithm using boolean logic operators (and/or) and use if-statements with the given variables in order to print out us a message : "You are in risky group"(if True ) or "You are not in risky group" (if False). # # In[1]: age = input("Are you a cigarette addict older than 75 years old?(yes/no)") if age == "yes": age = True else: age = False chronic = input("Do you have a severe chronic disease?(yes/no)") if chronic == "yes": chronic = True else: chronic = False immune = input("Is your immune system too weak?(yes/no)") if immune == "yes": immune = True else: immune = False risk = (age or chronic or immune) if risk == True : print("You are in risky group") else: print("You are not in risky group") # In[ ]:
true
0c898ed82418a89e1631206ae995c8bd2320524e
RevathiAsokan/Basic-Python-Programs
/p4_if_elif_statement.py
434
4.15625
4
""" To demonstrate if elif statement find whether a number lies in a range or not """ start = int(input("Enter the value of start of range: ")) end = int(input("Enter the value of end of range: ")) num = int(input("Enter the number to find in range: ")) if num > end: print(num, "greater than ", end) elif num < start: print(num, "less than ", start) else: print(num, "is in range ", start, " - ", end)
true
da8a65f9245158358340e5c916e0df1faeef5b09
RevathiAsokan/Basic-Python-Programs
/p7_break_statement.py
266
4.28125
4
""" To demonstrate break statement Accept only even number and quit when user enters odd number""" while True: num = input("Enter a even number: ") if int(num) % 2 != 0: print("Program ends! You have entered a odd number") break
true
8c9fc83f23f93840643e35d2901bea3e86d2af9d
mengjutsai/python-ci
/mean.py
752
4.25
4
def mean(num_list): # assert type(num_list)==list assert isinstance(num_list, list) for element in num_list: assert isinstance(element, int or float) # assert len(num_list)!=0 # if len(num_list)==0: # raise Exception("The algebraic mean of an empty list is undefined. Please provide a list of numbers.") # num_list = [] # print(sum(num_list), len(num_list)) # try to run with python # >>>> from mean import * # >>>> mean([]) # Then you will get the error msg try: return sum(num_list)/len(num_list) except ZeroDivisionError as detail: msg = "Please provide a list of numbers rather than an empty string" raise ZeroDivisionError(detail.__str__() + "\n" + msg)
true
c61c8f0c89a075c79d4136c6160c55862638ee19
11111010111/calculator
/math.py
2,117
4.125
4
operators = ["+", "-", "*", ".", "/", "**", "sqrt", "%", "<", "=", ">", "=/=", "//", "crt"] def sqrt(a): b = float(a) ** 0.5 return b def crt(a): b = float(a) ** (1/3) return b def the_actual_math(first, operation, second): first = float(first) second = float(second) if operation == operators[0]: result = first + second elif operation == operators[1]: result = first - second elif operation == (operators[2]): result = first * second elif operation == operators[4]: result = first / second elif operation == "**": result = first ** second elif operation == "crt": result = crt(first) elif operation == "sqrt": result = sqrt(first) elif operation == "%": result = first % second elif operation == "//": result = first // second elif operation == "<": if first < second: result = True else: result = False if result: result = (str(first) + " is indeed less than " + str(second)) else: result = (str(first) + " is not less than " + str(second)) elif operation == "=": if first == second: result = True else: result = False if result: result = (str(first) + " is indeed equal to " + str(second)) else: result = (str(first) + " is not equal to " + str(second)) elif operation == ">": if first > second: result = True else: result = False if result: result = (str(first) + " is indeed more than " + str(second)) else: result = (str(first) + " is not more than " + str(second)) elif operation == "=/=": if first != second: result = True else: result = False if result: result = (str(first) + " is indeed not equal to " + str(second)) else: result = (str(first) + " is indeed equal to " + str(second)) else: result = 0 return result
false
638e753d71041d95b80173507abdf9def713e74e
Shibaram404/Example
/003_python_List_operation/user_ip_list.py
639
4.3125
4
hatlist = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat. print("existing hatlist:", hatlist) # Step 1: write a line of code that prompts the user user_input = int(input("enter the number: ")) # to replace the middle number with an integer number entered by the user. hatlist[2] = user_input print("\nNew hsatlist:", hatlist) # Step 2: write a line of code here that removes the last element from the list. del hatlist[-1] # Step 3: write a line of code here that prints the length of the existing list. print("\nLength after remove ",len(hatlist)) print("\nafter deleting the last element:", hatlist)
true
b8ac79b7fcad2d4c3bd6f3fe33a6bdb9243c147b
Shibaram404/Example
/005_Python_datetime/itr_days.py
237
4.1875
4
import calendar # shoe date c = calendar.TextCalendar(calendar.SUNDAY) for i in c.itermonthdays(2020, 9): print(i) # show month for name in calendar.month_name: print(name) print() for day in calendar.day_name: print(day)
true
4c0a0df7a65dac6733bc479768dea9e766774fe4
Shibaram404/Example
/004_Python_function/global_scope.py
393
4.125
4
def myFunction(): global var1 var = 2 print("Do I know that variable?", var, var1) var1 += var var1 = 1 myFunction() print(var1) # Using this keyword inside a function with the name (or names separated with commas) of a variable(s), # forces Python to refrain from creating a new variable inside the function # the one accessible from outside will be used instead.
true
a9d884ca6c98545890738bc0ea10bea8f47e1f99
mgm09/learningPython
/c5/c5_printWordsRandom.py
385
4.15625
4
# Challenge # Print a list of words in random order. The programme should print all the words and not repeat any. import random random_list = [] WORDS = ["Smooth","Run","Little","Dady","Hunter","Pog","Art","Question"] print("\n\nOriginal list of words:", WORDS) while WORDS: word = random.choice(WORDS) random_list.append(word) WORDS.remove(word) print("\n", random_list)
true
91f3aa196784218cb9b91562bf2e7f95ee912e16
walkerzh0/python
/study/4_python_var.py
1,733
4.21875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # ֵͱ miles = 1000.0 # name = "John" # ַ print counter print miles print name #number print "number test",;print "a b c" a = b = c = 1 a = 3 #del b print b print a print c print "\n\n\n" #string str = "01234567" print "string test" print str[3] #3 print str[3 : 6] #345 print str[5 :] #567 print str[1:3] * 3 #121212 print str[1:4] + "hello" #123hello print "list test" list = [ 'runoob', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] #list[0:3] = 90 #error list[0] = 90 #ok print list # б print list[0] # бĵһԪ print list[1:3] # ڶԪ print list[2:] # ӵʼбĩβԪ print tinylist * 2 # б print list + tinylist # ӡϵб print "\n" print "tuple test" tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') #list[0:3] = 90 #error #tuple[0] = 90 #error:tuple only read print tuple # б print tuple[0] # бĵһԪ print tuple[1:3] # ڶԪ print tuple[2:] # ӵʼбĩβԪ print tinytuple * 2 # б print tuple + tinytuple # ӡϵб raw_input("hellll") ''' #űб#!/usr/bin/python #!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # ֵͱ miles = 1000.0 # name = "John" # ַ print counter print miles print name input() '''
false
079652b71651818290904d7a8f1e228b0d4952e4
unit8co/darts
/darts/ad/anomaly_model/__init__.py
1,494
4.21875
4
""" Anomaly Models -------------- Anomaly models make it possible to use any of Darts' forecasting or filtering models to detect anomalies in time series. The basic idea is to compare the predictions produced by a fitted model (the forecasts or the filtered series) with the actual observations, and to emit an anomaly score describing how "different" the observations are from the predictions. An anomaly model takes as parameters a model and one or multiple scorer objects. The key method is ``score()``, which takes as input one (or multiple) time series and produces one or multiple anomaly scores time series, for each provided series. :class:`ForecastingAnomalyModel` works with Darts forecasting models, and :class:`FilteringAnomalyModel` works with Darts filtering models. The anomaly models can also be fitted by calling :func:`fit()`, which trains the scorer(s) (in case some are trainable), and potentially the model as well. The function :func:`eval_accuracy()` is the same as :func:`score()`, but outputs the score of an agnostic threshold metric ("AUC-ROC" or "AUC-PR"), between the predicted anomaly score time series, and some known binary ground-truth time series indicating the presence of actual anomalies. Finally, the function :func:`show_anomalies()` can also be used to visualize the predictions (in-sample predictions and anomaly scores) of the anomaly model. """ from .filtering_am import FilteringAnomalyModel from .forecasting_am import ForecastingAnomalyModel
true
4b03561b06c5e9983f5b418d5902118b75e606cf
kartikay-leo/Keyword-and-Default-Arguments
/31 July Lab(Keyword and Default arguments).py
2,122
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[82]: ## CUBE ## without parameters def cube(): x=int(input("Enter the Number: ")) print(x**3) # In[83]: cube() # In[84]: ## with parameters def cube_3(x): print(x**3) # In[85]: x=int(input("Enter the Number: ")) cube_3(x) # In[86]: ## CIRCLE ## without parameters def area(): r=float(input("Enter the Radius of the Circle: ")) f=3.14*r**2 print('The area of the circle is: ',f) # In[87]: area() # In[88]: ## with parameters def area_1(a): f=3.14*a**2 print('The area of the circle is: ',f) # In[89]: a=float(input("Enter the Radius of the Circle: ")) area_1(a) # In[97]: ## sum of numbers from n1 to n2 ## without parameters def num(): n1=int(input("Enter the 1st Number: ")) n2=int(input("Enter the 2nd Number: ")) c=0 for i in range(n1,n2+1): c=c+i print('Sum of two numbers is:',c) # In[36]: num() # In[98]: ## with parameters def number(x1,x2): cnt=0 for i in range(x1,x2+1): cnt=cnt+i print('Sum of two numbers is:',cnt) # In[41]: x1=int(input("Enter the 1st Number: ")) x2=int(input("Enter the 2nd Number: ")) number(x1,x2) # In[99]: ## KEY WORD def key(y1,y2): ct=0 for i in range(y1,y2+1): ct=ct+i print('Sum of two numbers is:',ct) # In[91]: key(y2=8,y1=4) # In[100]: ## DEFAULT def defa(z1,z2=9): cnt=0 for i in range(z1,z2+1): cnt=cnt+i print('Sum of two numbers is:',cnt) # In[93]: z1=int(input("Enter the 1st Number: ")) defa(z1) # In[94]: #### CONCATINATE STRINGS def st(s1,s2): print(s1,s2) # In[74]: s1=input('Enter the 1st string: ') s2=input('Enter the 2nd string: ') st(s1,s2) # In[95]: ## KEY WORD def mk(a2,a1): print(a1,a2) # In[77]: mk(a1='Hello',a2='Mam!') # In[96]: ## DEFAULT def df(b1,b2,b3='are',b4='you.'): print(b1,b2,b3,b4) # In[81]: b1=input('Enter the 1st string: ') b2=input('Enter the 2nd string: ') df(b1,b2) # In[ ]: ################################## THE END ###############################
false
5151692cb4b880c478e7b6c5f5fc17151eb1172f
ChengQian505/StudyPython
/2019/12/first_week/day4_12-5.py
1,520
4.34375
4
''' today's tasks task1: 筛选出运算符 task2: 根据task1中的运算符分割输入字串 task3: 打印运算结果 ''' import re def subtract(c,d): return c-d def multiply(c,d): return c*d def divide(c,d): return c/d def add(c,d): return c+d def calculator1(): args=["+","-","*","/"] while 1: s=input("请输入:") for arg in args: arg1=s.split(arg,2) if arg1.__len__()==2: a=float(arg1[0]) b=float(arg1[1]) if arg == "+": print(add(a,b)) elif arg == "-": print(subtract(a,b)) elif arg == "*": print(multiply(a,b)) elif arg == "/": print(divide(a,b)) #进阶版 使用正则操作 def calculator(): while 1: s=input("请输入:") arg=re.findall(r'[+\-*/%]',s) if not arg.__len__()==1: print("目前只支持单个运算符") continue arg=arg[0] arg1 = s.split(arg, 2) a = float(arg1[0]) b = float(arg1[1]) if arg == "+": print(add(a, b)) elif arg == "-": print(subtract(a, b)) elif arg == "*": print(multiply(a, b)) elif arg == "/": print(divide(a, b)) elif arg == "%": print(a % b) calculator()
false
037e61e379fbcbd9e0e431be51b53843a26937a0
ssmores/hackerrank
/thirtydaysofcoding/warmup_simplearraysum.py
1,004
4.125
4
"""Warmup questions from HackerRank. Simple Array Sum by shashank21j Problem Submissions Leaderboard Discussions Editorial Given an array of N integers, can you find the sum of its elements? Input Format The first line contains an integer, N, denoting the size of the array. The second line contains N space-separated integers representing the array's elements. Output Format Print the sum of the array's elements as a single integer. Sample Input 6 1 2 3 4 10 11 Sample Output 31 Explanation We print the sum of the array's elements, which is: 1 + 2 + 3 + 4 + 10 + 11 = 33. #!/bin/python import sys n = int(raw_input().strip()) arr = map(int,raw_input().strip().split(' ')) ************** Featured solutions Python 2 number_of_elements = int(raw_input()) array = map(int, raw_input().split()) print sum(array) ************** """ n = int(raw_input().strip()) arr = map(int, raw_input().strip().split(' ')) sum = 0 for i in range(n): sum += arr[i] print sum
true
8fd2794407a645d9f658c02af8850867d851d2c5
ssmores/hackerrank
/thirtydaysofcoding/day16.py
1,631
4.1875
4
"""30 days of coding for HackerRank. Day 16: Exceptions - String to Integer by AvimanyuSingh Objective Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message. Check out the Tutorial tab for learning materials and an instructional video! Task Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String. Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 0 score. Input Format A single string, S. Constraints 1 <= |S| <= 6, where |S| is the length of string S. S is composed of either lowercase letters (a - z) or decimal digits (0 - 9). Output Format Print the parsed integer value of S, or Bad String if S cannot be converted to an integer. Sample Input 0 3 Sample Output 0 3 Sample Input 1 za Sample Output 1 Bad String Explanation Sample Case 0 contains an integer, so it should not raise an exception when we attempt to convert it to an integer. Thus we print the 3. Sample Case 1 does not contain any integers, so an attempt to convert it to an integer will raise an exception. Thus our exception handler prints Bad String. ************** Featured solutions Python 2 ************** """ #!/bin/python import sys S = raw_input().strip() def string_c(S): try: S = int(S) print S # If you try to convert a string to an integer, it will return a ValueError message. except ValueError: print 'Bad String' string_c(S)
true
b75d1146b51f656188f0fc9e49e119851dd76336
ssmores/hackerrank
/thirtydaysofcoding/warmup_diagonaldifference.py
2,192
4.25
4
"""Warmup questions from HackerRank. Diagonal Difference by vatsalchanana Given a square matrix of size N x N, calculate the absolute difference between the sums of its diagonals. Input Format The first line contains a single integer, N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns. Output Format Print the absolute difference between the two sums of the matrix's diagonals as a single integer. Sample Input 3 11 2 4 4 5 6 10 8 -12 Sample Output 15 Explanation: Given a square matrix of size , calculate the absolute difference between the sums of its diagonals. Input Format The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns. Output Format Print the absolute difference between the two sums of the matrix's diagonals as a single integer. Sample Input 3 11 2 4 4 5 6 10 8 -12 Explanation The primary diagonal is: 11 5 -12 Sum across the primary diagonal is 11 + 5 - 12 = 4 The secondary diagonal is: 4 5 10 Sum across the second diagonal: 4 + 5 + 10 = 19 Difference:|4-19| = 15 ************** Featured solutions Python 2 size = input() matrix = [] # reading input for _ in xrange(size): row = map(int, raw_input().split()) matrix.append(row) # initialize s1 for right diagonal and s2 for left diagonal s1, s2 = 0, 0 # summing up together in just 1 loop, -ve index # (-x) in python is actually (size - x) for i in xrange(size): s1 += matrix[i][i] s2 += matrix[-i-1][i] # printing absolute difference print abs(s1 - s2) ************** """ #!/bin/python import sys n = int(raw_input().strip()) a = [] for a_i in xrange(n): a_temp = map(int,raw_input().strip().split(' ')) a.append(a_temp) def d_diff(n, a): """Sum values across diagonals, subtract the second from the first, provide absolute value.""" p_diag = 0 s_diag = 0 for i in range(n): p_diag += a[i][i] s_diag += a[i][n - (i + 1)] diff = p_diag - s_diag if diff < 0: print -diff else: print diff d_diff(n,a)
true
8afbf1ab7844081acc337de050e571331982c968
waldirio/python-training
/Topic_02/code01/code01.py
896
4.21875
4
#!/usr/bin/env python from datetime import datetime def questions(): # Questions here name = raw_input("Your Name: ") address = raw_input("Your Address: ") dt_bday = raw_input("Your Birthday Date (dd/mm/yyyy): ") # Filtering just the year of my bday year_from_my_bday = dt_bday.split("/")[2] # Collecting the actual year actual_year = datetime.now().year # My age according the year # age = actual_year-year_from_my_bday # we will check this one age = actual_year-int(year_from_my_bday) # new line print("\n\n") # Printing everything print("Your name is {}".format(name)) print("Your Address is {}".format(address)) # Two diff ways, we can calculate here or just print the variable print("Your age is near {}".format(actual_year-int(year_from_my_bday))) print("Your age is near {}".format(age)) questions()
true
8452014c8055f4a1c0281356d0f4350d98ecc5f8
patrafner/portfolio
/Python/shipping_project.py
1,431
4.3125
4
print("""This will calculate the shipping cost depending on the weight and if we use ground, drone or premium shipping.""") def ground_shipping_cost(weight): if weight <= 2: cost = 1.50 * weight elif weight <= 6: cost = 3.00 * weight elif weight <= 10: cost = 4.00 * weight else: cost = 4.75 * weight return cost + 20 premium_cost = 125 def drone_shipping_cost(weight): if weight <= 2: cost = 4.50 * weight elif weight <= 6: cost = 9.00 * weight elif weight <= 10: cost = 12.00 * weight else: cost = 14.25 * weight return cost print("The price with ground shipping for 8.4 lbs is $" + str(ground_shipping_cost(8.4))) print("The price with drone shipping for 1.5 lbs is $" + str(drone_shipping_cost(1.5))) print("The price for premium ground is $" + str(premium_cost)) def cheapest(weight): if drone_shipping_cost(weight) <= ground_shipping_cost(weight) and drone_shipping_cost(weight) <= premium_cost: return "Cheapest is drone shipping $" + str(drone_shipping_cost(weight)) elif ground_shipping_cost(weight) <= drone_shipping_cost(weight) and ground_shipping_cost(weight) <= premium_cost: return "Cheapest is ground shipping $" + str(ground_shipping_cost(weight)) else: return "Cheapest is premium shipping $" + str(premium_cost) print("For 4.8 lbs " + cheapest(4.8)) print("For 41.5 lsb " + cheapest(41.5))
true
b99935339d932c2fcbd5621208113b348256002d
ffancer/studing
/8 kyu Is it a number?.py
520
4.21875
4
""" https://www.codewars.com/kata/57126304cdbf63c6770012bd/train/python Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not. Valid examples, should return true: isDigit("3") isDigit(" 3 ") isDigit("-3.23") should return false: isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero") """ def isDigit(string): try: s = float(string) return type(s) == float except: return string.isdigit()
true
b845166089a9a44c6da839c827e653b2f2a225d8
ffancer/studing
/7 kyu Milk and Cookies for Santa.py
793
4.5
4
""" Happy Holidays fellow Code Warriors! It's almost Christmas Eve, so we need to prepare some milk and cookies for Santa! Wait... when exactly do we need to do that? Time for Milk and Cookies Complete the function function that accepts a Date object, and returns true if it's Christmas Eve (December 24th), false otherwise. Examples time_for_milk_and_cookies(date(2013, 12, 24)) # True time_for_milk_and_cookies(date(2013, 1, 23)) # False time_for_milk_and_cookies(date(3000, 12, 24)) # True """ from datetime import date def time_for_milk_and_cookies(dt): return dt.day == 24 and dt.month == 12 print(time_for_milk_and_cookies(date(2013, 12, 24)), True) print(time_for_milk_and_cookies(date(2013, 10, 24)), False) print(time_for_milk_and_cookies(date(3000, 12, 24)), True)
true
75402022a7401c0594efda718ab496675c72c42e
ffancer/studing
/7 kyu Sum of integers in string.py
704
4.21875
4
""" https://www.codewars.com/kata/598f76a44f613e0e0b000026/train/python Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. Note: only positive integers will be tested. """ def sum_of_integers_in_string(s): total, num = 0, '' for i in s: if i.isdigit(): num += i elif num != '': total += int(num) num = '' if num != '': total += int(num) return total print(sum_of_integers_in_string('The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog'))
true
a9f53d9d6d3edb007b55de2a5ce4d280387c8801
ffancer/studing
/7 kyu Shortest Word.py
584
4.15625
4
""" https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9/train/python Simple, given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types. """ # mine: def find_short(s): s = s.split() l = 100 # "min_len" is better but autor choose 'l' for i in s: if l > len(i): l = len(i) return l # l: shortest word length # the best someone else's solution in my opinion: def find_short(s): return min(len(x) for x in s.split())
true
980c265e75bd9b82deb0154789a571a19b57cb25
priscillamawuana08/global-coding
/surface_area_and_volume_of_a_sphere.py
281
4.5625
5
#calculating the surface and volume of a sphere import math radius=input("enter the radius of the sphere") SA=4*math.pi*(radius**2) v=(4/3)*math.pi*(radius**3) print(" ") print(" ") print("The surface area of the sphere is:",SA) print(" ") print("The volume of the sphere is:",v)
true
016e4e06492901a326e66423f405ff205d9b1f9b
jlo87/PythonGames
/RockPaperScissorsV3.py
2,424
4.3125
4
# Rock, Paper, Scissors + Sleep function to delay the computer. import random, time, sys # time module for the mini pauses in the sleep function, # sys to allow player to exit the game. print('ROCK, PAPER, SCISSORS') print('By Jonathan Lo') print() # Blank line right here print('- Rock beats scissors.') print('- Paper beats rocks.') print('- Scissors beats paper.') # These variables keep track of the number of wins, losses, and ties. wins = 0 losses = 0 ties = 0 while True: # The main game loop. while True: # Keep asking until player enters R/P/S/Q. print(f'{wins} Wins, {losses} Losses, {ties} Ties') print('Enter your move: (R)ock (P)aper (S)cissors or (Q)uit') playerMove = input().upper() # Allows player to type either upper or lower case, # saved to a variable called playerMove. if playerMove == 'Q': sys.exit() if playerMove == 'R' or playerMove == 'P' or playerMove == 'S': break else: print('Type one of R, P, S, or Q.') if playerMove == 'R': print('ROCK versus...') playerMove = 'ROCK' elif playerMove == 'P': print('PAPER versus...') playerMove = 'PAPER' elif playerMove == 'S': print('SCISSORS versus...') playerMove = 'SCISSORS' # Count to three with dramatic pauses: time.sleep(0.5) print('1...') time.sleep(0.25) print('2...') time.sleep(0.25) print('3...') time.sleep(0.25) # Display what the computer chose: randomNumber = random.randint(1, 3) if randomNumber == 1: computerMove = 'ROCK' elif randomNumber == 2: computerMove = 'PAPER' elif randomNumber == 3: computerMove = 'SCISSORS' print(computerMove) # Display and record the win/lose/tie: if playerMove == computerMove: print('It\'s a tie!') # \ Tells python that the apostrophe is a part of the str. ties += 1 # Increase the value in ties by 1. elif playerMove == 'ROCK' and computerMove == 'SCISSORS': print('You win!') wins += 1 # Increase the value in wins by 1. elif playerMove == 'PAPER' and computerMove == 'ROCK': print('You win!') wins += 1 elif playerMove == 'SCISSORS' and computerMove == 'PAPER': print('You win!') wins += 1 elif playerMove == 'ROCK' and computerMove == 'PAPER': # Handling loss cases. print('You lose!') losses += 1 elif playerMove == 'PAPER' and computerMove == 'SCISSORS': print('You lose!') losses += 1 elif playerMove == 'SCISSORS' and computerMove == 'ROCK': print('You lose!') losses += 1
true
8620e568fa5dc65667f1edfeab3719672f05d99f
freakkid/study-hard
/python_learn/pyfile1/ex40_2.py
612
4.25
4
website = {1: "google", "sec": "baidu", 3: "facebook", "twitter": 4} print website.keys() print website.values() print website.items() print "__key__" # print the key for key in website.keys(): print key, type(key) print "_____" for key in website: print key, type(key) print "__value__" # print the value for value in website.values(): print value print "_____" for key in website: print website[key] print "__items__" #print items for k, v in website.items(): print str(k) + ":" + str(v) print "_____" for k in website: print str(k) + ":" + str(website[k])
false
f901cd96867a36652d012abaa2b2b0116506aacb
freakkid/study-hard
/python_learn/pyfile1/ex16.py
845
4.375
4
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." # read something raw_input("?") print "Opening the file..." target = open(filename, "w") print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." all_line = line1 + "\n" + line2 + "\n" + line3 + "\n" print all_line target.write(all_line) #target.write(line1) #target.write("\n") #target.write(line2) #target.write("\n") #target.write(line3) #target.write("\n") one = "give\n" all_lines = one, "hfho\n" print all_lines print "And finally, we close it." target.close()
true
c45011ecddf79f6663919f447ba4ffb94dd4269d
fedegott/Intro_Scripts
/Basic2.py
2,854
4.125
4
# Exercise for http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html # Write two Python functions to find the minimum number in a list. The first function should compare each number to every other number on the list O(n2). The second function should be linear O(n) import numpy as np import time import matplotlib.pyplot as plt # First Function O(n^2) ############################################################################## ############## The first function should compare each number to every other number on the list O(n2) # arr = np.random.normal(0,100,10) # arr_round = np.round(arr,0) # inputo = int(input('Do you want to see part O(N^2)(press 1) or O(logN) (press 2)?')) # if inputo == 1: total_time = [] def find_n2(N): for i in range(1, N): arr = np.random.randint(0, 100, i) # print(arr) min = arr[0] # first number in the list start = time.time() for x in range(len(arr)): for y in range(len(arr)): # print(arr[x]) # print(arr[y]) # print(arr[x] < arr[y]) if min > arr[y]: min = arr[y] print('The minimum is %d' % min) end = time.time() script_time = end - start print('the time it took is', script_time) total_time.append(script_time) ax = plt.axes() # fig = plt.figure() # np.linspace( start, stop, num) # stop is where to stop, num is number of samples to generate, whose default value is 50 x = np.linspace(1, N - 1, N - 1).round() ax.plot(x, total_time) # ax.plot(x,x*x) ax.set(title='time per input size', xlabel='input size', ylabel='time') ax.grid() plt.show() # the plot should be a parabola. # TODO: fit a N^2 parabole to the plot ##############The second function should be linear O(n) #### TIP: to INDENT a whole selected block just press TAB and SHIFT TAB for UNINDENT # else: def find_n(N): total_time = [] for i in range(1, N): arr = np.random.randint(0, 100, i) # print(arr) min = arr[0] start = time.time() for x in range(len(arr)): if min > arr[x]: min = arr[x] print('The minimum is %d' % min) end = time.time() script_time = end - start print('the time it took is', script_time) total_time.append(script_time) ax = plt.axes() # # fig = plt.figure() # # np.linspace( start, stop, num) stop is where to stop, num is number of samples to generate, whose default value is 50 x = np.linspace(1, N - 1, N - 1).round() ax.plot(x, total_time) # ax.plot(x,x*x) ax.set(title='time per input size', xlabel='input size', ylabel='time') ax.grid() plt.show() N = 500 # input size find_n2(N)
true
2b9c85a7028c8f0885a346e5e0215829a59b2d55
JMicrobium/progra
/pitagoras.py
455
4.25
4
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.""" N=1000 for a in range(1,N+1): for b in range(1,N+1): for c in range(1,N+1): if a+b>=c and a+c>=b and b+c>=a and (a**2)+(b**2)==(c**2) and a+b+c==1000: print(a,b,c)
true
70c23bc62bebca885524fe7a6f1f69b4ea91aae0
EyeDevelop/beginner-friendly-programming-exercises
/Solutions/ex10.py
1,016
4.375
4
# Get the input from the user number = int(input("A number: ")) # To get the last number, we divide by ten, round the number down, multiply it by 10 and subtract it from the number variable. # The division and rounding down happens in one step using the // operator. to_subtract = 10 * (number // 10) # Now we subtract them to get the last digit last_digit = number - to_subtract # Print it out # .format() is explained in previous solutions. print("The last digit of {} is: {}".format(number, last_digit)) # The easiest way to do it is using substrings, which is where you grab a specific part of a string. # Sadly this wasn't allowed in this exercise. # If it were, you'd have this as solution: # number = input("A number: ") # Notice the int() is gone. We do this to get a string, not an integer. # last_digit = number[-1] # We need the last character of number. -1 is a short operator for that, -2 for the second to last character, etc. # # print("The last digit of {} is: {}".format(number, last_digit))
true
cacf16a24103fceb9d424e73c3c30751e4e2c793
itshui3/cs-module-project-iterative-sorting
/src/iterative_sorting/insertion_sort.py
633
4.1875
4
def insertion_sort(arr): # i marks the beginning of the unsorted sub-list for i in range(1, len(arr)): curdex = i while curdex > 0: if arr[curdex] >= arr[curdex - 1]: break else: # arr[curdex - 1], arr[curdex] = arr[curdex], arr[curdex - 1] right_val = arr[curdex] left_val = arr[curdex - 1] arr[curdex] = left_val arr[curdex - 1] = right_val curdex -= 1 return arr # unsorted = [0, 5, 2, 3, 1, 8, 9, 2, 1, 3] # print(insertion_sort(unsorted)) # print(__name__)
true
b1ebd7b740b194d08b1902b000f315f235f2627a
danamkaplan/python_data_structures
/data_structures.py
2,064
4.1875
4
#!/usr/bin/python class Node(object): """ The building block of all the data structures I will build """ def __init__(self, data, pointer=None): self.data = data self.pointer = pointer def __repr__(self): print "%s" % (self.data) def get_data(self): return self.data def set_pointer(self, pointed_node): self.pointer = pointed_node def get_pointer(self): return self.pointer class LinkedList(object): """ """ def __init__(self): self.head = None self.tail = None # init def insert(self, obj): # inserts a new node into the list new_node = Node(obj) if self.head == None: # make new node the head self.head = new_node self.tail = new_node else: # older tail to this new node self.tail.set_pointer(new_node) self.tail = new_node def size(self): # returns size of list counter = 1 if self.head == None: counter = 0 current_node = self.head while current_node != self.tail: counter = counter + 1 current_node = current_node.get_pointer() return (counter) def search(self, obj): # searches list for a node containing the requested data and returns that # node if found, otherwise raises an error end def delete(self, obj): # searches list for a node containing the requested data and removes it # from list if found, otherwise raises an error end def print_list(self): current_node = self.head while current_node != self.tail: print current_node.get_data() current_node = current_node.get_pointer() class Stack(LinkedList): def __init__(self): end def push(obj): end def pop(): return(obj) ''' not quite ready class Queue(LinkedList): def __init__(self): end def '''
true
7c0f53ac104a44eed5aa452ad7ce4617e927e21f
KevinKronk/linear-regression
/plot_data.py
1,564
4.53125
5
from matplotlib import pyplot as plt import numpy as np def plot_data(x, y, theta): """ Plots the data and the linear regression line. Parameters ---------- x : array_like Shape (m, n+1), where m is the number of examples, and n is the number of features including the vector of ones for the zeroth parameter. y : array_like Shape (m,), where m is the value of the function at each point. theta : array_like Shape (n+1, 1). Optimized linear regression parameters. """ # Plots the data without the vector of ones for the zeroth parameter plt.plot(x[1, :], y, 'bo', ms=10, mec='k') # Creates y axis for the linear regression line new_y = np.dot(theta.T, x) plt.plot(x[1, :], new_y.T, '-', color='orange', linewidth=3) plt.title("Corporate Profit per City Population") plt.ylabel('Profit in $10,000') plt.xlabel('Population of City in 10,000s') plt.legend(['Training Data', 'Linear Regression']) plt.show() def plot_cost(iterations, cost_history): """ Plots the cost over each iteration of gradient descent. Parameters ---------- iterations : int The number of iterations for gradient descent. cost_history : list A list of the values of the cost function after each iteration. """ plt.plot(range(iterations), cost_history, linewidth=3) plt.title("Cost History") plt.xlabel("Iterations") plt.ylabel("Cost") plt.show()
true
217812b4701d352d0c2176f331a7a84871b483b9
BraeWebb/bazel-talk
/example/python/decode_enumerator/enumerator.py
1,863
4.46875
4
""" Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. """ def double_count(message): """Count the amount of letters in the message that could be interpreted as a double number. """ doubles = 0 overlaps = 0 last_double_index = -2 for i in range(len(message) - 1): double = int(message[i:i+2]) if double > 26: continue if i - last_double_index == 1: overlaps += 1 doubles += 1 last_double_index = i return doubles, overlaps def solve(message): """ Since each number in the message that can be interpreted as a double digit number essentially has two states we can express each message as a binary number. Where 0 = interpret the possible double digit as a single digit 1 = interpret the possible double digit as a double digit So for the number 127426 we have 12 and 26 as possible numbers that can be interpreted as a double digit. Therefore the possible interpretations are: 00 = each number is a single digit 01 = treat 26 as a double digit 10 = treat 12 as a double digit 11 = treat 12 and 26 as a double digit More generally, the message has 2^k encodings where k is the number of double digits. As this is the possible combinations of a k digit binary number. Finally we need to remove 1 for each overlapping double digit found in the message as the two doubles cannot be interpreted as doubles at the same time. """ doubles, overlaps = double_count(message) return (2 ** doubles) - overlaps def main(): assert solve("111") == 3 assert solve("127426") == 4 if __name__ == '__main__': main()
true