blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3b4ac26a260e4a0118d90637899ee3755c975a97
aburmd/leetcode
/Regular_Practice/easy/17_371_Sum_of_Two_Integers.py
1,883
4.125
4
""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = -2, b = 3 Output: 1 """ class Solution: def getPositivesum(self,a,b): while b!=0: bitcommon=a&b #Example: 4(100),5(101) bit common(a&b) is 4(100) a=a^b #Example: 4(100),5(101) bit diff(a^b) is 1(001) b=bitcommon<<1 #Example: one shift, 4 one shift (4(100)<<1) is 8(1000) return a def getNegativesum(self,apos,bneg): upperbound=0xfffffffff #f-1111 ie 0xf-15 define the max value for calculation upperbound_plus1=self.getPositivesum(upperbound,1) b=bneg&0xfffffffff #negative value starts in reverse order from upperbound #like (-1&0xf->15,-1&0xff->255) here -1&0xfffffffff = -1=68719476735) a=self.getPositivesum(apos,b) if a==upperbound: return -1 elif a>upperbound: return a%upperbound_plus1 else: return -1*((-1*a)&0xfffffffff) def getSum(self,a, b): if a==(-1)*b: return 0 elif a>=0 and b>=0: return self.getPositivesum(a,b) elif a<=0 and b<=0: apos=-1*a bpos=-1*b return -1*self.getPositivesum(apos,bpos) else: if b<0: return self.getNegativesum(a,b) else: return self.getNegativesum(b,a) """ SecondCommit: Runtime: 24 ms, faster than 91.03% of Python3 online submissions for Sum of Two Integers. Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Sum of Two Integers.. FirstCommit: Runtime: 24 ms, faster than 92.83% of Python3 online submissions for Sum of Two Integers. Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Sum of Two Integers. """
true
9eba98a92942adeb3cffc9bab950d03c384e56c0
MarthaSamuel/simplecodes
/OOPexpt.py
1,142
4.46875
4
#experimenting with Object Orienting Programming #defining our first class called apple class Apple: pass #we define 2 attributes of the class and initialize as strings class Apple: color = '' flavor = '' # we define an instance of the apple class(object) jonagold = Apple() # attributes of the object jonagold.color = 'red' jonagold.flavor = 'sweet' print(jonagold.color.upper()) # another instance golden = Apple() golden.color ='yellow' golden.flavor = 'soft' # this prints a poem class Flower: pass rose = Flower() rose.color = 'red' violet = Flower() violet.color= 'blue' pun = 'This pun is for you' print('Roses are {}'.format(rose.color)) print('Violets are {}'.format(violet.color)) print(pun) #sample 3 class Furniture: color = '' material = '' table = Furniture() table.color = 'brown' table.material = 'wood' couch = Furniture() couch.color = 'red' couch.material = 'leather' def describe_furniture(piece): return ('This piece of furniture is made of {} {}'.format(piece.color, piece.material)) print(describe_furniture(table)) print(describe_furniture(couch)) dir(" ") help({}) help(Apple)
true
4ac5b4a4d773a73aa6768d57afd9e44a3482cb86
AllenWang314/python-test-scaffolding
/interview.py
275
4.3125
4
""" returns square of a number x raises exception if x is not of type int or float """ def square(x): if type(x) != int and type(x) != float: raise Exception("Invalid input type: type must be int or float") print(f"the square is {x**2}") return x**2
true
84ed875a37f483f8acfa592c24bd6c9dd5b4cbf7
RuchirChawdhry/Python
/all_capital.py
1,163
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # script by Ruchir Chawdhry # released under MIT License # github.com/RuchirChawdhry/Python # ruchirchawdhry.com # linkedin.com/in/RuchirChawdhry """ Write a program that accept a sequence of lines* and prints the lines as input and prints the lines after making all the characters in the sequence capitalized. *blank line or CTRL+D to terminate """ import sys def all_caps(): lines = list() while True: sequence = input() if sequence: lines.append(str(sequence.upper())) else: break return "\n".join(lines) def all_caps_eof(): print("[CTRL+D] to Save & Generate Output") lines = list() while True: try: sequence = input() except EOFError: break lines.append(str(sequence.upper())) return "\n".join(lines) def all_caps_readlines(): print("[CTRL+D] to Save & Generate Output") lines = sys.stdin.readlines() return f"\n\nALL CAPS:\n {' '.join(lines).upper()}" # use single quotes w/ .join() when using it in fstring if __name__ == "__main__": print(all_caps_readlines())
true
656ae9779498767407dfbec47689c6aaf15907d3
RuchirChawdhry/Python
/circle_class.py
984
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # script by Ruchir Chawdhry # released under MIT License # github.com/RuchirChawdhry/Python # ruchirchawdhry.com # linkedin.com/in/RuchirChawdhry """ Define a class 'Circle' which can be constructed by either radius or diameter. The 'Circle' class has a method which can compute the area and perimeter. """ import math class Circle: def __init__(self, radius=0, diameter=0): self.radius = radius self.diameter = diameter def _area(self): if self.diameter: self.radius = self.diameter / 2 return math.pi * (self.radius * self.radius) def _perimeter(self): if self.diameter: self.radius = self.diameter / 2 return 2 * math.pi * self.radius def compute(self): return [self._area(), self._perimeter()] if __name__ == "__main__": c = Circle(diameter=10) print(f"Area of Cricle: {c.compute()[0]} \nPerimeter of Circle: {c.compute()[1]}")
true
f3c2abbab1697397006113c42c1fc03568d17719
Sanchi02/Dojo
/LeetCode/Strings/ValidPalindrome.py
742
4.125
4
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # Note: For the purpose of this problem, we define empty string as valid palindrome. # Example 1: # Input: "A man, a plan, a canal: Panama" # Output: true # Example 2: # Input: "race a car" # Output: false # Constraints: # s consists only of printable ASCII characters. class Solution: def isPalindrome(self, s: str) -> bool: modified = '' s = s.lower() for c in s: if(c.isalnum()): modified = modified + c size = len(modified) for i in range(size//2): if(modified[i]!=modified[size-i-1]): return False return True
true
768e42c29a97bcf3c2d6ec5992d33b9458fb56e8
ujjwalshiva/pythonprograms
/Check whether Alphabet is a Vowel.py
256
4.40625
4
# Check if the alphabet is vowel/consonant letter=input("Enter any letter from a-z (small-caps): ") if letter == 'a' or letter =='e' or letter =='i' or letter =='o' or letter =='u': print(letter, "is a Vowel") else: print(letter, "is a Consonant")
true
16e13a2f6042e3deae198df89a2956f6648edfb4
davidwang0829/Python
/小甲鱼课后习题/34/习题2.py
1,464
4.15625
4
# 使用try…except语句改写第25课习题3 print('''--- Welcome to the address book program --- --- 1:Query contact information --- --- 2:Insert a new contact --- --- 3:Delete existing contacts --- --- 4:Exit the address book program ---''') dic = dict() while 1: IC = input('\nPlease enter the relevant instruction code:') if IC == '1': name = input("Please enter the contact's name:") try: print(name + ':' + dic[name]) except KeyError: print('Sorry,the program failed to find the contact') if IC == '2': key = input("Please enter the contact's name:") try: print('''The name you entered already exists in the address book -->> %s:%s''' % (key, dic[key])) if input('Whether to modify the user information?(y/n)') == 'y': dic[key] = input('Please enter the new contact number:') except KeyError: dic[key] = input('Please enter the user contact number:') if IC == '3': key = input("Please enter the contact's name:") try: del(dic[key]) print('Address book has been successfully emptied') except KeyError: print('Sorry,the program failed to find the contact') if IC == '4': break else: print('You may entered a wrong instruction code.Please enter the correct instruction code') print('--- Thanks for using address book program ---')
true
be23213891eb1945990bd61cec32c986a29fba49
matvelius/Selection-Sort
/selection_sort.py
1,825
4.3125
4
# The algorithm divides the input list into two parts: # the sublist of items already sorted, which is built up from left # to right at the front (left) of the list, and the sublist of items # remaining to be sorted that occupy the rest of the list. # Initially, the sorted sublist is empty and the unsorted sublist is # the entire input list. The algorithm proceeds by finding the smallest # (or largest, depending on sorting order) element in the unsorted # sublist, exchanging (swapping) it with the leftmost unsorted element # (putting it in sorted order), and moving the sublist boundaries one # element to the right. myArray = [7, 3, -1, 0, 9, 2, 4, 6, 5, 8] def selectionSort(array): if len(array) <= 1: print("array length is 1 or less") return array unsortedIndex = 0 endOfArrayIndex = len(array) while unsortedIndex < endOfArrayIndex: print(f"starting another iteration of the while loop; unsortedIndex: {unsortedIndex}") # find smallest value in unsorted array smallestValue = array[unsortedIndex] smallestValueIndex = unsortedIndex for index in range(unsortedIndex, endOfArrayIndex): if array[index] < smallestValue: smallestValue = array[index] smallestValueIndex = index print(f"smallestValue found: {smallestValue} and index: {smallestValueIndex}") # swap the smallest value with leftmost value if array[smallestValueIndex] < array[unsortedIndex]: swap(unsortedIndex, smallestValueIndex, array) print(f"result so far: {array}") unsortedIndex += 1 print(array) return array # i & j are indices of numbers to swap def swap(i, j, array): array[i], array[j] = array[j], array[i] selectionSort(myArray)
true
52ae48b48dd9f7c9a60970dab786b3a02a7f76b0
abhi15sep/Python-Course
/introduction/loops/Loop_Example/exercise.py
637
4.125
4
# Use a for loop to add up every odd number from 10 to 20 (inclusive) and store the result in the variable x. # Add up all odd numbers between 10 and 20 # Store the result in x: x = 0 # YOUR CODE GOES HERE: #Solution Using a Conditional for n in range(10, 21): #remember range is exclusive, so we have to go up to 21 if n % 2 != 0: x += n #Solution using range step #Instead of looping over every number between 10 and 20, this solution only loops over the odd numbers. Remember, the 3rd argument to range() is the STEP or interval that you want the range to increment by. x = 0 for i in range(11, 21, 2): x += i
true
684a6a2571adb3bb17ea97230600d5ae76ed6570
abhi15sep/Python-Course
/collection/Dictionaries/examples/Dictionary.py
1,581
4.5625
5
""" A dictionary is very similar to a set, except instead of storing single values like numbers or strings, it associates those values to something else. This is normally a key-value pair. For example, we could create a dictionary that associates each of our friends' names with a number describing how long ago we last saw them: """ my_friends = { 'Jose': 6, 'Rolf': 12, 'Anne': 6 } """ The same constraints as sets apply, but only on the keys. You cannot have duplicate keys, and the keys are not ordered. The values can be duplicated as many times as you want. However, you cannot add or subtract dictionaries like you can do with sets. """ ## Nested dictionaries """ You can have anything as the value for a key. That includes a using a dictionary as a value! """ my_friends = { 'Jose': { 'last_seen': 6 }, 'Rolf': { 'surname': 'Smith' }, 'Anne': 6 } """ Notice how the values are each independent objects. They don't need to have the same keys (although they can). They don't even all have to be dictionaries! They can be anything you want them to be. """ ## Lists and dictionaries players = [ { 'name': 'Rolf', 'numbers': (13, 22, 3, 6, 9) }, { 'name': 'John', 'numbers': (22, 3, 5, 7, 9) } ] # How could we select one of these? player = players[0] # How could we add all the numbers of a player? sum(player['numbers']) # We have a function that takes in a list—it does not have to be a list of numbers # of a player. Indeed, we could do something like this: sum([1, 2, 3, 4, 5])
true
52432f6633d264b1f53d9c6e8a9bb834e4532d7b
abhi15sep/Python-Course
/introduction/example/lucky.py
502
4.15625
4
#At the top of the file is some starter code that randomly picks a number between 1 and 10, and saves it to a variable called choice. Don't touch those lines! (please). #Your job is to write a simple conditional to check if choice is 7, print out "lucky". Otherwise, print out "unlucky". # NO TOUCHING PLEASE--------------- from random import randint choice = randint(1, 10) # NO TOUCHING PLEASE--------------- # YOUR CODE GOES HERE: if choice == 7: print("lucky") else: print("unlucky")
true
2eab7e313a1104ca9384d3c73f8e3d3b10ff4491
abhi15sep/Python-Course
/Functions/examples/exercise4.py
600
4.4375
4
#Implement a function yell which accepts a single string argument. It should return(not print) an uppercased version of the string with an exclamation point aded at the end. For example: # yell("go away") # "GO AWAY!" #yell("leave me alone") # "LEAVE ME ALONE!" #You do not need to call the function to pass the tests. #Using string concatenation: def yell(word): return word.upper() + "!" #Using the string format() method: def yell(word): return "{}!".format(word.upper()) #Using an f-string. But only works in python 3.6 or later. def yell(word): return f"{word.upper()}!"
true
b8c247b00db447a205409067aad84ea853ad2040
abhi15sep/Python-Course
/introduction/example/positive_negative_check.py
970
4.46875
4
# In this exercise x and y are two random variables. The code at the top of the file randomly assigns them. #1) If both are positive numbers, print "both positive". #2) If both are negative, print "both negative". #3) Otherwise, tell us which one is positive and which one is negative, e.g. "x is positive and y is negative" # NO TOUCHING ====================================== from random import randint x = randint(-100, 100) while x == 0: # make sure x isn't zero x = randint(-100, 100) y = randint(-100, 100) while y == 0: # make sure y isn't zero y = randint(-100, 100) # NO TOUCHING ====================================== # YOUR CODE GOES HERE if x > 0 and y > 0: print("both positive") elif x < 0 and y < 0: print("both negative") elif x > 0 and y < 0: print("x is positive and y is negative") else: print("y is positive and x is negative") print("y is positive and x is negative") print("y is positive and x is negative")
true
9d18ab098eb2d59fbba6595cbc157dd3b629d87a
yogabull/LPTHW
/ex14.py
789
4.15625
4
# Exercise 14: Prompting and Passing from sys import argv script, user_name, last_name, Day = argv #prompt is a string. Changing the variable here, changes every instance when it is called. prompt = 'ENTER: ' #the 'f' inside the parenthesis is a function or method to place the argv arguements into the sentence. print(f'Hi {user_name} {last_name}, I\'m the {script} script.') print("I'd like to ask you a few questions.") print(f"Do you like me {user_name}?") likes = input(prompt) print(f"Where do you live {user_name}?") lives = input(prompt) print("What kind of computer do you have?") computer = input(prompt) print(f""" Alright, so you said {likes} about liking me. Today is {Day}, and you live in {lives}. Not sure where that is. And you have a {computer} computer. Nice """)
true
ef8d22e8ab44d0a3cad96db2c94779ab98c2d11c
Catrinici/Python_OOP
/bike_assignement.py
1,177
4.28125
4
class Bike: def __init__(self, price, max_speed, miles): self.price = price self.max_speed = max_speed self.miles = abs(0) def ride(self): print("Riding!") self.miles += 10 print(f"Total miles : {self.miles}") return self def reverse(self): print("Reversing!") self.miles -= 5 print(f"Total miles : {abs(self.miles)}") return self def displayInfo(self): print( f"The price of this bike is ${ self.price }. The maximum speed is {self.max_speed}.Total riding miles is: {abs(self.miles)} miles") return self # Have the first instance ride three times, reverse once and have it displayInfo(). bike1 = Bike(200,"24mph",0) i = 1 while i <=3: bike1.ride() i+=1 bike1.reverse().displayInfo() # Have the second instance ride twice, reverse twice and have it displayInfo(). bike2 = Bike(150,"20mph",0) i = 1 while i <=2: bike2.ride().reverse() i+=1 bike2.displayInfo() # Have the third instance reverse three times and displayInfo(). bike3 = Bike(110,"18mph",0) i = 1 while i <=3: bike3.reverse() i+=1 bike3.displayInfo()
true
459bbf3c436621c0b769c07740b44261bb84ff3d
Abeilles14/Java_exercises
/6.32_IfThenElseChallenge/IfThenElseChallenge.py
274
4.15625
4
#isabelle andre #14-07/18 #if challenge name = input("Enter your name: ") age = int(input("Enter your age: ")) #if age >= 18 and age <= 30: if 18 >= age <= 30: print("Welcome to the 18-30 holiday, {}".format(name)) else: print ("You are not eligible to enter the holiday")
true
8d69bd1f68bd1dfe19adb1909d0ed541fdef7b7c
mmsamiei/Learning
/python/dictionary_examples/create_grade_dictionary.py
532
4.1875
4
grades = {} while(True): print("Enter a name: (blank to quit):") name = raw_input() if name == '': break if name in grades: print(' {grade} is the grade of {name} ').format(grade=grades[name],name=name) else: print("we have not the grade of {name}").format(name=name) print("what is his/her grade?:") grade = input() grades[name]=grade print("Yes we updated database") for name in grades: print "{name} : {grade}".format(name=name,grade=grades[name])
true
6a07533146042655f2780ff329ecaff3089cedd6
ziyuanrao11/Leetcode
/Sum of 1d array.py
2,483
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 26 14:41:32 2021 @author: rao """ '''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. Example 2: Input: nums = [1,1,1,1,1] Output: [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].''' from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: length=len(nums) nums_new=[] for i in range(length): if i==0: add=nums[i] nums_new.append(add) else: add=nums[i] for j in range(i): add=add+nums[j] nums_new.append(add) return nums_new nums=[0,1,2,3,4] s=Solution() nums_new=s.runningSum(nums) print(nums_new) '''standard answer''' class Solution: def runningSum(self, nums: List[int]) -> List[int]: return [sum(nums[:i + 1]) for i in range(len(nums))] nums=[0,1,2,3,4] s=Solution() nums_new=s.runningSum(nums) print(nums_new) '''improved answer based on mine''' class Solution: def runningSum(self, nums: List[int]) -> List[int]: length=len(nums) nums_new=[] for i in range(length): add=sum(nums[:i+1]) nums_new.append(add) return nums_new nums=[0,1,2,3,4] s=Solution() nums_new=s.runningSum(nums) print(nums_new) '''another''' class Solution: def runningSum(self, nums): temp_sum = 0 for i, num in enumerate(nums): nums[i] += temp_sum temp_sum = nums[i] return nums '''another''' class Solution: def runningSum(self, nums: List[int]) -> List[int]: for i in range(1, len(nums)): nums[i] += nums[i-1] return nums '''another''' class Solution: def runningSum(self, nums): summ=0 lst=[] for i in nums: summ+=i lst.append(summ) return lst '''the best''' class Solution(object): def runningSum(self, nums): for i in range(1, len(nums)): nums[i] = nums[i-1] + nums[i] return nums
true
eb5b36fd683ead2eb4205f18ab6897eb76327aa0
pandiarajan-src/PyWorks
/educative_examples/benchmarking_ex3.py
1,192
4.15625
4
# Benchmarking # Create a Timing Context Manager """ Some programmers like to use context managers to time small pieces of code. So let’s create our own timer context manager class! """ import random import time class MyTimer(): def __init__(self): self.start = time.time() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): end = time.time() runtime = end - self.start msg = 'The function took {time} seconds to complete' print(msg.format(time=runtime)) def long_runner(): for x in range(5): sleep_time = random.choice(range(1,5)) time.sleep(sleep_time) if __name__ == '__main__': with MyTimer(): long_runner() """ In this example, we use the class’s __init__ method to start our timer. The __enter__ method doesn’t need to do anything other then return itself. Lastly, the __exit__ method has all the juicy bits. Here we grab the end time, calculate the total run time and print it out. The end of the code actually shows an example of using our context manager where we wrap the function from the previous example in our custom context manager. """
true
e86df3f56dc9ca95f6a2018b41e19aa3fc7f8e5b
pandiarajan-src/PyWorks
/Learn/converters_sample.py
1,108
4.28125
4
'''This example script shows how to convert different units - excercise for variables''' MILES_TO_KILO_CONST = 1.609344 RESOLUTION_CONST = 2 def miles_to_kilometers(miles): """Convert given input miles to kilometers""" return round((miles * MILES_TO_KILO_CONST), RESOLUTION_CONST) def kilometers_to_miles(kilometers): """Convert given inputs kilometers to miles""" return round((kilometers/MILES_TO_KILO_CONST), RESOLUTION_CONST) def main(): """main method to execute the complete code""" try: input_data = int(input("Enter input for miles to kilo and vice-versa : ")) print("Input: {0} Miles to Kilometers : {1}".format(input_data, \ miles_to_kilometers(input_data))) print("Input: {0} Kilometers to Miles : {1}".format(input_data, \ kilometers_to_miles(input_data))) except Exception as e_catch: # pylint: disable=broad-except print("Exception message {0}".format(e_catch.__str__)) if __name__ == "__main__": main()
true
58ef0063ab66182a98cfeb82a2173be41952ac75
chigginss/guessing-game
/game.py
1,870
4.21875
4
"""A number-guessing game.""" from random import randint def guessing_game(): # pick random number repeat = "Y" scores = [] #Greet player and get the player name rawinput print("Hello!") name = raw_input("What is your name? ") while repeat == "Y": start = int(raw_input("Choose a starting number: ")) end = int(raw_input("Choose an ending number: ")) number = randint(start, end) # Get the player to chose a number between 1 and 100 rawinput print("%s, I'm thinking of a number between 1 and 100, guess my number! You only get three guesses!") % name # print try to guess my number! digit = 0 guess = 0 while digit < 15 and guess != number: try: guess = int(raw_input("What is your guess? ")) if guess < 1 or guess > 100: print("Follow the instructions!!") elif guess < number: print("Your guess is too low, try again!") elif guess > number: print("Your guess is too high, try again!") except ValueError: print("Follow the instructions!!") digit += 1 if guess == number: scores.append(digit) lowest_score = min(scores) print("Congrats %s! You found my number in %d tries! \nYour best score is %d") % (name, digit, lowest_score) else: print("Too many tries!") repeat = raw_input("Do you want to play again? Y or N: ") guessing_game() #two rawinput for the start and end number at line 15 #change line 24 to var start and end #bigger the range the harder the game is >> 100 vs 50, the larger range is 2X, #divide larger range by smaller 5(2) for 50 and 5(1) for 100 #measuring range: end - start + 1 = range
true
fd6d45ba6fecb3605e025a74ed5f56abc63e6625
slayer6409/foobar
/unsolved/solar_doomsday.py
1,692
4.4375
4
""" Solar Doomsday ============== Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels. Due to the nature of the space station's outer paneling, all of its solar panels must be squares. Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors, and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares. For example, if you had a total area of 12 square yards of solar material, you would be able to make one 3x3 square panel (with a total area of 9). That would leave 3 square yards, so you can turn those into three 1x1 square solar panels. Write a function answer(area) that takes as its input a single unit of measure representing the total area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the largest squares you could make out of those panels, starting with the largest squares first. So, following the example above, answer(12) would return [9, 1, 1, 1]. Python ====== Your code will run inside a Python 2.7.6 sandbox. Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib. Test cases ========== Inputs: (int) area = 12 Output: (int list) [9, 1, 1, 1] Inputs: (int) area = 15324 Output: (int list) [15129, 169, 25, 1] """ def answer(area): # your code here n = '' m = '' area = n**2 result = [] print result print answer(area)
true
e77a9e0ab70fbb5916f12e1b864f5f5b7211ba48
gauravkunwar/PyPractice
/PyExamples/factorials.py
248
4.3125
4
num=int(input("Enter the value :")) if(num<0): print("Cannot be factorized:") elif (num==0): print("the factorial of 0 is 1:") else : for i in range(0 to num+1): factorial=factorial*i print"the factorial of a given number is:",factorial
true
48d1eeffbf97cdf144e0f8f1fb6305da1141b5be
gauravkunwar/PyPractice
/PyExamples/largestnum.py
352
4.3125
4
num1=float(input("Enter the first num:")) num2=float(input("Enter the second num:")) num3=float(input("Enter the third num:")) if: (num1>num2) and(num1>num3) print("largest=num1") elif: (num2>num3) and(num2>num1) print("largest=num2") else print("largest=num3") #print("The largest number among,"num1","num2",num3","is", largest )
true
f1ac7ce434862b7b26f5225810e65f539ec38838
Nike0601/Python-programs
/km_cm_m.py
322
4.3125
4
print "Enter distance/length in km: " l_km=float(input()) print "Do you want to convert to cm/m: " unit=raw_input() if unit=="cm": l_cm=(10**5)*l_km print "Length in cm is: "+str(l_cm) elif unit=="m": l_m=(10**3)*l_km print "Length in m is: "+str(l_m) else: print "Invalid input. Enter only cm or m"
true
f31a2f8ae56690da86253aed017a2dfa91a83343
okdonga/algorithms
/find_matches_both_prefix_and_suffix.py
2,873
4.15625
4
################ # Given a string of characters, find a series of letters starting from the left of the string that is repeated at the end of the string. # For example, given a string 'jablebjab', 'jab' is found at the start of the string, and the same set of characters is also found at the end of the string. # This is one match. Here, we call the first job - prefix, and the latter jab - suffix. Find all cases where a set of characters starting from the left of the string is also found at end of the string. The output should be the length of a series of letters that match this pattern. So, with 'jablebjab', a seris of letters that our pattern are 1, 'jab' 2, 'jablebjab'. So, the output is [3, 9] # More examples as follows: # eg1. # input: alaghggiualagihjkbcala # matches: 1. a 2. ala 3. alala # output: [1, 3, 5] # eg2. # input: ababcababababcabab # matches: 1. a 2. abab 3. ababcabab 4. ababcababababcabab # output: [2, 4, 9, 18] # PSEUDOCODE # input : dad's nume + mum's name # output : length of each combination of letters that can be both prefix and suffix # find all possible cases of repeated letters that starts with a(original[0]) and ends with last word in the combined string (b) # eg. ab, abab, ababcab, ababcabab, ababcababab, ... entire string # compare if the prefix also match the last x digits of the string # if it is, count the num and push it to to the results array # CORNER CASE: # 1. when there is no repeation in the string def find_words_that_can_be_both_prefix_and_suffix(str): total_length = len(str) # If there is no repetition in the string, no need to proceed further uniq_str = set(str) if len(uniq_str) == total_length: return [total_length] start = str[0] end = str[total_length-1] # Find all cases of prefix that start with the first letter of string and end with the last letter of string prefixes = [] for idx, letter in enumerate(str): if letter == end: prefixes.append(str[:idx+1]) # Out of all prefixes, find ones that also count as suffixes prefixes_and_suffixes = [] for prefix in prefixes: len_of_prefix = len(prefix) suffix_start_idx = total_length - len_of_prefix if str[suffix_start_idx:] == prefix: prefixes_and_suffixes.append(len_of_prefix) # prefixes_and_suffixes.append(prefix) return prefixes_and_suffixes print find_words_that_can_be_both_prefix_and_suffix('aaaaaa') # print find_words_that_can_be_both_prefix_and_suffix('jab56jab') # print find_words_that_can_be_both_prefix_and_suffix('a') # print find_words_that_can_be_both_prefix_and_suffix('ab') # print find_words_that_can_be_both_prefix_and_suffix('alala') # print find_words_that_can_be_both_prefix_and_suffix('abcde') # print find_words_that_can_be_both_prefix_and_suffix('ababcababababcabab')
true
6d0745071e38ee8949a6392e51d8f036faef9dcc
arnillacej/calculator
/calculator.py
397
4.34375
4
num1 = float(input("Please enter the first number: ")) operation = input("Please choose an arithmetical operation '+,-,*,/': ") num2 = float(input("Please enter the second number: ")) if operation == "+": print(num1+num2) elif operation == "-": print(num1-num2) elif operation == "*": print(num1*num2) elif operation == "/": print(num1/num2) else: print("Incorrect character")
true
74fd1b9071853159dbed349504f704be01534532
EricE-Freelancer/Learning-Python
/the power of two.py
426
4.40625
4
print("Hi! what is your name? ") name = input() anything = float(input("Hi " + name + ", Enter a number: ")) something = anything ** 2.0 print("nice to meet you " + name +"!") print(anything, "to the power of 2 is", something) #the float() function takes one argument (e.g., a string: float(string))and tries to convert it into a float #because we are inputing a number = float #input = string or alphabet only
true
be5e00cd27adb53a3e3c6f873ffdfc91acf1463f
Nayan356/Python_DataStructures-Functions
/Functions/pgm9.py
676
4.3125
4
# Write a function called showNumbers that takes a parameter called limit. # It should print all the numbers between 0 and limit with a label to # identify the even and odd numbers. def showNumbers(limit): count_odd = 0 count_even = 0 for x in range(1,limit): if not x % 2: count_even+=1 print(x, " is even") else: count_odd+=1 print(x," is odd") print("Number of even numbers :",count_even) print("Number of odd numbers :",count_odd) print("Enter a limit: ") l=int(input()) showNumbers(l)
true
b88b8781aff585532384232fae3028ec7ce2d82d
Nayan356/Python_DataStructures-Functions
/DataStructures_2/pgm7.py
472
4.4375
4
# # Write a program in Python to reverse a string and # # print only the vowel alphabet if exist in the string with their index. def reverse_string(str1): return ''.join(reversed(str1)) print() print(reverse_string("random")) print(reverse_string("consultadd")) print() # def vowel(text): # vowels = "aeiuoAEIOU" # print(len([letter for letter in text if letter in vowels])) # print([letter for letter in text if letter in vowels]) # vowel('consultadd')
true
c5a78bcae376bba759a179839b6eba037ecd6988
Nayan356/Python_DataStructures-Functions
/DataStructures/pgm7.py
232
4.375
4
# Write a program to replace the last element in a list with another list. # Sample data: [[1,3,5,7,9,10],[2,4,6,8]] # Expected output: [1,3,5,7,9,2,4,6,8] num1 = [1, 3, 5, 7, 9, 10] num2 = [2, 4, 6, 8] num1[-1:] = num2 print(num1)
true
84e673227276da95fa1bc8e4cf0801c5c77080a4
Nayan356/Python_DataStructures-Functions
/Functions/pgm7.py
519
4.4375
4
# Define a function that can accept two strings as input and print the string # with maximum length in console. If two strings have the same length, # then the function should print all strings line by line. def length_of_string(str1, str2): if (len(str1) == len(str2)): print(str1) #print("\n") print(str2) elif (len(str1) < len(str2)): print(str2) else: print(str1) stri1 = input(str("enter First String: ")) stri2 = input(str("enter Second String: ")) print("\n") length_of_string(stri1, stri2)
true
4f708d85e2be8dba03ad84c944f1192f7fb9c961
perryl/daftpython
/calc.py
846
4.15625
4
while True: try: x = int(raw_input('Enter a value: ')) break except: print "Integer values only, please!" continue while True: try: y = int(raw_input('Enter a second value: ')) break except: print "Integer values only, please!" continue add = x+y dif = abs(x-y) mul = x*y quo = x/y rem = x%y print 'The sum of ',x,' and ',y,' is ',add print 'The difference between ',x,' and ',y,' is ',dif print 'The product of ',x,' and ',y,' is ',mul if rem == 0: print 'The quotient of ',x,' and ',y,' is ',quo else: fquo = float(x)/y print 'The quotient of ',x,' and ',y,' is ',quo,' with a remainder of ',rem,' , ' print ' or when expressed as a decimal, ',fquo if add % 2 == 0: av1 = add/2 print 'Finally, the average of ',x,' and ',y,' is ',av1 else: av2 = float(add)/2 print 'Finally, the average of ',x,' and ',y,' is ',av2
true
c8c98a63020ff5971183ce90bd3d4a43d95f0b95
karayount/study-hall
/string_compression.py
1,012
4.53125
5
""" Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). >>> compress_string("aabcccccaaa") 'a2b1c5a3' """ def compress_string(string): compressed = "" char = string[0] count = 1 index = 1 while index < len(string): if string[index] == char: count += 1 else: compressed = compressed + char + str(count) char = string[index] count = 1 index += 1 compressed = compressed + char + str(count) if len(compressed) < len(string): return compressed else: return string if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** all tests passed.\n"
true
6190823da69071ca54625f541a5e90463c9876b7
karayount/study-hall
/highest_product.py
1,388
4.34375
4
"""Given a list_of_ints, find the highest_product you can get from three of the integers. The input list_of_ints will always have at least three integers. >>> find_highest_product([1, 2, 3, 4, 5]) 60 >>> find_highest_product([1, 2, 3, 2, 3, 2, 3, 4]) 36 >>> find_highest_product([0, 1, 2]) 0 >>> find_highest_product([-8, -1, 2, 0, 1]) 16 """ def find_highest_product_slow(arr): prod_seen = set() num_seen = set() max_prod = None for num in arr: if max_prod is None: max_prod = num for prod in prod_seen: possible_max = prod * num if possible_max > max_prod: max_prod = possible_max for seen in num_seen: prod_seen.add(seen*num) num_seen.add(num) return max_prod def find_highest_product(arr): highest_seen_prod = None lowest_seen_prod = None max_prod = None for num in arr: if max_prod is None: max_prod = num for prod in prod_seen: possible_max = prod * num if possible_max > max_prod: max_prod = possible_max for seen in num_seen: prod_seen.add(seen*num) num_seen.add(num) return max_prod if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. WE'RE WELL-MATCHED!\n"
true
52cffd996c81e097f71bec337c2dce3d69faecac
Potatology/algo_design_manual
/algorist/data_structure/linked_list.py
1,947
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Linked list-based container implementation. Translate from list-demo.c, list.h, item.h. Add iterator implementation. """ __author__ = "csong2022" class Node: """List node.""" def __init__(self, item, _next=None): self.item = item # data item self.next = _next # point to successor class List: def __init__(self): self.head = None def is_empty(self) -> bool: """Is list empty?""" return self.head is None def __contains__(self, x): """Check if list contains the value.""" return self.search(x) is not None def search(self, x) -> Node: p = self.head while p is not None and p.item != x: p = p.next return p def insert(self, x) -> None: """Insert value.""" self.head = Node(x, self.head) def delete(self, x) -> None: """Delete value iteratively.""" pred = None p = self.head while p is not None and p.item != x: pred = p p = p.next if p is not None: if pred is None: self.head = p.next else: pred.next = p.next p.next = None def delete_r(self, x) -> None: """Delete value.""" self.head = self._delete_r(self.head, x) def _delete_r(self, n, x) -> Node: """Delete value recursively.""" if n is None: return None elif n.item == x: return n.next else: n.next = self._delete_r(n.next, x) return n def __iter__(self): """Iterate over the linked list in LIFO order.""" current = self.head while current is not None: yield current.item current = current.next def print(self) -> None: for x in self: print(x, end=' '), print()
true
af76bb19fcfa690fa49ea0390ef6ea6e9716f133
Potatology/algo_design_manual
/algorist/data_structure/linked_queue.py
1,773
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implementation of a FIFO queue abstract data type. Translate from queue.h, queue.c. Implement with singly linked list. Add iterator implementation. """ __author__ = "csong2022" class Node: """Queue node.""" def __init__(self, item, _next=None): self.item = item # data item self.next = _next # point to successor class Queue: def __init__(self): self.count = 0 # number of queue elements self.first = None # first element self.last = None # last element def enqueue(self, x) -> None: """Enqueue""" old_last = self.last self.last = Node(x) if self.is_empty(): self.first = self.last else: old_last.next = self.last self.count += 1 def dequeue(self): """Dequeue""" if self.is_empty(): raise IndexError('Queue underflow') else: x = self.first.item self.first = self.first.next self.count -= 1 if self.is_empty(): self.last = None return x def headq(self): """Head of the queue.""" if self.is_empty(): raise IndexError('Queue empty') else: return self.first.item def is_empty(self) -> bool: """Is queue empty?""" return self.count == 0 def __iter__(self): """Iterate through the queue in FIFO sequence.""" current = self.first while current is not None: yield current.item current = current.next def print(self) -> None: for x in self: print(x, end=' ') print() def size(self): return self.count
true
fd96bd483b82593170856bc0d62ccab97ad33036
abriggs914/CS2043
/Lab2/palindrome.py
466
4.125
4
def palcheck(line, revline): half = (len(line) / 2) x = 0 while(half > x): if(line[x] == revline[x]): x += 1 else: return False return True class palindrome : line = raw_input("Please enter a string:") print(line) print(line[::-1]) revline = (line[::-1]) if(palcheck(line, revline)): print "line", line, "is a palindrome" else: print "line", line, "is not a palindrome"
true
85d156b95da272ad1d9cdb86cde272cd842e0fa0
imclab/introduction-to-algorithms
/2-1-insertion-sort/insertion_sort.py
728
4.34375
4
#!/usr/bin/env python # # insertion sort implementation in python # import unittest def insertion_sort(input): """ function which performs insertion sort Input: input -> array of integer keys Returns: the sorted array """ for j in xrange(len(input)): key = input[j] i = j - 1 # second index cursor while i >= 0 and input[i] > key: input[i + 1] = input[i] i -= 1 input[i + 1] = key return input class TestInsertionSort(unittest.TestCase): def test_insertion_sort(self): res = insertion_sort([3,5,6,1,2,4]) self.assertEqual(res, [1,2,3,4,5,6]) if __name__ == '__main__': unittest.main()
true
5e53080b0af272b0d9f0aa69e542bbaaa9af09f5
Azeem-Q/Py4e
/ex84.py
711
4.28125
4
""" 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. """ fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: line = line.rstrip() x = line.split() for i in x: lst.append(i) orglst = list() for i in lst: if i in orglst: continue else: orglst.append(i) orglst.sort() print(orglst) #print(len(lst)) #print(line.rstrip()) #print(range(4))
true
4877cfe0219914090f0eb38fec32a4cdafb780ec
mehnazchyadila/Python_Practice
/program45.py
512
4.15625
4
""" Exception Handling """ try: num1 = int(input("Enter Any Integer number : ")) num2 = int(input("Enter any integer number : ")) result = num1 / num2 print(result) except (ValueError,ZeroDivisionError,IndexError): print("You have to insert any integer number ") finally: print("Thanks") def voter(age): if age < 18: raise ValueError("Invalid Voter") return "You are allowed to vote " print(voter(19)) try: print(voter(17)) except ValueError as e: print(e)
true
87c7fa65332cd453521fbc957b430fd2878e2eb8
antoniougit/aByteOfPython
/str_format.py
916
4.34375
4
age = 20 name = 'Swaroop' # numbers (indexes) for variables inside {} are optional print '{} was {} years old when he wrote this book'.format(name, age) print 'Why is {} playing with that python?'.format(name) # decimal (.) precision of 3 for float '0.333' print '{0:.3f}'.format(1.0/3) # fill with underscores (_) with the text centered # (^) to 11 width '___hello___' print '{0:_^11}'.format('hello') # keyword-based 'Swaroop wrote A Byte of Python' print '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python') # comma to prevent newline (\n) after print print "a", print "b" print '''This is a triple-quoted string print in Python''' print 'This is the first line\nThis is the second line' print 'This is the first line\tThis is the second line after a tab' print "This is the first sentence. \ This is the second sentence." # raw strings, prefix r or R print r"Newlines are indicated by \n"
true
8f590bec22c64d0c9d89bfcc765f042883955a02
tprhat/codewarspy
/valid_parentheses.py
807
4.34375
4
# Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The # function should return true if the string is valid, and false if it's invalid. # Constraints # 0 <= input.length <= 100 # # Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, # the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as # parentheses (e.g. [], {}, <>). def valid_parentheses(string): stack = [] for x in string: try: if x == '(': stack.append(x) elif x == ')': stack.pop() except IndexError: return False if len(stack) == 0: return True return False
true
657dd462815393c877709d5dcdef2485ec6d8763
lidorelias3/Lidor_Elias_Answers
/python - Advenced/Pirates of the Biss‏/PiratesOfTheBiss‏.py
678
4.3125
4
import re def dejumble(scramble_word, list_of_correct_words): """ Function take scramble word and a list of a words and check what word in the list the scramble word can be :param scramble_word: word in pirate language :param list_of_correct_words: a list of words in our language :return: the words that the scramble word can make """ valid_words = [] # for each word for current_word in list_of_correct_words: if sorted(current_word) == sorted(scramble_word): valid_words.append(current_word) return valid_words if __name__ == '__main__': print(dejumble("ortsp", ['sport', 'parrot', 'ports', 'matey']))
true
8678b04cd9e28847b30d4b8ec7fe3f9aaddc1708
rohan8594/DS-Algos
/leetcode/medium/Arrays and Strings/ReverseWordsInAString.py
1,076
4.3125
4
# Given an input string, reverse the string word by word. # Example 1: # Input: "the sky is blue" # Output: "blue is sky the" # Example 2: # Input: " hello world! " # Output: "world! hello" # Example 3: # Input: "a good example" # Output: "example good a" # Note: # A word is defined as a sequence of non-space characters. # Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. # You need to reduce multiple spaces between two words to a single space in the reversed string. class Solution: def reverseWords(self, s: str) -> str: strArr = [] curWord, res = "", "" # strArr = s.split(" ") for char in s: if char == " ": strArr.append(curWord) curWord = "" continue curWord += char strArr.append(curWord) for i in range(len(strArr) - 1, -1, -1): if strArr[i] == "": continue res += strArr[i] + " " return res[:-1]
true
634119cf7cb1a5d461e0a320ac79151f217e00fd
rohan8594/DS-Algos
/leetcode/easy/Arrays and Strings/UniqueCharachters.py
476
4.25
4
# Given a string,determine if it is comprised of all unique characters. For example, # the string 'abcde' has all unique characters and should return True. The string 'aabcde' # contains duplicate characters and should return false. def uniqueChars(s): seen = set() for i in range(len(s)): if s[i] not in seen: seen.add(s[i]) else: return False return True print(uniqueChars("abcdefg")) print(uniqueChars("abcdefgg"))
true
a2510d4c072bbae473cee9ea22e27c081bd97a4c
MVGasior/Udemy_training
/We_Wy/reading_input.py
1,536
4.3125
4
# This program is a 1# lesson of In_Ou Udemy # Author: Mateusz Gąsior # filename = input("Enter filename: ") # print("The file name is: %s" % filename) file_size = int(input("Enter the max file size (MB): ")) print("The max size is %d" % file_size) print("Size in KB is %d" % (file_size * 1024)) print("-------------------------------------------------------") def check_int(s): """ This function checking if number is int :param s:number to check :return:True or False """ if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() input_a = input("Please insert parameter a of quadratic equation: ") input_b = input("Please insert parameter b of quadratic equation: ") input_c = input("Please insert parameter c of quadratic equation: ") if not check_int(input_a) or not check_int(input_b) or not check_int(input_c): print("The inserted values are not correct") else: a = int(input_a) b = int(input_b) c = int(input_c) if a == 0: print("This is not a quadratic equation !!!") else: delta = b ** 2 - 4 * a * c if delta < 0: print("The is no solution of that quadratic equation.") elif delta == 0: x1 = (- b - delta ** 0.5) / (2 * a) print("The only one zero point is: ", x1) else: x1 = (- b - delta ** 0.5) / (2 * a) x2 = (- b + delta ** 0.5) / (2 * a) print("The zero points are: ", x1, x2)
true
d1af7d34089b172801b7bef550955595791f2422
yujie-hao/python_basics
/datatypes/type_conversion_and_casting.py
1,689
4.75
5
# ================================================== """ https://www.programiz.com/python-programming/type-conversion-and-casting Key Points to Remember 1. Type Conversion is the conversion of object from one data type to another data type. 2. Implicit Type Conversion is automatically performed by the Python interpreter. 3. Python avoids the loss of data in Implicit Type Conversion. 4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user. 5. In Type Casting, loss of data may occur as we enforce the object to a specific data type. """ # ================================================== # implicit Type Conversion: Implicit Type Conversion is automatically performed by the Python interpreter. # 1. Converting integer to float: implicit conversion num_int = 123 num_flo = 1.23 num_new = num_int + num_flo print("datatype of num_int: ", type(num_int)) print("datatype of num_flo: ", type(num_flo)) print("datatype of num_new: ", type(num_new)) print("datatype of num_new: ", type(num_new)) # 2. Addition of string data type and integer datatype --> TypeError num_int = 123 num_str = "456" # num_new = num_int + num_str # TypeError: unsupported operand type(s) for +: 'int' and 'str' # print("Data type of num_new: ", type(num_new)) # print("num_new = ", num_new) # ================================================== # Explicit type conversion: <type>(), a.k.a: Type Casting num_int = 123 num_str = "456" num_str = int(num_str) print("Data type of num_str after type casting: ", type(num_str)) num_sum = num_int + num_str print("Data type of num_sum: ", type(num_sum), ", value: ", num_sum)
true
1eb815e71e54a98630a1c89715a1a59edabaf461
yujie-hao/python_basics
/objects/class_and_object.py
2,060
4.53125
5
# A class is a blueprint for the object class Parrot: # docstring: a brief description about the class. """This is a Parrot class""" # class attribute species = "bird" # constructor def __init__(self, name, age): # instance attribute self.name = name self.age = age # instance method def sing(self, song): return "{} sings {}".format(self.name, song) def dance(self): return "{} is now dancing".format(self.name) print("Parrot.__doc__: {}".format(Parrot.__doc__)) print("species: " + Parrot.species) print(Parrot.sing) # An object (instance) is an instantiation of a class blueParrot = Parrot("Blue", 10) greenParrot = Parrot("Green", 5) # access the class attributes print("Blue parrot is a {}".format(blueParrot.__class__.species)) print("Green parrot is a {}".format(greenParrot.__class__.species)) # access the instance attributes print("{} is {} years old".format(blueParrot.name, blueParrot.age)) print("{} is {} years old".format(greenParrot.name, greenParrot.age)) # call instance methods print(blueParrot.sing("'Happy'")) print(blueParrot.dance()) print(blueParrot.dance) # Constructors class ComplexNumber: def __init__(self, r=0, i=0): self.real = r self.imag = i def get_data(self): print(f'{self.real}+{self.imag}j') # Create a new ComplexNumber object num1 = ComplexNumber(2, 3) # Call get_data() method num1.get_data() # Create another ComplexNumber object # and create a new attribute 'attr' num2 = ComplexNumber(5) num2.attr = 10 print(num2.real, num2.imag, num2.attr) # print(num1.attr) # AttributeError: 'ComplexNumber' object has no attribute 'attr' # delete attributes and objects num1.get_data() del num1.imag # num1.get_data() # AttributeError: 'ComplexNumber' object has no attribute 'imag' num2.get_data() del ComplexNumber.get_data # num2.get_data() # AttributeError: 'ComplexNumber' object has no attribute 'get_data' c1 = ComplexNumber(1, 3) del c1 # c1.get_data() # NameError: name 'c1' is not defined
true
6a9980954beb1a423130f6eb65c83a2a4ec8a1b7
lekakeny/Python-for-Dummies
/file_operations.py
1,762
4.46875
4
""" File operation involves 1. opening the file 2. read or write the file 3. close file Here we are learning how to read and write files. I learnt how to read and write long time ago! How could I be learning now? Anyway, kwani ni kesho? """ f = open('text.txt', 'w', encoding='utf8') # open the file called text.txt if it does exist. If not the python will create one "Read from standard input and write to the file" """ inputs = input('input: ') # Define the input f.write(inputs) # write the input to the file using the write method f.close() # close the file so that the file object may not remain in memory. Data is only written when the file closes """ "Read from the file we have just created" f = open('text.txt', 'r') # r means read only print(f.read(6)) # read 6 characters from the current position (default is 0) print(f.read()) # read from current position to the end f.close() "Add more data to the file by using mode 'a'" f = open('text.txt', 'a') f.write(' I have just added this content to the file!') f.close() "Use 'with' statement to open file. File object will automatically close" with open('text1.txt', 'w') as f: f.write('I have learnt a new technique\n I am not very masai anymore\n call me stupid at your own risk') # use with statement to read the file with open('text1.txt', 'r') as f: print("This is the file I have created: \n", f.read()) 'Read the file line by line using the \'readline()\' method' with open('text1.txt', 'r') as f: line = f.readline() print("read one line: %s" % line) # use readlines to get a list of lines lines = f.readlines() # starts from the current position print(lines) "Can I call this file management? I now know how to read and write in python!"
true
ed5cb135e00272635753e85b0a7d8d859dea1e0d
lekakeny/Python-for-Dummies
/generator_and_decorators.py
2,132
4.59375
5
""" Generators are functions that return a lazy iterator lazy iterators do not store their contents in memory, unlike lists generators generate elements/values when you iterate over it It is lazy because it will not calculate the element until when we want to use the element """ "Use isinstance function to check if an object is iterable" import collections as c print(isinstance([], c.Iterable)) print(isinstance('a,b,c', c.Iterable)) print(isinstance(100, c.Iterable)) print(isinstance((1, 2, 3, 4, 5, 6,), c.Iterable)) "Create an iterator using iter function" l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11] l_iteration = iter(l) print("The type of iterator is: ", type(l_iteration)) "The next function provides the next element in the iterator" print("First Value is: ", next(l_iteration)) print("Second Value is: ", next(l_iteration)) print("Third Value is: ", next(l_iteration)) print("Fourth Value is: ", next(l_iteration)) # Generators: We define how each element in the iterator is generated "Use the example of n fibonacci numbers to learn the generators" print("fibonacci begins here") def fib(n): current = 0 num1, num2 = 0, 1 while current < n: num = num2 num1, num2 = num2, num1 + num2 current += 1 yield num # We use key word yield instead of return when building a generator yield "Done" g = fib(5) for number in g: print(number) "A shorter way to create generators is using list comprehensions" g = (x ** 2 for x in range(5)) print("This has been done using list comprehension") for x in g: print(x) """ Decorators Add functionality to an existing code without modifying its structure It is a function that returns another function. Callable object that returns another callable object Takes in a function, add some functionality and returns it Provides a flexible way of adding/extending the functionality of a function """ def decorate(decorated_function): def decorated(): print("This is the decorated function") decorated_function() return decorated() @decorate def plain(): print("I am not decorated at all!") plain()
true
8488ee8f09498521c1cc3054147370b793a35fe1
xs2tariqrasheed/python_exercises
/integer_float.py
722
4.1875
4
_ = print # NOTE: don't compare floating number with == # A better way to compare floating point numbers is to assume that two # numbers are equal if the difference between them is less than ε , where ε is a # small number. # In practice, the numbers can be compared as follows ( ε = 10 − 9 ) # if abs(a - b) < 1e-9: # a and b are equal # _(0.3*3+0.1) # x = 4.66668 # _(round(x, 2)) # c = 4 + 2j # complex # print(type(c)) # i = 9999999999999999999999999999999999 # f = 0.00000000000000000001 # print(f) # print(45.1e-2) # _(0.1 + 0.2) # TODO: reading https://docs.python.org/3.6/tutorial/floatingpoint.html # _(16 ** -2 == 1 / 16 ** 2) # True # _(17 / 3) # 5.666666666666667 # _(17 // 3) # 5 # _(17 % 3) # 2
true
6af88b90a7d58c79ee0e192212d0893c168bf45e
BinYuOnCa/DS-Algo
/CH2/stevenli/HW1/pycode/NumpyDemo.py
1,454
4.25
4
import numpy as np # Generate some random data data = np.random.randn(2, 3) print("first random data: ", data) # data * 10 data = data * 10 print("Data times 10: ", data) # try np shape print("Data shape: ", data.shape) # Print data value's type print("Data types:", data.dtype) # Create a new ndarray data_forarray = [6, 7.5, 8, 0, 1] np_array = np.array(data_forarray) print("Np array is: ", np_array) # create a second ndarry data_forarray2 = [[1, 2, 3, 4], [5, 6, 7, 8]] np_array2 = np.array(data_forarray2) # create a 1D array data_forarray3 = [10] np_array3 = np.array(data_forarray3) # Demo broadcasting, array 1 + array3 print("Broadcasting, array1 + array3: ", np_array+np_array3) # numpy array indexing and slicing np_array4 = np.arange(10) print("Initialize an array in range 10: ", np_array4) # print out the range 5:8. The 5th, 6th and 7th values will be printed out. The 8th value won't print("The range 5:8 is: ", np_array4[5:8]) # assign a slicing array_slice = np_array4[5:8] array_slice[1] = 12345 print("After slicing: ", np_array4) array_slice[:] = 64 print("Second slicing: ", np_array4) # Create a 2 dimensional array array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("The second element of array: ", array2d[1]) print("The 3rd value of 2nd sub array: ", array2d[1][2]) # Create a 3 Dimensional array array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print("The 3D array is: ", array3d)
true
416500cec0887721d8eb35ace2b89bc8d208a247
qasimriaz002/LeranOOPFall2020
/qasim.py
555
4.34375
4
from typing import List def count_evens(values: List[List[int]]) -> List[int]: """Return a list of counts of even numbers in each of the inner lists of values. # >>> count_evens([[10, 20, 30]]) [3] # >>> count_evens([[1, 2], [3], [4, 5, 6]]) [1, 0, 2] """ evenList = [] for sublist in values: count = 0 for eachValue in sublist: if eachValue % 2 == 0: count = count + 1 evenList.append(count) return evenList x = [[1, 2], [3], [4, 5, 6]] print(count_evens(x))
true
ad3a6c22485fece625f45f894962d548960b00b0
qasimriaz002/LeranOOPFall2020
/Labs/Lab_1/Lab_1_part_3.py
1,323
4.53125
5
# Here we will use the dictionaries with the list # We will create the record of 5 students in the different 5 dictionaries # Then we will add all of the these three dictionaries in the list containing the record of all student # Creating the dictionaries stdDict_1 = {"name": "Bilal", "age": 21, "rollno": "BSDS-001-2020"} stdDict_2 = {"name": "Ahsan", "age": 19, "rollno": "BSDS-002-2020"} stdDict_3 = {"name": "Hassan", "age": 22, "rollno": "BSDS-003-2020"} stdDict_4 = {"name": "Kashif", "age": 24, "rollno": "BSDS-004-2020"} stdDict_5 = {"name": "Talha", "age": 18, "rollno": "BSDS-005-2020"} # Creating the list listStudent_Record = [stdDict_1, stdDict_2, stdDict_3, stdDict_4, stdDict_5] # Getting the data from the list print(listStudent_Record) print("-----------------------------") # Getting the record of first dictionary from list print(listStudent_Record[0]) print("-----------------------------") # Getting the name of student from 1 dictionary from list print(listStudent_Record[0]["name"]) print("-----------------------------") # Getting the names of all the students present in all the dictionaries in the list print(listStudent_Record[0]["name"]) print(listStudent_Record[1]["name"]) print(listStudent_Record[2]["name"]) print(listStudent_Record[3]["name"]) print(listStudent_Record[4]["name"])
true
c2bf6604b053c51f040365c80ccdb95d3dae9fba
domsqas-git/Python
/vscode/myGame.py
1,044
4.21875
4
print("Bim Bum Bam!!") name = input("What's your name? ").upper() age = int(input("What's your age? ")) print("Hello", name, "you are", age, "years hold.") points = 10 if age >= 18: print("Hooray!! You can play!!") wants_to_play = input("Do you want to play? ").lower() if wants_to_play == "yes": print("Let's Rock&Roll!!") print("You're starting off with", points, "points") up_or_down = input("Choose.. Up or Down.. ").lower() if up_or_down == "up": ans = input("Great! There is an Helicopter.. Do you want to jump in? ").lower() if ans == "yes": print("The helicopter crashed, you're injured and lost 5 points") points -= 5 elif ans == "no": print("Good choice! You're safe!") elif ans == "down": print("Have a sit and someone will come and get you!") else: print("That's fine", name, "but you're missing big my Friend!") else: print("Sorry", name, "You can't play!")
true
04c9bfd9367c43b47f01ba345ba94a7a9ac61129
Nilutpal-Gogoi/LeetCode-Python-Solutions
/Array/Easy/674_LongestContinuousIncreasingSubsequence.py
856
4.21875
4
# Given an unsorted array of integers, find the length of longest continuous # increasing subsequence(Subarray). # Example 1: # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence is [1,3,5], its length # is 3. Even though [1,3,5,7] is also an increasing subsequence, it's # not a continuous one where 5 and 7 are separated by 4. # Example 2: # Input: [2,2,2,2,2] # Output: 1 # Explanation: The longest continuous increasing subsequence is [2], its length is 1. # Note: Length of the array will not exceed 10,000. def findLengthofLCIS(nums): result = 0 anchor = 0 for i in range(len(nums)): if i > 0 and nums[i-1] >= nums[i]: anchor = i result = max(result, i-anchor + 1) return result print(findLengthofLCIS([1,3,5,4,7]))
true
05365bc5a7afac8cb90b1078393aec87ec1867b4
Nilutpal-Gogoi/LeetCode-Python-Solutions
/Array/Easy/349_IntersectionOfTwoArrays.py
986
4.21875
4
# Given two arrays, write a function to compute their intersection. # Example 1: # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # Example 2: # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # Note: # Each element in the result must be unique. # The result can be in any order. # ------------------ Brute Force ----------------------------------------- def intersection(nums1, nums2): lis = [] for i in nums1: for j in nums2: if i == j: if i not in lis: lis.append(i) return lis # ---------------- Using inbuilt sets --------------------------------------- def intersection1(nums1, nums2): set1 = set(nums1) set2 = set(nums2) return set1.intersection(set2) # Time Complexity = O(n+m), O(n) time is used to convert nums1 into set, O(m) time # is used to convert nums2 # Space Complexity = O(n+m) in the worst case when all the elements in the arrays # are different.
true
8b9c0aac40b97452fc35f19f49f191bc161e90b9
Nilutpal-Gogoi/LeetCode-Python-Solutions
/LinkedList/Easy/21_MergeTwoSortedLists.py
1,184
4.21875
4
# Merge two sorted linked lists and return it as a new sorted list. The new list should # be made by splicing together the nodes of the first two lists. # Example: # Input: 1->2->4, 1->3->4 # Output: 1->1->2->3->4->4 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: first = l1 second = l2 if not first: return second if not second: return first if first.val < second.val: third = last = first first = first.next else: third = last = second second = second.next while first and second: if first.val < second.val: last.next = first last = first first = first.next else: last.next = second last = second second = second.next if first != None: last.next = first else: last.next = second return third
true
2ff343c91342b32581d3726eb92c6570eb4c049e
forgoroe/python-misc
/5 listOverLap.py
1,102
4.3125
4
""" ake two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Extras: Randomly generate two lists to test this Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon) """ import random a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] my_random = [random.sample(range(100),10), random.sample(range(100),10)] for sample in my_random: sample.sort() def commonElementsBetween(firstList, secondList): commonList = [] for element in firstList: if element in secondList: if element not in commonList: commonList.append(element) return commonList print('first list: ' + str(my_random[0]), '\nsecond list: ' + str(my_random[1])) print('elements in common: ' + str(commonElementsBetween(my_random[0],my_random[1])))
true
1e138a3770218338f66b78f14945e0508c1041a4
forgoroe/python-misc
/3 listLessThan.py
912
4.375
4
""" Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5. Extras: Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list. Write this in one line of Python. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user. """ a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] missing = None def listLessThan(myList, paramArg = missing): b = [] if paramArg is None: paramArg = 5 for element in myList: if element < paramArg: b.append(element) return b try: param = int(input('Create list of all the numbers less than (default is < 5): ')) print(listLessThan(a, param)) except: print(listLessThan(a))
true
7c57689eac501ab4bc6da1e8c17a5c7abe1dd58b
forgoroe/python-misc
/14 removeListDuplicates.py
771
4.21875
4
""" Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. """ listOfDuplicates = [1,1,1,2,2,2,5,5,5,9,10] def removeDuplicates(listParam): myList = list(set(listParam)) myList.sort() return myList def secondaryRemoveDuplicate(listParam): newList = [] for element in listParam: if element not in newList: newList.append(element) newList.sort() return newList print(removeDuplicates(listOfDuplicates)) print(secondaryRemoveDuplicate(listOfDuplicates))
true
c45559cbf2cd3491aa031ec9116ba6d2478dace9
notontilt09/Intro-Python-I
/src/prime.py
294
4.125
4
import math x = input("Enter a number, I'll let you know if it's prime:") def isPrime(num): if num < 2: return False for i in range(2, math.ceil(math.sqrt(num))): if num % i == 0: return False return True if isPrime(int(x)): print('Prime') else: print('Not prime')
true
4d343fedf8584b93d3835f74851898c2bbff0e8c
Tanner-Jones/Crypto_Examples
/Encryption.py
696
4.15625
4
from cryptography.fernet import Fernet # Let's begin by showing an example of what encryption looks like # This is an example random key. If you run the file again # you will notice the key is different each time key = Fernet.generate_key() print(key) # Fernet is just a symmetric encryption implementation f = Fernet(key) print(f) # Notice the Encrypted output of this example string # You don't need to worry about how the message is being encrypted # Just notice that the output is gibberish compared to the input token = f.encrypt(b"This is some example of a secret") print(token) # an accompanying decryption is established token = f.decrypt(token) print(token)
true
4b772bd2b3e80c5efb292bfedf7e74908aae1d7a
jonaskas/Programa-o
/7_colecoes-master/C_mutability2.py
489
4.15625
4
""" Mutability - Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions - Immutable objects: int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes - Mutable objects: list, dict, set, bytearray,user-defined classes """ def print_memory(obj): print(hex(id(obj)), ":", obj) # integers are immutable print() a = 5 print_memory(a) a += 1 print_memory(a) b = a print(a is b) # identity equality
true
3939d09d42684a7b934c5d81820cb8153b8c4b29
jonaskas/Programa-o
/7_colecoes-master/C_mutability4.py
684
4.3125
4
""" Mutability - Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions - Immutable objects: int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes - Mutable objects: list, dict, set, bytearray,user-defined classes """ def print_memory(obj): print(hex(id(obj)), ":", obj) # list are mutable print() my_list = [] print_memory(my_list) my_list += [11, 22] print_memory(my_list) my_list.append(33) print_memory(my_list) my_list.remove(11) print_memory(my_list) print() list1 = [1, 2, 3] list2 = [1, 2, 3] list3 = list1 print(list1 == list2) print(list1 is list2) print(list1 is list3)
true
62fb02699f26a16e7c18ba5d70b234068c05b0ee
jonaskas/Programa-o
/7_colecoes-master/C_mutability3.py
474
4.125
4
""" Mutability - Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions - Immutable objects: int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes - Mutable objects: list, dict, set, bytearray,user-defined classes """ def print_memory(obj): print(hex(id(obj)), ":", obj) # tuples are immutable tuple_ = (1, 2, 3) print_memory(tuple_) tuple_ += (4, 5, 6) print_memory(tuple_)
true
74494d848957c254dea03530e1cabe13b1b399b1
Jithin2002/pythonprojects
/List/element found.py
384
4.125
4
lst=[2,3,4,5,6,7,8] num=int(input("enter a number")) flag=0 for i in lst: if(i==num): flag=1 break else: flag=0 if(flag>0): print("element found") else: print("not found") #this program is caled linear search # we have to search everytime wheather element is thereor not # drawback increases complexity # to overcome this we use binary search
true
321f1e726d75e4f7013074163ce7cfeab25dbeb8
sunglassman/U3_L11
/Lesson11/problem3/problem3.py
253
4.1875
4
print('-' * 60) print('I am EvenOrOdd Bot') print() number = input('Type a number: ') number = int(number) if number == even: print('Your number is even. ') else: print('Your number is odd. ') print('Thank you for using the app! ') print('-' * 60)
true
639de603bbf4502f07acfdfe29d6e048c4a89076
rjtshrm/altan-task
/task2.py
926
4.125
4
# Algorithm (Merge Intervals) # - Sort the interval by first element # - Append the first interval to stack # - For next interval check if it overlaps with the top interval in stack, if yes merge them def merge_intervals(intervals): # Sort interval by first element sort_intervals_first_elem = sorted(intervals, key=lambda k: k[0]) stack = [] # stack iteration and interval operation for interval in sort_intervals_first_elem: if len(stack) == 0: stack.append(interval) else: f, e = interval tf, te = stack[-1] # top element in stack if tf <= f <= te: # interval overlap each other stack[-1][1] = max(e, te) else: stack.append(interval) return stack if __name__ == '__main__': intervals = [[25, 30], [2, 19], [14, 23], [4, 8]] print(merge_intervals(intervals))
true
132b54c3b4587e500e050d6be5cfadc4488f5da5
briantsnyder/Lutron-Coding-Competiton-2018
/move_maker.py
1,946
4.4375
4
"""This class is the main class that should be modified to make moves in order to play the game. """ class MoveMaker: def __init__(self): """This class is initialized when the program first runs. All variables stored in this class will persist across moves. Do any initialization of data you need to do before the game begins here. """ print("Matthew J Gunton and Brian Snyder") def make_move(self, mancala_board): # { # "MyCups": [4, 3, 2, 1, 5, 3], # "MyMancala": 0, # "OpponentCups": [3, 6, 2, 0, 1, 2], # "OpponentMancala": 3 # } #strategy: # 1) take all free moves as they happen # 2) can it land on an empty space & steal # 3) if all else fails, whichever is closest, you move NUMOFCUPS = 6 #1 for i in range(NUMOFCUPS-1,-1,-1): #we don't account for if you can go around and get this if mancala_board["MyCups"][i] == NUMOFCUPS - i: return i #2 if mancala_board["MyCups"][i] == 0 and mancala_board["OpponentCups"][5-i] != 0: for curIndex, stone_count in enumerate(mancala_board["MyCups"]): if i > curIndex: if i == stone_count - 13 + curIndex and stone_count != 0: print("we found a way to steal") return curIndex else: if stone_count == i - curIndex and stone_count != 0: print("we found a way to steal\n our index:"+str(i)+"\n current index: "+str(curIndex)+"\n stone count"+str(stone_count)) return curIndex print("nothing better") #3 for i in range(NUMOFCUPS - 1, -1, -1): if (mancala_board["MyCups"][i] != 0): return i return 0
true
c7363294a807a273dce1204c1c6b0a2b167590ee
nathancmoore/code-katas
/growing_plant/plant.py
528
4.34375
4
"""Return the number of days for a plant to grow to a certain height. #1 Best Practices Solution by Giacomo Sorbi from math import ceil; growing_plant=lambda u,d,h: max([ceil((h-u)/(u-d)),0])+1 """ def growing_plant(up_speed, down_speed, desired_height): """Return the number of days for a plant to grow to a certain height.""" height = 0 days = 0 while height < desired_height: days += 1 height += up_speed if height >= desired_height: return days height -= down_speed
true
d0f59bf4520f993c32505a7b3406d786a76befa9
PaviLee/yapa-python
/in-class-code/CW22.py
482
4.25
4
# Key = Name # Value = Age # First way to make a dictionary object database = {} database["Frank"] = 21 database["Mary"] = 7 database["John"] = 10 print(database) # Second way to make a dictionary object database2 = { "Frank": 21, "Mary": 7, "Jill": 10 } print(database2) for name, age in database2.items(): print(name + " is " + str(age) + " years old") # Make a phonebook dictionary # 3 key-value pairs # Key = name of person # Value = distinct phone number
true
832439c69ddbcbeb4b2ad961e7427b760306fb92
Th0rt/LeetCode
/how-many-numbers-are-smaller-than-the-current-number.py
999
4.125
4
# https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ import unittest from typing import List class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: length = len(nums) temp = sorted(nums) mapping = {} for i in range(length): if temp[i] not in mapping: mapping[temp[i]] = i return [mapping[nums[i]] for i in range(length)] class TestSolution(unittest.TestCase): def test_1(self): nums = [8, 1, 2, 2, 3] expect = [4, 0, 1, 1, 3] assert Solution().smallerNumbersThanCurrent(nums) == expect def test_2(self): nums = [6, 5, 4, 8] expect = [2, 1, 0, 3] assert Solution().smallerNumbersThanCurrent(nums) == expect def test_3(self): nums = [7, 7, 7, 7] expect = [0, 0, 0, 0] assert Solution().smallerNumbersThanCurrent(nums) == expect if __name__ == "__main__": unittest.main()
true
9f0d9d5ee1f94937f54a70330e70f5c3b5dc0358
JoeD1991/Quantum
/Joe_Problem_1.py
361
4.3125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ myList = set() N5 = 1000//5 N3 = 1000//3+1 for i in range(1,N3): myList.add(3*i) if i<N5: myList.add(5*i) print(sum(myList))
true
53684088e0af3d314c602a4c58439b76faf161cb
NGPHAN310707/C4TB13
/season6/validpasswordstourheart.py
212
4.125
4
while True: txt = input("Enter your password?") print(txt) if txt.isalpha() or len(txt)<=8 or txt.isdigit: print(txt,"is a name") break else: print("please don't")
true
144a61b43eab0992d60e4b0e8146734ed53347d0
JitinKansal/My-DS-code
/tree_imlementation.py
1,048
4.1875
4
# Creating a new node for the binary tree. class BinaryTree(): def __init__(self, data): self.data = data self.left = None self.right = None # Inorder traversal of the tree (using recurssion.) def inorder(root): if root: inorder(root.left) print(root.data,end=" ") inorder(root.right) # postorder traversal of the tree (using recurssion.) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.data,end=" ") # preorder traversal of the tree (using recurssion.) def preorder(root): if root: print(root.data,end=" ") preorder(root.left) preorder(root.right) root = BinaryTree(1) root.left = BinaryTree(2) root.right = BinaryTree(3) root.left.left = BinaryTree(4) root.left.right = BinaryTree(5) root.right.left = BinaryTree(6) root.right.right = BinaryTree(7) inorder(root) print() print() postorder(root) print() print() preorder(root)
true
86a9f9654568017337b9f306ebd4a8eea326b535
YaohuiZeng/Leetcode
/152_maximum_product_subarray.py
1,446
4.28125
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. """ """ Q: (1) could have 0, and negative (2) input contains at least one number (3) all integers? Algorithm: Time: O(n); Space: O(1). https://www.quora.com/How-do-I-solve-maximum-product-subarray-problems You have three choices to make at any position in array. 1. You can get maximum product by multiplying the current element with maximum product calculated so far. (might work when current element is positive). 2. You can get maximum product by multiplying the current element with minimum product calculated so far. (might work when current element is negative). 3. Current element might be a starting position for maximum product sub array """ class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ prev_max, prev_min, cur_max, res = nums[0], nums[0], nums[0], nums[0] for i in range(1, len(nums)): cur_max = max(prev_max * nums[i], prev_min * nums[i], nums[i]) cur_min = min(prev_max * nums[i], prev_min * nums[i], nums[i]) res = max(cur_max, res) prev_max, prev_min = cur_max, cur_min return res
true
d5ac5a0d89985b6525988e21ed9fe17a44fb4caa
YaohuiZeng/Leetcode
/280_wiggly_sort.py
1,227
4.21875
4
""" Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. """ """ 1. use python in-place sort() 2. one pass: compare current and next, if not the right order, swap. This works because: suppose we already have nums[0] <= nums[1] in the right order. Then when comparing nums[1] and nums[2], if nums[1] < nums[2], meaning the required ">=", we swap nums[1] and nums[2], the first "<=" still holding because nums[2] > nums[1] >= nums[0]. """ class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) nums.sort() for i in range(1, n-1, 2): nums[i], nums[i+1] = nums[i+1], nums[i] def wiggleSort2(self, nums): for i in range(0, len(nums)-1): if i % 2 == 0: if nums[i] > nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] else: if nums[i] < nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i]
true
6aea488ab45998317d8a8d5e180d539e5721873e
ariModlin/IdTech-Summer
/MAC.py
518
4.125
4
# finds the MAC of a message using two different keys and a prime number message = "blah blahs" key1 = 15 key2 = 20 prime_num = 19 def find_mac(): message_num = 0 for i in range(len(message)): # takes each letter of the message and finds its ASCII counterpart num = ord(message[i]) # adds each ASCII number to an integer message_num message_num += num # the mac of the message is equal to this equation m = ((key1 * message_num) + key2) % prime_num return m mac = find_mac() print(mac)
true
6fe51f731f777d02022852d1428ce069f0594cf4
ariModlin/IdTech-Summer
/one time pad.py
1,867
4.21875
4
alphabet = "abcdefghijklmnopqrstuvwxyz" message = input("input message you want to encrypt: ") key = input("input key you want to encrypt the message with: ") message_array = [] key_array = [] encrypted_numbers = [] decrypted_message = "" def convert_message(): for i in range(len(message)): # takes the message and converts the letters into numbers message_index = (alphabet.find(message[i])) message_array.append(message_index) return message_array def convert_key(): for j in range(len(key)): # takes the key and converts the letters into numbers key_index = (alphabet.find(key[j])) key_array.append(key_index) return key_array def encrypt_message(): encrypted_message = "" for x in range(len(message)): # adds each number letter from both the message array and the key array and mods 26 to get the new number new_num = (message_array[x] + key_array[x]) % 26 # adds each new number to an encrypted numbers array encrypted_numbers.append(new_num) # converts each of the new numbers into its corresponding letter new_letters = alphabet[encrypted_numbers[x]] encrypted_message += new_letters print("encrypted message: " + encrypted_message) return encrypted_message convert_message() convert_key() encrypt_message() question = input("do you wish to see the message decrypted again? y/n ") if question == "y": for a in range(len(encrypted_message)): decrypted_nums = encrypted_numbers[a] - key_array[a] if decrypted_nums < 0: decrypted_nums = 26 + decrypted_nums decrypted_letters = alphabet[decrypted_nums] decrypted_message += decrypted_letters print("decrypted message: " + decrypted_message) else: print("goodbye")
true
ada99ffe37296e78bbaa7d804092a495be47c1ba
dineshj20/pythonBasicCode
/palindrome.py
890
4.25
4
#this program is about Palindrome #Palindrom is something who have the same result if reversed for e.g. " MOM " #how do we know whether the given string or number is palindrome number = 0 reverse = 0 temp = 0 number = int(input("Please Enter the number to Check whether it is a palidrome : ")) print(number) temp = number #given number is copied in temp variable while(temp != 0): # until the number is reversed reverse = reverse * 10 # reverse will store the reversed number by one digit and shift the place of digit reverse = reverse + temp % 10 # remainder of the given number gives last digit every time and is stored in reverse temp = int(temp/10) # every last digit of given number is eliminated here if(reverse == number): print("Number is a Palindrome") else: print("Number is not a Palindrome")
true
6c5ee3e9cb85a24940a9238981b7f6fbf9ec1696
MichealPro/sudoku
/create_sudoku.py
2,158
4.375
4
import random import itertools from copy import deepcopy # This function is used to make a board def make_board(m=3): numbers = list(range(1, m ** 2 + 1)) board = None while board is None: board = attempt_board(m, numbers) return board # This function is used to generate a full board def attempt_board(m, numbers): n = m ** 2 board = [[None for _ in range(n)] for _ in range(n)] for i, j in itertools.product(range(n), repeat=2): i0, j0 = i - i % m, j - j % m # origin of m * m block random.shuffle(numbers) for x in numbers: if (x not in board[i] # row and all(row[j] != x for row in board) # column and all(x not in row[j0:j0 + m] for row in board[i0:i])): board[i][j] = x break else: return None return board # This function is used to print the whole Soduku out def print_board(board, m=3): numbers = list(range(1, m ** 2 + 1)) omit = 5 challange = deepcopy(board) for i, j in itertools.product(range(omit), range(m ** 2)): x = random.choice(numbers) - 1 challange[x][j] = 0 spacer = "++-----+-----+-----++-----+-----+-----++-----+-----+-----++" print(spacer.replace('-', '=')) for i, line in enumerate(challange): print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||" .format(*(cell or ' ' for cell in line))) if (i + 1) % 3 == 0: print(spacer.replace('-', '=')) else: print(spacer) return challange def print_answers(board): spacer = "++-----+-----+-----++-----+-----+-----++-----+-----+-----++" print(spacer.replace('-', '=')) for i, line in enumerate(board): print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||" .format(*(cell or ' ' for cell in line))) if (i + 1) % 3 == 0: print(spacer.replace('-', '=')) else: print(spacer) def generate(): Board = make_board() bo=print_board(Board) return bo
true
f605c356950e7e609d3e57c92169775cf4ed497a
sssvip/LeetCode
/python/num003.py
1,303
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-09-28 22:25:36 # @Author : David:admin@dxscx.com) # @Link : http://blog.dxscx.com # @Version : 1.0 """ Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int >>> print Solution().lengthOfLongestSubstring("bdbf") 3 >>> print Solution().lengthOfLongestSubstring("abcdd") 4 """ max_length = 0 pre_substr = "" for x in s: indexof = pre_substr.find(x) # optimizable point (make O(n^2)) if indexof >= 0: pre_substr = pre_substr[indexof + 1:] pre_substr = pre_substr + x max_length = max(max_length, len(pre_substr)) return max_length if __name__ == '__main__': import doctest doctest.testmod(verbose=True) # print Solution().lengthOfLongestSubstring("abcdd")
true
89db6d170e6eb265a1db962fead41646aaed6f9f
sssvip/LeetCode
/python/num581.py
1,606
4.21875
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num581.py @time: 2017/11/7 20:29 @description: Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=. """ class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int >>> print Solution().findUnsortedSubarray([1,2,3,4]) 0 >>> print Solution().findUnsortedSubarray([1,3,2,1,5,6]) 3 >>> print Solution().findUnsortedSubarray([2,6,4,8,10,9,15]) 5 """ n = len(nums) if n < 1: return 0 snums = sorted(nums) start = 0 end = 0 for x in range(n): if snums[x] != nums[x]: start = x break for x in range(n): if snums[n - x - 1] != nums[n - x - 1]: end = n - x - 1 break return end - start + 1 if (end - start) > 0 else 0 if __name__ == '__main__': import doctest doctest.testmod(verbose=True)
true
09eb0f8acf255d4471a41a56a50bccf24ed4c91c
MissBolin/CSE-Period3
/tax calc.py
230
4.15625
4
# Tax Calculator cost = float(input("What is the cost of this item? ")) state = input("What state? ") tax = 0 if state == "CA": tax = cost * .08 print("Your item costs ${:.2f}, with ${:.2f} in tax.".format(cost+tax, tax))
true
b9884eae05e9518e3ec889dd5280a8cea7c3c1d7
gandastik/365Challenge
/365Challenge/insertElementes.py
382
4.125
4
#Jan 24, 2021 - insert a elements according to the list of indices from typing import List def createTargetArray(nums: List[int], index: List[int]) -> List[int]: ret = [] for i in range(len(nums)): ret.insert(index[i], nums[i]) return ret lst = [int(x) for x in input().split()] index = [int(x) for x in input().split()] print(createTargetArray(lst, index))
true
20644bc6631d5eb8e555b1e2e61d1e0e6273bd00
gandastik/365Challenge
/365Challenge/matrixDiagonalSum.py
762
4.21875
4
#37. Feb 6, 2021 - Given a square matrix mat, return the sum of the matrix diagonals. # Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. from typing import List def diagonalSum(mat: List[List[int]]) -> int: res = 0 for i in range(len(mat)): for j in range(len(mat)): if(i+j == len(mat)-1): res += mat[i][j] if(i == j): res += mat[i][j] if(len(mat) % 2 != 0): return res-mat[len(mat)//2][len(mat)//2] return res n = int(input()) arr = [] for i in range(n): arr.append(list(map(int, input().split()))) print(diagonalSum(arr))
true
9fdedda65ec74a7ac9d9ab1510dcc1b63adf502d
ovidubya/Coursework
/Python/Programs/assign5part1.py
560
4.46875
4
def find_longest_word(wordList): print("The list of words entered is:") print(wordList) result = "" i = 0 while(i < len(wordList)): # iterates over the list to find the first biggest word if(len(result) < len(wordList[i])): result = wordList[i] i = i + 1 print("") print("The longest word in the list is:") print(result) # User enters words to be seperated in a list x = input("Enter a few words and I will find the longest:") # splits words into a list xyz = x.split() find_longest_word(xyz)
true
a5201821c6cd15088a4b1a4d604531bbcca68c69
mlrice/DSC510_Intro_to_Programming_Python
/fiber_optic_discount.py
1,297
4.34375
4
# DSC510 # 4.1 Programming Assignment # Author Michelle Rice # 09/27/20 # The purpose of this program is to estimate the cost of fiber optic # installation including a bulk discount from decimal import Decimal print('Hello. Thank you for visiting our site, we look forward to serving you.' '\nPlease provide some information to get started.\n') # Retrieve company name and feet of cable from customer company = input("What is your company name?") feetRequired = float(input("How many feet of fiber optic cable do you need? (please enter numbers only)")) # Set price tier price1 = .87 price2 = .80 price3 = .70 price4 = .50 # Determine price based on requested feet of cable if feetRequired > 500: discPrice = price4 elif 250 < feetRequired <= 500: discPrice = price3 elif 100 < feetRequired <= 250: discPrice = price2 else: discPrice = price1 # Calculate total cost def calculate(feet, price): cost = feet * price return cost totalCost = calculate(feetRequired, discPrice) # Print receipt with company name and total cost print("\n***RECEIPT***") print("\nCustomer: " + company) print("Required cable =", feetRequired, "feet at $", "{:.2f}".format(discPrice), "per foot") print("Total Cost = $", "{:.2f}".format(totalCost)) print("\nThank you for your business!")
true
65293fcbfb356d2f045eff563083e2b751e61326
martinkalanda/code-avengers-stuff
/wage calculaor.py
297
4.40625
4
#Create variables hourly_rate = int(input("what is your hourly rate")) hours_worked = int(input("how many hours have you worked per week")) #Calculate wages based on hourly_rate and hours_worked wages = hourly_rate * hours_worked print("your wages are ${} per week" .format(wages))
true
d1c8e6df0c2a44e543b879dcfcee89a2f77557ba
NishadKumar/interview-prep
/dailybyte/strings/longest_substring_between_characters.py
1,874
4.21875
4
# Given a string, s, return the length of the longest substring between two characters that are equal. # Note: s will only contain lowercase alphabetical characters. # Ex: Given the following string s # s = "bbccb", return 3 ("bcc" is length 3). # Ex: Given the following string s # s = "abb", return 0. # Approach: # To solve this problem we can leverage a hash map. Our hash map can keep track of the last index a specific character has occurred. # We can iterate through all the characters in our string s, continuously updating a variable max_length that will hold the length of the longest # substring we've found that occurs b/w 2 equal characters. At every iteration of our loop, we can start by first storing the current character # that we are on within s. With the current character stored, we can now check if our hash map already contains this character. If it is, that means # it has already occurred and therefore we can update our max_length variable to be the maximum between the current value of max_length and our current index i minus the # index that the first occurrence of our current character occurred. If our current character is not in our map, we can place it in our map with the current # index i that we are on. Once our loop ends, we'll have stored the longest length subarray b/w 2 equal characters in max_length and can simply return it. def longest_substring_between_characters(s): dictionary = {} max_length = -1 for i in range(len(s)): if s[i] in dictionary: max_length = max(max_length, i - dictionary[s[i]] - 1) else: dictionary[s[i]] = i return max_length # Time Complexity: # O(N) where N is the total number of characters in s. # Space complexity: # O(1) or constant since our hash map will at most grow to a size of twenty-six regardless of the size of s.
true
649fb09854bb5c385e3eaff27302436741f09e4f
NishadKumar/interview-prep
/leetcode/1197_minimum_knight_moves/minimum_knight_moves.py
2,147
4.125
4
# In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0]. # A knight has 8 possible moves it can make. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. # Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists. # Example 1: # Input: x = 2, y = 1 # Output: 1 # Explanation: [0, 0] -> [2, 1] # Example 2: # Input: x = 5, y = 5 # Output: 4 # Explanation: [0, 0] -> [2, 1] -> [4, 2] -> [3, 4] -> [5, 5] # Constraints: # |x| + |y| <= 300 # Approach: # BFS -> This problem boils down to finding shortest path from knight's origin to its destination. Dijkstra's algorithm is the most intuitive # approach one can think of. We start by queueing the origin and explore all the initial knight's possible directions. If we reach the vertex we # are looking for, we are done. Else, we repeat the process until we find it. Mind to have a data structure to not visit the already explored vertex. # A set can be used for that. Also, a queue to process vertex in order helps us achieve the task. def min_moves(x, y): offsets = [(2,1), (2,-1), (-2,1), (-2,-1), (1,2), (-1,2), (1,-2), (-1,-2)] def bfs(x, y): queue = [(0, 0)] visited = set() steps = 0 while queue: current_level_length = len(queue) for i in range(current_level_length): current_x, current_y = queue.pop(0) if (current_x, current_y) == (x, y): return steps for offset_x, offset_y in offsets: next_x, next_y = current_x + offset_x, current_y + offset_y if (next_x, next_y) not in visited: visited.add((next_x, next_y)) queue.append((next_x, next_y)) steps += 1 return bfs(x, y) # Time & Space Complexity: # If you have premium subscription on leetcode, then I would recommend reading the article by the author. # Tests: # python test_minimum_knight_moves.py
true
8488da7cb5989c2785a81faf81d9ac7a849c5b0d
Marcus-Mosley/ICS3U-Unit4-02-Python
/product.py
1,153
4.65625
5
#!/usr/bin/env python3 # Created by Marcus A. Mosley # Created on October 2020 # This program finds the product of all natural numbers preceding the # number inputted by the user (a.k.a. Factorial) def main(): # This function finds the product of all natural numbers preceding the # number inputted by the user (a.k.a. Factorial) # Input counter = 1 product = 1 natural_string = input("Enter a natural number (To Find Product 1 to N): ") print("") # Process & Output try: natural_integer = int(natural_string) except Exception: print("You have not inputted an integer, please input an integer" " (natural number)!") else: if natural_integer <= 0: print("You have not inputted a positive number, please input a" " positive number!") else: while counter <= natural_integer: product = product * counter counter = counter + 1 print("The product of all natural numbers 1 to {0} is {1}" .format(natural_integer, product)) if __name__ == "__main__": main()
true
e7958f906c313378efd5815b81b70b4f5c45c65e
robbyhecht/Python-Data-Structures-edX
/CH9/exercise1.py
776
4.15625
4
# Write a program that reads the words inwords.txtand stores them askeys in a dictionary. It doesn’t matter what the values are. Then youcan use theinoperator as a fast way to check whether a string is in thedictionary. from collections import defaultdict f = input("Enter file name: ") try: content = open(f) except: print("File no good", f) quit() counts = defaultdict(lambda: 0) # counts = dict() for line in content: words = line.split() for word in words: counts[word] += 1 # counts[word] = counts.get(word,0) + 1 def check_existance(word): if word in counts: print(f'Found it {counts[word]} times!') else: print("Didn't see it") word_to_find = input("Look for your word: ") check_existance(word_to_find)
true
566a23e9b7633a9ce17062fad16cb1088e33e155
TareqJudehGithub/Ardit_Sulce_Udemy
/Python_Mega/sec14_Numpy/numpy_practice.py
886
4.1875
4
""" Numpy - Numpy is a fundamental package for scientific computing with Python. - Official page: https://numpy.org/ - Numpy comes installed with Pandas library. """ import numpy # .arange(int) created a new array with the specified int number. n = numpy.arange(27) print(n) print(type(n)) print(len(n)) print("") # creating multi-dimintion array # .reshape() method creates a multi dimintion array # numpy.arrange(int).reshape(numb_of_arrs, num_of_rows, num_of_columns) new_array = numpy.arange(12) print(new_array) print("") print("two dimensional array") # two-dimintion array two_dim_arr = new_array.reshape(3, 4) # .reshape(rows, columns) print(two_dim_arr) print("") print("three dimensional array") # three-dimensional array # three-dimensional array are less frequently used than two-dimensional array three_dim = numpy.arange(24).reshape(3, 2, 4) print(three_dim)
true
fdb85dd88220653054dc4127e2273885515a9c53
TareqJudehGithub/Ardit_Sulce_Udemy
/Python_Mega/sec6_Basics_Proc_User_Input/string_formatting.py
653
4.125
4
""" String formatting in Python - More on: https://pyformat.info/ """ def greet_user(): name = input('What is your name? ') # this is the a string formatting method introduced in Python 2 return "Hello, %s!" %name.title() # using format() return "Hello, {}!".format(name.title) # using f string return f"Hello, {name.title()}!" def user_details(): name = input('Name? ') age = int(input('Age? ')) return 'You name is %s, and you age is %d' % (name.title(), age) if __name__ == "__main__": print(greet_user()) print(user_details()) print('{:_<10}'.format('test'))
true
ebdfab2cb3cc75734d4d514005ffbb2bef50fa67
TareqJudehGithub/Ardit_Sulce_Udemy
/Python_Mega/sec8_build_prog/input_problem.py
1,092
4.25
4
import re # Write a program, that asks the user for input(s), until # the user types \end # user inputs should not include any symbols. # return all user outputs def inputs_problem(): inputs = list() inputs_str = str() interrogatives = ('how', 'what', 'why', 'where') input_validator = re.compile(r"[\w a-z0-9']*$") while True: user_input = input('Type your input: ') if input_validator.fullmatch(user_input): if user_input.startswith(interrogatives): inputs.append(user_input.capitalize() + '?') else: inputs.append(user_input.capitalize() + '.') else: print('Bad input format.') print('') continue print more_input = input('More input? (yes/no) ') if more_input == 'no'.lower(): inputs_str = ' '.join(inputs) return inputs_str else: continue if __name__ == '__main__': print(inputs_problem())
true
f13e841d3a8ef2d2e46bd958811aa53409350686
niyatigulati/Calculator.py
/calc.py
524
4.125
4
def calc(choice, x, y): if (choice == 1): add(x, y) elif (choice == 2): sub(x, y) elif (choice == 3): mul(x,y) elif (choice == 2): div(x,y) # the below functions must display the output for the given arithmetic # TODO def add(a, b): pass def sub(a, b): pass def mul(a, b): pass def div(a, b): pass # TODO # main function here # Display options on what a calculator can do to perform (1 for add, 2 for sub and so on... ) # This must be in a while loop
true