blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5ec9098bbeaa87dd56a064b55169d4c24569277e
m1ghtfr3e/Number-Guess-Game
/Number_guess_game_3trials_FINE.py
853
4.3125
4
"""Guess number game""" import random attempt = 0 print(""" I have a number in mind between 1 and 10. Do you want to guess it? You have 3 tries! Enjoy :) """) letsstart = input("Do you want to start? (yes/no): ") if letsstart == 'yes': print("Let's start") else: print("Ok, see you :) ") computernumber = random.randrange(10) print("I think of a number between 0 and 10") while attempt < 3: guess = int(input("What is your guess?: ")) attempt = attempt + 1 if guess == computernumber: break elif guess <= computernumber: print("My number is bigger than yours") elif guess >= computernumber: print("My number is smaller than yours") if guess == computernumber: print("Nice, you got it! :-)") if guess != computernumber: print("try it again ;-) ")
true
10fabfbedc56aa8401cbe038bd69b8d0938d48f3
mahimadubey/leetcode-python
/maximum_subarray/solution2.py
675
4.15625
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. """ class Solution: # @param A, a list of integers # @return an integer def maxSubArray(self, A): if not A: return 0 res = A[0] cur_sum = A[0] n = len(A) for i in range(1, n): cur_sum = max(cur_sum + A[i], A[i]) res = max(res, cur_sum) # If negative sum is not allowed, add the following line: # if res < 0: return 0 return res
true
dcbe94018816bda8efcd8e5b702eb328c136d52f
binhyc11/MIT-course-6.0001
/Finger exercise 4.1.1.py
409
4.15625
4
# Write a function isIn that accepts two strings as arguments and # returns True if either string occurs anywhere in the other, and False otherwise. # Hint: you might want to use the built-in str operation in. def isIn (x, y): if x in y or y in x: return True else: return False x = input ('Enter a string: ') y = input ('Enter a string: ') z = isIn (x, y) print (z)
true
0727891d7bb90fcf5cdf57f35826dc033db1047c
Yogini824/NameError
/PartA_q3.py
2,401
4.53125
5
'''The game is that the computer "thinks" about a number and we have to guess it. On every guess, the computer will tell us if our guess was smaller or bigger than the hidden number. The game ends when we find the number.Also Define no of attemps took to find this hidden number.(Hidden number lies between 0 - 100)''' import random # importing random file to generate a random number def guess(n): # defining a function to guess hidden number c=1 # taken variable to count the number of chances a=0 # taken a variable for reference to check thet user guessed the number while c<=5: # As there are 5 chances to guess while loop runs for 5 times k=int(input("Guess a number: ")) # taken a variable to guess a number if(k==n): # if guessed number is equal to hidden number print("Hidden number is",H,",You have won the game in",c,"chances") # printing that user has guessed the number a=1 # making the variable for reference to 1 to know that number has been guessed break # after guessing there is no need for while so break it elif(c!=5): # if the count not equal to 5 if(k<n): # and if guessed number lessthan hiddden print("Hidden number is greater, Guess again") # print hidden is greater else: # if not print("Hidden number is lesser, Guess again") # print hidden is lesser c+=1 # counting the chances adding 1 if(a==0): # if reference variable is 0 then user havent guessed the number print("Sorry, Your chances are over") # printing chances are over H= random.randint(0,100) # taken a variable to store random number generated by randint in range of 0-100 guess(H) # calling the function to guess the number
true
ceaf43928789e3a45e0d54d0b9bf756506f5a251
Yogini824/NameError
/PartB_q3.py
1,082
4.15625
4
'''Develop a Python Program which prints factorial of a given number (Number should be User defined)''' def factorial(n): # calling function to calculate factorial of given number if n<0: # checking if n is positive or not print("Enter a positive number") # if negative print to entner positive number elif n==0: # checking whether n is 0 or not return 1 # if 0 return 1 as the factorial of 0 is 1 else: # if n is positive return factorial(n-1)*n # return the multiplication of calling the function(recursion) to 1 less to n and n n=int(input("Enter a number : ")) # taking the input of a number for which we need factorial k=factorial(n) # taking a variable and calling function and the returned value from the function is assigned to variable print("Factorial of",n,"is",k) # printing the factorial of given number
true
a139f9e0778fbd1d1fb3754cdcbd02bd308c5cc9
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/medium/inorder_binary_tree_traversal.py
886
4.1875
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: """ Time complexity: O(N) since visit exactly N nodes once. Space complexity: O(N) for skew binary tree; O(log N) for balance binary tree. Space due to recursive depth stack space Runtime: 32 ms, faster than 92.54% of Python3 online submissions for Binary Tree Inorder Traversal. """ def values(node: TreeNode, nums: List[int]) -> List[int]: if not node: return nums values(node.left, nums) nums.append(node.val) values(node.right, nums) return nums return values(root, [])
true
20f07ae9d39e0b191f52d4cc155a94493d1525b6
pagsamo/google-tech-dev-guide
/leetcode/recursion/reverse_string.py
419
4.15625
4
from typing import List def reverse_string(s:List[str]) -> None: """ To practice use of recursion """ def helper(start, end): if start < end: s[start], s[end] = s[end], s[start] helper(start + 1, end - 1) print("before", s) n = len(s) if n > 1: helper(0, n - 1) print("after", s) if __name__ == "__main__": reverse_string(["h", "e", "l", "l", "o"])
true
3231ef6292673615fafdfb53aa733d57ffc3c61b
pagsamo/google-tech-dev-guide
/70_question/dynamic_programming/water_area.py
1,119
4.1875
4
""" Water Area You are given an array of integers. Each non-zero integer represents the height of a pillar of width 1. Imagine water being poured over all of the pillars and return the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored. Sample input: [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3] Sample output: 48. """ def waterArea(heights, debug=False): n = len(heights) left_max = [0] * n right_max = [0] * n i = 1 while i < n: # Compute the max to the left/right of index i left_max[i] = max(heights[:i]) right_max[n-1-i] = max(heights[n - i:]) i += 1 area = 0 for l, r, pillar in zip(left_max, right_max, heights): min_height = min(l, r) if pillar < min_height: area += min_height - pillar if debug: print(heights) print(left_max) print(right_max) print("The water area for {} is {}".format(heights, area)) return area if __name__ == "__main__": x = [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3] waterArea(x)
true
4983f02c95329f98637ab43444ee4bf4e2da8346
sresis/practice-problems
/CTCI/chapter-1/string-rotation.py
799
4.125
4
# O(N) import unittest def is_substring(string, substring): """Checks if it is a substring of a string.""" return substring in string def string_rotation(str1, str2): """Checks if str2 is a rotation of str1 using only one call of is_substring.""" if len(str1) == len(str2): return is_substring(str1+str1, str2) return False print(is_substring('football', 'ball')) class Test(unittest.TestCase): '''Test Cases''' data = [ ('waterbottle', 'erbottlewat', True), ('foo', 'bar', False), ('foo', 'foofoo', False) ] def test_string_rotation(self): for [s1, s2, expected] in self.data: actual = string_rotation(s1, s2) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()
true
23114beb0d00f2b55d54c4c9390c41d6c89dc70e
sresis/practice-problems
/recursion-practice/q6.py
553
4.25
4
""" Write a recursive function that takes in a list and flattens it. For example: in: [1, 2, 3] out: [1, 2, 3] in: [1, [1, 2], 2, [3]] out: [1, 1, 2, 2, 3] """ def flatten_list(lst, result=None): ## if length of item is > 1, flatten it result = result or [] for el in lst: if type(el) is list: flatten(el, result) else: result.append(el) return result if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. RIGHT ON!\n")
true
dbd89843d85f927c8fb764183a2516d10863b26f
KyrillMetalnikov/A01081000_1510_V2
/lab07/exceptions.py
1,761
4.375
4
import doctest """Demonstrate proper exception protocol.""" def heron(number) -> float: """ Find the square root of a number. A function that uses heron's theorem to find the square root of a number. :param number: A positive number (float or integer) :precondition: number must be positive. :postcondition: A close estimate of the square root will be found :return: A close estimate of the square root as a float. >>> heron(9) 3.0 >>> heron(5.5) 2.345207879911715 """ try: if number < 0: number / 0 except ZeroDivisionError: print("Error: The number provided must be positive!") return -1 square_root_guess = number # arbitrary value for the heron formula for _ in range(0, 1000): # arbitrary amount of runs that get it close enough square_root_guess = (square_root_guess + (number / square_root_guess)) / 2 return square_root_guess def findAnEven(input_list: list) -> int: """ Return the first even number in input_list :param input_list: a list of integers :precondition: input_list must be a list of integers :postcondition: return the first even number in input_list :raise ValueError: if input_list does not contain an even number :return: first even number in input_list >>> findAnEven([1, 3, 5, 6, 8, 9]) 6 >>> findAnEven([2]) 2 """ even_number = [] for value in input_list: if value % 2 == 0: even_number.append(value) break if len(even_number) == 0: raise ValueError("input_list must contain an even number!") return even_number[0] def main(): heron(-1) doctest.testmod() if __name__ == "__main__": main()
true
6962206a6b3052cb75d5887eefc836a25b73df7e
KyrillMetalnikov/A01081000_1510_V2
/lab02/base_conversion.py
1,924
4.40625
4
""" Convert various numbers from base 10 to another base """ def base_conversion(): """ Convert a base 10 number to another base up to 4 digits. A user inputs a base between 2-9 then the program converts the input into an integer and displays the max number possible for the conversion. The user then inputs a number within allowed parameters which gets converted then the resulting conversion is displayed to the user. """ base = int(input("What base (2-9) do you want to convert to?")) # inputted base converts to int and is then stored print("The max value allowed is ", max_value(base)) number_base_10 = int(input("Please input the base 10 integer you wish to convert")) # inputted num is stored as int print(base_converter(number_base_10, base)) def max_value(base): """ Find the max possible value in a base conversion. Function uses an algorithm find the maximum value the conversion can hold when moving from base 10 using 4 digits :param base: the base being converted to: type integer :return: returns the max value the base can be converted to assuming there's 4 digits """ return base ** 4 - 1 def base_converter(number_base_10, base): """ Convert a number from base 10 to target base. Function uses an algorithm to convert a number from base 10 to a target base up to 4 digits :param number_base_10: the number in base 10 being converted: type integer :param base: the target base being converted to: type base :return: returns the 4 digits the base 10 number was converted to """ num0 = number_base_10 // base digit0 = str(number_base_10 % base) num1 = num0 // base digit1 = str(num0 % base) num2 = num1 // base digit2 = str(num1 % base) digit3 = str(num2 % base) return digit3 + digit2 + digit1 + digit0 if __name__ == "__main__": base_conversion()
true
b0bdc1aef3cbdb35b9d6745ef02046a1449d389a
nandansn/pythonlab
/Learning/tutorials/chapters/operators/bitwise.py
477
4.3125
4
# Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) print("bitwise {} and {}".format(x,y), x & y) print("bitwise {} or {}".format(x,y), x | y) print("bitwise not of {} ".format(x), ~x) print("bitwise {} xor {}".format(x,y), x ^ y) print("bitwise right shift".format(x), x >> 2) print("bitwise left shift".format(x), x << 2)
true
83e8412a46c0f05b0d7c37a92f90bd768ddb073f
nandansn/pythonlab
/Learning/tutorials/chapters/operators/comparison.py
556
4.125
4
x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) #check equal print("check {} and {} are equal".format(x,y),x == y) #check not equal print("check {} and {} are not equal".format(x,y),x != y) #check less than print("check {} is less than {} ".format(x,y),x <y) #check greater than print("check {} is greater than {} ".format(x,y),x > y) #check less than or equal print("check {} less than or equal to {}".format(x,y),x <= y) #check greater than equal print("check {} greater than or equal to {} ".format(x,y),x >= y)
true
a15aa28ac9f40f41a1b9c49ba70254c10d224139
nandansn/pythonlab
/durgasoft/chapter35/dict.py
797
4.25
4
''' update dictionary, ''' d = {101:'durga',102:'shiva'} d[103] = 'kumar' #if key not there, new value will be added. d[101]='nanda' #if key already available, new value will be updated. print(d) ' how to delete elements from the dictionary ' del d[101] # if the key present, then the key and value will be removed print(d) try: del d[101] except KeyError as key: print('key {} not available in {}'.format(key,d)) d.clear() ' to clear all the key/value pairs in dict' print(d) d.update({101:'abc'}) try: del d # this object is available for garbage collection. except NameError as name: print ('{} is not defined'.format(name)) 'how to speciy multiple values for the key' a={} a[100]=['nanda','kumar','k'] print(a)
true
b002c745c7813fb63f8ab1b327697342df62cbd7
nandansn/pythonlab
/durgasoft/chapter47/random-example.py
427
4.15625
4
from random import * for i in range(10): print(random()) for i in range(10): print(randint(i,567)) # generat the int value, inclusive of start and end. for i in range(10): print(uniform(i,10)) #generate the float value, within the range. not inclusive of start and end values. for i in range(10): print('random numbers') print(randrange(1,11,3)) # generate the random number with step value
true
89bad08e5b41e99386f42b0913f5434a4f6e9845
nandansn/pythonlab
/Learning/tutorials/chapters/operators/identity.py
331
4.28125
4
# is and is not are the identity operators in Python. # They are used to check if two values (or variables) are located on the same part of the memory. x ="hello" y ="hello" print("x is y", x is y) y = "Hello" print("x is y", x is y) print(" x is not y", x is not y) x = [1,2,3] y = [1,2,3] print("x is not y", x is not y)
true
20fde4ae652feef6eca4d69dbb116d740b9a2e28
nandansn/pythonlab
/Learning/forloopexample.py
311
4.1875
4
week_days = ['monday','tuesday','wednessday','thursday','friday'] week_ends= ['saturday','sunday'] count = 10; for c in range(count): print(c) for day in week_days: print(day) else: for day in week_ends: print(day) employees = {'name':'nanda'} for emp in employees: print(emp)
false
12fe67f6785b89a35ace0769e2733d45660b6b23
nandansn/pythonlab
/durgasoft/chapter33/functions_of_tuple.py
395
4.34375
4
''' functions of tuple: ''' 'len()' t = tuple(input('enter tuple:')) print(t) print(len(t)) 'count occurence of the elelement' print(t.count('1')) '''sorting: natural sorting order ''' t=(4,3,2,1) print(sorted(t)) print(tuple(sorted(t))) print(tuple(sorted(t,reverse=True))) 'min and max method to find in the tuple...' print(max(t)) print(min(t))
true
13477e55ca09f571ac8ed4a1d2c0bf8ee6b87a45
nandansn/pythonlab
/durgasoft/chapter15/using-eval-function.py
716
4.1875
4
print(""" we can use eval function to read data, when we use eval function no need to make type conversion""") #a,b,c,d,e=eval([x for x in input("Enter data:").split()]) a = eval(input("enter a:")) b = eval(input("enter b:")) c = eval(input("enter c:")) d = eval(input("enter d:")) e = eval(input("enter e:")) print("value:",a,"type:",type(a)) print("value:",b,"type:",type(b)) print("value:",c,"type:",type(c)) print("value:",d,"type:",type(d)) print("value:",e,"type:",type(e)) a,b,c,d,e=[eval(x) for x in input("Enter data:").split()] print("value:",a,"type:",type(a)) print("value:",b,"type:",type(b)) print("value:",c,"type:",type(c)) print("value:",d,"type:",type(d)) print("value:",e,"type:",type(e))
false
581ad96b03b49138a25783d9cacd4bb132984259
nandansn/pythonlab
/durgasoft/chapter13/shiftoperators.py
272
4.53125
5
print(""" shift operators how it works""") print (1 << 2) # Rotate left most 2 bits to the right most. print ( 10 >> 2) # Rotate right most 2 bits to the left most. # for positive numbers left most bit is 0 # for negative numbers right most bit is 1 print (-10 >> 2)
true
9ff4380dbf6e147c1ed42a320aa4fc16a123b92c
nandansn/pythonlab
/durgasoft/chapter35/functions-in-dict.py
1,274
4.5
4
'function: to create empty dict' d = dict() 'function: to create dict, by using list of tuples' d= dict([(100,'nanda'),(200,'kumar'),(300,'nivrithi'),(400,'valar')]) print(d) '''functions: dict() list of tuples, set of tuples, tuple of tuples. ''' 'fucntion:length of dict' print(len(d)) print(d.get(100)) print(d.get(101)) # if key not present, then none will be returned. print(d.get(101,'No value')) # o/p will be 'No value' 'to remove the value of the corresponding key' print(d.pop(100)) # returns the value print(d) d.popitem() # key will be chosen randaomly, and corresponding key/value removed and value returned. print(d) 'to get the keys in the dictionary, returned is not list object. it is dict_keys' print(d.keys()) 'to get only the values, returned is type of dict_values' print(d.values()) 'to get the items(key,value), returned type is dict_items' print(d.items()) for k,v in d.items() : print('key:{}, value:{}'.format(k,v)) d1= d.copy() print(d1) ''' if key already avaliable, return the existing value for the key, if the key unavailable, add the value for that key.return the newly added value. ''' print(d.setdefault('109','nanda') ) print(d.setdefault('200','jkl')) print(d)
true
12ce3055d8595e5e0be0910da1498e92cad8256e
nandansn/pythonlab
/durgasoft/chapter15/read-data.py
256
4.3125
4
print("""We have input function to read data from the console. The data will be in str type we need to do type conversion.""") dataFromConsole = input("Enter data:") print("type of input is:", type(dataFromConsole)) print(type(int(dataFromConsole)))
true
ca5af9fee83c047ecce7df3a506a0bcaf779ee7c
ziGFriedman/Useful_code_snippets
/Strings/Is_lower_case.py
314
4.21875
4
'''Преобразует строку в верхний регистр при помощи метода str.lower() и сравнивает ее с оригиналом.''' def is_lower_case(str): return str == str.lower() print(is_lower_case('abc')) print(is_lower_case('a3@$')) print(is_lower_case('Ab4'))
false
8b747601f10131996032aecdfc6375f4c2e99c4e
ziGFriedman/Useful_code_snippets
/Mathematics/Factorial.py
638
4.53125
5
'''Вычисляется факториал числа.''' # Используется рекурсия. Если num меньше или равно 1, возвращается 1, а # иначе – произведение num и factorial из num — 1. Сработает исключение, # если num будет отрицательным или числом с плавающей точкой. def factorial(num): if not ((num >= 0) & (num % 1 == 0)): raise Exception("Number( {num} ) can't be floating point or negative ".format(num)) return 1 if num == 0 else num * factorial(num - 1) print(factorial(6))
false
d667e5a3f4185900a22a751283b9346b5af2613d
aalabi/learningpy
/addition.py
233
4.1875
4
# add up the numbers num1 = input("Enter first number ") num2 = input("Enter second number ") # sum up the numbers summation = num1 + num2 # display the summation print("The sum of {0} and {1} is {2}".format(num1, num2, summation))
true
aa478143bf9f657b6938650e8d174dcb016d5f39
Yvonnekatama/control-flow
/conditionals.py
875
4.125
4
# if else age=25 if age >= 30: print('pass') else: print('still young') # ternary operator temperature=30 read="It's warm today" if temperature >= 35 else "Wear light clothes" print(read) # if elif else name='Katama' if name=='Yvonne': print('my name') elif name=='Katama': print("That's my sur name") elif name=='Muelani': print("That's my nick name") else: print("I do'nt know who that is") # logical operators and chained conditionals user='Student' logged_in=False if user=='Student' and logged_in == False: print('Student page') else: print('Admin page,password required') user='Student' logged_in=True if not logged_in: print('Please log in') else: print('Key in user password') user='Admin' logged_in=True if user=='Admin' or logged_in== True: print('Admin page') else: print('Student page,password required')
true
ee9e2becf70d3d9fc94ee4b6121913fa3cffd1ce
maloMal/Spirograph
/drawCircle.py
345
4.28125
4
import math import turtle #Draw the circle using turtle. def drawCircleTurtle(x, y, r): #move to the start of circle turtle.up() turtle.setpos(x + r, y) turtle.down() #Draw the circle for i in range(0, 365, 6): a = math.radians(i) turtle.setpos(x + r*math.cos(a), y + r*math.sin(a)) drawCircleTurtle(100, 100, 50) turtle.mainloop()
false
a4509cc29dfe24626d1f60e8c067b8078d039f75
syurskyi/Math_by_Coding
/Programming Numerical Methods in Python/2. Roots of High-Degree Equations/2.1 PNMP_2_01.py.py
287
4.15625
4
''' Method: Simple Iterations (for-loop) ''' x = 0 for iteration in range(1,101): xnew = (2*x**2 + 3)/5 if abs(xnew - x) < 0.000001: break x = xnew print('The root : %0.5f' % xnew) print('The number of iterations : %d' % iteration)
true
995c5e8d0ebb7a3012580a18c3bc14fcc15b187b
koheron2/pyp-w1-gw-language-detector
/language_detector/main.py
1,194
4.25
4
# -*- coding: utf-8 -*- """This is the entry point of the program.""" from collections import Counter def detect_language(text, languages): words_appearing = 0 selected_language = None """Returns the detected language of given text.""" for language in languages: words = len([word for word in language['common_words'] if word in text]) if words > words_appearing: words_appearing = words selected_language = language['name'] return selected_language def most_common_word(text): words = text.split() counted_words = Counter(words) most_common = counted_words.most_common(1)[0][0] return most_common def percentage_of_language(text, languages): words = text.split() percent_dict = {} percentages = "" #return percentage of each language for language in languages: lang_words = [word for word in language['common_words'] if word in text] percentage = 100 * len(lang_words)/len(words) percent_dict[language['name']] = "%.2f" % percentage for key, val in percent_dict.items(): percentages += key + ": "+val+"\n" return percentages
true
2970e898dbf7767dded0fca56e0c7cc30b32c3b9
bmallia/python_exercise
/source/symetric_difference.py
890
4.125
4
""" O termo matemático Symetric Difference (t ou B) de 2 conjuntos é um conjunto de elementos no qualquer um dos conjuntos mas não em ambos. Por exemplo: A = {1,2,3} e B = {2,3,4}, A E B = {1,4} Symetric difference é uma operação binária, isso significa que ela opera em apenas elementos. Então para avaliar uma expressão envolvendo symetric difference entre 3 elementos (A e B e C), você deve completar uma operação por vez. Exemplo: C = {2, 3}, A e B e C = (A e B) e C = {1,4} e {2,3} """ def sym(*args): sym_diff = set() for item in args: if sym_diff: a = __sym_pair__(sym_diff, item) a.extend(__sym_pair__(item, sym_diff)) sym_diff = a else: sym_diff = item return sorted(set(sym_diff)) def __sym_pair__(set_a, set_b): return [a for a in set_a if a not in set_b]
false
ed9c6d0b1ed6101d3aac0c6c75eaff51152b851d
joecmama/Python_0a
/02.py
868
4.21875
4
#!/usr/bin/env python # basic math print(2+3) # addition print(2*3) # multiplication print(2**3) # exponentiation # # # in python2: / means integer division (truncation) for integers # # and floating pt division for floating point number # # # # in python3: / always means floating point division (like perl) print(2/3) print(4/3) print(2.0/3.0) # # # either python2 or python3: // means integer division print(7//3) print(2.0//3.0) print(5.0 % 2.0) # remainder # # # one equals sign: assignment a = 37 print(a == 37) # two equals signs: comparison print(a < 40) print(a >= 12) # # # chained comparisons print(36 < a < 38) print(36 < a < 37) # # # Boolean operators b = 21 print(a == 37 and b == 20) print(a == 37 or b == 19) print(a != 37) print(not a == 37 ) # # # C style assignment operators a = 11 print(a) a += 2 print(a) a += 1 # # no a++ ! print(a)
false
77dec46a9d7fe561822d3ca4507ecbf773c433c0
joecmama/Python_0a
/03.py
469
4.28125
4
#!/usr/bin/env python # basic string operations a = 'hello ' b = 'world' c = a+b print(c) print(a == 'hello') print(a < 'zebra') print(a > 'zebra') print(a < 'aardvark') print(a != 'hello ') # print(c) print(c.startswith('hello')) print(c.endswith('world')) print(len(c)) # length of a string # print('lo wo' in c) # c contains a substring? print(c.find('lo wo')) print(c.find('blahbedy')) print(c.find('o')) # d = c.replace('hello','hi there') print(c) print(d)
false
690170d51cd1f93932925e019f01d1f7dd90712e
gladysmae08/project-euler
/problem19.py
1,430
4.375
4
# counting sundays ''' You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' month_days = { 'jan' : 31, 'feb' : 28, 'mar' : 31, 'apr' : 30, 'may' : 31, 'jun' : 30, 'jul' : 31, 'aug' : 31, 'sep' : 30, 'oct' : 31, 'nov' : 30, 'dec' : 31 } month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 366%7 = 2; 1 jan 1901 = wed year = 1901 sunday_count = 0 day_count = 1 is_sunday = lambda x : (x % 7 == 6) while (year < 2001): for month in month_lengths: if month == 28 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): month += 1 day_count += month if is_sunday(day_count): sunday_count += 1 year += 1 if is_sunday(day_count): sunday_count -= 1 print(sunday_count)
true
c9f7b46835e56102fd280a80f992b6b2a5d76cd3
shubhamrocks888/linked_list
/create_loop_or_length_loop.py
1,198
4.125
4
class node: def __init__(self,data=None): self.data = data self.next = None class linked_list: def __init__(self): self.head = None def push(self,data): new_node = node(data) new_node.next = self.head self.head = new_node # Function to create a loop in the # Linked List. This function creates # a loop by connnecting the last node # to n^th node of the linked list, # (counting first node as 1) def create_loop(self,n): loop_node = self.head for _ in range(1,n): loop_node = loop_node.next end_node = self.head while end_node.next: end_node = end_node.next end_node.next = loop_node def length(self): cur_node = self.head l = [] while cur_node: if cur_node in l: print (len(l)-l.index(cur_node)) return l.append(cur_node) cur_node = cur_node.next print ("loop not exists") li = linked_list() li.push(1) li.push(2) li.push(3) li.push(4) li.create_loop(4) ## Create a loop for testing ##li.head.next.next.next.next = li.head li.length()
true
5e82215b548f332f5f56d1270345d01d38db1c80
Explorerqxy/review_practice
/025.py
1,049
4.28125
4
def PrintMatrixClockwisely(numbers, columns, rows): if numbers == None or columns <= 0 or rows <= 0: return start = 0 while columns > start * 2 and rows > start * 2: PrintMatrixInCircle(numbers, columns, rows, start) start += 1 def PrintMatrixInCircle(numbers, columns, rows, start): endX = columns -1 - start endY = rows - 1 - start #从左到右打印一行 for i in range(start, endX+1): number = numbers[start][i] printNumber(number) #从上到下打印一列 if start < endY: for i in range(start+1, endY+1): number = numbers[i][endX] #从右到左打印一行 if start < endX and start < endY: for i in range(endX-1, start-1, -1): number = numbers[endY][i] printNumber(number) #从下到上打印一列 if start < endX and start < endY -1: for i in range(endY-1, start, -1): number = numbers[i][start] printNumber(number) def printNumber(number): print(number)
true
47a42cfced82ca19f33265c6d5752766e7163756
mariocpinto/0009_MOOC_Python_Data_Structures
/Exercises/Week_03/assignment_7_1.py
502
4.6875
5
# 7.1 Write a program that prompts for a file name, # then opens that file and reads through the file, # and print the contents of the file in upper case. # Use the file words.txt to produce the output below. # You can download the sample data at http://www.pythonlearn.com/code/words.txt file_name = input('Enter Filename: ') try: file_handle = open(file_name,'r') except: print('Error opening file.') exit() for line in file_handle : line = line.rstrip() print(line.upper())
true
55a730379685d64d717df81c1306430f6c6c5255
brash99/phys441
/nmfp/Cpp/cpsc217/area_triangle_sides.py
775
4.25
4
#!/usr/bin/env python import math s1 = input('Enter the first side of the triangle: ') s2 = input('Enter the second side of the triangle: ') s3 = input('Enter the third side of the triangle: ') while True: try: s1r = float(s1) s2r = float(s2) s3r = float(s3) if s1r<=0 or s2r<=0 or s3r<=0: print ("The side lengths must be greater than zero!!") break s = (s1r+s2r+s3r)/2.0 term = area = math.sqrt(s*(s-s1r)*(s-s2r)*(s-s3r)) print ("The area of a triangle with side lengths, %.3f, %.3f, and %.3f is %.3f." % (s1r,s2r,s3r,area)) break except ValueError: print("The values must be real numbers!!") break print('Exiting ... bye!')
true
c8216213d129bd12d845771e8a87f7b06eeb11fa
brash99/phys441
/digits.py
783
4.21875
4
digits = [str(i) for i in range(10)] + [chr(ord('a') + i) for i in range(26)] # List of digits: 0-9, a-f num_digits = int(input("Enter the number of digits: ")) # User input for the number of digits possible_numbers = [] # List to store the possible numbers def generate_numbers(digit_idx, number): if digit_idx == num_digits: possible_numbers.append(number) return for digit in digits: if digit_idx == 0 and digit == '0': continue # Exclude leading zero generate_numbers(digit_idx + 1, number + digit) generate_numbers(0, '') # Print the list of possible numbers #for number in possible_numbers: # print(number) print ("length = ", len(possible_numbers)) print ("predicted length = ",35*36**(num_digits-1))
true
4ccceec7ce99deb87c2465b14de535a4108100f7
brash99/phys441
/JupyterNotebooks/DataScience/linear_regression.py
1,380
4.34375
4
import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # create some data # # N.B. In linear regression, there is a SINGLE y-value for each data point, but there # may be MULTIPLE x-values, corresponding to the multiple factors that might affect the # experiment, i.e. y = b_1 * x_1 + b_2 * x_2 + b_3 * x_3 + ..... # Therefore, the x data is a TWO DIMENSIONAL array ... the columns correspond to the different # variables (x_1, x_2, x_3, ...), and the rows correspond to the values of those variables # for each data point. # # Data is y = x with some noise x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape((-1, 1)) y = np.array([1.1, 2.1, 2.9, 3.9, 5.1, 5.9, 6.9, 8.05, 9.1, 9.7]) print(x) print(y) # Linear Regression Model from scikit-learn model = LinearRegression() model.fit(x, y) r_sq = model.score(x, y) print(f"Correlation coefficient R^2: {r_sq}") print(f"intercept: {model.intercept_}") # beta_0 print(f"slope: {model.coef_}") # beta1, beta2, beta3, etc. x_low = min(x) x_high = max(x) x_pred = np.linspace(x_low, x_high, 100) y_pred = model.predict(x_pred) # print (y_pred) # Plotting! plt.plot(x, y, 'o', label='Data') plt.plot(x_pred, y_pred, 'r-', label="Linear Regression Fit") plt.title("Basic Linear Regression") plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.show()
true
b3fc68dceb1f57d89daa42ec09c214fe0807897c
mbarbour0/Practice
/Another Rock Paper Scissors Game.py
1,481
4.15625
4
# Yet another game of Rock Paper Scissors import os import random from time import sleep options = {"R": "Rock", "P": "Paper", "S": "Scissors"} def clear_screen(): """Clear screen between games""" if os.name == 'nt': os.system('cls') else: os.system('clear') def play_game(): """General function to call game play""" clear_screen() user_choice = input("Please enter 'R' for Rock, 'P' for Paper, or 'S' for Scissors\n>>> ").upper() if user_choice in list(options.keys()): print("You have selected {}.".format(options[user_choice])) else: print("Please select a valid option") exit() print("The computer is now selecting...") sleep(1) computer_choice = random.choice(list(options.keys())) print("The computer has selected {}.".format(options[computer_choice])) sleep(1) decide_winner(user_choice, computer_choice) def decide_winner(user_choice, computer_choice): """Function call to decide winner of the game""" if user_choice == "P" and computer_choice == "R": print("You win") elif user_choice == "R" and computer_choice == "S": print("You win") elif user_choice == "S" and computer_choice == "P": print("You win") elif user_choice == computer_choice: print("You tied") else: print("You lost") while __name__ == "__main__": play_game() quit_game = input("Continue? [Yn]\n>>> ").lower() if quit_game == 'n': break
true
dcb6d89fedc9ab9c2cd884a73904cf27633ba719
shraysidubey/pythonScripts
/Stack_using_LinkedList.py
1,634
4.21875
4
#Stack using the LinkedList. class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def appendHaed(self,new_data): new_node = Node(new_data) #create the new node 370__--> head new_node.next = self.head self.head = new_node #New_node Link to head def deleteHead(self): if self.head is None: print("Head is not in the LinkedList") return self.head = self.head.next def isEmpty(self): if self.head is None: return True else: return False def printList(self): temp = self.head while(temp!= None): print(str(temp.data) + "-->", end = " ") temp = temp.next return print() class Stack: def __init__(self): self.list = LinkedList() def push(self, item): self.list.appendHaed(item) return self.list def pop(self): if self.list.isEmpty(): print("Stack is empty") else: self.list.deleteHead() def printStack(self): self.list.printList() L = Stack() print("-------") L.push("1") L.printStack() print("-------") L.push("w") L.printStack() print("-------") L.push("r") L.printStack() print("-------") L.push("j") L.printStack() print("-------") L.push("t") L.printStack() print("-------") L.pop() L.printStack() print("-------") L.pop() L.printStack() L.pop() L.printStack() #print(L.list.head.data)
true
f0e18b65f8e66a9255a9dc7d110b775f916b6ff4
nvcoden/working-out-problems
/py_2409_1.py
744
4.21875
4
''' Question 1 Create methods for the Calculator class that can do the following: 1. Add two numbers. 2. Subtract two numbers. 3. Multiply two numbers. 4. Divide two numbers. Sample Output :- calculator = Calculator() calculator.add(10, 5) ➞ 15 calculator.subtract(10, 5) ➞ 5 calculator.multiply(10, 5) ➞ 50 calculator.divide(10, 5) ➞ 2 ''' class Calculator: def add(i,j): return i+j def subtract(i,j): return i-j def multiply(i,j): return i*j def divide(i,j): return i/j i = int(input("Enter the First no\n")) j = int(input("Enter the Second no\n")) print(Calculator.add(i,j)) print(Calculator.subtract(i,j)) print(Calculator.multiply(i,j)) print(Calculator.divide(i,j))
true
d16573cb2c78191a598895329f1889df7258c235
chaoshenglu/learnPythonEasily
/5基本数据类型之Tuple/2.Tuple.py
547
4.125
4
# 如何用元祖来表示全班同学的姓名? students = ('小明', '小红', '小强') # 如何获取元祖中第三个同学的姓名? print(students[2]) # 如何获取元祖中倒数第二个同学的姓名? print(students[-2]) # 如何获取元祖的第1个到第3个元素? print(students[0:3]) # 如何获取元祖的第1个到第-3个元素 print(students[0:-2]) # 将这个元祖重复两遍,形成一个新的元祖 students = students * 2 # 方法一 # students = students + students # 方法二 print(students)
false
eed94415f3966db3f3a0f7cd64af3ca53211b703
chaoshenglu/learnPythonEasily
/4基本数据类型之List/4.List.py
423
4.1875
4
cities = ['北京', '上海', '深圳', '广州'] # 访问数组的第1个元素 print("cities[0]: ", cities[0]) # 访问数组的第1个到第3个元素 print("cities[0:3]: ", cities[0:3]) # 访问数组的第1个到第-3个元素 print("cities[0:-2]: ", cities[0:-2]) # 将这个数组重复两遍,形成一个新的数组 cities = cities * 2 print(cities) # 遍历这个数组 for city in cities: print(city)
false
ff659057aa4b939990bb320b3e2223d0e368ef20
yujun858/mypython
/day29_1121_python/example02.py
1,246
4.34375
4
# 享元模式; # 咖啡出售系统 class Coffee(): name ='' price=0 def __init__(self,name): self.name = name self.price = len(name)#假设咖啡价格咖啡名字 def show(self): print('Coffee Name: %s Coffee Price %f'%(self.name,self.price)) class Customer(): name ='' coffeeFactory = '' def __init__(self,name,coffeeFactory): self.name = name self.coffeeFactory = coffeeFactory def order(self,coffee_name): print('Customer: %s ordered Coffee: %s'%(self.name,coffee_name)) return self.coffeeFactory.getCoffee(coffee_name) class CoffeeFactory(): coffeeDict ={} def getCoffee(self,name): if self.coffeeDict.__contains__(name) == False: self.coffeeDict[name] = Coffee(name) return self.coffeeDict[name] def coffeeCount(self): print(self.coffeeDict) return len(self.coffeeDict) if __name__ == '__main__': coffeeFactory = CoffeeFactory() c1 = Customer('YuJUn',coffeeFactory) co1 = c1.order('cappuccino') co1.show() co2 = c1.order('c2') co2.show() c2 = Customer('YJ',coffeeFactory) co3 = c2.order('c3') co4 = c2.order('c2') print(coffeeFactory.coffeeCount())
false
e2164210c928ad2d6db88c61eab833d8ab5a199a
rajjoan/PythonSamples
/Chapter 5/ADcalculator.py
729
4.34375
4
# Get user input num1 = input("Enter a number : ") num2 = input("Enter another number : ") symbol = input("Enter a symbol (* + - /) : ") # Subtraction if symbol == "-": if num2 >= num1: print(int(num2)-int(num1)) else: print(int(num1)-int(num2)) # Division if symbol == "/": if num2 >= num1: print(float(num2) / float(num1)) else: print(float(num1) / float(num2)) # Multiplication if symbol == "*": if num2 > num1: print(float(num2) * float(num1)) else: print(float(num1) * float(num2)) # Addition if symbol == "+": if num2 > num1: print(int(num2) + int(num1)) else: print(int(num1) + int(num2))
false
e853965a25662783b57054c0bf75a09a9ebe3615
rajjoan/PythonSamples
/Chapter 13/function7.py
215
4.25
4
def evenorodd(number): if number % 2 == 0: print("The number is even") else: print("this number is odd") n=int(input("Enter a number to finf even or odd : ")) evenorodd(n)
true
7fcf47e618ff34c9011d3cbd6ffca9bbaebff4b7
kuxingseng/learnPython
/TestItertools.py
544
4.1875
4
# 操作迭代器对象 # count # 死循环 # import itertools # natuals = itertools.count(1) # for n in natuals: # print(n) import itertools ns = itertools.repeat('abc', 2) for n in ns: print(n) # chain 串联迭代器 for c in itertools.chain('abc', 'def'): print(c) # groupby 把迭代器中相邻的重复元素挑出来放在一起 for key, group in itertools.groupby('aaabbBcCaacc'): print(key, list(group)) for key, group in itertools.groupby('aaabbBcCaacc', lambda x: x.upper()): print(key, list(group))
false
5bcf95b1954ac33b4698863f3900d466a6805539
angelblue05/Exercises
/codeacademy/python/while.py
1,298
4.21875
4
num = 1 while num < 11: # Fill in the condition # Print num squared print num * num # Increment num (make sure to do this!) num += 1 # another example choice = raw_input('Enjoying the course? (y/n)') while choice != "y" and choice != "n": # Fill in the condition (before the colon) choice = raw_input("Sorry, I didn't catch that. Enter again: ") # another example count = 0 while count < 10: # Add a colon print count # Increment count count += 1 # another example count = 0 while True: print count count += 1 if count >= 10: break # another example import random print "Lucky Numbers! 3 numbers will be generated." print "If one of them is a '5', you lose!" count = 0 while count < 3: num = random.randint(1, 6) print num if num == 5: print "Sorry, you lose!" break count += 1 else: print "You win!" # another example - guessing game from random import randint # Generates a number from 1 through 10 inclusive random_number = randint(1, 10) guesses_left = 3 # Start your game! while guesses_left > 0: guess = int(raw_input("Your guess: ")) if guess == random_number: print "You win!" break guesses_left -= 1 else: print "You lose."
true
98c0a56d846d180558421ee8ad664466349e85fd
Gaoliu19910601/python3
/tutorial2_revamp/tut4_boolean_cond.py
1,418
4.1875
4
print('') print('-----------------BOOLEAN AND CONDITION-----------------------') print('') language = 'Java' # If the language is python then it is a true condition and would print # the first condition and so forth for the next. However if everything # is False there would be no match if language is 'Python': print('Condition was true') elif language is 'Java': print('Yes, Language is Java') else: print('No match') user = 'Admin' logged_in = False # Use of 'or' means that one of them should be true to print the first statement # Use of 'and' means both should be true to print the first statement if user is 'Admin' or logged_in: print("He's working") else: print("He's in Reeperbahn") # Use of 'not' means the opposite of true or false but to first statement, the condition # should always be true if not logged_in: print('Please log in') else: print('Welcome') # Be always careful when using the 'is' condition instead of '==' a = [1,2,3] b = [1,2,3] b2 = a print(id(a)) print(id(b)) print(id(b2)) print(a is b) # two different objects print(a == b) # but have same value print(a is b2) # two same objects print(id(a) == id(b2)) # same as 'is' condition # False values: # False # None # numeric 0 # Empty string {}, [], '' # Everything else would give true values condition = None if condition: print('Evaluated to true') else: print('Evaluated to false')
true
e4771801e9edfa915000c7522e092b4447189169
Gaoliu19910601/python3
/tutorial2_revamp/tut5_loops.py
525
4.15625
4
nums = [1, 2, 3, 4, 5] # The for loop with an if condition along with a continue statement for num in nums: if num == 3: print('Found it!') continue print(num) print('') # Nested For loop for letter in 'abc': for num in nums: print(num,letter) print('') for i in range(1, 11): print(i) print('') # If the while loop is run as 'True' instead of 'x < 10' then # it would be infinite x = 0 while x < 10: if x==5: print('Found !') break print(x) x += 1
true
47de4cf8b2e8ac30e5ed01605a5fc48f0c784224
AakashKB/5_python_projects_for_beginners
/magic_8_ball.py
670
4.125
4
import random #List of possible answer the 8 ball can choose from potential_answers = ['yes','no','maybe','try again later', 'you wish','100% yes','no freaking way'] print("Welcome to the Magic 8 Ball") #Infinite loop to keep the game running forever while True: #Asks user for input, no need to store it input("Ask a yes or no question > ") #Choose a random number between 0 and the length of the answers list rand_num = random.randrange(len(potential_answers)) #Use random number as index to pick a response from the answers list response = potential_answers[rand_num] print(response)
true
c1f77aca918cb0b177d9f42a314ff9186c4cb051
rdegraw/numbers-py
/fibonacci.py
423
4.25
4
#---------------------------------------- # # Fibonacci number to the nth position # #---------------------------------------- position = int( raw_input( "Please enter the number of Fibonacci values you would like to print: " )) sequence = [0] while len(sequence) < position: # F(n) = F(n-1) + F(n-2) if len(sequence) == 1: sequence.append(1) else: sequence.append( sequence[-2] + sequence[-1]) print sequence
true
4d0987b5fca0c8342c604f9e18cec3493dbea869
limchiahau/ringgit
/ringgit.py
2,001
4.15625
4
from num2words import num2words import locale locale.setlocale(locale.LC_ALL,'') def to_decimal(number): ''' to_decimal returns the given number as a string with groupped by thousands with 2 decimal places. number is a number Usage: to_decimal(1) -> "1.00" to_decimal(1000) -> "1,000.00" ''' return locale.currency(number,symbol=False,grouping=True) def to_ringgit_word(amount): ''' to_ringgit_word return the amount of ringgit as text. The text will be formatted in title case. amount is a number Usage: to_ringgit_word(1100) -> "Ringgit Malaysia One Thousand One Hundred Only" ''' text = num2words(amount) without_comma = text.replace(',', '') title_case = without_comma.title() return 'Ringgit Malaysia ' + title_case + ' Only' def to_ringgit(amount): ''' to_ringgit returns the amount as a ringgit string. amount is a number Usage: to_ringgit(100) -> "RM100.00" ''' amount_str = to_decimal(amount) return f'RM{amount_str}' def format_ringgit(format, amount): ''' Format ringgit returns a string that is formatted using the format string and amount passed into the function. There are 2 variables usable in the format string. 1. @amount This represents the amount as ringgit in number format "RM100.00" 2. @text This represents the amount of ringgit in text format "RINGGIT MALAYSIA ONE HUNDRED ONLY" format is a string amount is a number Usage: format_ringgit("@text\n\t(@amount)", 100) returns: Ringgit Malaysia One Hundred Only (RM100.00) ''' with_amount = format.replace('@amount', to_ringgit(amount)) with_text = with_amount.replace('@text', to_ringgit_word(amount)) return with_text if __name__ == "__main__": import sys amount = float(sys.argv[1]) amount_text = format_ringgit('@text\n\t(@amount)', amount) print(amount_text)
true
20f1dbf7f0016a9a37158b325682504e3ca3fae9
Idealistmatthew/MIT-6.0001-Coursework
/ps4/ps4a.py
2,185
4.375
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. ''' ## Applying the base case if len(sequence) == 1: return sequence else: ## making a list out of the letters letter_list = list(sequence) ## storing the letter to be concatenated recursively concat_letter = letter_list[0] ## making a list to store the final permutations inductive_permutations = [] ## removing the frontmost letter from the list del letter_list[0] ## applying recursion on the function sub_permutations = get_permutations(letter_list) ## looping through the permutations obtained via recursion for permutation in sub_permutations: ## loop to add the concat_letter to every possible position within the permutation for i in range(len(permutation) + 1): ## making the permutation into a list of letters new_word_list = list(permutation) ## inserting the concat_letter into position i new_word_list.insert(i,concat_letter) ## join the list to form the permutation new_permutation = ''.join(new_word_list) ## append the permutation to the final list inductive_permutations.append(new_permutation) return inductive_permutations if __name__ == '__main__': #EXAMPLE example_input = 'abc' print('Input:', example_input) print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) print('Actual Output:', get_permutations(example_input))
true
16865ccc69e24a0ab37cc8b9dfa4f1e3ec7dbfac
sd-karthik/karthik-repo
/Training/5.python/DAY2/fun_var_arguments.py
264
4.40625
4
# FILE : fun_var_arguments.py # Function : Factorial of a number using recursion def recur(num): if not num: return num*recur(num-1) else: return 1 num1 = input("Enter a number to find its Factorial\n") total = recur(num1 ) print "FACT(", num1,"):", total
true
c665108b6cf623aae18c528df3fda336d7ce0864
sd-karthik/karthik-repo
/Training/python/DAY1/FIbanacci.py
711
4.125
4
# Print Fibonacci series print "PRINTING FIBONACCI SERIES" print "Choose your choice\n1.\t Using Maximum limit" print "2.\t Using Number of elements to be prtinted" choice = input() ele = 1 ele2 = 0 # Printing Fibonacci the maximum limit if choice == 1 : limit = input("Enter the Maximum limit") if (ele < 1): print "invalid input" exit() else: while ele <= limit: print ele temp = ele2+ele ele2 = ele ele = temp elif choice == 2: num = input("Enter the count of FIbonacci numbers to print") count = 0 if num < 1 : print "Invalid input" exit() else: while count < num: print ele temp = ele2+ele ele2 = ele ele = temp count+=1 else: print "Invalid choice"
true
0124d1b39ff94f880401d0ece0b0ef7612e9a8cc
sd-karthik/karthik-repo
/Training/5.python/DAY5/map.py
536
4.4375
4
# FILE: map.py # Functions : Implementation of map # -> Map will apply the functionality of each elements# in a list and returns the each element def sqr(x): return x*x def mul(x): return x*3 items = [1,2,3,4,5] print "map: sqr:", map(sqr, items) # returns a list list1 = map(lambda x:x*x*x, items ) print "map:lambda x:x*x*x:", list1 items.append('ha') print "append 'ha': map:mul", map(mul, items) items.remove("ha") # returns one value print "remove 'ha': reduce: lambda x,y:x+y:",reduce(lambda x,y:x+y, items,5)
true
329a3366d612789862c773edaded12703b68da32
wwymak/algorithm-exercises
/integrator.py
1,718
4.6875
5
""" Create a class of Integrator which numerically integrates the function f(x)=x^2 * e^−x * sin(x). You need to provide the class with the minimum value xMin, maximum value xMax and the number of steps N for integration. Then the integration process should be carried out accroding to the below information. Suppose that S=∫(xMin to xMax)f(x)dx ≈ ∑(from i = 0 to N−1)0f(xi)Δx Δx=(xMax−xMin)/(N−1) xi=xMin+iΔx. The class is composed of three methods: _init_, integrate and show: 1. The method of _init_ should initialize the xMin, xMax, N and other related parameters . 2. The method of integrate should perform the integration process with the given parameters. 3. The method of show should print on the screen the result of integration. The starter file has been attached. Fill the blank and run the code. Assign the parameters with value: xMin =1, xMax =3, N = 200. The result of integration of f(x) equals to (5 digital of accuracy): """ import numpy as np import math class Integrator: def __init__(self, xMin, xMax, N): self.xMin = xMin self.xMax = xMax self.N = N self.result = 0 def fx(self, x): return np.square(x) * np.exp(-x) * np.sin(x) def integrate(self): deltaX = (self.xMax - self.xMin) / (self.N ) for i in range(N): xcurr = self.xMin + i * deltaX; # print(xcurr, 'xcurr') temp = self.fx(xcurr) * deltaX # if N %20 == 0: # print(temp, self.result) self.result += temp def show(self): print(self.result) xMin =1.0 xMax =3.0 N = 199 examp = Integrator(xMin, xMax, N) examp.integrate() examp.show() # 0.76374
true
d79fbe4393091a929a8d1e645d17e73510275986
ryokugyu/machine-learning-models
/basic_CNN.py
1,692
4.1875
4
''' Implementing a simple Convolution Neural Network aka CNN Adapated from this article: https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5 Dataset: MNIST ''' import tensorflow as tf from keras.dataset import mnist from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten # downloading and splitting the dataset into test and train network (X_train, y_train), (X_test, y_test) = mnist.load_data() #checking the image shape print(X_train[0].shape) #reshaping data to fit model X_train = X_train.reshape(60000,28,28,1) X_test = X_test.reshape(10000,28,28,1) # one-hot encode target column #This means that a column will be created for each output category and a binary #variable is inputted for each category. For example, we saw that the first #image in the dataset is a 5. This means that the sixth number in our array #will have a 1 and the rest of the array will be filled with 0. y_train = to_categorical(y_train) y_test = to_categorical(y_test) # Check what we get from the to_categorical function print(y_train[0]) #Building the model layer by layer model = Sequential() #add model layers model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1))) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Flatten()) model.add(Dense(10, activation='softmax')) #Compiling the model takes three parameters: optimizer, loss and metrics. model.compile(optimizer='adam', loss='categorical_crossentropy') model.fit(X_train, y_train, validation_data=(X_test, y_test),epochs=3) #predict first 4 images in the test set model.predict(X_test[:4])
true
72cf8c17498315d97182bec675578d40e254633a
Chippa-Rohith/daily-code-problems
/daily problems pro solutions/problem4_sorting_window_range.py
835
4.1875
4
'''Hi, here's your problem today. This problem was recently asked by Twitter: Given a list of numbers, find the smallest window to sort such that the whole list will be sorted. If the list is already sorted return (0, 0). You can assume there will be no duplicate numbers. Example: Input: [2, 4, 7, 5, 6, 8, 9] Output: (2, 4) Explanation: Sorting the window (2, 4) which is [7, 5, 6] will also means that the whole list is sorted.''' def min_window_to_sort(nums): left=right=-1 max=float('-inf') for i in range(len(nums)): if max < nums[i]: max=nums[i] if nums[i]<max: right=i min=float('inf') for i in reversed(range(len(nums))): if min > nums[i]: min=nums[i] if nums[i]>min: left=i return (left,right) print(min_window_to_sort([2, 4, 7, 5, 6, 8, 9])) # (2, 4)
true
e3bfbdcefaa83965cf00323b9ed21e584d49a118
tdtshafer/euler
/problem-5.py
644
4.125
4
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ UPPER_LIMIT = 20 def main(): divisible_number = get_divisible_number() print("The smallest positive number divisible by all numbers 1-{} is {}".format(UPPER_LIMIT, divisible_number)) def get_divisible_number(): number = UPPER_LIMIT while not is_divisible(number): number += UPPER_LIMIT return number def is_divisible(number): for x in range(1,UPPER_LIMIT+1): if number % x != 0: return False return True main()
true
e12925a5059f4578698810992b1af350f525c099
rndmized/python_fundamentals
/problems/palindrome_test.py
632
4.53125
5
#Funtion will take a string, format it getting rid of spaces and converting all # characters to lower case, then it will reverse the string and compare it to # itself (not reversed) to chek if it matches or not. def is_palindrome(word): formated_word = str.lower(word.replace(" ","")) print(formated_word) #Using slices to reverse the word(using the step -1) reversed_word = formated_word[::-1] if formated_word == reversed_word: print('"',word,'"', "is a palindrome.") else: print(word, "is NOT a palindrome.") #Test sentence/word is_palindrome("A Santa dog lived as a devil God at NASA")
true
2c10cf1677039d7ddb669acf31f16cae1027d72d
bluelotus03/build-basic-calculator
/main.py
2,215
4.34375
4
# This is a basic calculator program built with python # It does not currently ensure numbers and operators are in the correct format when input, so if you want to enjoy the program, make sure you input numbers and operators that are allowed and at the right place <3 # ------------FUNCTIONS----------------------------------- # Welcome function def welcomeMsg(): print("\nHello! Welcome to our basic calculator with Python <3") print("\nCurrently, we support the following operations for 2 numbers at a time:\nAddition, Subtraction, Division, Multiplication") # Function to do the calculations def calculationTime(): # Takes user input for 2 numbers and an operator num1 = float(input("\n\nEnter a number: ")) operator = input("\nEnter the operation (+|-|/|*): ") num2 = float(input("\nEnter another number: ")) # Perform the correct operation based on user's input if operator == "+": result = (num1) + (num2) elif operator == "-": result = (num1) - (num2) elif operator == "/": result = (num1) / (num2) elif operator == "*": result = (num1) * (num2) # Print both numbers, the operator, and the result print("\n", num1, operator, num2, "=", result) # Ask the user to go again and return their answer def goAgainQ(): goAgain = input("\nWant to go again? (Y|N) ").lower() return goAgain # ------------MAIN PROGRAM----------------------------------- # By default when the program starts, set goAgain to y for yes goAgain = 'y' # Print the welcome message welcomeMsg() # While the user does not enter n for going again question while goAgain != 'n': # Call the function for calculations calculationTime() # At end of calculation results, ask user if they want to go again and assign the input returned to the yORn variable yORn = goAgainQ() # While user input is not 'y' or 'n,' tell them that's not valid input for this question and ask ask the question again while yORn !='y' and yORn !='n': print("\nSorry friend, that doesn't seem to be a Y or N") yORn = goAgainQ() # If user inputs 'n,' print goodbye msg and end program if yORn == 'n': print("\nIt was great having you here!\nHope to see you soon! 00\n") break
true
99bd1373e5c05ab985ec744988b9d25ba002b0aa
reeynaldo/Ejercicios-1er-Parcial
/Nota Final.py
411
4.15625
4
nota = int(input("¿Cuánto sacaste en tu nota final?: ")) if nota <= 0: print("Error, ingrese calificacion correcta") elif nota < 5: print("Suspenso") elif nota == 5: print("Suficiente") elif nota == 6: print("Aprobado") elif nota == 7: print("Notable") elif nota > 10: print("Error, ingrese calificacion correcta") elif nota >= 8: print("Sobresaliente")
false
552c626ee36d4c5bdf4f983872582ed95430ad40
I3at57/ScribUTT
/build/src/parts/code/example.py
651
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def square_and_multiply(x: int, exponent: int, modulus: int = None, Verbose: bool = False): """ Square and Multiply Algorithm x: positive integer exponent: exponent integer modulus: module Returns: x**exponent or x**exponent mod modulus when modulus is given """ b = bin(exponent).lstrip("0b") r = 1 for i in b: rBuffer = r r = r ** 2 if i == "1": r = r * x if modulus: r %= modulus if Verbose: print(f"{rBuffer}^2 = {r} mod {modulus}") return r
false
6789ade79015ec8d4fa7552882a90b21efe697de
rushabh95/practice-set
/1.py
306
4.1875
4
# Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a #tuple with those numbers. #Sample data : 3, 5, 7, 23 m=() n = [] i = 0 while i < 4: a = int(input("enter a number: ")) n.append(a) i+=1 print(n) m = tuple(n) print(m)
true
4ddda8da0be4ee303de96079c0ee4e247343836a
Jdicks4137/function
/functions.py
1,419
4.46875
4
# Josh Dickey 9/21/16 # This program solves quadratic equations def print_instructions(): """This gives the user instructions and information about the program""" print("This program will solve any quadratic equation. You will be asked to input the values for " "a, b, and c to allow the program to solve the equation.") def get_first_coefficient(): """This allows the user to input the values for a""" a = float(input("what is the value of a?")) return a def get_second_coefficient(): """This allows the user to input the values for b""" b = float(input("what is the value of b?")) return b def get_third_coefficient(): """This allows the user to input the values for c""" c = float(input("what is the value of c?")) return c def calculate_roots(a, b, c): """this is the formula the computer will calculate""" x = (-b + (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) y = (-b - (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) return x, y def main(): """this is the function that runs the entire program""" print_instructions() first_coefficient = get_first_coefficient() second_coefficient = get_second_coefficient() third_coefficient = get_third_coefficient() root1, root2 = calculate_roots(first_coefficient, second_coefficient, third_coefficient) print("the first root is:", root1, "and the second root is:", root2) main()
true
575de7537ae45b6d88a0b208999b95fd34dcb314
birkoff/data-structures-and-algorithms
/minswaps.py
1,856
4.40625
4
''' There are many different versions of quickSort that pick pivot in different ways. - Always pick first element as pivot. - Always pick last element as pivot (implemented below) - Pick a random element as pivot. - Pick median as pivot. ''' def find_pivot(a, strategy='middle'): if strategy and 'middle' == strategy: middle = int(len(a)/2) - 1 return middle # handle when value is too small or too big if a[middle] < if strategy and 'biggest' == strategy: biggest = None for i in range(len(a)): if biggest is None or a[i] > a[biggest]: biggest = i return biggest def partition(a, left, right): i_left = left # index of the smaller element if right >= len(a): return pivot = a[right] # Always pick last element as pivot for i_current in range(left, right): current = a[i_current] if current <= pivot: i_left = i_left + 1 a[i_left], a[i_current] = a[i_current], a[i_left] if (i_left + 1) < len(a): a[i_left+1], a[right] = a[right], a[i_left+1] return i_left + 1 def quicksort(a, left, right): if left < right and right < len(a): pi = partition(a, left, right) # Separately sort elements before # partition and after partition if pi is None: return quicksort(a, left, pi + 1) quicksort(a, pi + 1, right) # # pivot = find_pivot(a) # left = 0 # right = len(a) # # # for i_left in range(len(a)): # if a[i_left] > a[pivot]: # # return biggest def find_min_swaps(a): arr = a n = len(arr) quicksort(arr, 0, n-1) print("Sorted array is:") for i in range(n-1): print("%d" % arr[i]) a = [4, 3, 1, 2, 6, 9, 8, 7, 5] print(find_min_swaps(a))
true
4bc3fc901daf36615ffb6d76dc103c1fc56c9c69
alex-rantos/python-practice
/problems_solving/binaryTreeWidth.py
1,597
4.125
4
import collections """Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 indexDic = collections.defaultdict(list) def rightTraverse(node, index, depth): nonlocal indexDic if depth not in indexDic: indexDic[depth] = [index, index] else: indexDic[depth][0] = min(indexDic[depth][0], index) indexDic[depth][1] = max(indexDic[depth][1], index) #print(f'{depth} :: {node.val} -> {index}') nextIndex = index * 2 if node.left: rightTraverse(node.left, nextIndex - 1, depth + 1) if node.right: rightTraverse(node.right, nextIndex, depth + 1) rightTraverse(root, 1, 0) ans = 0 for depth in indexDic.keys(): ans = max(ans, indexDic[depth][1] - indexDic[depth][0] + 1) return ans
true
2991deeeb5aa13cc1a542f989111479f0b5680a8
alex-rantos/python-practice
/problems_solving/sortColors.py
1,248
4.21875
4
from typing import List """ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. """ class Solution: def sortColors(self, nums: List[int]) -> List[int]: # O(n) solution cur = zeros = 0 twos = len(nums)-1 while (cur <= twos): if (nums[cur] == 0): nums[cur], nums[zeros] = nums[zeros], nums[cur] cur += 1 zeros += 1 elif nums[cur] == 1: cur += 1 else: nums[cur], nums[twos] = nums[twos], nums[cur] twos -= 1 def sortColorsN2(self, nums: List[int]) -> List[int]: # O(n^2) solution dic = { 0: [], 1: [], 2: [] } for i, c in enumerate(nums): dic[c].append(i) for i in range(len(nums)): if i < len(dic[0]): nums[i] = 0 elif i < len(dic[0])+len(dic[1]): nums[i] = 1 else: nums[i] = 2
true
4d8a8b1dc9e26df64db21565ae4f6ba97d9120fd
alex-rantos/python-practice
/problems_solving/hammingDIstance.py
529
4.15625
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. """ class Solution: def hammingDistance(self, x: int, y: int) -> int: xorResult = x ^ y hd = 0 while xorResult > 0: hd += xorResult & 1 xorResult >>= 1 return hd def test(self): self.hammingDistance(1, 4) == 2 if __name__ == "__main__": sol = Solution() sol.test()
true
6fd1b9e364aa0650e4601f0973d79e8927c8759a
alex-rantos/python-practice
/problems_solving/remove_unnecessary_lists.py
906
4.375
4
""" Extracts all inner multi-level nested lists and returns them in a list. If an element is not a list return the element by itseft """ from itertools import chain # stackoverflow answer def remove_unnecessary_lists(nested_list): for item in nested_list: if not isinstance(item,list): yield item elif list(chain(*item)) == item: yield item else: yield from remove_unnecessary_lists(item) if __name__ == '__main__': my_nested_list = [['a', 'b', 'c', 'd'],['e', [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] l = [['a', 'b', 'c', 'd'],[["d","d","g"],[[["a"]]],[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] #my_nested_list = [['a', 'b', 'c', 'd'],['e', ['r'], [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] flat_list = list(remove_unnecessary_lists(my_nested_list)) print(flat_list)
true
20bd0c0f04c09ad0bb8fa522b113e43c5a99c0db
shilihui1/Python_codes
/dict_forloop.py
565
4.40625
4
'''for loop in dictionary, using dictionary method a.items()''' a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} # items method for dictionary for key, value in a.items(): print(str(key) + "--" + str(value)) # keys method for dictionary for key in a.keys(): print(key) # values method for dictionary for value in a.values(): print(value) print("\nBEGIN: REPORT\n") # Iterate over the key-value pairs of kwargs for keys, values in a.items(): # Print out the keys and values, separated by a colon ':' print(str(keys) + ": " + values) print("\nEND REPORT")
true
9de6c6484fb918a933fe19a4f8d90d0c7e4e91ed
Maksov/geekbrains-python
/lesson01/home_work/hw01_hard.py
804
4.34375
4
__author__ = 'Povalyaev Ivan' # Задание-1: # Ваня набрал несколько операций в интерпретаторе и получал результаты: # Код: a == a**2 # Результат: True # Код: a == a*2 # Результат: True # Код: a > 999999 # Результат: True # Вопрос: Чему была равна переменная a, если точно известно, что её # значение не изменялось? class A(object): def __eq__(self, other): return True def __pow__(self, other): return True def __mul__(self, other): return True def __gt__(self, other): return True a = A() print(a == a ** 2) print(a == a * 2) print(a > 999999)
false
e4960cabf2330beb1601b933756820e83b9f87f0
rickjiang1/python-automate-boring-stuff
/RegExp_Basic.py
915
4.375
4
#regular expression basics!! #this is the way of how to define a phonenumber ''' def isPhoneNumber(text): if len(text)!=12: print('This is more than 12 digit') return False for i in range(0,3): if not text[i].isdecimal(): return False #no area code if text[3]!='-': return False for i in range(4,7): if not text[i].isdecimal(): return False if text[7] !='-': return False #missing second dash for i in range(8,12): if not text[i].isdecimal(): return False return True print(isPhoneNumber('501-827-0039')) ''' #use regular expressions message='Call me 415-555-1011 tommorrow, or at 501-827-0039' foundNumber=False import re PhoneNUmberRe=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #find one print(PhoneNUmberRe.search(message).group()) print('\n') #find all print(PhoneNUmberRe.findall(message))
true
81c049631b64733a1583de85fdd078133dfd1476
Kennedy-Njeri/All-python
/scope.py
753
4.25
4
#x = 25 #def my_func(): # x = 50 #return x #print(x) #print(my_func()) x = 25 def my_func(): x = 50 return x #print(x) #print(my_func()) my_func() print (x) #example 2 name = "kennedy" def full(): #name = "sammy" def hello(): print ("hello "+ name) hello() full() x = 50 def func(x): print('x is:', x) x = 1000 print ('local x changed to:',x) func(x) print(x) x = 50 def func(): global x x = 1000 print ('The function call, x is: ', x) func() print ('after function call, x is: ', x) # Instead of using global x = 50 def func(): #global x x = 1000 return x print ('The function call, x is: ', x) x = func() print ('after function call, x is: ', x)
false
fad659a950108ac733dc6821e1506181c21c7fe5
makaiolam/conditions-and-loops
/main.py
1,955
4.125
4
# first = input("what is your first name") # last = input("what is your last name") # print(f"you are {last}, {first}") #loops #----------------------------- # print(1) # print(2) # print(3) # print(4) # print(5) #while loop # while loop takes a boolean epxression (t/f) #boolean operations #--------------------- #comparision operators # x < 5 (less than) # x > 5 (greater than) # x <= 5 (less than or equal too) # x >= 5 (greater than or equal too) # x == 5(equal) # x != 5 (not equal to) #logical operatos # and # or # not # infinite loop, watch out for # counter = 0 # while(counter <= 5): # print(counter) # counter = counter + 1 # for loops # range(5) => 0,1,2,3,4. # counter = 0 # for counter in range(5): # print(counter + 1) #list of numbers numbers = [1,2,3,4,5] sum = 0 for counter in range(1,6): sum = sum + counter print(sum) #conditionals #---------------------- # definition if x then y # ex. if i go to school then i will learn # money = 5 # if money == 5: # print("i have 5 dollars") # elif money == 6: # print ("i have 6 dollars") # elif money == 7: # print ("i have 7 dollars") # else: # print("i have a different amount of money") # winter, fall, summer, spring # season = input ("what is the season? ") # if season == "winter": # print("go inside") # if season == "spring": # print("go outside and plant") # if season == "summer": # print("go and water plants") # if season == "fall" # print("start to pick the plants") # guess the number game import random computernumber = randomnumber (0-10) numberoftries = 5 win = false play = true while play == true: while numberoftries > 0: playnumber: input("enter a number between 0-10:") playernumber = int(playernumber) if playernumber > 10: print("bad number") else: if playernumber < "computernumber": print("number too low") else: if playernumber > computernumber: print("number too high")
true
d26cd8f44b032e6233a2aa5399b4623ce2b3cfaf
TL-Web30/CS35_IntroPython_GP
/day1/00_intro.py
1,407
4.25
4
# This is a comment # lets print a string # print("Hello, CS35!", "Some other text", "and theres more...") # variables # label = value # let const var (js) # int bool short (c) # first_name = "Tom" # # print("Hello CS35 and" , first_name) # num = 23.87 # # f strings # my_string = " this is a string tom" # print(my_string) # print(my_string.strip()) # print(len(my_string)) # print(len(my_string.strip())) # print(f"Hello CS35 and {first_name}.......") # print("something on a new line") # collections # create an empty list? Array # print(my_list) # create a list with numbers 1, 2, 3, 4, 5 # add an element 24 to lst1 # print(lst1) # # print all values in lst2 # print(lst2) # loop over the list using a for loop # while loop # List Comprehensions # Create a new list containing the squares of all values in 'numbers' numbers = [1, 2, 3, 4] squares = [] print(numbers) print(squares) # Filtering with a list comprehension evens = [] # create a new list of even numbers using the values of the numbers list as inputs print(evens) # create a new list containing only the names that start with 's' make sure they are capitalized (regardless of their original case) names = ["Sarah", "jorge", "sam", "frank", "bob", "sandy"] s_names = [] print(s_names) # Dictionaries # Create a new dictionary # empty # key value pairs # access an element via its key
true
34ca0dcd4b1d1fe1187faa5e271f7cd58a8766f1
JasonLuis/python-basico
/estrutura_de_repeticao_for.py
549
4.3125
4
""" ## Estrutura de repetição – for """ print(1) print(2) print(3) print(4) print(5) for numero in range(1, 6): print(numero) 5 + 4 + 3 + 2 + 1 print("\n\n") for numero in range(5, 0, -1): print(numero) print("\n\n") soma = 0 for numero in range(1, 6): soma = soma + numero #print(soma) print(soma) print("\n\n") palavra = 'sorvete' for letra in palavra: #print(letra) if letra == 'v': print('Achou a letra v') print("\n\n") for i in range(0,5): print(i) print('---') for j in range(0,3): print(j) print()
false
166366c2f5457e02d5aee7dd44936a966ca17f56
tringhof/pythonprojects
/ex15.py
806
4.21875
4
#import argv from sys module from sys import argv #write the first argv argument into script, the second into filename script, filename = argv #try to open the file "filename" and save the file object into txt txt = open(filename) print "Here's your file %r: " %(filename) #use the read() command on that file object print txt.read() txt.close() print "Type the Filename again:" file_again = raw_input("> ") txt_again=open(file_again) print txt_again.read() txt.close() # close -- Closes the file. Like File->Save.. in your editor. # read -- Reads the contents of the file. You can assign the result to a variable. # readline -- Reads just one line of a text file. # truncate -- Empties the file. Watch out if you care about the file. # write('stuff') -- Writes "stuff" to the file.
true
3868ad37a26a7ca1b5799e155c5433200e5c98ff
bmilne-dev/cli-games
/hangman.py
2,259
4.40625
4
# a hangman program from scratch. from random import randint filename = "/home/pop/programming/python_files/word_list.txt" with open(filename) as f: words = f.read() word_list = words.split() # define a function to select the word def word_select(some_words): """choose a word for hangman from a word list""" some_word = some_words[randint(0, len(some_words) - 1)] return some_word # define a function to display the word using an external # list of previous guesses def display_word(some_word, my_guesses): """take the selected word and a list of user guesses and return a string that only shows previously guessed letters while replacing unknown letters with *""" hidden_list = [] for letter in some_word: if letter in my_guesses: hidden_list.append(letter) else: hidden_list.append('*') return ''.join(hidden_list) # define a function to receive the proper input # meaning, the user can only input valid char's and only 1 at a time def take_guess(): """accept user guesses and make sure they are the proper format""" user_guess = input("Take a guess!\n> ") while not user_guess.isalpha(): user_guess = input("\nAlpha-Numeric characters only!" "\nTake a guess!\n> ") while len(user_guess.strip()) > 1: user_guess = input("\nOne letter at a time please!" "\nTake a guess!\n> ") return user_guess # define a function to check if the guess is in the word def check_guess(user_guess, some_word, my_guesses): """see if user guessed correctly!""" if user_guess in some_word: return True else: return False word = word_select(word_list) guesses = [] n = 0 print(f"Welcome to hangman!") while True: if n == 6: print("Out of guesses!") print(f"The word was {word}!") break print(f"\nYou have {6 - n} guesses left") print("Your word:") print(display_word(word, guesses)) guess = take_guess() guesses.append(guess) display = display_word(word, guesses) if display == word: print(f"You got it!") break elif not check_guess(guess, word, guesses): n += 1
true
4b4a167aaefb2d6ccb840937f02b32a2fab0ae71
jamesledwith/Python
/PythonExercisesWk2/4PercentageFreeSpace.py
627
4.28125
4
#This program checks the percentage of disk space left and prints an apropiate response total_space = float(input("Enter total space: ")) amount_used = float(input("Enter amount used: ")) free_space_percent = 100 * (total_space - amount_used) / total_space; print(f"The percentage of free space is {free_space_percent:.1f}%") if amount_used > total_space: print("Input data is Invalid") elif total_space == amount_used: print("Warning: System full") elif 5 <= free_space_percent < 100: print("System has sufficient disk space") elif 0 <= free_space_percent < 5 : print("Warning, low disk space")
true
25f42be209ce937b382bd74243f2ce5a4df391c5
jamesledwith/Python
/PythonExercisesWk2/3MatchResults.py
472
4.125
4
#This program displays a match result of two teams hometeam_name = input("Home team name? ") hometeam_score = int(input("Home team score? ")) awayteam_name = input("Away team name? ") awayteam_score = int(input("Away team score? ")) if hometeam_score > awayteam_score: print("Winner: ",hometeam_name) elif awayteam_score > hometeam_score: print("Winner: ",awayteam_name) elif awayteam_score == hometeam_score: print("Draw") else: print("Invalid")
true
1de73cda72d4391293a1631173215ba74174d025
jamesledwith/Python
/PythonExercisesWk1/11VoltageToDC.py
327
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 12:59:21 2020 @author: James """ import math print("This program calculates the Voltage in a DC Circuit") power = int(input("Enter the power: ")) resistance = int(input("Enter the resistance: ")) voltage = math.sqrt(power * resistance) print(f"Voltage is {voltage}")
true
e8cd3d172cba768564a53ad50340913e243ef8fa
hsalluri259/scripts
/python_scripts/odd_even.py
946
4.53125
5
#!/opt/app/python3/bin/python3.4 ''' Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. ''' number = int(input("Enter a number:")) if number % 2 == 0 and number % 4 == 0: print("%d is divided by 4" % number) elif number % 2 == 0: print("%d is just Even" % number) else: print("%d is Odd" % number) num1 = int(input("Enter number1:")) num2 = int(input("Enter number2:")) if num1 % num2 == 0: print("%d is evenly divided by %d" % (num1,num2)) else: print("%d is not divided by %d" % (num1,num2))
true
5f33814fd3a76665dd4deef46a623231757236b1
MrWQ/Parser
/Analysis/Stack.py
1,323
4.25
4
class Stack(object): # 初始化栈为空列表 def __init__(self): self.items = [] # 判断栈是否为空,返回布尔值 def is_empty(self): return self.items == [] # 返回栈顶元素 def peek(self): if (self.is_empty() == False): return self.items[len(self.items) - 1] # 返回栈的大小 def size(self): return len(self.items) # 把新的元素堆进栈里面(压栈,入栈,进栈……) def push(self, item): self.items.append(item) # 把栈顶元素丢出去(出栈……) def pop(self): if (self.is_empty() == False): return self.items.pop() def stackToStr(self): if (self.is_empty() == False): strA = "".join(self.items) return (strA) else: return '' def stackToReverseStr(self): if (self.is_empty() == False): strA = "".join(self.items) strA = strA[::-1] return (strA) else: return '' # stack = Stack() # stack.push('a') # print(stack.stackToStr()) # stack.push('b') # stack.push('c') # print(stack.is_empty()) # print(stack.peek()) # print(stack.pop()) # print(stack.pop()) # print(stack.pop()) # print(stack.is_empty()) # # print(stack.pop())
false
8026ce987b2ed319dee7faf702c82772be01e708
dzhonapp/python_programs
/Loops/averageRainfall.py
1,003
4.375
4
'''Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.''' yearsToCalculate = int(input('How many years would you like to calculate rainfall? ')) monthlyRainfall = 0.0 for i in range(yearsToCalculate): for month in range(1, 13): print('Month #', month, end=" ") monthlyRainfall += float(input('Please input the rainfall! ')) print('For year ', i+1, 'the total rainfall was: ', monthlyRainfall, 'inches') print('The average rainfall was: ', format(monthlyRainfall/(yearsToCalculate*12, ',.2f')))
true
94b675bb81acbb2d07829c4180920a36bb601b8b
dzhonapp/python_programs
/Basics/Celsius to Fahreneit Temperature Converter.py
429
4.25
4
'''9. Celsius to Fahrenheit Temperature Converter Write a program that converts Celsius temperatures to Fahrenheit temperatures. The formula is as follows: F =9/5C+32 The program should ask the user to enter a temperature in Celsius, and then display the temperature converted to Fahrenheit. ''' fahreneit= int(input('What is todays Temperature in Fahrenheit? ')) print('Todays temperature in Celcius: ', (fahreneit-32)/(9/5))
true
8d0ae7668e921e6e0047c1143cfbcdbf56f701a6
dzhonapp/python_programs
/functions/milesPerGallon.py
507
4.34375
4
'''Miles-per-Gallon A car’s miles-per-gallon (MPG) can be calculated with the following formula: MPG = Miles driven / Gallons of gas used Write a program that asks the user for the number of miles driven and the gallons of gas used. It should calculate the car’s MPG and display the result. ''' def mpgCalculate(): miles = float(input('How many miles you drove?')) gallons= float(input('How many gallons of gas you filled? ')) return miles/gallons print('Your MPG is: ', mpgCalculate())
true
ebec474eb20cfa6f338595a9bccf23b95a541dfd
dzhonapp/python_programs
/Loops/oceanLevels.py
382
4.3125
4
''' Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an application that displays the number of millimeters that the ocean will have risen each year for the next 25 years. ''' millimeters=1.6 for years in range(25): print("Year #", years+1) print('Millimeters risen so far: ', format(millimeters, ',.2f')) millimeters+=1.6
true
7780f37587dc6bc07109b72911dc720f332268ad
garimadawar/LearnPython
/DynamicAvg.py
262
4.1875
4
print("Calculate the sum and average of two numbers") number1 = float(input("Enter the first number")) number2 = float(input("Enter the second number")) print("the sum equals to " , number1 + number2) print("average equals to " , (number1 + number2) / 2)
true
c1fa73caced9e5aeafe0e282ae88e6cb5c58a7fd
justinhinckfoot/Galvanize
/github/Unit 1 Exercise.py
1,662
4.34375
4
# Unit 1 Checkpoint # Challenge 1 # Write a script that takes two user inputted numbers # and prints "The first number is larger." or # "The second number is larger." depending on which is larger. # If the numbers are equal print "The two numbers are equal." first = int(input('Enter first test value: ')) second = int(input('Enter second test value: ')) if first > second: print('The first number is larger.') elif first < second: print('The second number is larger.') else: print('The two numbers are equal.') # Challenge 2 # Write a script that computes the factorial # of a user inputted positive numbers # and prints the result. user_input = int(input('Enter a value to compute its factorial: ')) total = 1 while user_input > 0: total *= user_input user_input -= 1 print(total) # Challenge 3 # Write a script that computes and prints # all of the positive divisors of a user inputted # positive number from lowest to highest. user_input = int(input('Enter a value to view all positive divisors: ')) x = 1 while user_input >= x: if user_input % x == 0: print(x) x += 1 else: x += 1 # Challenge 4 # Write a script that copmutes the greatest common divisor # between two user inputted positive numbers and prints the result. user_input = int(input('Please enter the first test value: ')) second_user_input = int(input('Please enter the second test value: ')) divisor = 1 gcd = 1 while divisor <= user_input or divisor <= second_user_input: if user_input % divisor == 0 and second_user_input % divisor == 0: gcd = divisor divisor += 1 else: divisor += 1 print(gcd)
true
2c86f82938fc6dd74902d3b17969b435f73a0f49
Dragonet-D/python3-study
/10-30/集合.py
1,801
4.15625
4
# 去重 关系测试 测试两个列表的 交集 并集 # 集合也是无序的 a = set([3, 4, 5, 6, 2, 3]) print(a) list_1 = [1, 3, 4, 5, 234, 23, 2, 2, 3, 4, 5] list_1 = set(list_1) list_2 = set([2, 3, 45, 4, 6, 12, 34]) list_3 = set([1, 2, 4]) ''' print(list_1, type(list_1)) # <class 'set'> print(list_1, list_2) # 取交集 intersection & print(list_1.intersection(list_2)) print(list_1 & list_2) # 并集 union print(list_1.union(list_2)) # 差集 difference list_1里面有的 list_2里面没有的 # in list_1 but not in list_2 print(list_1.difference(list_2)) print(list_2.difference(list_1)) # 子集 print(list_1.issubset(list_2)) # False print(list_3.issubset(list_1)) # True # 父级 print(list_1.issuperset(list_2)) # False print(list_1.issuperset(list_3)) # True # 对称差集 去掉两个列表的交集 print(list_1.symmetric_difference(list_2)) print('--------------------------') # 判断两个集合有没有交集 list_4 = set([5, 6, 8]) print(list_3.isdisjoint(list_4)) # True ''' # 交集 print(list_1 & list_2) # 并集 print(list_1 | list_2) # 差集 print(list_1 - list_2) # in list_1 but not on list_2 # 对称差集 print(list_1 ^ list_2) # subset and upperset 子集 # 操作 # 添加 list_1.add(1000) list_1.update([1,2,3,4,56,7,664]) print(list_1) # 删除 print(list_1.remove(5)) # pop 删除并返回当前的元素 # 长度 len(list_1) # x in a print(1 in list_1) # x not in a print(1 not in list_1) # 删除第一个 并返回删除的那个 print(list_1.pop()) print(list_1.pop()) print(list_1.pop()) print(list_1.pop()) print(list_1.pop()) """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ list_2.discard(34) # 没有返回值 # remove 要是没有的话会报错 print(list_2) print(not None)
false
9519d3910c4cd9122b1cb633016d1f72e5c3a080
yash001dev/learnpython
/_13.if_Project.py
248
4.125
4
weight=input("Enter Weight:") unit=input('(L)bs or (K)g:') if unit.upper()=="L": converter=float(weight)*0.45 print(f"You are {converter} Kilos") else: converter=float(weight)/0.45 print(f"You are {converter} Pounds")
false
95350d0995ec53e75601c3db0010b9da7ce90ebe
ricek/lpthw
/ex11/ex11-1.py
265
4.40625
4
# Prompt the user to enter their name # end='' arg tells print function to not end the line print("First Name:", end=' ') first = input() print("Last Name:", end=' ') last = input() # Prints out formatted string with the given input print(f"Hello {first} {last}")
true
9013585a902e8aa2384f162b4a8c25e730429778
arossholm/Py_Prep
/egg_problem.py
1,347
4.125
4
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle # http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/ INT_MAX = 32767 def eggDrop(n, k): # A 2D table where entery eggFloor[i][j] will represent minimum # number of trials needed for i eggs and j floors. eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)] print("eggFloor") print(eggFloor) # We need one trial for one floor and 0 trials for 0 floors for i in range(1, n + 1): eggFloor[i][1] = 1 eggFloor[i][0] = 0 print("eggFloor2") print(eggFloor) # We always need j trials for one egg and j floors. for j in range(1, k + 1): eggFloor[1][j] = j print("eggFloor3") print(eggFloor) # Fill rest of the entries in table using optimal substructure # property # eggFloor[egg(i)][floor(j)] for i in range(2, n + 1): for j in range(2, k + 1): eggFloor[i][j] = INT_MAX for x in range(1, j + 1): res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]) if res < eggFloor[i][j]: eggFloor[i][j] = res print (eggFloor) # eggFloor[n][k] holds the result print("eggFloor Resultat") print (eggFloor) return eggFloor[n][k] print(eggDrop(2,10))
true
15736fddabeae0cc481fec6bc6c40bdecae06799
KabanguJDTshikuma/my-practices
/Who likes it/whoLikesIt.py
546
4.125
4
def likes(names): if len(names) == 1: return names[0] + ' likes this' elif len(names) == 2: return str(names[0]) + ' and ' + str(names[1]) + ' like this' elif len(names) == 3: return str(names[0]) + ', ' + str(names[1]) + ' and ' + str(names[2]) + ' like this' elif len(names) > 3: return str(names[0]) + ', ' + str(names[1]) + ' and ' + str(len(names) - 2) + ' others like this' else: return 'no one likes this' print(likes(['Dadi', 'soso', 'lody', 'damimi']))
false
7059aba4cb753cfbd24f357b8ca4a1aac5cea3ae
sagaar333/Python
/mergeSort.py
573
4.25
4
import Bubble_Sort def mergeSort(l1,l2): l3=[] i=0 j=0 while(i<len(l1))&(j<len(l2)): if(l1[i]<l2[j]): l3.append(l1[i]) i+=1 else: l3.append(l2[j]) j+=1 if(i<len(l1)): l3.extend(l1[i:]) else: l3.extend(l2[j:]) print(l3) def main(): l1=eval(input("Enter 1st List :")) l2=eval(input("Enter 2nd List :")) Bubble_Sort.BubbleSort(l1) Bubble_Sort.BubbleSort(l2) mergeSort(l1,l2) if __name__=='__main__': main()
false