blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e79e52b336b37444bcdc95b151c50e080e8ab2e3
Jethet/Practice-more
/python-katas/28_Last2.py
300
4.15625
4
# Given a string, return the count of the number of times that a substring # length 2 appears in the string and also as the last 2 chars of the string, # so "hixxxhi" yields 1 (we won't count the end substring). def last2(str): x = str[-2:] return str.count(x) - 1 print(last2('axxxaaxx'))
true
3837c735626d9ea89162da3f3f15e3514bcd859a
Jethet/Practice-more
/python-katas/EdabCheckEnd.py
646
4.5
4
# Create a function that takes two strings and returns True if the first # argument ends with the second argument; otherwise return False. # Rules: Take two strings as arguments. # Determine if the second string matches ending of the first string. # Return boolean value. def check_ending(str1, str2): if str1.endswith(str2): return True else: return False print(check_ending("abc", "bc")) # True print(check_ending("abc", "d")) # False print(check_ending("samurai", "zi")) # False print(check_ending("feminine", "nine")) # True print(check_ending("convention", "tio")) # False
true
baf3c6195df0fc2638e72ae9f9bf4be5bba73e38
Jethet/Practice-more
/python-katas/EdabTrunc.py
684
4.3125
4
# Create a one line function that takes three arguments (txt, txt_length, # txt_suffix) and returns a truncated string. # txt: Original string. # txt_length: Truncated length limit. # txt_suffix: Optional suffix string parameter. # Truncated returned string length should adjust to passed length in parameters # regardless of length of the suffix. def truncate(txt, txt_length, *txt_suffix): return txt[0:txt_length]+str(txt_suffix).strip('()').replace("'", "").replace(",","") print(truncate("CatDogDuck", 6, "Rat")) # "CatDogRat" print(truncate("DogCat", 3)) # "Dog" print(truncate("The quick brown fox jumped over the lazy dog.", 15, "...")) # "The quick br..."
true
bd0304c63470267b120d29de75b00b480960a0a7
Jethet/Practice-more
/python-katas/EdabAddInverse.py
333
4.125
4
# A number added with its additive inverse equals zero. Create a function that # returns a list of additive inverses. def additive_inverse(lst): print(additive_inverse([5, -7, 8, 3])) #➞ [-5, 7, -8, -3] print(additive_inverse([1, 1, 1, 1, 1])) #➞ [-1, -1, -1, -1, -1] print(additive_inverse([-5, -25, 35])) #➞ [5, 25, -35]
true
5797703b59a09ee3915451417c6e4205feb47ee5
Marhc/py_praxis
/hello.py
1,590
4.4375
4
"""A simple **"Hello Function"** for educational purposes. This module explores basic features of the Python programming language. Features included in this module: - Console Input / Output; - Function Definition; - Module Import; - Default Parameter Values; - String Interpolation (**'fstrings'**); - Single line and Multiline comments; - Docstrings (**'Google Python Style Guide'**); - 'Falsy' coalescing operator (**'or'**); - Conditional Statements; - Custom main entry point and exit point; - Private function naming convention; - Special, **'dunder'** or **'magic'** variables; - Command line arguments handling; """ import sys def hello_user(name=""): """Returns a greeting message with the user name. This is an example of a parameterized function with a default value. If no name is provided the function returns **"Hello Everyone!"** by default. Args: name (str): The user name typed in the Console. Returns: str: The greeting message. """ return f"Hello { name or 'Everyone' }!" def _custom_main(argv): # Python has no a default main entry point. """Example of a custom main function with command line arguments handling.""" # Avoids an exception if no args. Ternary Operator is more explicit and longer. user_name = (argv + [""])[1] or input("Type your name: ") print(hello_user(user_name)) if __name__ == '__main__': # Skips execution when importing the module, # but allows it when calling the script. sys.exit(_custom_main(sys.argv))
true
cf3c88cf74d7f26207959aaa43329d8332c9a673
beanj25/Leap-year-program
/jacob_bean_hw1_error_handling.py
1,020
4.125
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Jacob # # Created: 15/01/2021 # Copyright: (c) Jacob 2021 # Licence: <your licence> #------------------------------------------------------------------------------- def isLeap(year): if(year%100 == 0): if((year >=400) and (year%400 == 0)): return True return False elif(year%4 == 0): return True else: return False def main(): pass if __name__ == '__main__': main() year = input("enter year to check for leep year:") while(year.isdigit() == False): year = input("Not valid input, please use numbers") year = int(year) while (year <=0): year = int(input("Invalid Year, please enter a new year above 0:")) print("is the year "+ str(year) +" a leap year?") if(isLeap(year) == True): print ("yes") else: print("no") input("Press Enter to exit")
true
33b7628e6bdb51f4f146db155335768f3d873892
Ayesha116/piaic.assignment
/q19.py
340
4.28125
4
#Write a Python program to convert the distance (in feet) to inches, yards, and miles. 1 feet = 12 inches, 3 feet = 1 yard, 5280 feet = 1 mile feet = float(input("enter height in feet: ")) print(feet,"feet is equal to",feet*12, "inches ") print(feet, "feet is equal to",feet/3, "yards") print(feet, "feet is equal to",feet/5280,"miles")
true
96f67acf3b9cae1727f5ae4737edb54ea4a5f6c1
helloprogram6/leetcode_Cookbook_python
/DataStruct/BiTree/字典树.py
1,390
4.21875
4
# -*- coding:utf-8 -*- # @FileName :字典树.py # @Time :2021/3/20 13:37 # @Author :Haozr from typing import List class TrieNode: def __init__(self, val=''): self.val = val self.child = {} self.isWord = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ t = self.root for w in word: if w not in t.child: t.child[w] = TrieNode(w) t = t.child[w] t.isWord = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ t = self.root for w in word: if w not in t.child: return False t = t.child[w] if t.isWord: return True return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ cur = self.root for w in prefix: if w not in cur.child: return False cur = cur.child[w] return True if __name__ == '__main__': s = Trie() print(s.insert("Trie")) print(s.startsWith("a"))
true
7c1dfbbc1baf98904272f598608d04659b7b9053
jorzel/codefights
/arcade/python/competitiveEating.py
930
4.21875
4
""" The World Wide Competitive Eating tournament is going to be held in your town, and you're the one who is responsible for keeping track of time. For the great finale, a large billboard of the given width will be installed on the main square, where the time of possibly new world record will be shown. The track of time will be kept by a float number. It will be displayed on the board with the set precision precision with center alignment, and it is guaranteed that it will fit in the screen. Your task is to test the billboard. Given the time t, the width of the screen and the precision with which the time should be displayed, return a string that should be shown on the billboard. Example For t = 3.1415, width = 10, and precision = 2, the output should be competitiveEating(t, width, precision) = " 3.14 ". """ def competitiveEating(t, width, precision): return "{:.{}f}".format( t, precision ).center(width)
true
72b951eebf3317d9a36822ef3056129257781ef1
jorzel/codefights
/challange/celsiusVsFahrenheit.py
1,549
4.4375
4
""" Medium Codewriting 2000 You're probably used to measuring temperature in Celsius degrees, but there's also a lesser known temperature scale called Fahrenheit, which is used in only 5 countries around the world. You can convert a Celsius temperature (C) to Fahrenheit (F), by using the following formula: F = 9 * C / 5 + 32 Your friend lives in Palau (where the Fahrenheit system is used), and you've been trying to find out which of you lives in a warmer climate, so you've each kept track of your respective daily temperatures for the past n days. Given two arrays of integers yourTemps and friendsTemps (each of length n), representing the local daily temperatures (in Celsius and Fahrenheit, respectively), find how many days were hotter in Palau. Example For yourTemps = [25, 32, 31, 27, 30, 23, 27] and friendsTemps = [78, 83, 86, 88, 86, 89, 79], the output should be celciusVsFahrenheit(yourTemps, friendsTemps) = 3. Converting your recorded temperatures to Fahrenheit gives the results [77, 89.6, 87.8, 80.6, 86, 73.4, 80.6], which can be compared to the temperatures your friend recorded: your temps friend's temps 77 78 89.6 83 87.8 86 80.6 88 86 86 73.4 89 80.6 79 There were 3 days where your friend recorded hotter temperatures, so the answer is 3. """ def to_fahrenheit(temp): return float(9 * temp) / 5 + 32 def celsiusVsFahrenheit(yourTemps, friendsTemps): counter = 0 for you, friend in zip(yourTemps, friendsTemps): if friend > to_fahrenheit(you): counter += 1 return counter
true
658593501932b67c86b33a4f1a0ba2a1257e2de5
jorzel/codefights
/interview_practice/hash_tables/possibleSums.py
876
4.28125
4
""" You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins. Example For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be possibleSums(coins, quantity) = 9. Here are all the possible sums: 50 = 50; 10 + 50 = 60; 50 + 100 = 150; 10 + 50 + 100 = 160; 50 + 50 = 100; 10 + 50 + 50 = 110; 50 + 50 + 100 = 200; 10 + 50 + 50 + 100 = 210; 10 = 10; 100 = 100; 10 + 100 = 110. As you can see, there are 9 distinct sums that can be created from non-empty groupings of your coins. """ def possibleSums(values, counts): sums = {0} for v, c in zip(values, counts): sums |= {i + choice for choice in range(v, v * c + 1, v) for i in sums} return len(sums) - 1
true
4193ada270f7accddd799997c1c705545eb243f3
jorzel/codefights
/arcade/core/isCaseInsensitivePalindrome.py
742
4.375
4
""" Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters. Example For inputString = "AaBaa", the output should be isCaseInsensitivePalindrome(inputString) = true. "aabaa" is a palindrome as well as "AABAA", "aaBaa", etc. For inputString = "abac", the output should be isCaseInsensitivePalindrome(inputString) = false. All the strings which can be obtained via changing case of some group of letters, i.e. "abac", "Abac", "aBAc" and 13 more, are not palindromes. """ def isCaseInsensitivePalindrome(inputString): length = len(inputString) for i in range(length / 2): if inputString[i].lower() != inputString[-1 - i].lower(): return False return True
true
495f3051e8737856cf1adbc0dbd601166b185ec5
jorzel/codefights
/arcade/intro/evenDigitsOnly.py
346
4.25
4
""" Check if all digits of the given integer are even. Example For n = 248622, the output should be evenDigitsOnly(n) = true; For n = 642386, the output should be evenDigitsOnly(n) = false. """ def evenDigitsOnly(n): el_list = [int(i) for i in str(n)] for p in el_list: if p % 2 != 0: return False return True
true
051faa94e67dcb9db8c35ec2bb577d8fb0598c32
jorzel/codefights
/arcade/intro/growingPlant.py
704
4.625
5
""" Each day a plant is growing by upSpeed meters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level. Example For upSpeed = 100, downSpeed = 10 and desiredHeight = 910, the output should be growingPlant(upSpeed, downSpeed, desiredHeight) = 10. """ def growingPlant(upSpeed, downSpeed, desiredHeight): days = 0 height = 0 while True: height = height + upSpeed days += 1 if height >= desiredHeight: return days height = height - downSpeed return days
true
455f2a51259a5c06c167a5c6560cf0a22e4f2ce3
jorzel/codefights
/arcade/python/tryFunctions.py
1,035
4.125
4
""" Easy Recovery 100 Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extremely difficult to comprehend. To understand what function is applied to x instead of the one that should have been applied, you decided to go ahead and compare the result with results of all the functions you could come up with. Given the variable x and a list of functions, return a list of values f(x) for each x in functions. Example For x = 1 and functions = ["math.sin", "math.cos", "lambda x: x * 2", "lambda x: x ** 2"], the output should be tryFunctions(x, functions) = [0.84147, 0.5403, 2, 1]. """ def tryFunctions(x, functions): return [eval('({})({})'.format(f, x)) for f in functions]
true
94c2397a4ecb9cbfbe88f8b5c7831805fc246562
jorzel/codefights
/interview_practice/arrays/rotateImage.py
471
4.46875
4
""" Note: Try to solve this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview. You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). Example For a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the output should be rotateImage(a) = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] """ def rotateImage(a): return list([list(reversed(p)) for p in zip(*a)])
true
7757551f8a04e9875fd09f7cce05b1a06aafab49
jorzel/codefights
/arcade/intro/longestDigitsPrefix.py
439
4.15625
4
""" Given a string, output its longest prefix which contains only digits. Example For inputString="123aa1", the output should be longestDigitsPrefix(inputString) = "123". """ def longestDigitsPrefix(inputString): max_seq = "" for i, el in enumerate(inputString): if i == 0 and not el.isdigit(): return "" if el.isdigit(): max_seq += el else: break return max_seq
true
bfc993bfda53b5a1e69f4b1feefc9b0eea4bdb22
jorzel/codefights
/arcade/core/concatenateArrays.py
282
4.15625
4
""" Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b. Example For a = [2, 2, 1] and b = [10, 11], the output should be concatenateArrays(a, b) = [2, 2, 1, 10, 11]. """ def concatenateArrays(a, b): return a + b
true
cc9e43e94fd96b2407b289ef20cf5a7c04652c3d
jorzel/codefights
/interview_practice/strings/findFirstSubstringOccurence.py
751
4.3125
4
""" Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview. Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1. Example For s = "CodefightsIsAwesome" and x = "IA", the output should be strstr(s, x) = -1; For s = "CodefightsIsAwesome" and x = "IsA", the output should be strstr(s, x) = 10. """ import re def findFirstSubstringOccurrence(string, x): p = re.search(x, string) if p: return p.start() else: return -1
true
df6930a4776a2e67381065e5dbfc8d5dfe64bf03
jorzel/codefights
/arcade/python/isWordPalindrome.py
374
4.625
5
""" Given a word, check whether it is a palindrome or not. A string is considered to be a palindrome if it reads the same in both directions. Example For word = "aibohphobia", the output should be isWordPalindrome(word) = true; For word = "hehehehehe", the output should be isWordPalindrome(word) = false. """ def isWordPalindrome(word): return word == word[::-1]
true
d800d63f49158fcbb0f2af79a9d315061e028fdb
jorzel/codefights
/arcade/intro/biuldPalindrome.py
575
4.25
4
""" Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome. Example For st = "abcdc", the output should be buildPalindrome(st) = "abcdcba". """ def isPalindrome(st): for i in range(len(st) / 2): if st[i] != st[-1 - i]: return False return True def buildPalindrome(st): if isPalindrome(st): return st rev = st[::-1] for i in range(len(st)): if isPalindrome(rev[:i + 1]): index = i return st + rev[index + 1:]
true
0725fe8ef04175b03de2315a61be93a6bbf4aa2e
jorzel/codefights
/arcade/intro/firstDigit.py
414
4.28125
4
""" Find the leftmost digit that occurs in a given string. Example For inputString = "var_1__Int", the output should be firstDigit(inputString) = '1'; For inputString = "q2q-q", the output should be firstDigit(inputString) = '2'; For inputString = "0ss", the output should be firstDigit(inputString) = '0'. """ def firstDigit(inputString): for s in inputString: if s.isdigit(): return s
true
e520b1fc70883eacd427dc2b6ffe006d2f75d926
jorzel/codefights
/interview_practice/dynamic_programming_basic/climbingStairs.py
688
4.1875
4
""" Easy Codewriting 1500 You are climbing a staircase that has n steps. You can take the steps either 1 or 2 at a time. Calculate how many distinct ways you can climb to the top of the staircase. Example For n = 1, the output should be climbingStairs(n) = 1; For n = 2, the output should be climbingStairs(n) = 2. You can either climb 2 steps at once or climb 1 step two times. """ def fib(n): if n == 0 or n == 1: return n old, new = 0, 1 for _ in range(n): old, new = new, old + new return new def climbingStairs(n): return fib(n) def climbingStaircase(n, k): if n == 0: return [[]] return climbing(n, k, [], [])
true
7872f5adf499f79df9cec821fb8020c8f3bbadbb
jorzel/codefights
/arcade/core/fileNames.py
856
4.15625
4
""" You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet. Return an array of names that will be given to the files. Example For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]. """ def fileNaming(names): results = [] for name in names: if name in results: counter = 1 new_name = name while new_name in results: new_name = name + '(' + str(counter) + ')' counter += 1 name = new_name results.append(name) return results
true
79907a750c9bffa2f140a3f1be68acf207da1f59
jorzel/codefights
/interview_practice/common_techinques_basic/containsDuplicates.py
640
4.15625
4
""" Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true if any element appears at least twice in the array, and it should return false if every element is distinct. Example For a = [1, 2, 3, 1], the output should be containsDuplicates(a) = true. There are two 1s in the given array. For a = [3, 1], the output should be containsDuplicates(a) = false. The given array contains no duplicates. """ def containsDuplicates(a): d = {} for n in a: if n not in d: d[n] = 1 else: return True return False
true
388748ed56911db4eefc35817dee3e0bafe07404
jorzel/codefights
/challange/maxPoints.py
1,212
4.15625
4
""" World Cup is going on! One of the most fascinating parts of it is the group stage that has recently ended. A lot of great teams face each other to reach the playoff stage. In the group stage, each pair of teams plays exactly one game and each team receives 3 points for a win, 1 point for a draw and 0 points for a loss. You fell asleep. What a shame. While you were sleeping, your team has played a lot of games! Now you know how many matches your team has played, how many goals it has scored and how many has missed. Now you need to find out the maximum amount of points your team can have. Example For matches = 2, goalsFor = 1 and goalsAgainst = 2, the output should be maxPoints(matches, goalsFor, goalsAgainst) = 3; For matches = 2, goalsFor = 3 and goalsAgainst = 2, the output should be maxPoints(matches, goalsFor, goalsAgainst) = 4. """ def maxPoints(matches, goalsFor, goalsAgainst): points = 0 while goalsFor > 0 and matches > 1: goalsFor -= 1 matches -= 1 points += 3 while matches > 1: points += 1 matches -= 1 if goalsAgainst == goalsFor: points += 1 elif goalsFor > goalsAgainst: points += 3 return points
true
ca8dd729003dd665c4e3fba57289fc4b315128ec
MulderPu/legendary-octo-guacamole
/pythonTuple_part1.py
767
4.15625
4
''' Write a Python program to accept values (separate with comma) and store in tuple. Print the values stored in tuple, sum up the values in tuple and display it. Print the maximum and minimum value in tuple. ''' user_input = input("Enter values (separate with comma):") tuple = tuple(map(int, user_input.split(','))) print('~~~~~~~~~~') print("Values stored in tuple") print("Tuple:",tuple) print("~~~~~~~~~~") print('Total:',sum(tuple)) print('Maximum',max(tuple)) print('Minimum',min(tuple)) number=int(input('Enter a number to see how many times it has appeared inside the tuple:')) count = tuple.count(number) if(count==0): print('%i appeared %i time in tuple list.'%(number,count)) else: print('%i appeared %i times in tuple list.'%(number, count))
true
71c4d79d3e982de8875def381e621b8a8dd46247
MulderPu/legendary-octo-guacamole
/guess_the_number.py
801
4.25
4
import random print('~~Number Guessing Game~~') try: range = int(input('Enter a range of number for generate random number to start the game:')) rand = random.randint(1,range) guess = int(input('Enter a number from 1 to %i:'%(range))) i=1 while (i): print() if guess == 0 or guess < 0: print('Give up? Try again next time!') break elif guess < rand: print('Number too small.') guess = int(input('Enter a number from 1 to %i:'%(range))) elif guess > rand: print('Number too large.') guess = int(input('Enter a number from 1 to %i:'%(range))) elif guess == rand: print('Congratulation. You made it!') break except: print('Wrong Input.')
true
ce71585126ae1e765a99600203ba6e2585860f60
ProNilabh/Class12PythonProject
/Q11_RandomGeneratorDICE.py
307
4.28125
4
#Write a Random Number Generator that Generates Random Numbers between 1 and 6 (Simulates a Dice) import random def roll(): s=random.randint(1,6) return s xD= str(input("Enter R to Roll the Dice!-")) if xD=="r": print(roll()) else: print("Thanks for Using the Program!")
true
014674cad94445da44a1c2f258777d6529687270
Raghavi94/Best-Enlist-Python-Internship
/Tasks/Day 8/Day 8.py
2,983
4.21875
4
#TASK 8: #1)List down all the error types and check all the errors using a python program for all errors #Index error #Name error #zerodivision error a=[0,1,2,3] try: print(a[1]) print(a[4],a[1]//0) except(IndexError,ZeroDivisionError): print('Index error and zero division error occured') #2)Design a simple calculator app with try and except for all use cases import math while 1: print ("1) Add") print ("2) Subtract") print ("3) Divide") print ("4) Multiply") print ("0) Exit") try: # This is a try statement used to handle errors answer = int(input("Option: ")) if answer == 1: first = float(input("First Number: ")) second = float(input("Second Number: ")) final = first + second print ("Answer:", float(final)) print() elif answer == 2: first = float(input("First Number: ")) second = float(input("Second Number: ")) final = first - second print ("Answer:", float(final)) print() elif answer == 3: first = float(input("First Number: ")) second = float(input("Second Number: ")) final = first / second print ("Answer:", float(final)) print() elif answer == 4: first = float(input("First Number: ")) second = float(input("Second Number: ")) final = first * second print ("Answer:", float(final)) print() elif answer == 0: break else: print ("\nPlease select a valid option number\n") except NameError: print ("\nNameError: Please Use Numbers Only\n") except SyntaxError: # SyntaxError means we typed letters or special characters i.e !@#$%^&*( or if we tried to run python code print ("\nSyntaxError: Please Use Numbers Only\n") except TypeError: # TypeError is if we entered letters and special characters or tried to run python code print ("\nTypeError: Please Use Numbers Only\n") except AttributeError: # AttributeError handles rare occurances in the code where numbers not on the list are handled outside of the if statement print ("\nAttributeError: Please Use Numbers Only\n") #3)print one message if the try block raises a NameError and another for other errors try: print(x) except NameError: print('NameError:x is not defined') #4)When try-except scenario is not required? #try-except is used for checking and validation purpose,otherwise it is not needed #5)Try getting an input inside the try catch block try: n=int(input('Enter a number')) print('Input you gave is valid') except ValueError: print('Invalid input')
true
19b00f3cace5617652435d104b04dc24b68513ea
ezekielp/algorithms-practice
/integer_break.py
1,227
4.25
4
""" Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. Note: You may assume that n is not less than 2 and not larger than 58. """ # 23 # 5 * 5 * 5 * 5 * 3 = 1875 # 4 * 4 * 4 * 4 * 4 * 3 = 3072 # 6 * 6 * 6 * 5 = 1080 # import math # You never need a factor greater than or equal to 4. # Explain: If an optimal product contains a factor f >= 4, then you can replace it with factors 2 and f-2 without losing optimality, as 2*(f-2) = 2f-4 >= f. # class Solution(object): # def integerBreak(self, n): # """ # :type n: int # :rtype: int # """ # square_root = math.sqrt(n) # rounded_sqrt = math.floor(square_root) # diff = n - (rounded_sqrt ** 2) # count = 0 # sum_so_far = 0 # nums = [] # while sum_so_far < n - diff: # count += 1 # sum_so_far += rounded_sqrt # nums.append(rounded_sqrt) # nums.append(diff) # return nums.reduce() # variable = math.sqrt(10) # print(math.floor(variable))
true
679b8b24eda016b5e320624a0ead00bfdf12903b
dple/Strings-in-Python
/pangram.py
706
4.15625
4
""" A pangram is a string that contains every letter of the alphabet. Given a sentence determine whether it is a pangram in the English alphabet. Return either pangram or not pangram as appropriate. For example: Input: We promptly judged antique ivory buckles for the next prize Output: pangram """ def pangrams(s): alphabet = 'abcdefghijklmnopqrstuvwxyz' states = 26*[0] for c in s: if c.lower() in alphabet: states[alphabet.index(c.lower())] = 1 for i in range(26): if states[i] == 0: return 'not pangram' return 'pangram' if __name__ == '__main__': s= 'We promptly judged antique ivory buckles for the next prize' print(pangrams(s))
true
31c86f9b3b49aca2002fa01058ca4763312c3046
Gaurav1921/Python3
/Basics of Python.py
1,703
4.375
4
""" to install any module first go in command prompt and write 'pip install flask' and then come here and write modules are built in codes which makes our work more easier and pip is package manager which pulls modules """ import flask """ to print something the syntax for it is """ print("Hello World") """ using python as calculator """ print(36 + 8) # returns the addition print(36 - 8) # returns the subtraction print(36 * 8) # returns the multiplication print(36 / 8) # returns the division print(36 // 8) # returns the quotient print(30 % 8) # returns the remainder """ comments for multi line """ # comments for single line """ if we don't want to add another line while printing statement use end (by default its a new line character) """ print("Gaurav is the best", end=" ") # python thinks that the space is the end of the line & starts printing new line from there print("Do like and subscribe the channel") """ escape sequence character """ # for more go to Quackit.com escape char print("Gaurav\nSingh") # new line character print("Gaurav\"Singh\"") # when extra "" used print("Gaurav\tSingh") # extra space character """ assigning values to a variable """ var1 = "Hello World" var2 = 4 # we can add two integers or two strings but not strings and int var3 = 3.4 """ to know the type of variable""" print(type(var2)) print(type(var1)) print(type(var3)) """ doing typecast """ a = int("54") # originally 54 and 73.3 were strings but now typecasted to integers and float b = float("73.3") print(a+b) """ we can multiply string with int """ print("Gaurav"*5)
true
d1ee3c94491b93693cd9bd09f65e7e4d31ad4511
Enin/codingTest
/amazon/6_determine_if_a_binary_tree_is_a_binary_search_tree.py
2,728
4.28125
4
### # Given a Binary Tree, figure out whether it’s a Binary Sort Tree. # In a binary search tree, each node’s key value is smaller than the key value of all nodes in the right subtree, # and is greater than the key values of all nodes in the left subtree. # Below is an example of a binary tree that is a valid BST. import collections class node: def __init__(self, value): self.value = value self.left, self.right = None, None class BST: def __init__(self, head): self.head = head def insert(self, value): self.current_node = self.head while True: if value < self.current_node.value: if self.current_node.left != None: self.current_node = self.current_node.left else: self.current_node.left = node(value) break else: if self.current_node.right != None: self.current_node = self.current_node.right else: self.current_node.right = node(value) break def check_tree(self): self.queue = [collections.deque(), collections.deque()] self.current_queue = self.queue[0] self.next_queue = self.queue[1] self.tree_level = 0 self.current_queue.append(self.head) while self.current_queue: self.temp = self.current_queue.popleft() if self.temp.left is not None: if self.temp.value < self.temp.left.value: print("worng BST on level {}. {} < {}".format(self.tree_level, self.temp.value, self.temp.value.left.value)) return False self.next_queue.append(self.temp.left) if self.temp.right is not None: if self.temp.value > self.temp.right.value: print("worng BST on level {}. {} > {}".format(self.tree_level, self.temp.value, self.temp.value.left.value)) return False self.next_queue.append(self.temp.right) if not self.current_queue: self.tree_level += 1 self.current_queue = self.queue[(self.tree_level % 2)] self.next_queue = self.queue[(self.tree_level + 1) % 2] print("The tree is correct BST") return True def create_BST(input): for i in range(len(input)): if i == 0: root = node(input[i]) tree = BST(root) else: tree.insert(input[i]) return tree def main(): arr = [100, 50, 200, 25, 75, 90, 350] test_tree = create_BST(arr) result = test_tree.check_tree() print(result) main()
true
74af819f062dc0dff568fbbfdd2767be07f4f603
Enin/codingTest
/amazon/7_string_segmentation.py
907
4.375
4
# You are given a dictionary of words and a large input string. # You have to find out whether the input string can be completely segmented into the words of a given dictionary. # The following two examples elaborate on the problem further. import collections # recursion과 memoization을 사용 given_dict = ['apple', 'apple', 'pear', 'pie'] input_string = ['applepie', 'applepeer'] def can_segment_string(str, dict): for s in range(1, len(str)+1): first_word = str[0:s] if first_word in dict: second_word = str[s:] if not second_word or second_word in dict or can_segment_string(second_word, dict): return True return False def test(): dict_set = set(given_dict) if can_segment_string(input_string[1], dict_set): print("Input string can be segmented") else: print("Input string can't be segmented") test()
true
d3302d00ebca7dd0ff302f38cd78d1b87ccb5c1f
AdishiSood/Jumbled_Words_Game
/Jumbled_words_Game.py
2,419
4.46875
4
#To use the random library, you need to import it. At the top of your program: import random def choose(): words=["program","computer","python","code","science","data","game"] pick=random.choice(words) #The choice() method returns a list with the randomly selected element from the specified sequence. return pick def jumble(word): jumbled="".join(random.sample(word,len(word))) #The join() method takes all items in an iterable and joins them into one string. #The sample() method returns a list with a randomly selection of a specified number of items from a sequence. return jumbled def thank(p1n,p2n,p1,p2): print("========= Score board ============= ") print(p1n,'Your score is : ',p1) print(p2n,'Your score is : ',p2) print('Thanks for playing') print('Have a nice day') print("===================================") def main(): p1name= input('Player 1, Please enter your name') #p1name= name of player1 p2name= input('Player 2, Please enter your name') #p2name= name of player2 pp1 =0 #points of player 1 pp2 =0 #points of player 2 turn =0 #To keep track of whose turn it is let us have some variable or turn initially let it be zero i while(1): #computer's task picked_word =choose() #create question qn=jumble(picked_word) print (qn) #player1 if turn%2==0: print(p1name,'its Your turn, What is on your mind?') ans=input() if ans==picked_word: pp1=pp1+1 print('Your score is : ',pp1) else: print("Oh! better luck next time.") print('The correct answer is :',picked_word) c=int(input('Press 1 to continue and 0 to quit : ')) if c==0: thank(p1name,p2name,pp1,pp2) break #player2 else: print(p2name,'its Your turn, What is on your mind?') ans=input() if ans==picked_word: pp2=pp2+1 print('Your score is : ',pp2) else: print("Oh! better luck next time.") print('The correct answer is :',picked_word) c=int(input('Press 1 to continue and 0 to quit : ')) if c==0: thank(p1name,p2name,pp1,pp2) break turn=turn+1 main()
true
bb984eb7c1ecb5e4d1407baa9e8599209ff05f3b
xASiDx/other-side
/input_validation.py
794
4.25
4
'''Input validation module Contains some functions that validate user input''' def int_input_validation(message, low_limit=1, high_limit=65536, error_message="Incorrect input!"): '''User input validation The function checks if user input meets set requirements''' user_input = 0 #we ask user to enter an integer number between low_limit and high_limit #until he enters correctly while True: user_input = input(message) #if user input meets the requirments... if user_input.isdecimal() and (int(user_input) in range(low_limit,high_limit+1)): #we return user input return int(user_input) else: #otherwise we print the error message and continue the loop print(error_message)
true
d0219bd6ffe2d00bba2581b72b852b858c8c1a07
QARancher/file_parser
/search/utils.py
710
4.1875
4
import re from search.exceptions import SearchException def search(pattern, searched_line): """ method to search for string or regex in another string. :param pattern: the pattern to search for :param searched_line: string line as it pass from the file parser :return: matched object of type re :raise: SearchException if the strings invalid """ try: pattern = re.compile(pattern, re.IGNORECASE) for match in re.finditer(pattern=pattern, string=searched_line): return match except re.error: raise SearchException(message="Failed compiling pattern" " {pattern}".format(pattern=pattern))
true
74e87bf28436a832be8814386285a711b627dab9
ohaz/adventofcode2017
/day11/day11.py
2,179
4.25
4
import collections # As a pen&paper player, hex grids are nothing new # They can be handled like a 3D coordinate system with cubes in it # When looking at the cubes from the "pointy" side and removing cubes until you have a # plane (with pointy ends), each "cube" in that plane can be flattened to a hexagon # This means that 3D coordinates can be used easily to get a 2D representation of a hex grid # Examples and explanations are on https://www.redblobgames.com/grids/hexagons/ # # x = 0 # \ n / # nw +--+ ne # z = 0 /y \ y = 0 # -+ x+- # y = 0 \z / z = 0 # sw +--+ se # / s \ # x = 0 Point = collections.namedtuple('Point', ['x', 'y', 'z']) def add_point(p1: Point, p2: Point): if p2 is None: print('Did not add anything') return p1 return Point(x=p1.x + p2.x, y=p1.y+p2.y, z=p1.z+p2.z) def distance(p1: Point, p2: Point): # The Manhattan distance in a hex grid is half the Manhattan distance in a cube grid. # coincidentally this is also just the max of the three distances return max(abs(p1.x - p2.x), abs(p1.y - p2.y), abs(p1.z - p2.z)) def calculate_solution(): with open('day11/day11_input.txt', 'r') as f: content = f.read() steps = content.split(',') max_distance = 0 zero = Point(x=0, y=0, z=0) current_pos = Point(x=0, y=0, z=0) for step in steps: modifier = None # Go around clockwise and create modify vectors if step == 'n': modifier = Point(x=0, y=1, z=-1) elif step == 'ne': modifier = Point(x=1, y=0, z=-1) elif step == 'se': modifier = Point(x=1, y=-1, z=0) elif step == 's': modifier = Point(x=0, y=-1, z=1) elif step == 'sw': modifier = Point(x=-1, y=0, z=1) elif step == 'nw': modifier = Point(x=-1, y=1, z=0) else: print('Unknown direction', step) current_pos = add_point(current_pos, modifier) max_distance = max(max_distance, distance(current_pos, zero)) return distance(current_pos, zero), max_distance
true
9e9f9151efbe59c7e0100048c3d46f7d8786bba5
dennis-omoding3/firstPython
/task.py
630
4.15625
4
taskList=[23,"jane",["lesson 23",560,{"currency":"kes"}],987,(76,"john")] # 1. determine the type of var in task list using an inbuilt function print(type(taskList)) # 2.print kes print(taskList[2][2]["currency"]) # 3.print 560 print(taskList[2][1]) # 4. use a function to determine the length of taskList print(len(taskList)) # 5. change 987 to 789 using an inbuilt method or assignment print(str(taskList[3])[::-1] )#typecasting into a string because integer cannot be reversed #print(a.reverse()) # 6. change the name "john" to "jane" without using assignment #NA a tuple cannot be modified #print(taskList.index("jane"))
true
ea53fb163337a49762314dbc38f2788a74846343
SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex
/Lesson24_multiline_print.py
666
4.5
4
# The idea of multi-line printing in Python is to be able to easily print # across multiple lines, while only using 1 print function, while also printing # out exactly what you intend. Sometimes, when making something like a text-based # graphical user interface, it can be quite tedious and challenging to make everything # line up for you. This is where multi-line printing can be very useful. print( ''' This is a test ''' ) print( ''' So it works like a multi-line comment, but it will print out. You can make kewl designs like this: ============== | | | | | BOX | | | | | ============== ''' )
true
77181ee32df9fc60121bcdb41aca5717c4245405
HarrietLLowe/python_turtle-racing
/turtle_race.py
1,278
4.28125
4
from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a colour: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] turtles = [] for x in range (0, 6): new_turtle = Turtle(shape="turtle") turtles.append(new_turtle) num = 0 def style_turtle(turtle): global num turtle.color(colors[num]) num += 1 y_axis = -230 x_axis = -125 def starting_pos(turtle): turtle.penup() global x_axis global y_axis for each in turtles: x_axis += 5 turtle.goto(y_axis,x_axis) for each in turtles: style_turtle(each) starting_pos(each) if user_bet: is_race_on = True while is_race_on: for turtle in turtles: if turtle.xcor() > 230: winning_colour = turtle.pencolor() is_race_on = False if winning_colour == user_bet: print(f"You've won! The winning turtle is {winning_colour}!") else: print(f"You lost! The winning turtle is {winning_colour}!") random_distance = random.randint(0, 10) turtle.forward(random_distance) screen.exitonclick()
true
28d4c117c564ad0926fafd890f182ec7c3938c22
Deepu14/python
/cows_bulls.py
1,637
4.28125
4
""" Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls""" import random import string import sys def cows_bulls(): num = ''.join([random.choice(string.digits) for i in range(4)]) num = list(num) #print(num) cows = 0 bulls = 0 guess=0 attempt =0 while(num != guess): guess = input("guess the number: ") if(len(guess) == 4): guess = list(guess) else: print("Invalid. Please enter a four digit number: ") continue for i in range(4): if num[i] == guess[i]: cows = cows + 1 elif num[i] in guess and num[i] != guess[i]: bulls = bulls + 1 attempt = attempt + 1 print(cows,"cows") print(bulls,"bulls") print("number of valid attempts are: ",attempt) if __name__ == "__main__": cows_bulls()
true
25697204d6da732977cef03994324d00368ce1cb
hari1811/Python-exercises
/Quiz App/common.py
685
4.15625
4
def get_int_input(prompt, high): while(1): print() try: UserChoice = int(input(prompt)) except(ValueError): print("Error: Expected an integer input!") continue if(UserChoice > high or UserChoice < 1): print("Error: Please enter a valid choice!") else: break return UserChoice def get_yes_no_input(prompt): while(1): print() UserChoice = input(prompt).lower() if(UserChoice == 'y'): return 1 elif(UserChoice == 'n'): return 0 else: print("Error: Please enter y or n!")
true
a20fc079740a8d7ff9b022fe5e491b3218b2559a
acheval/python
/python_exercices/exercice06.py
402
4.3125
4
#!/bin/python3 # 6. Write a Python program to count the number of characters in a string. # Sample String : 'google.com' Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': # 1, 'l': 1, 'm': 1, 'c': 1} string = 'google.com' d = dict() for letter in string: if letter in d: d[letter] = d[letter]+1 else: d[letter] = 1 for key in list(d.keys()): print(key, ": ", d[key])
true
358cb695ab1430599eba277be1d2873ae862ccb8
pranavchandran/redtheme_v13b
/chapter_2_strings_and_text/numbers_dates_times/rounding_numerical_values.py
1,408
4.125
4
# rounding numerical values # simple rounding print(round(1.23, 1)) print(round(1.27, 1)) print(round(1.25362, 3)) a = 1627731 print(round(a, -1)) print(round(a, -2)) print(round(a, -3)) x = 1.23456 print(format(x, '0.2f')) print(format(x, '0.3f')) print('value is {:0.3f}'.format(x)) a = 2.1 b = 4.2 c = a + b # c = round(c, 2) # print(c) # float they cant accurately represent base-10 decimals print(a + b == 6.3) # you want more performance you can use the decimal module from decimal import Decimal a = Decimal('4.2') b = Decimal('2.1') print(a + b) print((a + b) == Decimal(6.3)) from decimal import localcontext a = Decimal('1.3') b = Decimal('1.7') print(a/b) with localcontext() as ctx: ctx.prec = 3 print(a/b) nums = [1.23e+18, 1, -1.23e+18] print(sum(nums)) #1 disappears import math print(math.fsum(nums)) x = 1234.56789 # 2 decimal places of accuracy print(format(x, '0.2f')) # right justified in 10 chars, one digit accuracy print(format(x, '>10.1f')) # left justified print(format(x, '<10.1f')) # centred print(format(x, '^10.1f')) print(format(x, ',')) print(format(x, '0,.1f')) print(format(x, 'e')) print(format(x, '0.2E')) x = 1234.56789 print(format(x, '0,.1f')) print(format(-x, '0,.1f')) swap_separators = {ord('.'): ',', ord(','):'.'} print(format(x, ',').translate(swap_separators)) print('%0.2f'%x) print('%10.1f'%x) print('%-10.1f'%x)
true
f8d026245e19a202915e9cdc57dd0e9e4949760a
pranavchandran/redtheme_v13b
/chapter_2_strings_and_text/matching_string_using_shell_wild_cards/aligning _text_strings.py
718
4.3125
4
# Aligning of strings the ljust(), rjust() and center() text = 'Hello World' print(text.ljust(20)) print(text.rjust(20)) print(text.center(20)) print(text.rjust(20, '=')) print(text.center(20,'*')) # format() function can also be used to align things print(format(text, '>20')) print(format(text, '<20')) print(format(text, '^20')) # fill the charachter other than a space print(format(text, '=>20')) print(format(text, '=>20')) print(format(text, '*^20s')) # These format codes can also be used in the format() method when formatting # multiple values. print('{:>10s}{:>10s}'.format('Hello', 'World')) x = 1.2345 print(format(x, '>20')) print(format(x, '^10.2f')) print('%-20s'%text) print('%20s'%text)
true
1d34800f127f69e26a9622e5e42407420657a055
akhilavemuganti/HelloWorld
/Exercises.py
2,984
4.1875
4
#Exercises #bdfbdv ncbgjfv cvbdggjb """ Exercise 1: Create a List of your favorite songs. Then create a list of your favorite movies. Join the two lists together (Hint: List1 + List2). Finally, append your favorite book to the end of the list and print it. """ listSongs=["song1","song2","song3","song4"] listMovies=["movie1","movie2","movie3","movie4"] print(listSongs) print(listMovies) newList=listSongs+listMovies print(newList) newList.append("Book1") print(newList) #---------------------------------------------------------------------------------------------------------- """ Exercise 2: There were 20 people on a bus. 10 got off. 3 came on. 15 came on. 5 came off. If there were 3 more buses, and each had 15 people throughout the bus ride, how many people were on all the buses at the last stop? (Should be done via one equation in Python Shell) """ bus=20-10+3+15-5+(3*15) print(bus) #---------------------------------------------------------------------------------------------------------- """ Exercise 3: Create a small program that will take in a User’s name and last name (Hint: varName = input(“Enter your name”)), store both in two variables. And then print out a message saying (“Hello there, FirstName LastName”) (Using the %s symbols) """ firstName=input("Enter your first name") lastName=input("Enter your last name") print("Hello there %s"%firstName+" "+"%s"%lastName) #---------------------------------------------------------------------------------------------------------- """ Exercise 1: Create a loop that prints out either even numbers, or odd numbers all the way up till your age. Ex: 2,4,6,….,14 """ for i in range(0,31): if(i%2==0): print(i) ##OR for i in range(0,31,2): print(i) #---------------------------------------------------------------------------------------------------------- """ Exercise 2: Using if statements, create a variable called day, set it to “Tuesday”. Check to see if day is equal to “Monday” or “Tuesday”, and if it is, print, “Today is sunny”. If it is not, print “Today it will rain” """ day="Tuesday" if(day=="Monday" or day=="Tuesday"): print("Today is sunny") else: print("Today it will rain") #---------------------------------------------------------------------------------------------------------- """ Exercise 3: The weight of a person on the moon is 1/6th the weight of a person standing on earth. Say that your weight on earth increases by 1 kg every year. Write a program that will print your weight on the moon every year for the next 10 years. (Your initial weight can be anything.) """ weightOnEarth=140 weightOnMoon=weightOnEarth*(1/6) for i in range(1,11): weightOnMoon = weightOnEarth * (1 / 6) weightOnEarth = weightOnEarth + 1 print("Weight on Earth %d" %weightOnEarth) print("Weight on Moon %d" %weightOnMoon) #----------------------------------------------------------------------------------------------------------
true
6d63007d90bae6eb2137cced9d5ee0b47665d547
rvcjavaboy/udemypythontest
/Methods_and_Functions/function_test/pro4.py
229
4.15625
4
def old_macdonald(name): result="" for c in range(0,len(name)-1): if c==0 or c==3: result+=name[c].upper() else: result+=name[c] return result print(old_macdonald('macdonald'))
true
8d90a7edcc4d49f85ea8d35dda6d58dcb7654bd0
PinCatS/Udacity-Algos-and-DS-Project-2
/min_max.py
1,298
4.125
4
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if ints is None: return None if len(ints) == 1: return (ints[0], ints[0]) minValue = None maxValue = None for e in ints: if minValue is None or minValue > e: minValue = e if maxValue is None or maxValue < e: maxValue = e return (minValue, maxValue) ## Example Test Case of Ten Integers import random print("Test case 1") l = [i for i in range(0, 10)] # a list containing 0 - 9 random.shuffle(l) print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail") # other test cases print("Test case 2") l = [] # None, None print ("Pass" if ((None, None) == get_min_max(l)) else "Fail") print("Test case 3") l = [1] # (1, 1) print ("Pass" if ((1, 1) == get_min_max(l)) else "Fail") print("Test case 4") l = None # None print ("Pass" if (None == get_min_max(l)) else "Fail") print("Test case 5") l = [-1, -5] # (-5, -1) print ("Pass" if ((-5, -1) == get_min_max(l)) else "Fail") print("Test case 6") l = [1, 2, 3] # (1, 3) print ("Pass" if ((1, 3) == get_min_max(l)) else "Fail")
true
c1d957f7ca914ba5113124684e8b0c21663df2bd
sakshigupta1997/code-100
/code/python/day-1/pattern15.py
326
4.1875
4
'''write a program to print enter the number4 * ** *** ****''' n=int(input("enter the number")) p=n k=0 for row in range(n): for space in range(p,1,-1): print(" ",end='') #for star in range(row): for star in range(row+1): print("*",end='') print() p=p-1
true
e02ba552e441eb412b25f7f9d15299288e34ad37
Iansdfg/9chap
/4Binary Tree - Divide Conquer & Traverse/85. Insert Node in a Binary Search Tree.py
857
4.125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: root: The root of the binary search tree. @param: node: insert this node into the binary search tree @return: The root of the new binary search tree. """ def insertNode(self, root, node): # write your code here head = dummy = TreeNode(float('-inf')) dummy.right = root while root: dummy = root if node.val > dummy.val: root = root.right elif node.val < root.val: root = root.left if node.val > dummy.val: dummy.right = node else: dummy.left = node return head.right
true
399106fc8885d5f892d49b080084a393ab5dbb4a
jack-sneddon/python
/04-lists/list-sort.py
596
4.46875
4
# sort - changes the order permenantly cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla'] cars.sort() print (cars) # reverse sort cars.sort(reverse = True) print (cars) # temporary sort - sorted cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla'] print("here is the original list:") print (cars) print("here is the sorted list:") print(sorted(cars)) print("here is the original list again:") print (cars) # reverse the order print("here is the original list:") print (cars) cars.reverse() print("here is the reverse list:") print (cars) cars_length = len(cars) print (cars_length)
true
9a6c909e0fec1e2b90318ed7644d97e8a1663182
jack-sneddon/python
/04-lists/lists-while-loop.py
2,007
4.40625
4
# a for loop is effective for looping through a list, but you shouldn't modify a # list inside for loop because Pything will have trouble keeping track of the items # in the list. To modify a list as you work throuh it, use a while loop. # Using while loops with lists and dictionaries allows you to collect, store, and # organize lots of input to examine and report on later. # # move items from one list to another # # start with populated list and an empty list unconfirmed_users = ['alice', 'bob', 'candice'] confirmed_users = [] # verfiy each user until there are no more unconfirmed users. # move each verified user into the list of confirmed users. while unconfirmed_users: confirmed_user = unconfirmed_users.pop() print(f"Verifying user: {confirmed_user.title()}") confirmed_users.append(confirmed_user) # remove all instances of a specific values from a list pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(f"\npets = {pets}") # use the 'remove' command only removes the first instance pets.remove('cat') print(f"\npets = {pets}") # use while loop pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] while 'cat' in pets : pets.remove('cat') print(f"\npets = {pets}") # # Fill out a dictionary # responses = {} # Set active flag to indicate that polling is active polling_active = True while polling_active : # prompt for the pserson's name and response. name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # store the response in the dictionary responses[name] = response # find out if anyone else is going to take the poll. repeat = input ("Would you like to let another person respond (yes/no) ") if repeat == 'no': polling_active = False # Polling complete, Show results print("\n --- Polling Results ---") for name, response in responses.items() : print(f"{name.title()} would like to climb {response.title()}")
true
17ff6eaf25026ada4fd159e2ae3905854fd56d2f
GeoMukkath/python_programs
/All_python_programs/max_among_n.py
280
4.21875
4
#Q. Find the maximum among n numbers given as input. n = int(input("Enter the number of numbers : ")); print("Enter the numbers: "); a = [ ]; for i in range(n): num = int(input( )); a.append(num); maximum= max(a); print("The maximum among the given list is %d" %maximum);
true
b9a895f074168c0be5f86592214a316b46bbc98b
JLarraburu/Python-Crash-Course
/Part 1/Hello World.py
1,574
4.65625
5
# Python Crash Course # Jonathan Larraburu print ("Hello World!") # Variables message = "Hello Python World! This string is saved to a variable." print(message) variable_rules = "Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number." variable_rules_ext = variable_rules print(variable_rules_ext) # Strings simple = 'strings are very simple in Python' example_string = "I can use quotes or apostrophes 'or both'" name = 'ada lovelace' print(name.title()) print(name.upper()) print(name.lower()) first_name = 'jon' last_name = 'larraburu' full_name = first_name + ' ' + last_name print(full_name) print('Hello, ' + full_name.title() + '!') print('\t This will add a tab.') print('\nThis is add a new line. This one is very convenient if you remember c++') print('combine the two...\n') print('\tLanguages:\n') print('\t\tPython!') print('\t\tC++!') print('\t\tJavaScript!') stripping_whitespace = 'python ' stripping_whitespace.rstrip() print(stripping_whitespace) stripping_whitespace = stripping_whitespace.rstrip() print(stripping_whitespace) # Numbers this_is_how_exponents_work = 2 ** 8 age = 32 happy_birthday = 'Happy ' + str(age) + 'nd birthday!' # I know how comments work! # We love comments! # More comments the better! # The main reason to write comments is to explain what your code is supposed to do and how you are making it work. """ There is no reason you can't use this as a multiline comment when writing python.""" # Still cleaner to just use comments imo
true
c9c2548eb74b5375baeea0d7d526d0dd8446e653
Varun-Mullins/Triangle567
/Triangle.py
1,623
4.46875
4
# -*- coding: utf-8 -*- """ Updates on Friday January 31 2020 @author: Varun Mark Mullins cwid:10456027 This file takes in three lengths of a triangle and checks the validity of the triangle and returns the type of triangle and checks if it is a right angle triangle or not. """ def classifyTriangle(a, b, c): """Function checks the type of triangle""" # verify that all 3 inputs are integers # Python's "isinstance(object,type) returns True if the object is of the specified type if not (isinstance(a, int) and isinstance(b, int) and isinstance(c, int)): """Checks if the input is valid""" return 'InvalidInput' # require that the input values be >= 0 and <= 200 if a > 200 or b > 200 or c > 200: """Checks if the input is within 200""" return 'InvalidInput' if a <= 0 or b <= 0 or c <= 0: """Returns an invalid input if the input is negative or zero""" return 'InvalidInput' if (a > (b + c)) or (b > (a + c)) or (c > (a + b)): """Checks if the triangle is a valid triangle or not""" return 'NotATriangle' # now we know that we have a valid triangle if a == b and b == c: """If triangle is Equilateral""" return 'Equilateral' elif ((a ** 2) + (b ** 2)) == (c ** 2) or ((b ** 2) + (c ** 2)) == (a ** 2) or ((a ** 2) + (c ** 2)) == (a ** 2): """If not equilateral but a right angle triangle""" return 'Right' elif (a != b) and (b != c): """If the triangle is scalene""" return 'Scalene' else: """If the triangle is Isosceles""" return 'Isosceles'
true
ac349eb4da08279d11d242bf2bb67556729f4393
zeirn/Exercises
/Week 4 - Workout.py
815
4.21875
4
x = input('How many days do you want to work out for? ') # This is what we're asking the user. x = int(x) # These are our lists. strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings'] cardio = ['Running', 'Swimming', 'Biking', 'Jump rope'] workout = [] for d in range(0, x): # This is so that 'd' (the day) stays within the range of 0 and whatever x is. # 'z' and 'z2' are the exercises in the lists. z = strength[d % len(strength)] # The number of days divided by the length of the number of items in the z2 = cardio[d % len(cardio)] # list strength/cardio. z is the answer to the first equation. z2 is answer to other. workout.append(z + ' and ' + z2) # This adds these two answers to the end of the workout list. print('On day', d+1, (workout[d]))
true
3186c75b82d1877db3efe13a8a432355503ec9f3
TMcMac/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
526
4.28125
4
#!/usr/bin/python3 """This will get a line count on a text file""" def number_of_lines(filename=""): """ A function to get a line count on a file parameters - a file """ line_count = 0 with open(filename, 'r') as f: """ Opens the file as f in such as way that we don't need to worry about f.close() """ for line in f: """ we'll loop through the file one list at a time """ line_count += 1 return line_count
true
5c8df2051d971311883b58f15fbf17a1987655fd
TMcMac/holbertonschool-higher_level_programming
/0x06-python-classes/102-square.py
831
4.46875
4
#!/usr/bin/python3 """Defines class square and takes in a size to intialize square""" class Square(): """Class Square for building a square of #s""" def __init__(self, size=0): """Initializes an instance of square""" self.size = size def area(self): """Squares the size to get the area""" return (self.__size ** 2) @property def size(self): """Just a call to get the size of a side""" return self.__size @size.setter def size(self, value): """Sets the size of the square""" if type(value) != int or float: # If its not an int or a flt raise TypeError("size must be a number") elif value < 0: # If it is a neg number raise ValueError("size must be >= 0") else: self.__size = value
true
6191e450436393fc4ac30c36d1e16665b9cebdb2
wahahab/mit-6.0001
/ps1/ps1c.py
1,204
4.21875
4
# -*- coding: utf-8 -*- import math from util import number_of_month SCALE = 10000 if __name__ == '__main__': months = 0 current_savings = 0 portion_down_payment = .25 r = .04 min_portion_saved = 0 max_portion_saved = 10000 best_portion_saved = 0 semi_annual_raise = .07 total_cost = 1000000 it_count = 0 start_salary = float(input('Enter the starting salary: ')) while months != 36 and max_portion_saved > min_portion_saved + 1: best_portion_saved = (min_portion_saved + max_portion_saved) / 2 months = number_of_month(portion_down_payment, total_cost, current_savings, start_salary, float(best_portion_saved) / SCALE, r, semi_annual_raise) it_count += 1 if months > 36: min_portion_saved = best_portion_saved elif months < 36: max_portion_saved = best_portion_saved if (max_portion_saved == SCALE and min_portion_saved == SCALE - 1): print 'It is not possible to pay the down payment in three years.' else: print 'Best savings rate: ', float(best_portion_saved) / SCALE print 'Steps in bisection search: ', it_count
true
bc9a56767843484f90d5fe466adee8c1289a9052
JohanRivera/Python
/GUI/Textbox.py
1,360
4.125
4
from tkinter import * raiz = Tk() myFrame = Frame(raiz, width=800, height=400) myFrame.pack() textBox = Entry(myFrame) textBox.grid(row=0,column=1) #grid is for controlate all using rows and columns #Further, in .grid(row=0, column=1, sticky='e', padx=50) the comand padx o pady move the object, in this case #50 pixels to este, this direction can changed with the comand sticky #Besides, the color and others features of the text box can changed passBox = Entry(myFrame) passBox.grid(row=1,column=1) passBox.config(show='*')#this line is for changed the characters with a character special """ Text Box to comments""" commentsBox = Text(myFrame,width=10,height=5) #Form to create the comment box commentsBox.grid(row=2,column=1) scrollVertical = Scrollbar(myFrame,command=commentsBox.yview) # Form to make a scroll in the comment box scrollVertical.grid(row=2,column=2,sticky='nsew') # the command nsew is what the scroll it have the same size #that comment box commentsBox.config(yscrollcommand=scrollVertical.set) #For the scroll myLabel = Label(myFrame, text = 'Ingrese el nombre: ') myLabel.grid(row=0,column=0) #grid is for controlate all using rows and columns myPass = Label(myFrame, text = 'Ingrese contraseña: ') myPass.grid(row=1,column=0) myComments = Label(myFrame, text = 'Comentarios: ') myComments.grid(row=2,column=0) raiz.mainloop()
true
5f004bd21d1553a87a446be505865cba2acd19a7
JustinCThomas/Codecademy
/Python/Calendar.py
2,021
4.125
4
"""This is a basic CRUD calendar application made in Python""" from time import sleep, strftime NAME = "George" calendar = {} def welcome(): print("Welcome", NAME) print("Opening calendar...") sleep(1) print(strftime("%A %B %d, %Y")) print(strftime("%H:%M:%S")) sleep(1) print("What would you like to do?") def start_calendar(): welcome() start = True while start: user_choice = input("Enter one of the following: \n A to Add: \n U to Update: \n V to View: \n D to Delete: \n X to exit: \n") user_choice = user_choice.upper() if user_choice == "V": if len(calendar.keys()) == 0: print("The calendar is currently empty.") else: print(calendar) elif user_choice == "U": date = input("What date? ") update = input("Enter the update: ") calendar[date] = update print("Calendar updated!") print(calendar) elif user_choice == "A": event = input("Enter event: ") date = input("Enter date (MM/DD/YYYY): ") if len(date) > 10 or int(date[6:]) < int(strftime("%Y")): print("Please enter the date in the proper (MM/DD/YYYY) format") try_again = input("Try Again? Y for Yes, N for No: ") try_again = try_again.upper() if try_again == "Y": continue else: start = False else: calendar[date] = event print("Event successfully added!") print(calendar) elif user_choice == "D": if len(calendar.keys()) == 0: print("The calendar is currently empty. There is nothing to delete!") else: event = input("What event?") for date in calendar.keys(): if event == calendar[date]: del calendar[date] print("Event deleted!") print(calendar) break else: print("You entered a non-existent event!") elif user_choice == "X": start = False else: print("Invalid command") break start_calendar()
true
765d21e3ef208f0a197c71a5b1543f71fd7aa4dc
penroselearning/pystart_code_samples
/16 Try and Except - Division.py
415
4.125
4
print('Division') print('-'*30) while True: try: dividend = int(input("Enter a Dividend:\n")) divisor = int(input("Enter a Divisor:\n")) except ValueError: print("Sorry! You have not entered a Number") else: try: result = dividend/divisor except ZeroDivisionError: print("Division by Zero has an Undefined Value") else: print(f'The quotient is {result}') break
true
6716efaf012f7ed75775f9dca8dad3593c5a4773
venkatakaturi94/DataStructuresWeek1
/Task4.py
1,271
4.21875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv list_tele_marketers=[] with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) list_from =[] list_to =[] for to in texts: list_from.append(to[0]) list_to.append(to[1]) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) list_from_call =[] list_to_call =[] for to1 in calls: list_from_call.append(to1[0]) list_to_call.append(to1[1]) for x in list_from_call: if ((x not in list_to_call) and (x not in list_from) and (x not in list_to)): list_tele_marketers.append(x) print("These numbers could be telemarketers:") no_duplicates = sorted(set(list_tele_marketers)) for j in no_duplicates: print(j) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """
true
c4c760f5840cd67678114569f3fe0cc890f501ac
codeguru132/pythoning-python
/basics_lists.py
526
4.34375
4
hat_list = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat. # Step 1: write a line of code that prompts the user # to replace the middle number with an integer number entered by the user.li hat_list[2] = int(input("ENter a number here: ...")) # Step 2: write a line of code that removes the last element from the list. del hat_list[-1] # Step 3: write a line of code that prints the length of the existing list. print("\nLength of the list is: ...", len(hat_list)) print(hat_list)
true
32e14721978cac96a0e1c7fe96d1e7088f928658
rciorba/plp-cosmin
/old/p1.py
1,246
4.21875
4
#!/usr/bin/python # Problem 1: # Write a program which will find all such numbers which are divisible by 7 but # are not a multiple of 5, between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence on a # single line. # to nitpick: min and max are builtin functions, and you should avoid using these names for variables def numbers(min, max): # result = [] # for number in xrange(min, max): # you want to go to max+1, xrange(1, 3) gives you [1, 2] for number in xrange(min, max + 1): if number % 7 == 0 and number % 5 is not 0: # result.append(number) yield number # if you use yield you get a generator, and we don't need to build # up the list in memory; think of it as a sort of lazy list # yield is like having a function "return" a value then continue to execute # return result # printed_result = "" # for number in numbers(2000, 3200): # printed_result = "{} {},".format(printed_result, number) # print printed_result[:-1] # just use the join method of the string type, pass it a list of strings and no # more trailing comma to handle print ",".join( [str(num) for num in numbers(2000, 3200)] )
true
a57e1fe462002e2797275191cba5b2ebd0d2cfc5
ak45440/Python
/Replace_String.py
667
4.1875
4
# Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, # if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. # Sample String : 'The lyrics is not that poor!' # 'The lyrics is poor!' # Expected Result : 'The lyrics is good!' # 'The lyrics is poor!' def aparece(frase): Snot = frase.find('not') Spoor = frase.find('poor') if Spoor > Snot and Spoor > 0 and Snot > 0: frase = frase.replace(frase[Snot:Spoor+4], 'good') return frase else: return frase frase = input('Digite uma frase: ') print(aparece(frase))
true
41126620e671d2c5298381eeda1f0a67b8f6a560
Wei-Mao/Assignments-for-Algorithmic-Toolbox
/Divide-and-Conquer/Improving QuickSort/quicksort.py
2,645
4.5
4
# python3 from random import randint from typing import List, Union def swap_in_list(array, a, b): array[a], array[b] = array[b], array[a] def partition3(array: List[Union[float, int]] , left: [int], right: [int]) -> int: """ Partition the subarray array[left,right] into three parts such that: array[left, m1-1] < pivot array[m1, m2] == pivot array[m2+1, right] > pivot The above is also the loop invariant, which should hold prior to the loop and from iteration to iteration to ensure the correctness of the algorithm.(right is replaced by the loop variable i - 1) Args: array(List[Union[float, int]]): Reference to the original array. left(int): Left index of the subarray. right(int): Right index of the subarray. Returns: m1[int], m2[int]: array[m1,..., m2] == pivot and in their final positions. Time Complexity: O(right - left) Space Complexity: O(1) """ pivot_idx = randint(left, right) pivot = array[pivot_idx] # print(pivot) # Move the pivot to the start of the subarray. swap_in_list(array, left, pivot_idx) # loop invariant: # array[left, m1-1] < pivot if m1 > left or empty if m1=left # array[m1, m2] == pivot # array[m2+1, i-1] > pivot if i > m2 + 1 or empty m1, m2 = left, left for i in range(left + 1, right + 1): if array[i] < pivot: swap_in_list(array, i, m1) m1 += 1 m2 += 1 swap_in_list(array, i, m2) elif array[i] == pivot: m2 += 1 swap_in_list(array, i, m2) return m1, m2 def randomized_quick_sort(array, left, right): """ Time Complexity: O(nlogn) on average and O(n^2) in the worst case. Space Complexity: O(logn) in worst case """ while left < right: m1, m2 = partition3(array, left, right) # array[left, m1-1] < pivot # array[m1, m2] == pivot # array[m2+1, right] > pivot if (m1 - left) < (right - m2): randomized_quick_sort(array, left, m1-1) left = m2 + 1 else: randomized_quick_sort(array, m2+1, right) right = m1 - 1 if __name__ == '__main__': input_n = int(input()) elements = list(map(int, input().split())) assert len(elements) == input_n randomized_quick_sort(elements, 0, len(elements) - 1) print(*elements) # input_array = [randint(-10, 10) for _ in range(6)] # input_array.append(input_array[0]) # print(input_array) # m1, m2 = partition3(input_array, 0, 6) # print(input_array) # print(f"m1 {m1} and m2 {m2}")
true
26ab13287b1ea07319831266fe190de1762bb084
pombredanne/Revision-Scoring
/revscores/languages/language.py
591
4.125
4
class Language: """ Constructs a Language instance that wraps two functions, "is_badword" and "is_misspelled" -- which will check if a word is "bad" or does not appear in the dictionary. """ def __init__(self, is_badword, is_misspelled): self.is_badword = is_badword self.is_misspelled = is_misspelled def badwords(self, words): for word in words: if self.is_badword(word): yield word def misspellings(self, words): for word in words: if self.is_misspelled(word): yield word
true
10fed729debcd5ba51cfa9da23c2a6e548f6a0ac
kunalrustagi08/Python-Projects
/Programming Classroom/exercise7.py
920
4.21875
4
''' We return to the StringHelper class, here we add another static method called Concat, this method receives a single parameter called Args, which is a "Pack of parameters", which means that we can pass as many parameters as we want, then, within this function there will be A variable called Curr that will be initialized as an empty string, and using a for iterator, the "Parameters Pack" will be traversed and each parameter will be concatenated to Curr variable, after the for it must return the value of the Curr variable. ''' class StringHelper: @staticmethod def reverse(originalStr: str): return str(originalStr[::-1]) @staticmethod def concat(*args): curr = '' for arg in args: curr += arg return curr print(StringHelper.concat('Hello')) print(StringHelper.concat('Hello', 'Hector')) print(StringHelper.concat('Hello', ' ', 'Hector'))
true
580438f74309cbffd7841166b374f8814c04eea3
kunalrustagi08/Python-Projects
/Programming Classroom/exercise3.py
1,441
4.46875
4
''' Create a class called Calculator. This class will have four static methods: Add() Subtract() Multiply() Divide() Each method will receive two parameters: "num1" and "num2" and will return the result of the corresponding arithmetic operation. Example: The static addition method will return the sum of num1 and num2. Then, you must choose numbers of your preference and perform an operation with them for each method, for example, you can choose 10 and 50 to make the sum. Print the result of each method. ''' class Calculator: @staticmethod def add(num1, num2): sum = num1 + num2 return sum @staticmethod def subtract(num1, num2): dif = num1 - num2 return dif @staticmethod def multiply(num1, num2): prod = num1 * num2 return prod @staticmethod def divide(num1, num2): quo = format((num1 / num2), '.2f') return quo @staticmethod def int_divide(num1, num2): int_quo = num1 // num2 return int_quo @staticmethod def remainder(num1, num2): rem = num1 % num2 return rem print(f'Sum is {Calculator.add(10,50)}') print(f'Difference is {Calculator.subtract(50, 30)}') print(f'Product is {Calculator.multiply(1,0)}') print(f'Division equals {Calculator.divide(10,3)}') print(f'Integer Division equals {Calculator.int_divide(10,3)}') print(f'Remainder equals {Calculator.remainder(10,3)}')
true
130d9e5dd29b1f817b661e9425ffe278ccc44e8d
rebht78/course-python
/exercises/solution_01_04.py
347
4.125
4
# create first_number variable and assign 5 first_number = 5 # create second_number variable and assign 5 second_number = 5 # create result variable to store addition of first_number and second_number result = first_number + second_number # print the output, note that when you add first_number and second_number you should get 10 print(result)
true
39e669b95b5b08afdab3d3b16cb84d673aecbf8e
ctsweeney/adventcode
/day2/main.py
2,106
4.375
4
#!/usr/bin/env python3 def read_password_file(filename: str): """Used to open the password file and pass back the contents Args: filename (str): filepath/filename of password file Returns: list: returns list of passwords to process """ try: with open(filename, "r") as f: # Return list of passwords to perform password logic on contents = f.readlines() return contents except FileNotFoundError: print("File %s not found" % filename) def check_password1(data): """Used to check the password policy one problem Args: data (str): A list object containing all the passwords that we want to check against policy """ TOTAL = 0 for password in data: DATA = password.split() RANGE = DATA[0].split('-') POLICY_LETTER = DATA[1].replace(':', '') POLICY_MIN = int(RANGE[0]) POLICY_MAX = int(RANGE[1]) PASSWORD = DATA[2] LIMIT = 0 for letter in PASSWORD: if letter == POLICY_LETTER: LIMIT += 1 if LIMIT >= POLICY_MIN and LIMIT <= POLICY_MAX: TOTAL += 1 return str(TOTAL) def check_password2(data): """Used to check the password policy two problem Args: data (str): A list object containing all the passwords that we want to check against policy """ TOTAL = 0 for password in data: DATA = password.split() RANGE = DATA[0].split('-') POLICY_LETTER = DATA[1].replace(':', '') POLICY_MIN = (int(RANGE[0]) - 1) POLICY_MAX = (int(RANGE[1]) - 1) PASSWORD = list(DATA[2]) if PASSWORD[POLICY_MIN] == POLICY_LETTER or PASSWORD[POLICY_MAX] == POLICY_LETTER: if PASSWORD[POLICY_MIN] != PASSWORD[POLICY_MAX]: TOTAL += 1 return str(TOTAL) PASSWORD_DATA = read_password_file('passwords.txt') print(check_password1(PASSWORD_DATA) + " passwords that meet password policy one") print(check_password2(PASSWORD_DATA) + " passwords that meet password policy two")
true
017a3268e5de015c8f0c25045f44ae7a4ffe7a50
dky/cb
/legacy/fundamentals/linked-lists/03-08-20/LinkedList.py
1,893
4.1875
4
class Node: def __init__(self, item, next=None): self.item = item self.next = next class LinkedList: def __init__(self): # We always have a dummy node so the list is never empty. self.head = Node("dummy") self.size = 0 def __str__(self): out = "" cur = self.head.next while (cur): out += str(cur.item) + "/" cur = cur.next return out # Description: Insert a node at the front of the LinkedList def insertFront(self, item): # H => 1 => 2 # insert 3 # H => 3 => 1 => 2 # Store H => 1, now head = 1 prevNext = self.head.next # Insert a new node item ex: 3, this would replace 1 with 3. self.head.next = Node(item) # Set the next pointer of the new node to point to 1, which was the # previous head. self.head.next.next = prevNext # increment the size self._size += 1 def insertLast(self, item): # Since we cannot just insert at the end of a singly linked list we # have to iterate to the end to insert an item. # keep track of node we are on cur = self.head # This can also be while (cur.next) while (cur.next is not None): cur = cur.next cur.next = Node(item) self._size += 1 # Description: Remove a node from the beginning. def removeBeginning(self): # No idea what assert is? assert (self.size() > 0) # H => 1 => 2 # removeBeginning # H => 2 # H => 1, Now, set it to point to 2. self.head.next = self.head.next.next self._size -= 1 def size(self): return self._size if __name__ == "__main__": # test cases linkedList = LinkedList for i in range(1, 6): # print(i) linkedList.insertFront(i)
true
9390e6095c6140ba0117bfd18fb63844189d7a68
abhijnashree/Python-Projects
/prac1.py
218
4.28125
4
#Read Input String i = input("Please insert characters: ") #Index through the entire string for index in range(len(i)): #Check if odd if(index % 2 == 0): #print odd characters print(i[index])
true
e0c62280d0a17510b152d5aff2671bc89e0de4d4
DevOpsStuff/Programming-Language
/Python/PythonWorkouts/NumericTypes/run_timings.py
488
4.125
4
#!/usr/bin/env python def run_timing(): """ Asks the user repeatedly for numberic input. Prints the average time and number of runs """ num_of_runs = 0 total_time = 0 while True: one_run = input('Enter 10 Km run time: ') if not one_run: break num_of_runs += 1 total_time += float(one_run) average_time = total_time / num_of_runs print(f'Average of {average_time}, over {num_of_runs} runs') run_timing()
true
1aa76c29644208c7094733bfbb3a876c1ffb9b83
aswathyp/TestPythonProject
/Assignments/Loops/2_EvenElementsEndingWith0.py
362
4.1875
4
# Even elements in the sequence numbers = [12, 3, 20, 50, 8, 40, 27, 0] evenElementCount = 0 print('\nCurrent List:', numbers, sep=' ') print('\nEven elements in the sequence: ') for num in numbers: if num % 2 == 0: print(num, end=' ') evenElementCount = evenElementCount + 1 print('\n\nTotal Count of Even Numbers: ', evenElementCount)
true
e0fe9a4a068ebbdd0956bbfc525f83551b75b2b0
gowtham9394/Python-Projects
/Working with Strings.py
788
4.40625
4
# using the addition operator without variables [String Concatenation] name = "Gowtham" + " " + "Kumar" print(name) # using the addition operator with variables first_name = "Gowtham" last_name = "Kumar" full_name = first_name + " " + last_name print(full_name) # using the new f strings [after python 3.6] print( f"Hello {full_name}") # using indexes to print each element word = "Computer" print( word [0]) print( word [1]) print( word [2]) print( word [3]) print( word [4]) print( word [5]) print( word [6]) print( word [7]) print( word [-0]) print( word [-1]) print( word [-2]) print( word [-3]) print( word [-4]) print( word [-5]) print( word [-6]) print( word [-7]) # using string slicing to print each element print(word [0:1]) print(word [0:8]) print( word[ 0 : 5 : 3 ] )
true
f9bfecf22f03336080907a61c1f21adc95668396
pinnockf/project-euler
/project_euler_problem_1.py
490
4.3125
4
''' Multiples of 3 and 5 Problem 1 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. ''' def main(threshold): multiples = [] for number in range(threshold): if number % 3 is 0 or number % 5 is 0: multiples.append(number) return sum(multiples) if __name__ == '__main__': assert main(10) is 23 print(main(1000))
true
3654c2a1ca8756660b6da99b2d571c6a508a9568
shefali-pai/comp110-21f-workspace
/exercises/ex07/data_utils.py
2,561
4.15625
4
"""Utility functions.""" __author__ = "730466264" from csv import DictReader def read_csv_rows(filename: str) -> list[dict[str, str]]: """Read the rows of a csv into a 'table'.""" result: list[dict[str, str]] = [] file_handle = open(filename, "r", encoding="utf8") csv_reader = DictReader(file_handle) for row in csv_reader: result.append(row) file_handle.close() return result def column_values(table: list[dict[str, str]], column: str) -> list[str]: """Produce a list[str] of all values in a single column.""" result: list[str] = [] for row in table: item: str = row[column] result.append(item) return result def columnar(row_table: list[dict[str, str]]) -> dict[str, list[str]]: """Transform a row-oriented table to a column-oriented table.""" result: dict[str, list[str]] = {} first_row: dict[str, str] = row_table[0] for column in first_row: result[column] = column_values(row_table, column) return result def head(tbl: dict[str, list[str]], rw_nmbr: int) -> dict[str, list[str]]: """Creating a dictionary from the table.""" return_dict: dict[str, list[str]] = {} if rw_nmbr >= len(tbl): return tbl for clmn in tbl: n_list: list[str] = [] i: int = 0 while i < rw_nmbr: n_list.append(tbl[clmn][i]) i += 1 return_dict[clmn] = n_list return return_dict def select(clmn_tbl: dict[str, list[str]], clmn: list[str]) -> dict[str, list[str]]: """Creating a table from columns from an original column table.""" return_dict: dict[str, list[str]] = {} for key in clmn: return_dict[key] = clmn_tbl[key] return return_dict def concat(dict_1: dict[str, list[str]], dict_2: dict[str, list[str]]) -> dict[str, list[str]]: """Producing a table made out of columns from 2 tables from columns.""" return_dict: dict[str, list[str]] = {} for key in dict_1: return_dict[key] = dict_1[key] for key in dict_2: if key in return_dict: return_dict[key] += dict_2[key] else: return_dict[key] = dict_2[key] return return_dict def count(values: list[str]) -> dict[str, int]: """Counting the frequency of values.""" return_dict: dict[str, int] = {} for key in values: if key in return_dict: value_present: int = return_dict[key] return_dict[key] = value_present + 1 else: return_dict[key] = 1 return return_dict
true
57b07d75c2d81356bab342880380353f6debbc25
meginks/data-structure-notes
/Queues/queues.py
2,152
4.15625
4
class ListQueue: def __init__(self): self.items = [] self.size = 0 def enqueue(self, data): """add items to the queue. Note that this is not efficient for large lists.""" self.items.insert(0, data) #note that we could also use .shift() here -- the point is to add the new thing at index 0 to mimic a queue self.size += 1 def dequeue(self): """removes an item from the queue""" data = self.items.pop() self.size -= 1 return data class StackBasedQueue: """this is a stack-based queue""" def __init__(self): self.inbound_stack = [] self.outbound_stack = [] def enqueue(self, data): """adds item to the incoming stack""" self.inbound_stack.append(data) def dequeue(self, data): if not self.outbound_stack: while self.inbound_stack: self.outbound_stack.append(self.inbound_stack.pop()) return self.outbound_stack.pop() class Node: def __init__(self, data=None, next=None, prev=None): self.data = data self.next = None self.prev = None def __str__(self): return str(self.data) class NodeBasedQueue: """a doubly linked list that behaves like a queue""" def __init__(self): self.head = None self.tail = None self.count = 0 def enqueue(self, data): new_node = Node(data, None, None) if self.head is None: self.head = new_node self.tail = self.head else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.count += 1 def dequeue(self): # current = self.head -- book example included this line, but I don't really understand why because it doesn't matter? if self.count == 1: self.count -= 1 self.head = None self.tail = None elif self.count > 1: self.head = self.head.next self.head.prev = None self.count -= 1
true
319d2d9261047ba9218b7b696fb33ad7fc1895a3
neelindresh/try
/VerificationFunctions.py
2,729
4.1875
4
import numpy as np import pandas as pd import operator def check_column(df, ops, first_mul, col_name, oper, value): ''' This function will return the list of valid and invalid rows list after performing the operation first_mul * df[col_name] oper value ex: [ 1*df['age'] >= 25 ]. ''' valid_rows_list = [] invalid_rows_list = [] for i, row in enumerate(df[col_name]): if ops[oper](first_mul*row, value): valid_rows_list.append(i) else: invalid_rows_list.append(i) return valid_rows_list, invalid_rows_list def values_in(df,col_name, inp_list): ''' This function will iterate the df[col_name] and checks if all the values in df[col_name] are in inpu_list. This returns the valid_rows_list which contains indexes of all rows which are in inp_list and invalid_rows_list which contains indexes of all rows which are not in inp_list ''' valid_rows_list = [] invalid_rows_list = [] if 'float' in str(df[col_name].dtype): inp_list = list(map(float, inp_list)) elif 'int' in str(df[col_name].dtype): inp_list = list(map(int, inp_list)) for i, value in enumerate(df[col_name]): if value in inp_list: valid_rows_list.append(i) else: invalid_rows_list.append(i) return valid_rows_list, invalid_rows_list def compare_columns(df,ops,col_name1, col_name2, oper, first_mul=1, sec_mul=1): ''' This function returns the list of indexes of rows which satisfy and doesn't satisfy the condition [first_mul*col_name1 op1 sec_mul*col_name2] ex: [1*mayRevenue >= 1.5*aprilRevenue]. ''' valid_rows_list = [] invalid_rows_list = [] for i in range(len(df[col_name1])): if ops[oper](first_mul*df[col_name1][i], sec_mul*df[col_name2][i]): valid_rows_list.append(i) else: invalid_rows_list.append(i) return valid_rows_list, invalid_rows_list def check_not_null(df, oper, col_name): ''' This function will check for the null in df[col_name] and returns the list of indexes which is not equal to null and the list of list of indexes which is equal to null ''' valid_rows_list = [] invalid_rows_list = [] for i, value in enumerate(df[col_name]): if oper=='!=' and not(pd.isnull(value)): valid_rows_list.append(i) elif oper=='==' and pd.isnull(value): valid_rows_list.append(i) else: invalid_rows_list.append(i) return valid_rows_list, invalid_rows_list
true
d8d791d01895b3a173b4d8003b2e2b648905b3da
AlirezaTeimoori/Unit_1-04
/radius_calculator.py
480
4.125
4
#Created by: Alireza Teimoori #Created on: 25 Sep 2017 #Created for: ICS3UR-1 #Lesson: Unit 1-04 #This program gets a radius and calculates circumference import ui def calculate_circumferenece(sender): #calculate circumference #input radius = int(view['radius_text_field'].text) #process circumference=2*3.14*radius #output view['answer_lable'].text = "Circumference is: " + str(circumference) + "cm" view = ui.load_view() view.present('sheet')
true
e2c0ea3f0638d3d181a0d291eb488839f1596001
Yasin-Yasin/Python-Tutorial
/005 Conditionals & Booleans.py
1,415
4.375
4
# Comparisons # Equal : == # Not Equal : != # Greater Than : > # Less Than : < # Greater or Equal : >= # Less or Equal : <= # Object Identity : is # if block will be executed only if condition is true.. if True: print("Conditinal was true") if False: print("Conditinal was False") # else language = 'Java' if language == 'Python': print("Language is Python") else: print('No Match') # elseif -elif if language == 'Python': print("Language is Python") elif language == 'Java': print("Language is Java") elif language == 'Javascript': print("Language is Javascript") else: print('No Match') # BOOLEAN - and or not user = "Admin" logged_in = True if user == 'Admin' and logged_in: print("Admin Page") else: print("Bad Creds") # not if not logged_in: print("Please Log In") else: print("Welcome") # is a = [1,2,3] b = [1,2,3] print(a == b) b = a # Now a is b will be true. print(id(a)) print(id(b)) print(a is b) # Comparing identity : id(a) == id (b) print(id(a) == id(b)) # False Values : Below Condition will be evaluated as False # False # None - will be Flase # Zero of any numeric type # Any empty sequence, for example, "", (), [] # Any empty mapping, for example, {} condition = 'Test' if condition: print("Evaluated to True") else: print("Evaluated to False")
true
f17feb86a3277de3c924bcecb2cc62dee8801e1b
Yasin-Yasin/Python-Tutorial
/014 Sorting.py
1,686
4.28125
4
# List li = [9,1,8,2,7,3,6,4,5] s_li = sorted(li) print("Sorted List\t", s_li) # This function doesn't change original list, It returns new sorted list print('Original List\t', li) li.sort() # sort method sort original list, doesn't return new list, this method is specific to List obj print('Original List, Now Sorted\t', li) # Reverse Sorting li1 = [9,1,8,2,7,3,6,4,5] s_li1 = sorted(li1, reverse=True) li1.sort(reverse=True) print("Sorted Reverse List\t", s_li1) print("Sorted Reverse Original List\t", li1) # Tuple tup = (9,1,8,2,7,3,6,4,5) s_tup = sorted(tup) print('Sorted Tuple\t', s_tup) # It will return list # Dictionary di = {'name' : 'Corey', 'Job' : 'Programming', 'age' : None, 'OS' : 'Mac'} s_di = sorted(di) # It will return sorted list of keys print("Sorted Dic", s_di) # Key parameter with sorted function li2 = [-6,-5,-4,1,2,3] s_li2 = sorted(li2) print(s_li2) s_li2 = sorted(li2, key=abs) print(s_li2) # Sort Employee Object by name, age , Salary, class Employee(): def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary # str representation of class instance/object def __repr__(self): return f'{(self.name, self.age, self.salary)}' e1 = Employee('Carl', 37, 70000) e2 = Employee('Sarah', 29, 80000) e3 = Employee('John', 43, 90000) employees = [e1, e2, e3] def e_sort(emp): return emp.name s_employees = sorted(employees, key=e_sort) # s_employees = sorted(employees, key=lambda emp:emp.name) # Amother way to do above thing is # from operator import attrgetter # s_employees = sorted(employees, key=attrgetter('salary')) print(s_employees)
true
074ac0d3a6836dbf02831280eb8cd55adb3a508d
ZHANGYUDAN1222/Assignment2
/place.py
1,282
4.3125
4
""" 1404 Assignment class for functions of each place """ # Create your Place class in this file class Place: """Represent a Place object""" def __init__(self, name='', country='', priority=0, v_status=''): """Initialise a place instance""" self.name = name self.country = country self.priority = priority self.v_status = v_status if self.v_status == False: self.v_status = 'n' elif self.v_status == True: self.v_status = 'v' def __str__(self): """Return string representation of place object""" return "{} in {} priority {}, visited = {}".format(self.name, self.country, self.priority, self.v_status) def mark_visited(self): """Return visited for unvisited place""" self.v_status = 'v' return self.v_status def mark_unvisited(self): """Return unvisited for visited place""" self.v_status = 'n' return self.v_status def isimportant(self): """Return T if priority <=2, vise reverse""" if self.priority <= 2: # print('{} is important'.format(self.name)) return True else: # print('{} is not important'.format(self.name)) return False
true
79144ad6f7efd0fcdc7d3fe20e04a881cb1b544a
Diwyang/PhytonExamples
/demo_ref_list_sort3.py
1,206
4.40625
4
# A function that returns the length of the value: #list.sort(reverse=True|False, key=myFunc) #Sort the list descending cars = ['Ford', 'BMW', 'Volvo'] cars.sort(reverse=True) print(cars) #Sort the list by the length of the values: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(key=myFunc) print(cars) #Sort a list of dictionaries based on the "year" value of the dictionaries: # A function that returns the 'year' value: def myFunc1(e): return e['year'] cars = [ {'car': 'Ford', 'year': 2005}, {'car': 'Mitsubishi', 'year': 2000}, {'car': 'BMW', 'year': 2019}, {'car': 'VW', 'year': 2011} ] cars.sort(key=myFunc1) print(cars) #Sort the list by the length of the values and reversed: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(reverse=True, key=myFunc) print(cars) #Sort the list by the length of the values and reversed: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(reverse=True, key=myFunc) print(cars)
true
ba6e01baaa2b69497ede48f24737831c8d35fa68
Diwyang/PhytonExamples
/Example4.py
531
4.21875
4
# My Example 3 """There are three numeric types in Python: int - Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. float - Float, or "floating point number" is a number, positive or negative, containing one or more decimals. complex - Complex numbers are written with a "j" as the imaginary part Variables of numeric types are created when you assign a value to them.""" x = 1 # int y = 2.8 # float z = 1j # complex print(type(x)) print(type(y)) print(type(z))
true
a6158f2bf6ce87e6213cb5de60d4b82d9cd5000c
guoguozy/Python
/answer/ps1/ps1b.py
648
4.21875
4
annual_salary = float(input('Enter your annual salary: ')) portion_saved = float( input('Enter the percent of your salary to save, as a decimal: ')) total_cost = float(input('Enter the cost of your dream home: ')) semi_annual_raise = float(input('Enter the semi­annual raise, as a decimal: ')) current_savings = 0.0 month = 0 while current_savings < (total_cost*0.25): if month != 0 and month % 6 == 0: annual_salary += annual_salary*semi_annual_raise current_savings = (current_savings*0.04)/12 + \ annual_salary/12*portion_saved+current_savings month = month+1 print('Number of months:%s\n'% month)
true
123f44d763fe59334151321a24a1c3a3cf7b284c
Ret-David/Python
/IS 201/Concept Tests/CT05_David_Martinez.py
689
4.21875
4
# David Martinez # Write a pseudo code to design a program that returns the # of occurrences of # unique values but sorted from the list. For example, with the input list # [1, 2, -2, 1, 0, 2, 4, 0], the program should provide the output as follows: # unique value (# of occurrences) # -2(1) # 0(2) # 1(2) # 2(2) # 4(1) #============================== #-------------- my seudo code ---------------- # create an empty output dictionary # for step through input_list, use set for dupes # count through values and identify dupes # append duplicates and count to output_dict # for step through keys of sorted dictionary # print format for screen output
true
879206042b294d5da53faf0c85858394a2e7b28e
Ret-David/Python
/IS 201/Module 1/HOP01.py
1,789
4.34375
4
# HOP01- David Martinez # From Kim Nguyen, 4. Python Decision Making Challenge # Fix the program so that the user input can be recognized as an integer. # Original Code guess = input("Please guess a integer between 1 and 6: ") randomNumber = 5 if (guess == randomNumber): print("Congrats, you got it!") else: print("Oops, goodluck next time!") # Corrected code identifying guess and randomNumber as integers. guess = input("Please guess a integer between 1 and 6: ") randomNumber = 5 if (int(guess) == int(randomNumber)): print("Congrats, you got it!") else: print("Oops, goodluck next time!") # ------------------------------ # From Kim Nguyen, 5. While loop # Fix the program so that the it only allows three guesses. # Original Code attempt = 0 randomNumber = 5 while attempts <= 3: guess = input("Please guess a integer between 1 and 6: ") if (guess == randomNumber): print("Congrats, you got it!") else: print("Oops, goodluck next time!") attempts += 1 # Corrected code that allows for only three guesses. # I found that you could either set the variable attempt to 1 # or you can change the while attempts to <= 2. attempts = 1 randomNumber = 5 while attempts <= 3: guess = input("Please guess a integer between 1 and 6: ") if (guess == randomNumber): print("Congrats, you got it!") else: print("Oops, goodluck next time! Attempt #", attempts) attempts += 1 # or you can change the while attempts to <= 2. attempts = 0 randomNumber = 5 while attempts <= 2: guess = input("Please guess a integer between 1 and 6: ") if (guess == randomNumber): print("Congrats, you got it!") else: print("Oops, goodluck next time! Attempt #", attempts) attempts += 1
true
0d022905006e7bb3113a9726c9780b13eb55b544
Ret-David/Python
/IS 201/Practical Exercises/PE05_David_Martinez_4.py
1,725
4.34375
4
# David Martinez # Make two files, cats.txt and dogs.txt. # Store at least three names of cats in the first file and three names of dogs in # the second file. # Write a program that tries to read these files and print the contents of the file # to the screen. # Wrap your code in a try-except block to catch the FileNotFound error, and print a # friendly message if a file is missing. while True: # while statement to loop through exception handling till a True value is produced try: # run the following code block, test for errors cat_file_open = open("PE05_David_Martinez_4_cats.txt", "r") # variable assigned to file cat_file_open.readline() # read the lines of the file into the variable for cats in cat_file_open: # for each cat name in the file print(cats, end='') # print their name to screen, strip the new line print("\n") # add a new line at the end of the names cat_file_open.close() # close the open file dog_file_open = open("PE05_David_Martinez_4_dogs.txt", "r") # variable assigned to file dog_file_open.readline() # read the lines of the file into the variable for dogs in dog_file_open: # for each dog name in the file print(dogs, end='') # print their name to screen, strip the new line print("\n") # add a new line at the end of the names dog_file_open.close() # close the open file break # exit this while statement except FileNotFoundError: # if an file name is produced, print the following message print("Your code needs a valid file name or path, please.") break # exit this while statement
true
92acf42a33fefc55d10db64cb4a2fd7856bc21de
Ret-David/Python
/IS 201/Concept Tests/CT09_David_Martinez.py
616
4.375
4
# David Martinez # Write a pseudo code to design a program that returns I-th largest value # in a list. For example, with the input list [3, 2, 8, 10, 5, 23] # and I = 4, the program prints the value 5 as it is 4 th largest value. # ========== My Pseudo Code ========== # >> 5 is in index 4 position but is the 3rd largest value # >> largest value is in index 5 position # variable = input list values # variable = I-th largest value # variable = unsorted output for index position I-th # variable = sorted output for nth largest value # print I-th value # print nth value # print largest value in index location
true
5e7b828d0d74462a10fefbbee34d14c3f29f4c0c
ChloeDumit/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
1,674
4.28125
4
#!/usr/bin/python3 """ Write the class Rectangle that inherits from Base""" from .rectangle import Rectangle """ creating new class """ class Square(Rectangle): """ class Square """ def __init__(self, size, x=0, y=0, id=None): "initializes data" self.size = size super().__init__(self.__size, self.__size, x, y, id) @property def size(self): """ getter """ return self.__size @size.setter def size(self, value): """size setter""" if (type(value) is not int): raise TypeError("width must be an integer") if value <= 0: raise ValueError("width must be > 0") self.__size = value def __str__(self): """override str""" return ("[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y, self.__size)) def update(self, *args, **kwargs): """ update arguments """ attributes = ["id", "size", "x", "y"] if args and len(args) != 0: for arg in range(len(args)): if arg == 0: super().update(args[arg]) elif arg < len(attributes): setattr(self, attributes[arg], args[arg]) else: for key, value in kwargs.items(): if key == 'id': super().update(value) else: setattr(self, key, value) def to_dictionary(self): """ returns a dictionary of a class """ dic = {'id': self.id, 'size': self.__size, 'x': self.x, 'y': self.y } return dic
true
b12bbaf3e31c5362fd198c6512d76d858470ac8d
jinayshah86/DSA
/CtCI-6th-Edition/Chapter1/1_6/string_compression_1.py
1,653
4.1875
4
# Q. 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 letter (a-z). # Time complexity: O(N); N is the length of the string. # Space complexity: O(N); N is the length of the string. import unittest def string_compression(string: str) -> str: # Check for empty string if not string: return string # Check for string with alphabets only if not string.isalpha(): raise ValueError compressed_str = [] char_count = 0 for index, character in enumerate(string): char_count += 1 if (index + 1) >= len(string) or character != string[index + 1]: compressed_str.append(character) compressed_str.append(str(char_count)) char_count = 0 # Convert list to string compressed_str = "".join(compressed_str) return compressed_str if len(compressed_str) < len(string) else string class TestStringCompression(unittest.TestCase): def test_compress(self): self.assertEqual(string_compression("aabcccccaaa"), "a2b1c5a3") def test_uncompress(self): self.assertEqual(string_compression("mickey"), "mickey") def test_exception(self): self.assertRaises(ValueError, string_compression, "a2b1c5a3") def test_empty(self): self.assertEqual(string_compression(""), "") if __name__ == "__main__": unittest.main()
true
bfb24a739c79bffb1f60dbb54481ceb9ecd13ceb
BoynChan/Python_Brief_lesson_answer
/Char7-Import&While/char7.1.py
511
4.125
4
car = input("What kind of car do you want to rent?: ") print("Let me see if I can find you a "+car) print("------------------------------") people = input("How many people are there?: ") people = int(people) if people >= 8: print("There is no free table") else: print("Please come with me") print("------------------------------") number = input("Input a number and i will tell you if this number integer times of 10: ") number = int(number) if number%10 == 0: print("Yes") else: print("No")
true
529402a5a5de14174db8206be4d1d24cef30396b
veshhij/prexpro
/cs101/homework/1/1.9.py
422
4.21875
4
#Given a variable, x, that stores #the value of any decimal number, #write Python code that prints out #the nearest whole number to x. #You can assume x is not negative. # x = 3.14159 -> 3 (not 3.0) # x = 27.63 -> 28 (not 28.0) x = 3.14159 #DO NOT USE IMPORT #ENTER CODE BELOW HERE #ANY CODE ABOVE WILL CAUSE #HOMEWORK TO BE GRADED #INCORRECT s = str( x + 0.5 ) dot = s.find( '.' ) print s[:dot]
true
01ccaa78ebe6cc532d8caca853365d8d05f29b22
francomattos/COT5405
/Homework_1/Question_08.py
2,021
4.25
4
''' Cinderella's stepmother has newly bought n bolts and n nuts. The bolts and the nuts are of different sizes, each of them is from size 1 to size n. So, each bolt has exactly one nut just fitting it. These bolts and nuts have the same appearance so that we cannot distinguish a bolt from another bolt, or a nut from another nut, just by looking at them. Fortunately, we can compare a bolt with a nut by screwing them together, to see if the size of the bolt is too large, or just fitting, or too small, for the nut. Cinderella wants to join the ball held by Prince Charming. But now, her wicked stepmother has mixed the bolts, and mixed the nuts, and tells her that she can go to the ball unless she can find the largest bolt and the largest nut in time. An obvious way is to compare each bolt with each nut, but that will take n2 comparisons (which is too long). Can you help Cinderella to find an algorithm requiring only o(n2) comparisons? For instance, O(n) comparisons? ''' def find_largest_match(nuts, bolts): # Starting with first nut and bolt. index_nuts = 0 index_bolts = 0 match = { "nut": 0, "bolt": 0 } # Go through nuts and bolts but stop when you get to last one. while index_nuts < len(nuts) and index_bolts < len(bolts): # If one is smaller than the other. # Set aside the smallest item and pick up another one if nuts[index_nuts] < bolts[index_bolts]: index_nuts += 1 elif bolts[index_bolts] < nuts[index_nuts]: index_bolts += 1 else: # If they are equal, mark as the match, set aside the nut and pick up another match = { "nut": nuts[index_nuts], "bolt": bolts[index_bolts] } index_nuts += 1 return match if __name__ == "__main__": nuts = [0, 1, 2, 3, 4, 5, 6, 15, 7, 12, 8, 16, 9, 10, 14] bolts = [8, 7, 6, 12, 5, 16, 9, 10, 15, 14, 4, 3, 2, 1, 0] print(find_largest_match(nuts, bolts))
true
db0682bd8033187a2ec73514dd2d389fb30ff2d0
wpiresdesa/hello-world
/stable/PowerOf2.py
639
4.5625
5
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ # Add this line today - 29/October/2018 11:08Hs # Add another line (this one) today 29/October/2018 11:10Hs # Add another line (this one) today 29?october/2018 11:18Hs # Python Program to display the powers of 2 using anonymous function # Change this value for a different result terms = 10 # Uncomment to take number of terms from user # terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) # display the result print("The total terms is:", terms) for i in range(terms): print("2 raised to power", i, "is", result[i])
true