blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fd2958044308c991ea843b73987860bb7fc75a3b
Anushree-J-S/Launchpad-Assignments
/problem1.py
412
4.15625
4
#Create a program that asks the user to enter their name and age. #Print out a message addressed to them that tells them the year that they will turn 100 years old print("Code for problem 1") from datetime import datetime name=input("Enter your name:") age=int(input("Enter your age:")) year=int((100-age) +datetime.now().year) print("Hey! ",name) print("You will turn 100 in the year " ,year)
true
2c07ea5764d7173d72c7b85a1d0622a6a7c8e145
vinodh1988/python-code-essentials
/conditional.py
436
4.15625
4
name=input('enter you name >> ') print(len(name)) if(len(name)>=5): print('Valid name it has more than 4 characters') print('We shall store it in the database') elif(len(name)==3 or len(name)==4): print('type confirm to store it into the database >>') if 'confirm'==input(): print('stored in the database') else: print('wrong input') else: print('name should have atleast three characters')
true
e3c217f79478ea89de35f9f7b761d19fbfdde837
x223/cs11-student-work-Karen-Gil
/Countdown2.py
438
4.28125
4
countdown = input('pick a number') number= countdown while number>0: #number has to be grater than zero in order for it to countdown duh!!! print number number= number-1 #In order for there to be a countdown it has to be number-1 print('BOOM!!!') # I origanaly wrote print boom as showen below but it printed boom after every number it counted down so I didnt put any white #space that fixed my code #print ('boom')
true
0da6b491db0b5599895b81f1fd57a72df49b1393
Farheen2302/ds_algo
/algorithms/sorting/quicksort.py
1,223
4.25
4
def quicksort(arr, start, end): if start < end: pivot = _quicksort(arr, start, end) left = quicksort(arr, 0, pivot - 1) right = quicksort(arr, pivot + 1, end) return arr def _quicksort(arr, start, end): pivot = start left = start + 1 right = end done = False while not done: while left <= right and arr[left] < arr[pivot]: left += 1 while right >= left and arr[right] > arr[pivot]: right -= 1 if left >= right: done = True else: """ Making use of python's swapping technique http://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python """ arr[left], arr[right] = arr[right], arr[left] #swap(arr, left, right) arr[pivot], arr[right] = arr[right], arr[pivot] #swap(arr, pivot, right) return right def swap(arr, left, right): temp = arr[left] arr[left] = arr[right] arr[right] = temp # Test Cases arr = [8, 7, 6, 5, 4, 3, 2, 1] arr1 = [54, 26, 93, 17, 77, 31, 44, 55, 20] assert sorted(arr1) == quicksort(arr1, 0, len(arr1) - 1) assert sorted(arr) == quicksort(arr, 0, len(arr)-1)
true
0bb37602e0531c8d9340ce0f9335d817c0730b97
donato/notes
/interviews/2017/practice/linked-list-palindrome.py
1,265
4.15625
4
def find_middle(head): """FInd meddle of linked list using 2 runner strategy and return if it's an odd length list return middle_node, is_odd(Bool) """ r1 = head r2 = head while r2.next: if not r2.next.next: return r1, False r1 = r1.next r2 = r2.next.next return r1, True def reverse_list(head, end): prev = head head = head.next while head != end: next = head.next head.next = prev prev = next head.next = prev def compare_lists(head1, head2): while head1 and head2: if head1.data != head2.data: return False head1 = head1.next head2 = head2.next return True def palindrome(head): middle, is_odd = find_middle(head) list_2 = middle.next reverse_list(head, middle) if is_odd: list_1 = middle.next else: list_1 = middle result = compare_lists(list_1, list_2) reverse_list(middle, head) return result class LinkedListNode: data = None next = None def __init__(self, d): self.data = d l1 = LinkedListNode('p') l2 = LinkedListNode('o') l2 = LinkedListNode('o') l3 = LinkedListNode('p') l1.next = l2 l2.next = l3 print(palindrome(l1))
true
4701dc2609fcbc88935c0a52dca736fd40fa5099
Ricardo-Sillas/Project-1
/Main.py
964
4.21875
4
import hashlib def hash_with_sha256(str): hash_object = hashlib.sha256(str.encode('utf-8')) hex_dig = hash_object.hexdigest() return hex_dig # starts numbers off with length 3, increments the number by one, then increments length by one at the end of that length def getNum(s, n): if len(s) == n: check(s) return for i in range(10): getNum(s + str(i), n) # Gets number from getNum, adds the salt value to the end, hashes it, and then checks if the two hashed passwords are the same def check(s): text = open("password_file.txt", "r") read = text.readlines() for line in read: parts = line.split(",") user = parts[0] salt = parts[1] old = parts[2].replace('\n','') new = hash_with_sha256(s + salt) if(old == new): print("The password for", user, "is", s) return text.close() def main(): hex_dig = hash_with_sha256('This is how you hash a string with sha256') print(hex_dig) for n in range(3,8): getNum("",n) main()
true
09f75de95ac1f64a6ffd3b73e803b32ed8a209a8
rakeshsukla53/interview-preparation
/Rakesh/python-basics/call_by_reference_in_python.py
1,081
4.28125
4
def foo(x): x = 'another value' # here x is another name bind which points to string variable 'another value' print x bar = 'some value' foo(bar) print bar # bar is named variable and is pointing to a string object # string objects are immutable, the value cannot be modified # you can not pass a simple primitive by reference in Python bar += 'rakesh' # here you are creating another object of string type print bar # you can pass reference only in immutable types in Python like list, dictionary # call by value and call by reference are definitely a thing but we need to take care of which type of object are we talking about here # we can pass by reference the following objects # Mutable: everything else, # # mutable sequences: list, byte array # set type: sets # mapping type: dict # classes, class instances # etc. # we cannot pass by reference the following objects, because here a complete new object will be created # Immutable: # # numbers: int, float, complex # immutable sequences: str, tuples, bytes, frozensets
true
de4fc062a33d209172ed71d02074dda15ebbe5d4
rakeshsukla53/interview-preparation
/Rakesh/trees/Symmetric_Tree_optimized.py
888
4.28125
4
# for this method I am going to use the reverse binary tree method to check for symmetric tree # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def __init__(self): self.count = True def sym(self, L, R): if L is None and R is None: return True if L and R and L.val == R.val: self.sym(L.left, R.right) self.sym(L.right, R.left) else: self.count = False def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root or (root.left is None and root.right is None): return True self.sym(root.left, root.right) return self.count # optimized solution of symmetric tree
true
dc53ce7c76f9b149441aeda751214149d8933c17
rakeshsukla53/interview-preparation
/Rakesh/python-iterators/remove_while_iteration.py
636
4.125
4
__author__ = 'rakesh' somelist = range(10) for x in somelist: somelist.remove(x) #so here you are modifying the main list which you should not be doing print somelist somelist = range(10) for x in somelist[:]: #Because the second one iterates over a copy of the list. So when you modify the original list, you do not modify the copy that you iterate over somelist.remove(x) print somelist #list(somelist) will convert an iterable into a list. somelist[:] makes a copy of an object that supports slicing. So they don't necessarily do the same thing. In this case I want to make a copy of the somelistobject, so I use [:]
true
d9d3972659395307fb5353071b3615a0ad82c1bc
rakeshsukla53/interview-preparation
/Rakesh/Google-interview/breeding_like_rabbits_optimized_method.py
2,970
4.5
4
__author__ = 'rakesh' #here we have to know about memoization #Idea 1 - To sabe the result in some variables ---but it is not feasible. Fibonacci can be done since only two variables #are required. Also in the memoization part there is only recursion process not all. #Idea 2 - Use some kind of hash table here, but it will occupy lots of memory. Chances of memory error #Idea 3 - For this type of problem if you have do memoization through recursion #Idea 4 - if there is no base condition then there is no way a recursion can happen and the base condition should keep on decreasing #Idea 5 - ''' Yes. The primitive recursive solution takes a lot of time. The reason for this is that for each number calculated, it needs to calculate all the previous numbers more than once. Take a look at the following image. Tree representing fibonacci calculation It represents calculating Fibonacci(5) with your function. As you can see, it computes the value of Fibonacci(2) three times, and the value of Fibonacci(1) five times. That just gets worse and worse the higher the number you want to compute. What makes it even worse is that with each fibonacci number you calculate in your list, you don't use the previous numbers you have knowledge of to speed up the computation – you compute each number "from scratch." There are a few options to make this faster: 1. Create a list "from the bottom up" The easiest way is to just create a list of fibonacci numbers up to the number you want. If you do that, you build "from the bottom up" or so to speak, and you can reuse previous numbers to create the next one. If you have a list of the fibonacci numbers [0, 1, 1, 2, 3], you can use the last two numbers in that list to create the next number. This approach would look something like this: >>> def fib_to(n): ... fibs = [0, 1] ... for i in range(2, n+1): ... fibs.append(fibs[-1] + fibs[-2]) ... return fibs ... Then you can get the first 20 fibonacci numbers by doing >>> fib_to(20) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] Or you can get the 17th fibonacci number from a list of the first 40 by doing >>> fib_to(40)[17] 1597 2. Memoization (relatively advanced technique) Another alternative to make it faster exists, but it is a little more complicated as well. Since your problem is that you re-compute values you have already computed, you can instead choose to save the values you have already computed in a dict, and try to get them from that before you recompute them. This is called memoization. It may look something like this: >>> def fib(n, computed = {0: 0, 1: 1}): ... if n not in computed: ... computed[n] = fib(n-1, computed) + fib(n-2, computed) ... return computed[n] This allows you to compute big fibonacci numbers in a breeze: >>> fib(400) 176023680645013966468226945392411250770384383304492191886725992896575345044216019675 '''
true
1b1e945ef82db250c50dd635c5da0a86a8ec32fc
rakeshsukla53/interview-preparation
/Rakesh/Common-interview-problems/product of array except self.py
912
4.15625
4
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] Logic : You will use two loops one going from left to right, and other from right to left for example if a = [1, 2, 3, 4] Going from left -> a = [1, 1, 2, 6] Going from right -> a = [24,12,8,6] here you will refer back to [1,2,3,4] The problem is the list will grow with the input array """ size, temp = len(nums), 1 output = [1] * size # left loop array for i in range(1, size): temp *= nums[i - 1] output[i] = temp temp = 1 for j in range(size - 2, -1, -1): temp *= nums[j + 1] output[j] *= temp return output # this slicing and merging of the arrays are O(n) operation Solution().productExceptSelf([1, 2, 3, 4])
true
23ca1215a474d6a40ac0c93df2446b5475adce9a
rakeshsukla53/interview-preparation
/Rakesh/Common-interview-problems/Ordered_Dict.py
1,795
4.21875
4
__author__ = 'rakesh' #What is orderedDict #An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. from collections import OrderedDict LRUCache = OrderedDict() count = 1 for i in [2, 4, 5, 6, 7, 9, 10]: LRUCache[i] = count count += 1 print LRUCache LRUCache.popitem(last=False) print LRUCache # print LRUCache # # # del LRUCache[2] #if you delete the old entry then you ened # # LRUCache[2] = "" # # print LRUCache # # #The best thing about orderedDict is that it remembers the order in which the keys are inserted. If the new entry overwrites and existing entry, the original insertion position will remain unchanged. Deleting an entry and reinseeting it will move to the end. This is really good for LRU Cache will deletes the entry # # #dictionary sorted by key # # LRUCache = sorted(LRUCache.items(), key= lambda t: t[1]) # print LRUCache #It is really amazing that you can sort your LRUCache # # #there are lots of operation that you can perform # # >>> # regular unsorted dictionary # # >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # # # # >>> # dictionary sorted by key # # >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) # # OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) # # # # >>> # dictionary sorted by value # # >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) # # OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) # # # # >>> # dictionary sorted by length of the key string # # >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) # # OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
true
dcb5dc0d8b77109893f6c8f0446daf75e4cf57f8
rakeshsukla53/interview-preparation
/Rakesh/Natural Language Processing/word_tokenize.py
750
4.1875
4
__author__ = 'rakesh' #http://pythonprogramming.net/tokenizing-words-sentences-nltk-tutorial/ from nltk.tokenize import sent_tokenize, word_tokenize EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard." print(sent_tokenize(EXAMPLE_TEXT)) print(word_tokenize(EXAMPLE_TEXT)) ''' Now, looking at these tokenized words, we have to begin thinking about what our next step might be. We start to ponder about how might we derive meaning by looking at these words. We can clearly think of ways to put value to many words, but we also see a few words that are basically worthless. These are a form of "stop words," which we can also handle for. '''
true
6d3aba17b75e3eff3b706bc6ec4bdf1b583dc0a8
katiemharding/ProgrammingForBiologyCourse2019
/problemsets/PythonProblemSets/positiveOrNegative.py
996
4.59375
5
#!/usr/bin/env python3 import sys # for testing assign a number to a value unknown_number = int(sys.argv[1]) # first test if it is positive if unknown_number>0: print(unknown_number, "is positive") if unknown_number > 50: # modulo (%) returns the remainder. allows testing if divisible by if unknown_number%3 == 0: print(unknown_number, "is larger than 50 and divisible by 3") else: print(unknown_number, "is bigger than 50") elif unknown_number == 50: print(unknown_number, "is even and equal to 50") else: print(unknown_number, "is less than 50") # modulo tests if a number is even. # it returns the remainder (the numbers remaining after division) # if it is zero then there is no remainder if unknown_number%2 == 0: print(unknown_number, "is even") else: print(unknown_number, "is odd") # What to do if not positive: # test if equals 0 elif unknown_number == 0: print("equals 0") # if not positive test if negative? else: print(unknown_number, "is negative")
true
c97df9692c0d772e8cef6a60bdb23a59ba803ccd
sxd7/p_ython
/python.py
413
4.21875
4
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import math >>> radius=float(input("enter the radius of the circle:")) enter the radius of the circle:5 >>> area=math.pi*radius*radius; >>> print("area of the circle is:{0}".format(area)); area of the circle is:78.53981633974483 >>>
true
222f287965120511ecb52663994e286d2752d363
PradeepNingaiah/python-assginments
/hemanth kumar python assginment/14.exception.py
1,734
4.5625
5
#1. Write a program to generate Arithmetic Exception without exception handling try: a = 10/0 print (a) except ArithmeticError: print ("This statement is raising an arithmetic exception.") else: print ("Success.") #----------------------------------------------------------------------------- #6.Write a program to create your own exception class notaccepted(Exception): def __init__(self, hai): self.hai=hai try: raise notaccepted("i'm busy right now") except notaccepted as err: # perform any action on YourException instance print("Message:", err.hai) #----------------------------------------------------------------------------- #7. Write a program with finally block #Implementing try,except and finally try: x=int(input("Enter First No:")) y=int(input("Enter Second No:")) z=x/y print(z) except(ZeroDivisionError): print("2nd No cannot be zero") finally: # here prints msg of finally block before terminating abnormally print("welcome to hyd...........") print("end") #Try the execution for all the 3 cases ,in all 3 cases finally will be executed #----------------------------------------------------------------------------- #9. Write a program to generate FileNotFoundException #FileNotFoundError: try: f=open("C:/data/demo5.txt","r") #r--->read mode print(f.read()) f.close() except(FileNotFoundError): print("File doesnt exist") except: print("Error") else: print("File opened Successully") print("end") #------------------------------------------------------------------------------
true
9bcaa72b193d3b5ce12db67faffd751c3f1cc7c5
girisagar46/KodoMathOps
/kodomath/mathops/quiz_service.py
1,377
4.15625
4
from decimal import Decimal from asteval import Interpreter class SubmissionEvaluator: """A helper class to evaluate if submission if correct or not. """ def __init__(self, expression, submitted_result): self.expression = expression self.submitted_result = submitted_result # https://stackoverflow.com/a/18769210/4494547 @staticmethod def remove_exponent(num): """To remove trailing zeros form a floating point number Args: num: Decimal object Returns: Decimal object with 2 decimal places if there is no trailing zero Example: >>> SubmissionEvaluator.remove_exponent(Decimal(1.01)) 1.010000000000000008881784197 >>> SubmissionEvaluator.remove_exponent(Decimal(1.0)) 1 """ return num.quantize(Decimal(1)) if num == num.to_integral() else num.normalize() def evaluate(self): """A helper method to check if submitted answer for the provided question is correct or not. This helper function uses asteval to perform check """ expression_interpreter = Interpreter() correct = SubmissionEvaluator.remove_exponent( Decimal("{:.3f}".format(expression_interpreter(self.expression))[:-1]) ) return str(correct) == self.submitted_result
true
493cc5ee3132d01c05cca6495738e3e4f6ab1436
rbodduluru/PythonCodes
/Duplicatenumsinlist.py
448
4.25
4
# #!/usr/bin/python # Python program to find the duplicate numbers in the list of numbers def finddup(myList): for i in set(myList): if myList.count(i) > 1: print "Duplicate number(s) in the list : %i"%i if __name__ == '__main__': myList = [] maxNumbers = 10 while len(myList) < maxNumbers: numbers = input("Enter numbers to find duplicates :") myList.append(numbers) finddup(myList)
true
20c489dd909c4846446ecf15b8169f6a5fe9da13
dwambia/100daysofhacking
/Tiplator.py
565
4.28125
4
#Simple python code to calculate amount a user is to tip total_bill = input("What is your total bill? ") #ignore the $ sign if user inputs total_bill= total_bill.replace("$","") #convert users bill to float total_bill=float(total_bill) print(total_bill) #list of possible tips calculation tip_1= 0.15*total_bill tip_2= 0.18*total_bill tip_3= 0.20*total_bill #list out all tips print("Here's a recommendation of amounts that you can tip") #converts results of calculation to 2 d.p print(f"1. ${tip_1:.2f}") print(f"2. ${tip_2:.2f}") print(f"3. ${tip_3:.2f}")
true
b7a4c138b9106c64d6db33f53e6cd0b5b35e5648
olotintemitope/Algo-Practice
/quick_sort.py
1,732
4.125
4
def quick_sort(lists): lists_length = len(lists) if lists_length > 2: current_position = 0 """ Partition the lists """ for index in range(1, lists_length): pivot = lists[0] if lists[index] <= pivot: current_position += 1 swap = lists[index] lists[index] = lists[current_position] lists[current_position] = swap """ End of partitioning """ swap = lists[0] lists[0] = lists[current_position] lists[current_position] = swap left_sorted = quick_sort(lists[0:current_position]) right_sorted = quick_sort(lists[current_position + 1:lists_length]) lists = left_sorted + [lists[current_position]] + right_sorted return lists print(quick_sort([1, 4, 21, 3, 9, 20, 25, 6, 21, 14])) def QuickSort(arr): elements = len(arr) # Base case if elements < 2: return arr current_position = 0 # Position of the partitioning element for i in range(1, elements): # Partitioning loop if arr[i] <= arr[0]: current_position += 1 temp = arr[i] arr[i] = arr[current_position] arr[current_position] = temp temp = arr[0] arr[0] = arr[current_position] arr[current_position] = temp # Brings pivot to it's appropriate position left = QuickSort(arr[0:current_position]) # Sorts the elements to the left of pivot right = QuickSort(arr[current_position + 1:elements]) # sorts the elements to the right of pivot arr = left + [arr[current_position]] + right # Merging everything together return arr print(QuickSort([21, 4, 1, 3, 9, 20, 25, 6, 21, 14]))
true
3f749cb2850ed64d6f566e23b75c1df30023bab7
Divyalok123/CN_Data_Structures_And_Algorithms
/more_problems/Test2_P2_Problems/Minimum_Length_Word.py
298
4.28125
4
#Given a string S (that can contain multiple words), you need to find the word which has minimum length. string = input() newArr = string.split(" ") result = newArr[0] for i in range(1, len(newArr)): if(len(newArr[i]) < len(result)): result = newArr[i] print(result)
true
f312341382425fcd01f4a489b0fc7e615ac3ba22
diek/backtobasics
/trade_apple_stocks.py
1,541
4.1875
4
'''Suppose we could access yesterday's stock prices as a list, where: The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time. So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.''' stock_prices_yesterday = [10, 7, 5, 8, 11, 9] # No "shorting"—you must buy before you sell. You may not buy and sell in the # same time step (at least 1 minute must pass). def get_best_profit(stock_prices_yesterday): # we'll greedily update min_price and best_profit, so we initialize # them to the first price and the first possible profit min_price = stock_prices_yesterday[0] best_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0] for index, stock in enumerate(stock_prices_yesterday): # skip the first (0th) time if index == 0: continue # see what our profit would be if we bought at the # min price and sold at the current price potential_profit = stock - min_price # update best_profit if we can do better best_profit = max(best_profit, potential_profit) # update min_price so it's always # the lowest price we've seen so far min_price = min(min_price, stock) return best_profit print(get_best_profit(stock_prices_yesterday))
true
a0e534755de438b61477b6e823fca6069a07aeb4
beggerss/algorithms
/Sort/quick.py
1,410
4.1875
4
#!/usr/bin/python2 # Author: Ben Eggers (ben@beneggers.com) import time import numpy as np import matplotlib.pyplot as plt import itertools # Implementation of a quicksort in Python. def main(): base = 10000 x_points = [] y_points = [] for x in range(1, 20): arr = [np.random.randint(0, base*x) for k in range(base*x)] start = int(round(time.time() * 1000)) arr = quick_sort(arr) end = int(round(time.time() * 1000)) x_points.append(len(arr)) y_points.append(end - start) print("%d ms required to sort array of length %d using quicksort." % (end - start, len(arr))) make_plot(x_points, y_points) def quick_sort(arr): if len(arr) <= 1: return arr # There are many ways to choose a pivot, we'll just grab a random element pivot_index = np.random.randint(0, len(arr) - 1) pivot = arr[pivot_index] del arr[pivot_index] less = [] greater = [] for x in arr: if x <= pivot: less.append(x) else: greater.append(x) lists = [quick_sort(less), [pivot], quick_sort(greater)] # pivot must be in its own sublist for the below list comprehension to work return [item for sublist in lists for item in sublist] def make_plot(x_points, y_points): plt.plot(x_points, y_points, 'ro') plt.axis([0, max(x_points), 0, max(y_points)]) plt.xlabel('length of array') plt.ylabel('time to sort (milliseconds)') plt.title('Efficiency of quick sort') plt.show() if __name__ == "__main__": main()
true
3c50a395000e9474c8be1cd4233e55137df20293
jscs9/assignments
/moves.py
1,681
4.1875
4
import random as rand def request_moves(how_many): ''' Generates a string representing moves for a monster in a video game. how_many: number of move segments to be generated. Each segment occurs in a specific direction with a distance of between 1 and 5 steps. Segment directions do not repeat, or immediately double back on themselves, e.g. 'u' cannot follow 'd', 'l' cannot follow 'r', etc. Returns: A string of characters made of 'l', 'r', 'u', 'd' that describes how the monster moves. ''' dirmap = ['l', 'r', 'u', 'd'] # a list of abbreviations for directions # generate an initial direction and distance between 1 and 5 steps dir = dirmap[rand.randint(0, 3)] moves = dir*rand.randint(1, 5) # For each move, randomly determine its direction, and how far (between 1 and 5 steps) for i in range(how_many-1): # get a random number between 0 and 3 # generate directions randomly until we get a direction that # is not the same as the previous direction. dir = moves[-1] while (dir == moves[-1] or (dir == 'r' and moves[-1] == 'l') or (dir == 'u' and moves[-1] == 'd') or (dir == 'l' and moves[-1] == 'r') or (dir == 'd' and moves[-1] == 'u')): dir = dirmap[rand.randint(0, 3)] # map the number to a legal move character using 'dirmap', # make between 1 and 5 copies of that move character, # and concatenate it with the existing moves generated so far. moves = moves + dir * rand.randint(1, 5) return moves
true
1e9d15bcc381cea35ba1496e94a25c4ed981878f
krzysztof-laba/Python_Projects_Home
/CodeCademy/SchoppingCart.py
970
4.15625
4
class ShoppingCart(object): """Creates shopping cart objects for users of our fine website""" items_in_cart = {} def __init__(self, customer_name): self.customer_name = customer_name print("Customer name:", self.customer_name) def add_item(self, product, price): """Add product to the cart""" if not product in self.items_in_cart: self.items_in_cart[product] = price print(product, " added.") else: print(product, " is arleady in the cart.") def remove_item(self, product): """Remove product from the cart.""" if product in self.items_in_cart: del self.items_in_cart[product] print(product, " removed") else: print(product, " is not in the cart.") my_cart = ShoppingCart("Krzysztof Laba") my_cart.customer_name my_cart.add_item("Mleko", 3) my_cart.add_item("Bułka", 0.5) my_cart.add_item("Ciastko", 2.2) my_cart.add_item("Jabłko", 1.5) print(ShoppingCart.items_in_cart) my_cart.remove_item("Bułka") print(ShoppingCart.items_in_cart)
true
05aa5bd36eba8a10f25800c4d61829f1e5710a67
RadioFreeZ/Python_October_2018
/python_fundamentals/function_basic2.py
1,655
4.34375
4
#Countdown - Create a function that accepts a number as an input. Return a new array that counts down by one, from the number # (as arrays 'zero'th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0]. def countdown(num): return [x for x in range(num, -1,-1)] print(countdown(5)) #Print and Return - Your function will receive an array with two numbers. Print the first value, and return the second. def printAndReturn(arr): print("First Value -", arr[0]) return(arr[1]) print(printAndReturn([5,6])) def firstPlusLength(arr): return arr[0] + len(arr) print(firstPlusLength([1,2,3,4])) #Values Greater than Second - Write a function that accepts any array, # and returns a new array with the array values that are greater than its 2nd value. # Print how many values this is. If the array is only one element long, have the function return False def greaterThanSecond(arr): if (len(arr) == 1): return False array = [] for val in arr: if(val > arr[1]): array.append(val) print(len(array)) return array print(greaterThanSecond([1,4,6,7,8,1,2])) # This Length, That Value - Write a function called lengthAndValue which accepts two parameters, size and value. # This function should take two numbers and return a list of length size containing only the number in value. # For example, lengthAndValue(4,7) should return [7,7,7,7]. def LengthAndValue(size, value): # new_arr = [] # for count in range(size): # new_arr.append(value) # return new_arr return [value for i in range(size)] print(LengthAndValue(7,5))
true
9257ae7106cf111e01eae338b262a65947204458
DishaCoder/Solved-coding-challenges-
/lngest_pall_str.py
221
4.125
4
inputString = input("Enter string : ") reverse = "".join(reversed(inputString)) size = len(inputString) if (inputString == reverse): print("Longest pallindromic string is ", inputString) else: for
true
eb31fc6b5c6b5957bf62c9a7c48864dee92aeba5
lyvd/learnpython
/doublelinkedlist.py
1,521
4.5
4
#!/usr/bin/python ''' Doubly Linked List is a variation of Linked list in which navigation is possible in both ways either forward and backward easily as compared to Single Linked List. ''' # A node class class Node(object): # Constructor def __init__(self, data, prev, nextnode): # object data self.data = data # previous node self.prev = prev # next node self.next = nextnode # Dobule list of nodes class DoubleList(object): def __init__(self): self.head = None self.tail = None # append a node to the list def append(self, data): tail = Node(data, None, None) # create a new node new_node = Node(data, None, None) # if node is the last node if self.head is None: # head = tail = new node self.head = self.tail = new_node else: # point prev link of new node to tail new_node.prev = self.tail # create a new node new_node = None # point next link of tail to new node self.tail.next = new_node # tail is the new node self.tail = new_node # Show nodes def show(self): print("Showing list data:") # external variable point to head current_node = self.head # loop until the end of the list while current_node is not None: print(current_node.data) if hasattr(current_node.prev, "data") else None, print(current_node.data), print(current_node.next.data) if hasattr(current_node.next, "data") else None current_node = current_node.next d = DoubleList() d.append(5) d.append(6) d.append(50) d.append(30) d.show()
true
df9f7a91df1bbb03d9f9661ece0c905936aba7b8
lyvd/learnpython
/node.py
552
4.1875
4
#!/usr/bin/python # Create a class which presents a node class BinaryTree: def __init__(self, rootObj): # root node self.key = rootObj # left node self.leftChild = None self.rightChild = None # Insert a left node to a tree def insertLeft(self, newNode): # if there is no left node if self.leftChild == None: self.leftChild == BinaryTree(newNode) # if there is an existing left node # adding the existing node to the node we are adding else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t
true
030139068d2f3eafd4e60f3e3bfabf374a174e30
akjalbani/Test_Python
/Misc/Tuple/xycoordinates.py
499
4.15625
4
""" what are the Mouse Coordinates? """ ## practical example to show tuples ## x,y cordinates stored as tuple, once created can not be changed. ## use python IDLE to test this code. ## 08/06/2020 import tkinter def mouse_click(event): # retrieve XY coords as a tuple coords = root.winfo_pointerxy() print('coords: {}'.format(coords)) print('X: {}'.format(coords[0])) print('Y: {}'.format(coords[1])) root = tkinter.Tk() root.bind('<Button>', mouse_click) root.mainloop()
true
e6d26f45c62d5a0b943c6c43e712fe04dc9307d1
akjalbani/Test_Python
/Misc/Network/dictionary_examples.py
2,039
4.5
4
# let us have list like this devices = ['router1', 'juniper', '12.2'] print(devices) ############### Another way to print values ######################### for device in devices: print(device) #If we build on this example and convert the list device to a dictionary, it would look like this: devices = {'hostname': 'router1', 'vendor': 'juniper', 'os': '12.1'} print(devices) ###########Print only keys################################################# for device in devices: print(device) # this will print keys ###############Print only values ############################################# for v in devices.values(): print(v) ##############print key and value############################################## for device in devices: print(device,devices[device]) # print key and value ##### OR####print key and value############################################### for k,v in devices.items(): print(k,v) ############################################ ############################## ### access any desired value pass the key print("host name: "+ devices['hostname']) print("host name: "+ devices['vendor']) print("host name: "+ devices['os']) ######################################################################### ## how to get keys print(devices.keys()) # how to get values print(devices.values()) ################################################################## ## How to add new value - key and value- this will add as a last item in the dictionary devices['location'] = "room2.31" print(devices) ################################################################ ## create new empty dictionary and add items to it student = {} student["id"] = 100232 student["name"] = "Michael" student["class"] = "python" student["year"] = 2020 print(student) ################################################################ # dictionary built in functions print(dir(dict)) ############################################################### # how to delete item # pop() key to delete particualr key and value student.pop('id') print(student)
true
29900772d1df82995e52988be2eba8303b1457fd
akjalbani/Test_Python
/Misc/Turtle_examples/shape2.py
288
4.15625
4
# Turtle graphics- turtle will draw angle from 0-360 (15 deg) # tested in repl.it # Type- collection and modified import turtle turtle = turtle.Turtle() for angle in range(0, 360, 15): turtle.setheading(angle) turtle.forward(100) turtle.write(angle) turtle.backward(100)
true
255724b8bd84e1a0dbd793d35eec9d935fb480f5
susankorgen/cygnet-software
/Python100DaysClass2021/py/CoffeeMachineOOP/coffee_maker.py
2,064
4.15625
4
# Instructor code. # Except: Student refactored the self.resources structure and added get_resources. class CoffeeMaker: """Models the machine that makes the coffee""" def __init__(self): self.resources = { "water": { "amount": 500, "units": "ml", }, "milk": { "amount": 200, "units": "ml", }, "coffee": { "amount": 100, "units": "g", }, } def report(self): """Prints a report of all resources.""" for item in self.resources: drink = self.resources[item] print(f"{item.title()}: {drink['amount']}{drink['units']}") def is_resource_sufficient(self, drink): """Returns True when order can be made, False if ingredients are insufficient.""" can_make = True for item in drink.ingredients: if drink.ingredients[item] > self.resources[item]['amount']: print(f"Sorry, there is not enough {item} to make {drink.name}.") can_make = False return can_make def make_coffee(self, order): """Deducts the required ingredients from the resources.""" for item in order.ingredients: self.resources[item]['amount'] -= order.ingredients[item] print(f"Here is your {order.name} ☕. Enjoy!") # Student added. def get_resources(self): """ Prompt for and process an amount of refill of each resource. Silently convert bad input to zero. :rtype: None """ print("Before refill:") self.report() for item in self.resources: units = self.resources[item]['units'] added = input(f"Add {item} ({units}): ").strip() try: adding = int(added) except ValueError: adding = 0 self.resources[item]['amount'] += adding print("After refill:") self.report()
true
84541b7ceb0b56ad10f0fede67d7c32823d09814
ianmanalo1026/Projects
/Biginners/Guess the number (Project1).py
2,015
4.15625
4
import random class Game: """Player will guess the random Number""" def __init__(self): self.name = None self.number = None self.random_number = None self.indicator = None def generateNumber(self): self.random_number = random.randint(1,5) return self.random_number def enterNumber(self): self.number = input("Enter Number:") while type(self.number) is not int: try: self.number = int(self.number) except ValueError: self.number = input("Enter a valid Number:") return self.number def start(self): self.indicator = list() self.name = input("Your Name: ") self.random_number = self.generateNumber() print(f"Hi {self.name}") print("Start the game! You have 3 attempts to guess the number!") print("Guess the Number from 1 - 5") self.enterNumber() while len(self.indicator) <= 1: if self.number < self.random_number: self.indicator.append(self.number) print("higher") self.enterNumber() if self.number > self.random_number: self.indicator.append(self.number) print("lower") self.enterNumber() elif int(self.number) == int(self.random_number): print("You got it!") print(f"The random number is {self.random_number}") x = input("Would you like to play again? (yes or no): ") if x == "yes": self.start() else: print(f"Thanks for playing {self.name}") break print(f"The random number is {self.random_number}") x = input("Would you like to play again? (yes or no): ") if x == "yes": self.start() else: print(f"Thanks for playing {self.name}") x = Game() x.start()
true
488421439b7188696f4e4d7f33dcc682e1bb3ef9
120Davies/Intro-Python-I
/src/13_file_io.py
1,074
4.375
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" with open('foo.txt') as f: # Using with is more brief than opening and closing separately. read_data = f.read() print(read_data) print(f.closed) # To show the file closed after printing # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain with open('bar.txt', 'w') as f: f.write("This is the first line of bar.txt.\n") f.write("Their wives and children will mourn as Jeremiah.\n") f.write("This is the last line of bar.txt.") with open('bar.txt') as f: print(f.read())
true
845883db9a28eb311b552650748ce4037f0ccb21
RocioPuente/KalAcademyPython
/HW3/Palindrome.py
353
4.1875
4
def reverse(number): rev=0 while number > 0: rev = (10*rev)+number%10 number//=10 return rev #print(reverse (number)) def isPalindrome(number): if number == reverse(number): return ("The number is a Palindrome") else: return ("The number is not a Palindrome") #print (isPalindrome(number))
true
427d378903744e1d5e6b11fffcd1833e4a4e1465
fannifulmer/exam-basics
/oddavg/odd_avg.py
520
4.15625
4
# Create a function called `odd_average` that takes a list of numbers as parameter # and returns the average value of the odd numbers in the list # Create basic unit tests for it with at least 3 different test cases def odd_average(numbers): new_list = [] try: for number in range(len(numbers)): if numbers[number] % 2 != 0: new_list.append(numbers[number]) return sum(new_list) / len(new_list) except ZeroDivisionError: return None odd_average([2, 3, 4])
true
c9314fef90c6104045e9fc0ddb376f8b70304c5d
nipunramk/Introduction-to-Computer-Science-Course
/Video19Code/video19.py
1,490
4.1875
4
def create_board(n, m): """Creates a two dimensional n (rows) x m (columns) board filled with zeros 4 x 5 board 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 x 2 board 0 0 0 0 0 0 >>> create_board(4, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> create_board(3, 2) [[0, 0], [0, 0], [0, 0]] """ if n == 0 or m == 0: raise IndexError("dimensions cannot both be zero") if n < 0 or m < 0: raise IndexError("dimensions cannot be negative") board = [] rows = [0] * m for i in range(n): board.append(rows) return board def invert(x): """A special invert function that will return 1/x, except in the case that we pass in x = 0, in which case we return 1 """ try: return 1 / x except ZeroDivisionError as e: print(e) return 1 class RangeIterable: """Implements the __iter__ method, making objects of the class iterable""" def __init__(self, start, end): self.start = start self.end = end def __iter__(self): return RangeIterator(self.start, self.end) class RangeIterator: """Implements both __iter__ and __next__ methods, making objects of this class function as both iterables and iterators """ def __init__(self, start, end): self.start = start self.end = end self.current = start def __next__(self): if self.current == self.end: self.current = self.start raise StopIteration result = self.current self.current = self.current + 1 return result def __iter__(self): return self
true
4d1423ccc90971c23c833e73bbdc3374da797e0d
hannahpaxton/calculator-2
/arithmetic.py
2,463
4.1875
4
"""Functions for common math operations.""" def add(num1, num2): """Return the sum of the two inputs.""" # define a variable "sum" # set this variable as the sum of num1, num2. sum = num1+num2 # return sum sum_nums = num1 + num2 return sum_nums def subtract(num1, num2): """Return the second number subtracted from the first.""" #def variable for subtract #set subtract variable to find difference between two numbers #return subtract variable difference = num1 - num2 return difference def multiply(num1, num2): """Multiply the two inputs together.""" #define variable for result #save result of num1 multiplied by num2 #return result product = num1 * num2 return product def divide(num1, num2): """Divide the first input by the second and return the result.""" #define function for divide #add quotient variable that divides num1 and num2 #return quotient quotient = num1/num2 return quotient def square(num1): """Return the square of the input.""" #define variable for square #save result of squaring to the variable #return result [squared] squared = num1 ** 2 return squared def cube(num1): """Return the cube of the input.""" #define variable for a cube #take num1 to the third power #return the cube variable is_cubed = num1 ** 3 return is_cubed def power(num1, num2): """Raise num1 to the power of num2 and return the value.""" #define variable for result #save result of num1 raised to num2 into result #return result exponent_result = num1 ** num2 return exponent_result def mod(num1, num2): """Return the remainder of num1 / num2.""" #define remainder variable #capturn remainder when num1 / num2 #return remainder variable remainder = num1 % num2 return remainder # define function add_mult with 3 parameters # add num1 and num2, multiply the result with num3 # return the final result def add_mult(num1, num2, num3): """ Return the sum of num 1 + num2 multiplied by num3""" equation = (num1 + num2) * num3 return equation #define function add_cubes with 2 parameters #define vaiable that takes the cubes of num1 and num2 and adds them together #return the sum of the cubes save in that variable def add_cubes(num1, num2) : """ Return the sum of cubes.""" sum_cubes = (num1**3) + (num2**3) return sum_cubes
true
b072e29a8a8f7ef5256c727290fe2a5c9fb949f5
ArpitaDas2607/MyFirst
/exp25.py
2,222
4.3125
4
def break_words(stuff): '''This function will, break up words for us.''' words = stuff.split(' ') return words #Trial 1: #print words stuff = "Now this looks weird, it\'s blue and green and all in between" statements = break_words(stuff) print statements #-----------------------------------------------------------------------------# def sort_words(words): '''This will sort words''' return sorted(words) #Trial 2: wordsNew = "Expeliarimus" trial = sort_words(wordsNew) print trial #-----------------------------------------------------------------------------# def print_first_word(words): '''Prints the first word after popping it off''' word = words.pop(0) return word #Trial 3: #Note that an argument for pop is always a list which can be created from a sentence by split(' ') #aList = [123, 'xyz','zara','abc'] print statements firstWord = print_first_word(statements) print firstWord #-----------------------------------------------------------------------------# def print_last_word(words): '''Prints last word after popping it off''' word = words.pop(-1) print word #Trial 4: print statements LastWord = print_last_word(statements) print LastWord #-----------------------------------------------------------------------------# def sort_sentence(sentence): '''Takes in a full sentence and returns the sorted words''' words = break_words(sentence) return sort_words(words) #Trial 5: Break = sort_sentence("I am Das") print Break #-----------------------------------------------------------------------------# def print_first_and_last(sentence): '''Prints the first and last words of the sentence''' words = break_words(sentence) a = print_first_word(words) b = print_last_word(words) return a,b #Trial 6: A,B = print_first_and_last("I am Das too") print A print B #-----------------------------------------------------------------------------# def print_first_and_last_sorted(sentence): '''Sorts the words then prints the first and last one ''' words = sort_sentence(sentence) a = print_first_word(words) b = print_last_word(words) #Trial 7: A,B = print_first_and_last("I am Das as well") print A print B
true
771482ef77c84b1daf7d50d8fce7d4d0aabf94ce
Anthima/Hack-CP-DSA
/Leetcode/BinarySearch/solution.py
877
4.125
4
# RECURSIVE BINARY SEARCH. class Solution: def binarySearch(self,arr,start,end,target): if(start <= end): # FINDING THE MIDDLE ELEMENT. mid = start+((end-start)//2) # CHECKING WHETHER THE MIDDLE ELEMENT IS EQUAL TO THE TARGET. if(arr[mid] == target): return mid # CHECKING WHETHER THE MIDDLE ELEMENT IS LESSER THAN THE TARGET. elif(arr[mid] < target): return self.binarySearch(arr,mid+1,end,target) # CHECKING WHETHER THE MIDDLE ELEMENT IS GREATER THAN THE TARGET. elif(arr[mid] > target): return self.binarySearch(arr,start,mid-1,target) return -1 def search(self, nums: List[int], target: int) -> int: return self.binarySearch(nums,0,len(nums)-1,target)
true
9687ded4776870f4a119959b99ef6bb5dda412ba
Anthima/Hack-CP-DSA
/Leetcode/Valid Mountain Array/solution.py
596
4.3125
4
def validMountainArray(arr): i = 0 # to check whether values of array are in increasing order while i < len(arr) and i+1 < len(arr) and arr[i] < arr[i+1]: i += 1 # i == 0 means there's no increasing sequence # i+1 >= len(arr) means the whole array is in increasing order if i == 0 or i + 1 >= len(arr): return False # to check whether values of array are in decreasing order while(i < len(arr) and i+1 < len(arr)): if arr[i] <= arr[i+1]: return False i += 1 return True print(validMountainArray([0, 3, 2, 1]))
true
1eb14c2eb2e8174f6e5e759daaa32afba5bc9612
rowand7906/cti110
/M3HW1_AgeClassifier_DanteRowan.py
421
4.34375
4
#Age Classifier #June 14, 2017 #CTI 110 M3HW1 - Age Classifier #Dante' Rowan # Get the age of the person age = int(input('Enter the age of the person: ')) # Calculate the age of the person. # Determine what age the person is if 1: print('Person is an infant.') elif 1 > 13: print('Person is a child.') if 13 > 20: print('Person is a teenager.') if 20: print('Person is an adult.')
true
2da8a1ca5b0ee01c712e682cdeef21c8b5f836bf
diesears/E01a-Control-Structues
/main10.py
2,414
4.3125
4
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') #making the greetings text appear colors = ['red','orange','yellow','green','blue','violet','purple'] #outlines the possible responses play_again = '' #enabling the play again feature for more responses best_count = sys.maxsize #no limit on how many times to play # the biggest number while (play_again != 'n' and play_again != 'no'): #establishing possible negative answers to playing again match_color = random.choice(colors) #allows the computer to insert a random answer from the given choices count = 0 #establishes where the computer should start counting the attempts color = '' #sets the area for a response while (color != match_color): #establishes the condtion that the response must match the correct answer color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line color = color.lower().strip() #this allows answers in upper and lower case and with spaces before or after count += 1 #establishes that after this attempt the total attempts will be 1 if (color == match_color): #the condition for which to print correct print('Correct!') # what will be printed with a correst response else: #establishing the other possible answers print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #what will be printed for an incorrect response an a counter to count how many total responses print('\nYou guessed it in {0} tries!'.format(count)) #printing to inform the reader how many tries it took them to guess correctly if (count < best_count): #establishing a specific condition for the computer to react to, when its the readers best guess print('This was your best guess so far!') # displaying the fact that this was their closest guess best_count = count #changing this new best score to reflect the overall best score play_again = input("\nWould you like to play again? ").lower().strip() #displaying the question if the reader wants to play again with a chance for input print('Thanks for playing!') #shows the final line that thanks the reader for playing
true
a4933426e475c8d8d34bc7ea7ca00f9706836202
stanwar-bhupendra/LetsLearnGit
/snum.py
411
4.1875
4
#python program to find smallest number among three numbers #taking input from user num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) num3 = int(input("Enter 3rd number: ")) if(num1 <= num2) and (num1 <= num3): snum = num1 elif(num2 <=num1) and (num2 <=num3): snum = num2 else: snum = num3 print("The smallest number among ", num1,",", num2,",", num3 ,"is :", snum)
true
773b41d9f6a9ad8133fda4c9954c35ca45dece2d
patrickbeeson/python-classes
/python_3/homework/Data_as_structured_objects/src/coconuts.py
1,034
4.15625
4
""" API for coconut tracking """ class Coconut(object): """ A coconut object """ def __init__(self, coconut_type, coconut_weight): """ Coconuts have type and weight attributes """ self.coconut_type = coconut_type self.coconut_weight = coconut_weight class Inventory(object): """ An inventory object for managing Coconuts. """ coconuts = [] def add_coconut(self, coconut): """ Add a coconut to inventory. Raise AttributeError if object isn't a coconut. """ if isinstance(coconut, Coconut): self.coconuts.append(coconut) else: raise AttributeError('Only coconuts can be added to inventory.') def total_weight(self): """ Calculate the total weight of coconuts in inventory. """ weight = 0 for coconut in self.coconuts: weight += coconut.coconut_weight return weight
true
30cfd0f856263b7889e535e9bea19fd645616ef9
patrickbeeson/python-classes
/python_1/homework/secret_code.py
870
4.59375
5
#!/usr/local/bin/python3 """ This program takes user input, and encodes it using the following cipher: Each character of the string becomes the character whose ordinal value is 1 higher. Then, the output of the program will be the reverse of the contructed string. """ # Get the user input as a string user_input = str(input('Enter the message to be obfuscated: ')) # Create our list of letters from the string letter_list = list(user_input) # Create our empty changed letter list changed_letter_list = [] # Loop through the letters in the list for letter in letter_list: # Advance the ordinal number for each letter by one changed_letter_ord = ord(letter) + 1 # Add our changed letters to the changed letter list changed_letter_list += chr(changed_letter_ord) # Print a reversed changed letter list print(''.join(reversed(changed_letter_list)))
true
81de86c9e5ae59d686bb8155ea4a75fd8c26e84e
dinodre1342/CP1404_Practicals
/Prac5/week5_demo3.py
802
4.28125
4
def subject(subject_code, subject_name): """ This is a function for printing subject code and name. :param subject_code: This is the JCU unique code for each subject :param subject_name: This is the associated name matching the code :return: A string message displaying both code and name """ string_msg = "This subject {} refers to {}".format (subject_code, subject_name) print(string_msg) return string_msg def main(): #print(subject()) #print (subject("3400", "New Subject")) #print (subject("4000")) #print (subject(subject_name="abc")) print (subject.__name__) print (subject.__doc__) print (subject.__str__) print (subject.__dict__) #print(subject("","").__doc__) #print subject ("1404", "Intro to programming") main()
true
91b5a6c3d5e2e6e9efea43f259386b8633ced137
tomasztuleja/exercises
/practisepythonorg/ex2_1.py
324
4.1875
4
#!/usr/bin/env python # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html inp = int(input("Type an Integer: ")) test = inp % 2 testfour = inp % 4 if test == 0: print("It's an even number!") if testfour == 0: print("It's also a multiple of 4!") else: print("It's an odd number!")
true
3ce1a459cb6ffcbc9630c5944134b68c71c2d4ba
Manjunath823/Assessment_challenge
/Challenge_3/nested_dictionary.py
844
4.34375
4
def nested_key(object_dict, field): """ Input can be nested dict and a key, the function will return value for that key """ keys_found = [] for key, value in object_dict.items(): if key == field: keys_found.append(value) elif isinstance(value, dict): #to check whether the value is key for nested dictionary out = nested_key(value, field) for each_out in out: keys_found.append(each_out) elif isinstance(value, list): for item in value: if isinstance(item, dict): more_results = nested_key(item, field) for another_result in more_results: keys_found.append(another_result) return keys_found #Example usage nested_key(object, key)
true
1480e4f71cc8b0bc2b27f113937ba4b1cafe8cfb
saif93/simulatedAnnealingPython
/LocalSearch.py
2,948
4.125
4
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" implementation of Simulated Annealing in Python Date: Oct 22, 2016 7:31:55 PM Programmed By: Muhammad Saif ul islam """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" import math import random from copy import deepcopy from Tour import Tour from City import city class LocalSearch: temp = 10000 coolingRate = 0.003 def __init__(self): self.cities = deepcopy(city.cities) def acceptanceProbability(self,energy, newEnergy, temperature): # If the new solution is better, accept it if (newEnergy < energy): return 1.0 # // If the new solution is worse, calculate an acceptance probability return math.exp((energy - newEnergy) / temperature) def simulatedAnnealing(self): currentSolution = Tour() currentSolution.generateIndividual() print("Initial solution distance: " , currentSolution.getDistance()) print("Initil path:",currentSolution.getTour()) # // Set as current best best = deepcopy(Tour(currentSolution.getTour())) # // Loop until system has cooled while (self.temp > 1) : # // Create new neighbour tour newSolution = deepcopy(Tour(currentSolution.getTour())) # // Get a random positions in the tour random.randrange(0,19,1) tourPos1 = random.randrange(0,newSolution.tourSize(),1) tourPos2 = random.randrange(0,newSolution.tourSize(),1) # // Get the cities at selected positions in the tour citySwap1 = newSolution.getCity(tourPos1) citySwap2 = newSolution.getCity(tourPos2) # // Swap them newSolution.setCity(tourPos2, citySwap1); newSolution.setCity(tourPos1, citySwap2); # // Get energy of solutions currentEnergy = currentSolution.getDistance() neighbourEnergy = newSolution.getDistance() # // Decide if we should accept the neighbour if (self.acceptanceProbability(currentEnergy, neighbourEnergy, self.temp) >= random.randint(1,19)) : currentSolution = deepcopy(Tour(newSolution.getTour())) # // Keep track of the best solution found if (currentSolution.getDistance() < best.getDistance()) : best = deepcopy(Tour(currentSolution.getTour())) # // Cool system self.temp *= 1- self.coolingRate print("\n\nFinal solution distance: " , best.getDistance()) print("Final path: " , best.getTour()) """ Testing """ initializeCities = city() localSearch = LocalSearch() localSearch.simulatedAnnealing()
true
31d9dc0b6c3e23b9c7dbee6a63139df021b69b27
SarwarSaif/Python-Problems
/Hackerank-Problems/Calendar Module.py
842
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 2 14:20:23 2018 @author: majaa """ import calendar if __name__ == '__main__': user_input = input().split() m = int(user_input[0]) d = int(user_input[1]) y = int(user_input[2]) print(list(calendar.day_name)[calendar.weekday(y, m, d)].upper()) #first calendar.weekday(y,m,d) returns the number of the day e.g: returns 6 for sunday #calendar.day_name returns the days name in an array #list(calendar.day_name) returns ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] #then we get list(calendar.day_name)[6] we get the day name in 6th index #then turn them into upper case letters by apply ".upper()" at the end #print(calendar.weekday(y, m, d)) #print(list(calendar.day_name)[calendar.weekday(y, m, d)])
true
0dfcd53fb2f4d82b58ce43b5726c6d682b61dc95
SarwarSaif/Python-Problems
/Hackerank-Problems/NestedList.py
1,897
4.25
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 29 12:30:26 2018 @author: majaa """ if __name__ == '__main__': marksheet=[] """ for _ in range(int(input())): marksheet.append([input(),float(input())]) """ n = int(input()) marksheet = [[input(), float(input())] for _ in range(n)] second_lowest= sorted(list(set([marks for name, marks in marksheet])))[1] #list index started from 1 print('\n'.join([a for a,b in sorted(marksheet) if b == second_lowest])) #print(sorted(marksheet)) """ Testcase 0 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Testcase 2 5 Harsh 20 Beria 20 Varun 19 Kakunami 19 Vikas 21 #initialising an empty list! marksheet = [] #iterating through a for loop starting from zero, to some user input(default type string) - that is converted to int for i in range(0,int(input())): #appending user input(some string) and another user input(a float value) as a list to marksheet marksheet.append([raw_input(), float(input())]) #[marks for name, marks in marksheet] - get all marks from list #set([marks for name, marks in marksheet]) - getting unique marks #list(set([marks for name, marks in marksheet])) - converting it back to list #sorting the result in decending order with reverse=True and getting the value as first index which would be the second largest. second_highest = sorted(list(set([marks for name, marks in marksheet])),reverse=True)[1] #printing the name and mark of student that has the second largest mark by iterating through the sorted list. #If the condition matches, the result list is appended to tuple -` [a for a,b in sorted(marksheet) if b == second_highest])` #now join the list with \n - newline to print name and mark of student with second largest mark print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest])) """
true
afb1f832a96caef7312c407477962a7b7ccbd0e5
kubawyczesany/python
/case_swapping.py
253
4.375
4
# Given a string, simple swap the case for each of the letters. # e.g. HeLLo -> hEllO string = input ("Give a string to swap: ") def swap(string_): _string = ''.join([i.upper() if i.islower() else i.lower() for i in string_]) return (_string)
true
dc31d568218f5f710d20afc46f9b876c0e09c8a9
lsaggu/introduction_to_python
/programs/programs.py
1,874
4.28125
4
#! /usr/bin/python import sys ''' her is the task i like you to do to reinforce the learning experience once you are done with the tutorial. a) write a program that uses loops over both x and y coordinates while x is in 1,2,3,4,5 and y is in 5,4,3,2,1 and prints the x and y coordinate b) write a program that sums up all values in x and y c) write a program just like a) but does not print values where x is equal to 2 and y is equal to 4 d) write a function that takes in a word and returns it in reverse order e) provide a program that uses dicts f) read up on classes we will cover this in more detail next week. we will create an icecream machine that produces icecream in with tiny flavor, medium flavor and large flavor. in addition the icecream cone will be wrapped into some paper that has an image on it. Images will be Penguin, Apple, ''' xlist = [1, 2, 3, 4, 5] ylist = [5, 4, 3, 2, 1] zlist = [4, 5, 2, 1, 3] print(xlist) print(ylist) print(zlist) print "GREGORS TASK" for x in xlist: for y in ylist: print (x, y) print ('Hello world') print ("Task A") # x and y cordinates index = 1 for y in ylist: for x in xlist: print index, (x, y) index += 1 print ("Task B") sum = 0 for y in ylist: for x in xlist: sum += y + x print ("The sum is", sum) print ("Task C") for x in xlist: sum = (x, y) print('\n\n The Sum of x and y cordinates is: + str(sum)') for y in ylist: if y == 5 or y < 4: for x in xlist: if x >= 3 or x < 2: print (x, y) print ("task D") tim = {'cheese': xlist, 'burger': ylist} tim['ham'] = zlist for a in tim: print (a) print ("task F") class clown: number_of_noise = 1 jack = clown() jack.number_of_noise = 3 print "Jack has %s noise." % jack.number_of_noise class clown: number_of_noise = 1 def nose(self): print "Big" jack = clown() jack.nose()
true
e689091397f37f3b4b166d1510e3dac045b8f799
AbdulMoizChishti/python-practice
/Pfundamental Lab/Lab 7/task 2.py
269
4.25
4
def max(a, b, c): if a>b and a>c: print(a) elif b>c and b>a: print(b) else: print(c) a=int(input("first number=")) b=int(input("second number=")) c=int(input("third number=")) max(a, b, c) print("is the maximum of three integers")
true
461ad5fff551ecfbb109842b78c03a33c3fe6156
akshaali/Competitive-Programming-
/Hackerrank/minimumDistances.py
1,525
4.375
4
""" We define the distance between two array values as the number of indices between the two values. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, print . For example, if , there are two matching pairs of values: . The indices of the 's are and , so their distance is . The indices of the 's are and , so their distance is . Function Description Complete the minimumDistances function in the editor below. It should return the minimum distance between any two matching elements. minimumDistances has the following parameter(s): a: an array of integers Input Format The first line contains an integer , the size of array . The second line contains space-separated integers . Constraints Output Format Print a single integer denoting the minimum in . If no such value exists, print . Sample Input 6 7 1 3 4 1 7 Sample Output 3 """ #!/bin/python3 import math import os import random import re import sys # Complete the minimumDistances function below. def minimumDistances(a): flag = 0 min = 888888888 for i in range(len(a)): for j in range(i+1,len(a)): if a[i] == a[j] and abs(i-j)< min: min = abs(i-j) flag = 1 return min if flag else "-1" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) a = list(map(int, input().rstrip().split())) result = minimumDistances(a) fptr.write(str(result) + '\n') fptr.close()
true
34240c8a1cd3c2132e6bd8121ae449b44ec92c58
akshaali/Competitive-Programming-
/Hackerrank/TimeConversion.py
1,432
4.1875
4
""" Given a time in -hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Function Description Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format. timeConversion has the following parameter(s): s: a string representing time in hour format Input Format A single string containing a time in -hour clock format (i.e.: or ), where and . Constraints All input times are valid Output Format Convert and print the given time in -hour format, where . Sample Input 0 07:05:45PM Sample Output 0 19:05:45 """ #!/bin/python3 import os import sys # # Complete the timeConversion function below. # def timeConversion(s): # # Write your code here. n = len(s) if s == "12:00:00PM": return s[:n-2] if s == "12:00:00AM": return "00:00:00" if s[:2]=="12" and s[n-2:]=="PM": return s[:n-2] if s[:2] == "12" and s[n-2:]=="AM": return (str("00")+ s[2:n-2]) if s[n-2:] == "AM": return(s[:n-2]) else: return(str(int(s[:2])+ 12)+s[2:n-2]) # if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close()
true
689a7f8c2643819de8930cfc93ceab46697b605a
akshaali/Competitive-Programming-
/Hackerrank/pickingNumbers.py
2,479
4.5625
5
""" Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion: and . The maximum length subarray has elements. Function Description Complete the pickingNumbers function in the editor below. It should return an integer that represents the length of the longest array that can be created. pickingNumbers has the following parameter(s): a: an array of integers Input Format The first line contains a single integer , the size of the array . The second line contains space-separated integers . Constraints The answer will be . Output Format A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is . Sample Input 0 6 4 6 5 3 3 1 Sample Output 0 3 Explanation 0 We choose the following multiset of integers from the array: . Each pair in the multiset has an absolute difference (i.e., and ), so we print the number of chosen integers, , as our answer. Sample Input 1 6 1 2 2 3 1 2 Sample Output 1 5 """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code here if a == None: return 0 ai = list(set(a)) dic = {} for i in ai: dic1 = {i:a.count(i)} dic.update(dic1) l = [] f = 0 print(dic) key1 = ai[0] value1 = dic[ai[0]] dic1 = dic.copy() del dic[ai[0]] print(dic) if not bool(dic): return value1 for key, value in dic.items(): if abs(key1-key) <=1: f = 1 l.append(value1+value) key1 = key value1 = value print(dic1) key_max = max(dic1.keys(), key=(lambda k: dic1[k])) if f: return max(max(l), dic1[key_max]) else: key_max = max(dic1.keys(), key=(lambda k: dic1[k])) return key_max if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = pickingNumbers(a) fptr.write(str(result) + '\n') fptr.close()
true
c9488b2c6856e3c6b87db68ee117bb4e01380325
akshaali/Competitive-Programming-
/Hackerrank/designerPDFViewer.py
2,008
4.21875
4
""" When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In this PDF viewer, each word is highlighted independently. For example: PDF-highighting.png In this challenge, you will be given a list of letter heights in the alphabet and a string. Using the letter heights given, determine the area of the rectangle highlight in assuming all letters are wide. For example, the highlighted . Assume the heights of the letters are and . The tallest letter is high and there are letters. The hightlighted area will be so the answer is . Function Description Complete the designerPdfViewer function in the editor below. It should return an integer representing the size of the highlighted area. designerPdfViewer has the following parameter(s): h: an array of integers representing the heights of each letter word: a string Input Format The first line contains space-separated integers describing the respective heights of each consecutive lowercase English letter, ascii[a-z]. The second line contains a single word, consisting of lowercase English alphabetic letters. Constraints , where is an English lowercase letter. contains no more than letters. Output Format Print a single integer denoting the area in of highlighted rectangle when the given word is selected. Do not print units of measure. Sample Input 0 1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 abc Sample Output 0 9 """ #!/bin/python3 import math import os import random import re import sys # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): max = 0 for i in range(len(word)): if max < h[ord(word[i])-97]: max = h[ord(word[i])-97] return max*len(word) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) fptr.write(str(result) + '\n') fptr.close()
true
0e016e34e46435270dc0bba650016e7ba56a2ced
akshaali/Competitive-Programming-
/Hackerrank/gridChallenge.py
2,281
4.15625
4
""" Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not. For example, given: a b c a d e e f g The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row. Function Description Complete the gridChallenge function in the editor below. It should return a string, either YES or NO. gridChallenge has the following parameter(s): grid: an array of strings Input Format The first line contains , the number of testcases. Each of the next sets of lines are described as follows: - The first line contains , the number of rows and columns in the grid. - The next lines contains a string of length Constraints Each string consists of lowercase letters in the range ascii[a-z] Output Format For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise. Sample Input 1 5 ebacd fghij olmkn trpqs xywuv Sample Output YES Explanation The x grid in the test case can be reordered to abcde fghij klmno pqrst uvwxy This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all lexicographically sorted. """ #!/bin/python3 import math import os import random import re import sys # Complete the gridChallenge function below. def gridChallenge(grid): row = len(grid) column = len(grid[0]) for i in range(row): grid[i] = sorted(grid[i], key=ord) for i in range(column): for j in range(row-1): if ord(grid[j][i]) > ord(grid[j+1][i]): return("NO") return("YES") if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) grid = [] for _ in range(n): grid_item = input() grid.append(grid_item) result = gridChallenge(grid) fptr.write(result + '\n') fptr.close()
true
918519d14aa6d0984c66c9bd431c51d9ac82c263
akshaali/Competitive-Programming-
/Hackerrank/anagram.py
2,668
4.4375
4
""" Two words are anagrams of one another if their letters can be rearranged to form the other word. In this challenge, you will be given a string. You must split it into two contiguous substrings, then determine the minimum number of characters to change to make the two substrings into anagrams of one another. For example, given the string 'abccde', you would break it into two parts: 'abc' and 'cde'. Note that all letters have been used, the substrings are contiguous and their lengths are equal. Now you can change 'a' and 'b' in the first substring to 'd' and 'e' to have 'dec' and 'cde' which are anagrams. Two changes were necessary. Function Description Complete the anagram function in the editor below. It should return the minimum number of characters to change to make the words anagrams, or if it's not possible. anagram has the following parameter(s): s: a string Input Format The first line will contain an integer, , the number of test cases. Each test case will contain a string which will be concatenation of both the strings described above in the problem. The given string will contain only characters in the range ascii[a-z]. Constraints consists only of characters in the range ascii[a-z]. Output Format For each test case, print an integer representing the minimum number of changes required to make an anagram. Print if it is not possible. Sample Input 6 aaabbb ab abc mnop xyyx xaxbbbxx Sample Output 3 1 -1 2 0 1 Explanation Test Case #01: We split into two strings ='aaa' and ='bbb'. We have to replace all three characters from the first string with 'b' to make the strings anagrams. Test Case #02: You have to replace 'a' with 'b', which will generate "bb". Test Case #03: It is not possible for two strings of unequal length to be anagrams of one another. Test Case #04: We have to replace both the characters of first string ("mn") to make it an anagram of the other one. Test Case #05: and are already anagrams of one another. Test Case #06: Here S1 = "xaxb" and S2 = "bbxx". You must replace 'a' from S1 with 'b' so that S1 = "xbxb". """ #!/bin/python3 import math import os import random import re import sys # Complete the anagram function below. def anagram(s): n = len(s) if n % 2 != 0: return("-1") else: coun = 0 for i in set(s[:n//2]): coun += min(s[:n//2].count(i), s[n//2:].count(i)) return n//2 - coun if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): s = input() result = anagram(s) fptr.write(str(result) + '\n') fptr.close()
true
54c0a48e87f31af1f129a16230921cce367a1dbc
akshaali/Competitive-Programming-
/Hackerrank/AppendandDelete.py
2,682
4.125
4
""" You have a string of lowercase English alphabetic letters. You can perform two types of operations on the string: Append a lowercase English alphabetic letter to the end of the string. Delete the last character in the string. Performing this operation on an empty string results in an empty string. Given an integer, , and two strings, and , determine whether or not you can convert to by performing exactly of the above operations on . If it's possible, print Yes. Otherwise, print No. For example, strings and . Our number of moves, . To convert to , we first delete all of the characters in moves. Next we add each of the characters of in order. On the move, you will have the matching string. If there had been more moves available, they could have been eliminated by performing multiple deletions on an empty string. If there were fewer than moves, we would not have succeeded in creating the new string. Function Description Complete the appendAndDelete function in the editor below. It should return a string, either Yes or No. appendAndDelete has the following parameter(s): s: the initial string t: the desired string k: an integer that represents the number of operations Input Format The first line contains a string , the initial string. The second line contains a string , the desired final string. The third line contains an integer , the number of operations. Constraints and consist of lowercase English alphabetic letters, . Output Format Print Yes if you can obtain string by performing exactly operations on . Otherwise, print No. Sample Input 0 hackerhappy hackerrank 9 Sample Output 0 Yes Explanation 0 We perform delete operations to reduce string to hacker. Next, we perform append operations (i.e., r, a, n, and k), to get hackerrank. Because we were able to convert to by performing exactly operations, we print Yes. Sample Input 1 aba aba 7 Sample Output 1 Yes """ #!/bin/python3 import math import os import random import re import sys # Complete the appendAndDelete function below. def appendAndDelete(s, t, k): commonLength = 0 for i in range(min(len(t), len(s))): if s[i] == t[i]: commonLength +=1 else: break if len(s) + len(t) - 2*commonLength > k: return("No") elif (len(s) + len(t) - 2*commonLength)%2 == k%2: return("Yes") elif len(s) + len(t)-k < 0 : return("Yes") else: return("No") if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() t = input() k = int(input()) result = appendAndDelete(s, t, k) fptr.write(result + '\n') fptr.close()
true
83e4ae0872601c41974ea40725d6dace62e0d338
ariv14/python
/Day3_if_else/ifelse.py
328
4.4375
4
# Even or odd number finder print("Welcome!! Please input any number to check odd or even !!\n") # Get the input number as integer number = int(input("Which number do you want to check? ")) #Write your code below this line if number % 2 == 0: print("The number is even number") else: print("The number is odd number")
true
5b05abfb21bf9b8dea2dd9de4d1d859b09dc0dd5
selinoztuurk/koc_python
/inclass/day1Syntax/lab1.py
1,416
4.25
4
def binarify(num): """convert positive integer to base 2""" if num<=0: return '0' digits = [] division = num while (division >= 2): remainder = division % 2 division = division // 2 digits.insert(0, str(remainder)) digits.insert(0, str(division % 2)) return ''.join(digits) print(binarify(10)) def int_to_base(num, base): """convert positive integer to a string in any base""" if num<=0: return '0' digits = [] division = num while (division >= base): remainder = division % base division = division // base digits.insert(0, str(remainder)) digits.insert(0, str(division % base)) return ''.join(digits) print(int_to_base(10, 3)) def base_to_int(string, base): """take a string-formatted number and its base and return the base-10 integer""" if string=="0" or base <= 0 : return 0 result = 0 for i in range(len(string), 0, -1): int(string[i-1]) return result print(base_to_int("101", 3)) ## 10 def flexibase_add(str1, str2, base1, base2): """add two numbers of different bases and return the sum""" result = int_to_base(tmp, base1) return result def flexibase_multiply(str1, str2, base1, base2): """multiply two numbers of different bases and return the product""" result = int_to_base(tmp, base1) return result def romanify(num): """given an integer, return the Roman numeral version""" result = "" return result
true
c08f06f789fc81a1672e797a41c1d8cc39801864
ptrkptz/udemy_python
/Python_Course/17_conditionals.py
841
4.125
4
grade1 = float(input ("Type the grade of the first test: ")) grade2 = float(input ("Type the grade of the second test: ")) absenses = int(input ("Type the number of absenses: ")) total_classes = int(input("Type the total number of classes: ")) avg_grade = (grade1 + grade2) /2 attendance = (total_classes - absenses) / total_classes print("Avg grade: ", round(avg_grade,2)) print("Attendance rate: ", str(round((attendance*100),2))+"%") if(avg_grade >= 6) : if (attendance >= 0.8) : print ("The student was approved.") else: print ("The student has failed due to attendance rate lower than 80%") elif(attendance >= 0.8): print ("The student has failed due to an average grade lower than 6.0.") else: print ("The student has failed due to an average grade lower than 6.0 & attendance rate lower than 80%")
true
1055f864fb549ae4202482553b16be2c046ff3d6
ptrkptz/udemy_python
/Python_Course/15_booleans.py
249
4.125
4
num1 = float(input("Type the 1st num:")) num2 = float(input("Type the 2nd num:")) if (num1 > num2): print(num1, " is greater than ", num2) elif(num1==num2): print(num1, " is equal to ", num2) else: print(num1, " is less than ", num2)
true
504b12b8de997337e4c6166ded242ff6d93d14ce
nimus0108/python-projects
/Tri1/anal_scores.py
535
4.25
4
# Su Min Kim # Analysis Scores num = input("") num_list = num.split() greater = 0 less = 0 def get_mean (num_list): m = 0 i = 0 x = len(num_list) for i in range (0, x): number = int(num_list[i]) m += number mean = m/x return mean for num in num_list: number = int(num) mean = get_mean(num_list) if number >= mean: greater += 1 else: less += 1 print("# of values equal to or greater than the mean: ", greater) print("# of values less than the mean: ", less)
true
c876053f4a23e86dcda291995c5142396ae5709f
meanJustin/Algos
/Demos/MergeSort.py
1,451
4.15625
4
# Python program for implementation of Selection # Sort import sys import time def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+= 1 else: arr[k] = R[j] j+= 1 k+= 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+= 1 k+= 1 while j < len(R): arr[k] = R[j] j+= 1 k+= 1 # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] # Using readlines() file1 = open('myfile.txt', 'r') Lines = file1.readlines() arr = [] # Strips the newline character for line in Lines: arr.append(line.strip()) length = len(arr) print ("count :", length) start_time = time.perf_counter() mergeSort(arr) end_time = time.perf_counter() #Driver code to test above print ("Sorted array") for i in range(length): print(arr[i]) print ("time : Duration : Bubble Sort", end_time - start_time)
true
181accc46b0d03467a765e1b6f1fe8949f2799dc
prathapSEDT/pythonnov
/Collections/List/Slicing.py
481
4.1875
4
myList=['a',4,7,2,9,3] ''' slicing is the concept of cropping sequence of elements to crop the sequence of elements we need to specify the range in [ ] synatx: [starting position: length] here length is optinal, if we wont specify it, the compiler will crop the whole sequence form the starting position ''' # from index 3 get all the elements print(myList[3:]) # from index 3 get exactly one element print(myList[3:4]) # from index 3 get exactly two elements print(myList[3:5])
true
8c94185a47805431f457cb157523350c318ba831
prathapSEDT/pythonnov
/Collections/List/Len.py
208
4.1875
4
''' This length method is used to get the total length of elements that are available in the given list ''' myList=['raj','mohan','krish','ram'] ''' get the toatal length of a given list''' print(len(myList))
true
3aee5a7a4a62a9ab4339ff518c5efaa5e0afa539
prathapSEDT/pythonnov
/looping statements/WhileLoop.py
244
4.1875
4
''' while loop is called as indefinite loop like for loop , while loop will not end by its own in the while we need write a condition to break the loop ''' ''' Print Numbers from 1-50 using while loop ''' i=1 while(i<=50): print(i) i+=1
true
9266236293a7e1c49900110e7e408876fcddf99d
VectorSigmaGen1/Basic_Introductory_Python
/Practical 10 - 3rd October 2019/p10p1.py
1,261
4.28125
4
# program to calculate the positive integer square root of a series of entered positive integer """ PSEUDOCODE request input for a positive integer and assign to variable num print "Please enter the positive integer you wish to calculate the square root of (Enter a negative integer to exit program): " WHILE num >= 0 assign the value of 0 to a variable root WHILE root squared < num root = root + 1 IF root squared is exactly equal to num THEN print"The square root of" num "is" root ELSE THEN print num "is not a perfect square." print "You have entered a negative integer. The program is terminated" """ num = int(input('Please enter the positive integer you wish to calculate the square root of\n(Enter a negative integer to exit program): ')) while num >= 0: root = 0 while root**2 < num: root += 1 if root**2 == num: print('The square root of', num, 'is', root) else: print(num, 'is not a perfect square.') num = int(input('Please enter another positive integer you wish to calculate the square root of\n(Enter a negative integer to exit program): ')) print('You have entered a negative integer\nThe program is terminated')
true
13080a3947d52e11797bd399fe8e3e3342dc4091
VectorSigmaGen1/Basic_Introductory_Python
/Practical 13 - 10th October/p13p5.py
1,013
4.53125
5
# Program to illustrate scoping in Python # Added extra variables and operations """ Pseudocode DEFINE function 'f' of variable 'x' and variable 'y' PRINT "In function f:" Set x = x+1 Set y = y * 2 set z = x-1 PRINT "x is", 'x' PRINT "y is", 'y' PRINT "z is", 'z' RETURN 'x' & 'y' Set x = 5 Set y = 10 Set z = 15 print "Before function f:" print "x is", 'x' print "y is", 'y' print "z is", 'z' CALL function 'f' print "After function f:" print "x is", 'x' print "y is", 'y' print "z is", 'z' """ def f(x, y): """Function that adds 1 to its argument and prints it out""" print("In function f:") x+=1 y*=2 z=x-1 print("x is", x) print("y is", y) print("z is", z) return x, y x, y, z = 5, 10, 15 print("Before function f:") print("x is", x) print("y is", y) print("z is", z) x, y=f(x, y) print("After function f:") print("x is", x) print("y is", y) print("z is", z)
true
7d1038aaa9fe2af8374685ac523187026e58280a
VectorSigmaGen1/Basic_Introductory_Python
/Practical 09 - 3rd October 2019/p9p3.py
969
4.28125
4
# program to calculate the factorial of an entered integer """ Pseudocode Set num = 0 WHILE input >= 0; Request input Print "Please enter a positive integer (If you wish to terminate the program, please enter a negative integer): " run = 1 for i in range(1, input+1, 1) run = run * i if input >= 1 print 'The factorial of the integers up to and including your number is: ', run print 'You have entered a negative integer' print 'Program Terminated' """ num = int(0) while num >= 0: num = int(input('Please enter a positive integer (If you wish to terminate the program, please enter a negative integer): ')) run = 1 for i in range(1, num+1): run *= i if num >= 0: print('The factorial of the integers up to and including your number is: ', run) print('You have entered a negative integer') print('Program Terminated')
true
0f1ad4d9a1bb6273f8e442b39f5c3281b4bd7e1a
VectorSigmaGen1/Basic_Introductory_Python
/Practical 07 - 26th Sep 2019/p7p3.py
619
4.34375
4
# program to print the first 50 integers and their squares # for this program, I've used the first 50 positive integers starting with 0 and ending with 49 ''' print 'This is a program to print the integers 0 to 49 and their squares' set variable=int(0) While variable <50 print variable print variable squared set variable=variable+1 print 'the program is now complete' ''' print ('This is a program to print the integers 0 to 49 and their squares') Num=int(0) while Num<50: print ('The square of', Num, 'is', Num**2) Num=(Num+1) print ('The program is now complete')
true
7a63238e5cb6c4ea552dfa07a6c3f7470c452dfa
VectorSigmaGen1/Basic_Introductory_Python
/Practical 12 - 8th October 2019/p12p2.py
1,703
4.40625
4
# Define the function fibonacci which displays 'a' number of terms of the Fibonacci Sequence # Program to check if an entered integer is a positive integer and if so to apply the function factorial to produce an answer """ Pseudocode Define function 'fibonacci' of a variable 'a': IF a > 0 set variable 'num1' = 0 set variable 'num2' = 1 print "Your Fibonacci sequence is " num1 and suppress newline FOR i in range (1,a) set num1 = current value of num 2 set new value of num2 = num1 + num2 print num1 print newline ELSE print "You have entered zero. This has returned no terms." request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " IF length < 0: print "Error: Number entered was less than 0." ELSE execute the function 'fibonacci' on length """ #Defining function to caluclate and display 'a' number of terms of the Fibonacci Sequence def fibonacci(a): if a>0: num1=0 num2=1 print("Your Fibonacci sequence is ", num1, " ", sep="", end="") for i in range(1,a): num1, num2 = num2, (num1+num2) print(num1, " ", sep="", end="") print() else: print("You have entered zero. This has returned no terms.") # program to check entered integer and call function if appropriate length = int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) if length < 0: print("Error: Number entered was less than 0.") else: fibonacci(length)
true
6f859d260c8d4fd41bb03d315defb665e4bc20f2
VectorSigmaGen1/Basic_Introductory_Python
/Practical 11 - 3rd October 2019/p11p3.py
1,772
4.5
4
# Program to check if an entered integer is a positive integer and if so to display that number of terms from the Fibonacci Sequence """ Pseudocode request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " WHILE length >= 0 IF length > 0 set variable 'num1' = 0 set variable 'num2' = 1 print "Your Fibonacci sequence is " num1 and suppress newline FOR i in range (1, length) set new value of num1 = current value of num 2 set new value of num2 = num1 + num2 print num1 print newline ELSE print "You have entered zero. This has returned no terms." request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " print "You have entered a negative number - it isn't possible to display a negative number of terms. Please run the program again." """ length=int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) while length>=0: if length>0: num1=0 num2=1 print("Your Fibonacci sequence is ", num1, " ", sep="", end="") for i in range(1, length): num1, num2 = num2, (num1+num2) print(num1, " ", sep="", end="") print() else: print("You have entered zero. This has returned no terms.") length=int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) print("You have entered a negative number - it isn't possible to display a negative number of terms. Please run the program again.")
true
7fb84f004a36f1ca3e2b6dee6c5c91652c8b46ef
VectorSigmaGen1/Basic_Introductory_Python
/Practical 07 - 26th Sep 2019/p7p4.py
746
4.28125
4
# program to add the first 5000 integers and give an answer # for this program, I've used the first 5000 positive integers, # starting with 0 and ending with 4999. """ print 'This is a program to add the integers 0 to 4999 and give a total' set variable=int(0) set sum=int(0) While variable <5000 set sum=sum+variable set variable=variable+1 print 'the program is now complete' print 'The sum of all of the integers from 0 to 4999 is', sum """ print('This is a program to add the integers from 0 to 4999 and give a total') Num = int(0) Sum = int(0) while Num < 5000: Sum = (Sum+Num) Num = (Num+1) print('The program is now complete') print('The sum of all of the integers from 0 to 4999 is', Sum)
true
db540b0084bd73a4f11a39cdadc04c394ad4e7cb
VectorSigmaGen1/Basic_Introductory_Python
/Practical 18 - 17th October 2019/p18p1.py
1,328
4.34375
4
# an iterative version of the isPal function # Checks whether a supplied string is a palindrome """ Pseudocode DEFINE function 'isPal(s)' Get the length of 's' and assign it to variable 'length' IF 'length' <=1 RETURN TRUE ELSE set variable 'check' = 0 FOR 'i' in range (start = 0, end = 'length'/2, iteration = 1) set variable 'result' = ('s' character[i] = 's' character['length'-1-'i']) IF 'result' is FALSE change variable 'check' to 1 IF check is not equal to 0 variable 'result2' = FALSE print 's' "is not a palindrome" ELSE variable 'result2' = TRUE print 's' "is a palindrome" RETURN 'result2' """ def isPal(s): length = len(s) if length <= 1: return True else: check=0 for i in range(length//2): result = s[i]==s[length-1-i] if not result: check=1 if check!=0: result2=False print(s, "is not a palindrome") else: result2=True print(s, "is a palindrome") return result2 # Container to request arguement and call function s=str(input("please enter a string for palindrome check: ")) isPal(s)
true
6416bbd289069b4ad2208b0db6efe9e78c2cd05b
LuckyTyagi279/Misc
/python/loops_if.py
481
4.1875
4
#!/usr/bin/python # Loops # While Loop while 0 : Var=0 while Var < 5 : Var = Var + 1 print Var print "This is not in the loop!" # Conditional Statement # If statement while 0 : Var=1 if Var == 2 : print "Condition is TRUE!" else : print "Condition is FALSE!" while 0 : Var = 0 while Var <= 100 : if Var % 2 == 0 and Var % 3 == 0 : # Multiple Conditions use 'or' (||) / 'and' (&&) print Var elif Var % 7 == 0 : print Var Var = Var + 1 print "Here"
true
0adc8e05c38e52d54f8667a0fc8e4a99337941ed
traines3812/traines3812.github.io
/range_demo.py
605
4.5625
5
# The range function generates a sequence of integers a_range = range(5) print('a_range ->', a_range) print('list(a_range) ->', list(a_range)) # It is often used to execute a "for"loop a number of times for i in range (5): print(i, end= ' ') # executed five times print() # It is similar to the slice function with a start, stop, and step a_range = range(10) # stop only print('list(a_range) ->', list(a_range)) a_range = range(10, 16) # start and stop print('list(a_range) ->', list(a_range)) a_range = range(10, -1, -1) # start, stop and step print('list(a_range) ->', list(a_range))
true
7fea623eb32b3b2fbb1b8ef06f61ff42a4f5aeeb
HumayraFerdous/Coursera_Python_Basics
/Week4.py
1,728
4.125
4
#Methods mylist=[] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist.insert(1,12) print(mylist) print(mylist.count(12)) print(mylist.index(3)) print(mylist.count(5)) mylist.reverse() print(mylist) mylist.sort() print(mylist) mylist.remove(5) print(mylist) lastitem=mylist.pop() print(lastitem) print(mylist) #Strings scores=[("Rodney Dangerfield",-1),("Marlon Brando", 1),("You",100)] for person in scores: name=person[0] score=person[1] print("Hello {}.Your score is {}.".format(name,score)) #calculating discount origPrice=float(input('Enter the original price: $')) discount=float(input('Enter discount percentage: ')) newPrice=(1-discount/100)*origPrice calculation='${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice,discount,newPrice) print(calculation) #Accumulator patterns ## nums=[3,5,8] accum=[] for w in nums: x=w**2 accum.append(x) print(accum) ## verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"] ing=[] val="" for word in verbs: val=word+"ing" ing.append(val) print(ing) ## numbs = [5, 10, 15, 20, 25] newlist=[] for item in numbs: newlist.append(item+5) print(newlist) ## numbs = [5, 10, 15, 20, 25] i=0 for item in numbs: item=item+5 numbs[i]=item i+=1 print(numbs) ## lst_nums = [4, 29, 5.3, 10, 2, 1817, 1967, 9, 31.32] larger_nums=[] for item in lst_nums: larger_nums.append(item*2) print(larger_nums) ## s=input("Enter some text: ") ac="" for c in s: ac=ac+c+"-"+c+"-" print(ac) ## s = "ball" r = "" for item in s: r = item.upper() + r print(r) output="" for i in range(35): output+='a' print(output) ## a = ["holiday", "celebrate!"] quiet = a quiet.append("company") print(a)
true
96bf134d00802ad032852d9f789349fc358b042f
Jennykuma/coding-problems
/codewars/Python/invert.py
368
4.15625
4
''' Invert Values Level: 8 kyu Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] You can assume that all values are integers. ''' def invert(lst): return list(map(lambda x: x*-1, lst))
true
b36a9a9b65550021d6a95067e28fadf68555ec67
nishantgautamIT/python_core_practice
/pythonbasics/SetInPython.py
1,273
4.125
4
# Set in python # method in set # 1.union() set1, set2, set3 = {1, 2, 3}, {3, 4, 5}, {5, 6, 7} set_UN = set1.union(set2, set3) print(set1) print(set_UN) # 2. intersection() set_int = set2.intersection(set1) print(set_int) # 3. difference() set_diff = set1.difference(set2) print(set_diff) # 4. symmetric_difference() setSymDiff = set1.symmetric_difference(set2) print(setSymDiff) # 5. intersection_update() # It update the set on which perform intersection operation set1.intersection_update(set2) print(set1) # 6. difference_update() set4, set5, set6 = {1, 2, 3}, {3, 4, 5}, {5, 6, 7} set4.difference_update(set5) print(set4) # 7. symmetric_difference_update() set5.symmetric_difference_update(set6) print(set5) # 8. copy() set1 = set5.copy() # 9. disjoint() # This method returns True if two sets have a null intersection. set8, set9 = {1, 2, 3}, {4, 5, 6} print(set8.isdisjoint(set9)) # 10. issubset() # 11. issuperset() # Iterating on a Set for i in set5: print(i) # i. The frozenset # A frozen set is in-effect an immutable set. # You cannot change its values. Also, a set can’t be used a key for a dictionary, but a frozenset can. frozenset1 = {{1, 2}: 3} # frozenset2 = {frozenset(1, 2): 3} frozenset3 = {frozenset([1, 2]): 3} print(frozenset3)
true
a250d32dc61ec7b738b96e5e911c09434cc6f25f
nvincenthill/python_toy_problems
/string_ends_with.py
417
4.25
4
# Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). # Examples: # string_ends_with('abc', 'bc') # returns true # string_ends_with('abc', 'd') # returns false def string_ends_with(string, ending): length = len(ending) sliced = string[len(string) - length:] return sliced == ending # print(string_ends_with('abc', 'bc'))
true
c5167aaf0b17bc6b744043c389924270e3e235fe
nguyenlien1999/fundamental
/Session05/homework/exercise3.py
408
4.625
5
# 3 Write a Python function that draws a square, named draw_square, takes 2 arguments: length and color, # where length is the length of its side and color is the color of its bound (line color) import turtle def draw_square(size,colors): f = turtle.Pen() f.color(colors) # f.color(color) for i in range(3): f.forward(size) f.right(90) f.forward(size) f.done() draw_square(200,"blue")
true
3c927b72492f4f9a438ed8711aaff757b0f56009
Elijah-M/Module10
/class_definitions/invoice.py
2,468
4.40625
4
""" Author: Elijah Morishita elmorishita@dmacc.edu 10/26/2020 This program is used for creating an example of the uses of a class """ class Invoice: """ A constructor that sets the variables """ def __init__(self, invoice_id, customer_id, last_name, first_name, phone_number, address, items_with_price={}): self._invoice_id = invoice_id self._customer_id = customer_id self._last_name = last_name self._first_name = first_name self._phone_number = phone_number self._address = address self._items_with_price = items_with_price def __str__(self): """ A string conversion method :return: """ return "Invoice ID: " + self._invoice_id + "\n" \ "Customer ID: " + self._customer_id + "\n"\ + self._last_name + ', ' + self._first_name + "\n" \ + self._phone_number + "\n" \ + self._address def __repr__(self): """ An official true string conversion (more accurate) :return: """ return "Invoice ID: " + self._invoice_id + "\n" \ "Customer ID: " + self._customer_id + "\n"\ + self._last_name + ', ' + self._first_name + "\n" \ + self._phone_number + "\n" \ + self._address def add_item(self, x): """ This function adds items to a dictionary :param x: :return: """ self._items_with_price.update(x) def create_invoice(self): """ This function calculates the values of the dictionary, prints the tax total, and prints the full total :return: """ print(invoice, "\n", "=" * 40) for x, y in self._items_with_price.items(): print(x, y) tax = 0.06 # tax amount tax_total = list(self._items_with_price.values()) # converting the values of the dict to a list tax_total_sum = 0 for x in range(0, len(tax_total)): tax_total_sum = tax_total_sum + tax_total[x] tax = tax_total_sum * tax # Tax Total total = tax_total_sum + tax # Total invoice with tax print("Tax.....", tax) print("Total...", total) # Driver invoice = Invoice("9908", "432", "Morishita", "Elijah", "(555) 555-5555", "123 Main st.\nDes Moines, IA 50265") invoice.add_item({"Soda": 0.99}) invoice.add_item({"Hamburger": 3.99}) invoice.create_invoice()
true
60769c7f9ecb97369f20e2fcbdb9ba9fd8c70b85
jasanjot14/Data-Structures-and-Algorithms
/Algorithms/iterative_binary_search.py
1,661
4.375
4
# Function to determine if a target (target) exists in a SORTED list (list) using an iterative binary search algorithm def iterative_binary_search(list, target): # Determines the search space first = 0 last = len(list) - 1 # Loops through the search space while first <= last: # Updates the midpoint in the search space midpoint = first + (last - first) // 2 # Compares target to the midpoint and returns midpoint if true if target == list[midpoint]: return midpoint # Removes all elements in the right side of the search space if target is lower than the midpoint value elif target < list[midpoint]: last = midpoint - 1 # Removes all elements in the left side of the search space if target is higher than the midpoint value else: first = midpoint + 1 # Returns None if target does not exist in the list return None # Function to display the results of the implemented algorithm def verify(index): # Notifies the user of where the target exists in the list if found if index is not None: print("The target was found at index", index, "in the list.") # Notifies the user that the target does not exist in the list else: print("The target was not found in the list.") # Example case for if target exists in the list result = iterative_binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9) verify(result) # Example case for if target does not exist in the list result = iterative_binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 13) verify(result)
true
06bf16ed3dc113f6c43578271d1e63088317cfbc
ajit-jadhav/CorePython
/1_Basics/7_ArraysInPython/a1_ArrayBasics.py
2,409
4.40625
4
''' Created on 14-Jul-2019 @author: ajitj ''' ## Program 1 ## Creating an integer type array import array a = array.array('i',[5,6,7]) print('The array elements are: ') for element in a: print (element) ## Program 2 ## Creating an integer type array v2 from array import * a = array('i',[5,6,7]) print('The array elements are: ') for element in a: print (element) ## Program 3 ## Creating an array with group of characters. from array import * arr = array('u',['a','b','c','d','e']) print('The array elements are: ') for ch in arr: print (ch) ## Program 4 ## Creating an array from another array. from array import * arr1 = array('d',[1.5,2.5,3,-4]) #use same type code and multiply each element of arr1 with 3 arr2 = array(arr1.typecode,(a*3 for a in arr1)) print('The array2 elements are: ') for i in arr2: print (i) #################### Indexing and Slicing in Array ############################### ## Program 5 ## A program to retrieve the elements of an array using rray index # accessing elements of an array using index from array import * x = array('i',[10,20,30,40,50]) #find number of elements in array n=len(x) #Display array elements using indexing for i in range(n): # repeat from 0 to n-1 print (x[i],end=' ') ## Program 7 ## A program that helps to know effects of slicingoperations on an array from array import * x = array('i',[10,20,30,40,50]) # create array y with elements from 1st to 3rd from x y = x[1:4] print(y) # create array y with elements from 0th till end from x y = x[0:] print(y) # create array y with elements from 0th to 3rd from x y = x[0:4] print(y) # create array y with last 4 elements from x y = x[-4:] print(y) # create array y with last 4th element and with 3 [-4-(-1)=-3]elements towards right y = x[-4:-1] print(y) # create array y with 0th to 7th elements from x # Stride 2 means, after 0th element, retrieve every 2nd element from x y = x[0:7:2] print(y) ##Program 8: ## Program to retrieve and display only a range of elements from an array using slicing. # using slicing to display elements of an array from array import * x = array('i',[10,20,30,40,50,60,70]) # display elements from 2nd to 4th only for i in x[2:5]: print(i)
true
fac0907fa4db80c8d9aa200e6f2f25d260e7e3d0
alex-gagnon/island_of_miscripts
/pyisland/src/classic_problems/StringToInteger.py
1,677
4.15625
4
import re class Solution: """Convert a string to an integer. Whitespace characters should be removed until first non-whitespace character is found. Next, and optional plus or minus sign may be found which should then be followed by any number of numerical digits. The digits should then be converted to and returned as an integer. """ def myAtoi(str) -> int: """Strips string of white space characters and searches for strings that may only start with 0 or 1 '+' or '-' signs followed by and ending with digits. If the pattern is found, returns the integer or the max or min if it exceed 2**31 - 1 or -2**31. """ str = str.strip() pattern = r"^[+-]?\d+" if re.search(pattern=pattern, string=str): num = re.search(pattern=pattern, string=str).group() return max(-pow(2, 31), min(pow(2, 31) - 1, int(num))) else: return 0 def myAtoi2(str) -> int: """Another possible solution similar to above but utilizes if statements to determine which int value to return. """ int_max = 2**31 - 1 int_min = -2**31 str = str.strip() pattern = re.compile('^[+-]?\d+') result = re.search(pattern, str) if result: num = int(result[0]) if num > int_max: return int_max elif num < int_min: return int_min else: return num else: return 0 if __name__ == '__main__': test = Solution() result = test.myAtoi(" 42") print(result)
true
d42c35cf40853e6e1b60742c5c8aadf0a840d573
returnzero1-0/logical-programming
/sp-7.py
315
4.21875
4
# Python Program to Read Two Numbers and Print Their Quotient and Remainder ''' Quotient by floor division // Remainder by mod % ''' num1=int(input("Enter number 1 :")) num2=int(input("Enter number 2 :")) quotient=num1//num2 remainder=num1%num2 print("Quotient is :",quotient) print("Remainder is :",remainder)
true
533516eaf7b44a007b79a9f00e283bfd865ad017
friedaim/ITSE1359
/PSET4/PGM1.py
1,934
4.125
4
# Program to calculate loan interest, # monthly payment, and overall loan payment. def calcLoan(yrRate,term,amt): monthRate = yrRate/12 paymentNum = (pow(1+monthRate,term)*monthRate) paymentDen = (pow(1+monthRate,term)-1) payment = (paymentNum/paymentDen)*amt paybackAmt = payment*term totalInterest = paybackAmt-amt print(f""" Loan Amount: ${amt} Annual Interest Rate: {round(yrRate*100,2)}% Number of Payments: {term} Montly Payment: ${round(payment,2)} Amount Paid Back: ${round(paybackAmt,2)} Interest Paid: ${round(totalInterest,2)}""") print("Loan Calculator Program- Type 'help' for help.") while True: command = input("Enter Command: ") if(command=="exit"): break # Help menu if(command=="help"): print(""" ----------- Available commands: 'help' - displays this menu 'loan' - calculate a loan payment 'exit' - leave the program ----------- """) # Loan calculations and input validation if(command == "loan"): rate = 0 term = 0 amount = 0 while True: # Use try catch for taking only the corrent input try: rate = float(input("What is the yearly interest rate? ")) except: continue break #rate = float(input("What is the yearly interest rate? " #"(exclude % sign) ")) while True: try: term = int(input("What is the loan term (months)? ")) except: continue break while True: try: amount = float(input("What is the total amount for the loan? $")) except: continue break rate = rate/100 calcLoan(rate,term,amount)
true
532eb7059007dab0ce39b0e7a53559d12c696d86
mjadair/intro-to-python
/functions/arguments.py
1,473
4.375
4
# Navigate to functions folder and type python arguments.py to run # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Define a function "sayHello" that accepts a "name" parameter. It should return a string of 'Hello (the name)!' # ? Call and print the result of the function twice, passing different "name" arguments. # ? Define a function "add" that accepts two numbers, "a" and "b" as parameters. It should return the result of adding them together # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "wordLength" that takes a string as a parameter, it should return a number of the length of that passed string # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "shout" that accepts two strings as parameters. It should return the strings joined together in all uppercase eg 'hello', 'world' --> 'HELLOWORLD' # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "findCharacterIndex" that accepts two parameters, a string, and a number. The function should return the character in the passed string found at the passed index number. If the index to return is longer than the string, it should return the string 'Too long' # ? Call and print the result of the function a few times, passing different arguments.
true
485f7f408cbe0ba4f7ed22f940dfe1da28fc18b4
mjadair/intro-to-python
/control-flow/loops.py
1,190
4.1875
4
# * ----- FOR LOOPS ------ * # ! Navigate to the directory and type `python loops.py` to run the file # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Write a for loop that prints the numbers 0 - 10 # ? Write a for loop that prints the string 'Hello World' 10 times # ? Write a for loop that prints the numbers 50 to 88 # ? BONUS - Declare a "let" with the label "result" and the value empty string. # ? use a for loop and string concatenation to built the string '123456789' and print it to the console # * ----- WHILE LOOPS ------ * # ! Remember, run`python loops.py` to run the file # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Write a while loop that prints the numbers 0 - 10 # ? Write a while that prints the string 'Hello World' 5 times # ? BONUS - Write a while loop that will check if a random number is above or below 0.5, If it is the loop should print 'still running!' and the random number. When it has finished, it should print 'Stopped', and the randomNumber is stopped with. How many times will this log print?
true
afca7c31b72f51f3cf3b96c33dcf0e9da76a4f39
Zahidsqldba07/Python_Practice_Programs
/college/s3p4.py
235
4.1875
4
# WAP to find largest and smallest value in a list or sequence nums = [] n = int(input("How many numbers you want to input? ")) for i in range(n): nums.append(int(input(">"))) print("Max: %d\nMin: %d" % (max(nums), min(nums)))
true
1d91eda9d5e992d2ba82dd74cec9586b5d0c58b4
Zahidsqldba07/Python_Practice_Programs
/college/p7.py
279
4.375
4
# WAP to read a set of numbers in an array & to find the largest of them def largest(arr): return max(arr) arr = list() num = input("How many elements you want to store? ") for i in range(int(num)): num = input("Num: ") arr.append(int(num)) print(largest(arr))
true
6c39bdf7ab868326265d9724569004623651d493
Zahidsqldba07/Python_Practice_Programs
/college/s2p7.py
269
4.125
4
# WAP that demonstrates the use break and continue statements to alter the flow of the loop. while True: name = str(input("Name: ")) if name.isalpha(): print("Hello %s" % name) break else: print("Invalid name.\n") continue
true
b2cece558ed3391220af52e1e13b2329bca82ab3
Zahidsqldba07/Python_Practice_Programs
/college/s8p2.py
358
4.1875
4
# Define a class name circle which can be constructed using a parameter radius. # The class has a method which can compute the area using area method. class Circle: radius = 0 def __init__(self, radius): self.radius = radius def displayArea(self): print("Area:", (3.14 * (self.radius ** 2))) a1 = Circle(5) a1.displayArea()
true
6a77a5bca7b96861c6bbd9404ebc467afd28d470
kokilavemula/python-code
/inheritances.py
922
4.25
4
#Create a Parent Class class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("kokila", "vemula") x.printname() #Create a child class class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): pass x = Student("Mysore", "palace") x.printname() #super() Function class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) x = Student("vemula", "kokila") x.printname()
true