blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
73601e344b62ecc1b895c7485c0654c73927cb81
sanket-qp/IK
/3-Recursion/strings_from_wildcard.py
2,544
4.34375
4
""" You are given string s of length n, having m wildcard characters '?', where each wildcard character represent a single character. Write a program which returns list of all possible distinct strings that can be generated by replacing each wildcard characters in s with either '0' or '1'. Any string in returned list must not contain '?' character i.e. you have to replace all '?' with either '0' or '1'. Sample Test Case 1: Sample Input 1: s = "1?10" Sample Output 1: result = ["1010", "1110"] or ["1110", "1010"]. Explanation 1: "?" at index 1 (0 based indexing) can be replaced with either '0' or '1'. So, generated two strings replacing "?" with '0' and '1'. Sample Test Case 2: Sample Input 2: s = "1?0?" Sample Output 2: result = ["1000", "1001", "1100", "1101"] or any other list having same strings but in different order. Explanation 2: Input string have two '?' characters. Each one can be replaced with either '0' or '1'. So, total 2*2 strings are possible as ('?' at index 1, '?' at index 3) can be replaced with ('0','0'), ('0','1'), ('1', '0'), ('1', '1'). Approach: We find the first wild card character in the string and explore two branches by placing '0' and '1' on that index and recursively calling the function on those branches once we are done from both the branches, we should put back the wildcard so that remaining branches can be explored """ def __strings_from_wildcard(s, idx, wildcard, result): if idx == len(s): result.append("".join(s)) return if s[idx] != wildcard: __strings_from_wildcard(s, idx + 1, wildcard, result) else: s[idx] = '0' __strings_from_wildcard(s, idx + 1, wildcard, result) s[idx] = '1' __strings_from_wildcard(s, idx + 1, wildcard, result) # backtrack the wildcard after exploring both possibilities so that # other branches can be explored s[idx] = wildcard def strings_from_wildcard(s, wildcard): result = [] __strings_from_wildcard(list(s), 0, wildcard, result) return result def main(): wildcard = '?' s = "??" actual = strings_from_wildcard(s, wildcard) assert 4 == len(actual) assert ["00", "01", "10", "11"] == actual s = "1?0?" actual = strings_from_wildcard(s, wildcard) assert 4 == len(actual) assert ["1000", "1001", "1100", "1101"] == actual s = "1?0?1?" actual = strings_from_wildcard(s, wildcard) assert 8 == len(actual) if __name__ == '__main__': main()
true
91acc9bd925f21654d1992dc9048232b8a8482c6
duhjesus/practice
/hackerrank/countingInversions.py
2,916
4.25
4
#!/bin/python3 import math import os import random import re import sys # function: helper function # merges left and right half arrays in sorted order # input:nums= array to be sorted # temp= place holder array, hard to do inplace sorting # leftStart = start index of the left half array # rightEnd = end index of the right half array # ouput: none # effect: sorts portion of nums array def mergeHalves(nums, temp, leftStart,rightEnd): leftEnd = leftStart+ (rightEnd-leftStart)//2 #middle rightStart = leftEnd +1 # middle +1 size = rightEnd -leftStart +1 left = leftStart right = rightStart index = leftStart cnt = 0 #comparing elements of the two halves #smaller element of the two taken and copied into temp array #then the array's(that the smaller element was in) ptr is incremented #compared again until you reach the end of one of the arrays first while(left <= leftEnd and right<=rightEnd): if nums[left] <=nums[right]: temp[index]=nums[left] left =left +1 else: temp[index] = nums[right] right = right +1 cnt = cnt + leftEnd+1 -left index = index +1 # recall python array slices go from left index : to right index (not inclusive on the right end) # only one or the other of the halves will have remaining elements so only one of the two following lines # will have an effect # copying remaining elements of left half and right half temp[index:index + leftEnd-left+1]=nums[left:left +leftEnd-left+1] temp[index:index + rightEnd-right+1]=nums[right: right +rightEnd-right+1] nums[leftStart:leftStart+size]=temp[leftStart:leftStart+size] #print("result:",nums) return cnt def mergesort(nums, temp, leftStart, rightEnd): if leftStart >= rightEnd: return 0 middle = leftStart+ (rightEnd-leftStart)//2 #written like this b/c (leftstart+rightend )/2 <-overflows cntl = mergesort(nums,temp,leftStart,middle) cntr = mergesort(nums,temp,middle+1,rightEnd) cntm = mergeHalves(nums,temp, leftStart,rightEnd) return cntl+cntr+cntm # Complete the countInversions function below. def countInversions(arr): temp = list(0 for i in range(0,len(arr))) theCnt =mergesort(arr,temp,0,len(arr)-1) return theCnt if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) arr = list(map(int, input().rstrip().split())) success = True for i in range(0,len(arr)-1-1): if arr[i]<= arr[i+1]: continue else: success =False break if success == True: result = 0 else: result = countInversions(arr) fptr.write(str(result) + '\n') fptr.close()
true
c393f87657b09fc9fb90621ef0d6ffe8eef1c47d
ErikBrany/python-lab2
/Lab 2_Exercise 2.py
914
4.125
4
from sys import task_list print(sorted(task_list)) index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: ")) while index != 4: if index == 1: new_list = input("What task would you like to add: ") task_list.append(new_list) index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: ")) elif index == 2: remove_list = input("What task would you like to remove: ") task_list.remove(remove_list) index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: ")) elif index == 3: task_list.sort() print(task_list) index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
true
80c06bb6aeb90514d45d55fd50a8459630e99056
Arboreus-zg/Unit_converter
/main.py
642
4.53125
5
print("Hello! This is unit converter. It will convert kilometers into miles. Just follow instruction on screen") while True: kilometers = float(input("Enter a number in kilometers: ")) conv_fac = 0.621371 miles = kilometers * conv_fac print("Your kilometers converted into miles are: ", miles) #Ovo dalje od 10-tog reda nisam znao sam rijesiti odnosno kopirao sam iz ponuđenog rješenja.. choice = input("Would you like to do another conversion (y/n): ") if choice.lower() != "y" and choice.lower() != "yes": print("Thank you for using the converter") break
true
e78ef7ff493875a8789ac1022917b9208ba1aadc
siddeshgr/python-practice
/main.py
1,599
4.21875
4
#1 print("hello world") name = input("enter your name: ") print("hello siddesh") #1 variables in python x = 100 y = 100 z = 200 print(x,y,z) #2 float [float] x1 = 20.20 y1 = 30.30 print(x1,y1) name = "hello" print("single character",name[1]) name = "hello" print("snigle character",name[3]) # Conditions for variable name # 1. Variable should not starts with number # 2. Should not contain space # 3. Should not contain special characters # Rules for long variable name PEP8 # 1. Single word # a. Name -- correct # b. name -- correct # c. namE -- wrong # 2. More than one word # a. FullName -- correct -- Title Case # b. Full_Name -- correct # c. full_name -- correct #3 string indexing name ="hello world" length =len(name) print("length of string;",length) print("single character;",name[3]) print("multiple chatrater",name[0:3]) print("mulitiple character;",name[0:4]) print("multiple charater;",name[2:5]) print("multiple charatrer start to end;",name[2::]) print("last element:",name[-1]) print("multiple last elements:",name[:-3]) #4 boolean #value = true #negative = false # basic maths operators ( + , - , * ,/ , % , //) # basic maths print("x= ",x) print("y= ",y) #A addition x = 40 y = 25 z = x+y print("addition ",z) #B substraction sub = x-y print("substraction",sub) #C multiplication mul = x*y print("multiplication",mul) #D dividion div = x/y print("dividion",div) #E modulus x1= 5 y1 = 2 mod = x1%y1 print("modulus",mod) #F division div = x//y print("division",div)
true
652ab15329f9c2dbf8ddc7f2053cbea0fe987617
earamosb8/holbertonschool-web_back_end
/0x00-python_variable_annotations/7-to_kv.py
305
4.125
4
#!/usr/bin/env python3 """ Module - string and int/float to tuple """ from typing import Union, Tuple def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]: """function to_kv that takes a string k and an int OR float v as arguments and returns a tuple.""" return (k, v * v)
true
1e7d3ef971b8905b62be1a515dc9b82b24502def
earamosb8/holbertonschool-web_back_end
/0x00-python_variable_annotations/3-to_str.py
224
4.15625
4
#!/usr/bin/env python3 """ Module - to string """ def to_str(n: float) -> str: """function to_str that takes a float n as argument and returns the string representation of the float.""" return str(n)
true
4693a753a7e8f36f6f7c8e7f051c3e1a345ca0cd
Moussaddak/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
317
4.3125
4
#!/usr/bin/python3 """ Method """ def append_write(filename="", text=""): """ appends a string at the end of a text file (UTF8) and returns the number of characters added: """ with open(filename, mode='a', encoding='utf-8') as file: nb_char = file.write(text) return nb_char
true
990e1956b147a5641d1bb759ddcb99da0ba470fc
SvWer/MultimediaInteractionTechnologies
/05_Excercises03_12/02.py
637
4.3125
4
#Write a Python program to calculate number of days between two dates. Sample dates: (2019, 7, 2) (2019, 7, 11) from datetime import date from datetime import timedelta if __name__ == '__main__': date1 = input("What is the first date (dd.mm.jjjj)") print("Date 1: ", date1) day1, month1, year1 = map(int, date1.split('.')) d1 = date(year1, month1, day1) date2 = input("What is the second date (dd.mm.jjj)") print("date 2: ", date2) day2, month2, year2 = map(int, date2.split('.')) d2 = date(year2, month2, day2) delta = d1 - d2 if (delta.days < 0): delta *= -1 print("Day difference between the two dates: ", delta.days)
true
58b4ca15f45d8c5400b683b9a9ddbbddb159b816
pniewiejski/algorithms-playground
/data-structures/Stack/bracket_validation.py
955
4.21875
4
# Task: # You are given a string containing '(', ')', '{', '}', '[' and ']', # check if the input string is valid. # An input string is valid if: # * Open brackets are closed by the same type of brackets. # * Open brackets are closed in the correct order. from collections import deque OPENING_BRACKETS = ['(', '[', '{'] ALLOWED_CLOSING = { ')': ['(', '}', ']'], ']': ['[', '}', ')'], '}': ['{', ']', ')'] } def validate_brackets(string): stack = deque() for symbol in string: if symbol in OPENING_BRACKETS: stack.append(symbol) else: bracket = stack.pop() if bracket == ALLOWED_CLOSING[symbol]: return False return len(stack) == 0 if __name__ == "__main__": print(validate_brackets("[()({})]")) # Expect True print(validate_brackets("[(())({})]{")) # Expect False print(validate_brackets("[(()({})]{}")) # Expect False
true
3c4465418f980be01250fa017db3031a6a69e33b
barenzimo/Basic-Python-Projects
/2-tipCalculator(2).py
410
4.28125
4
#A simple tip calculator to calculate your tips print("Welcome to the tip calculator \n") bill=float(input("What was the total bill paid? $")) tip_percent=float(input("What percentage of bill would you like to give? 10, 12 or 15? ")) people=int(input("How many people are splitting the bill? ")) total=float(bill+(bill*tip_percent/100)) answer=round(total/people,2) print(f"Each person should pay ${answer}")
true
0a08293e35d0d181b03ef54814b13f75e8748f6f
chrihill/COM170-Python-Programming
/Program1.py
590
4.21875
4
# Christian Hill #Program Assignment 1 #COMS-170-01 #Display basic information about a favorite book #Variabels: strName - my name, strBookName - stores book name, strBookAuthor - author name, strDate - copy right date, strPage - number of pages strName = 'Christian Hill' strBookName = 'The Fall of Reach' strBookAuthor = 'Eric Nylund' strDate = '2001' strPage = '365 pages' #Display Infoormation about me print ('My name is ' + strName) print ('My favorite book is ' + strBookName) print ('written by ' + strBookAuthor) print ('It was written in ' + strDate) print ('It has ' + strPage)
true
a25c3917dfc3fd580e9bcb107df8a50c0e9719ff
alliequintano/triangle
/main.py
1,412
4.1875
4
import unittest # Function: triangle # # Given the lengths of three sides of a triangle, classify it # by returning one of the following strings: # # "equ" - The triangle is equilateral, i.e. all sides are equal # "iso" - The triangle is isoscelese, i.e. only two sides are equal # "sca" - The triangle is scalene, i.e. no sides are equal # "err" - The arguments do not describe a valid triangle # def triangle(a, b, c): for item in a, b, c: if not isinstance(item, int) and not isinstance(item, float): return "err" if (item <= 0): return "err" listOfSides = sorted([a, b, c]) if (listOfSides.pop() > sum(listOfSides)): return "err" if (a == b and b == c): return "equ" if (a == b or a == c or b == c): return "iso" return "sca" class Tests(unittest.TestCase): def testTriangle(self): self.assertEqual('equ', triangle(1, 1, 1)) self.assertEqual('iso', triangle(1, 1, 2)) self.assertEqual('iso', triangle(1, 2, 2)) self.assertEqual('sca', triangle(1, 2, 3)) self.assertEqual('err', triangle(1, 1, "x")) self.assertEqual('err', triangle(1, -1, 1)) self.assertEqual('iso', triangle(1/6, 1, 1)) self.assertEqual('sca', triangle(1, 1.5, 2)) self.assertEqual('err', triangle(1, 2, 4)) # handle zero length unittest.main()
true
808e12eef51c92d2ef004a9b39a638b1e5334fd4
Tometoyou1983/Python
/Automate boring stuff/collatz.py
2,119
4.1875
4
''' import os, sys os.system("clear") print("Lets introduce you to collatz sequence or problem") print("its an algorithm that starts with an integer and with multiple sequences reaches at 1") numTries = 0 accumlatedNum = "" newNumber = 0 def collatz(number): if number % 2 == 0: newNumber = number // 2 else: newNumber = 3 * number + 1 return newNumber try: while True: myInteger = int(input("Enter a integer: ")) while (newNumber != 1): newNumber = collatz(myInteger) numTries = numTries + 1 if accumlatedNum == "": accumlatedNum = accumlatedNum + str(newNumber) else: accumlatedNum = accumlatedNum + ", " + str(newNumber) myInteger = newNumber print("It took " + str(numTries) + " tries to come to 1") print("the sequence is: " + accumlatedNum) playAgain = input("Would you like to play again? (Yes/No) ") if playAgain == "Yes": continue else: sys.exit() except ValueError: print("You did not enter an integer") myInteger = input("Enter a valid integer: ") ''' import os, sys os.system("clear") print("Lets introduce you to collatz sequence or problem") print("its an algorithm that starts with an integer and with multiple sequences reaches at 1") def collatz(number): count = 0 print(str(number)) if number == 1: return count elif (number % 2 == 0): count = (collatz(int(number /2)) + 1) elif (number % 2 != 0): count = (collatz(int(3 * number + 1)) + 1) return count try: while True: myInteger = int(input("Enter a integer: ")) numTries = collatz(myInteger) print("It took " + str(numTries) + " tries to come to 1") playAgain = input("Would you like to play again? (Yes/No) ") if playAgain == "Yes": continue else: sys.exit() except ValueError: print("You did not enter an integer") myInteger = input("Enter a valid integer: ")
true
b4b469aeb580da7bf9a83b6b1b3c64a967cd3dc8
Turhsus/coding_dojo
/python/bike.py
736
4.21875
4
class Bike(object): def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print "Price:", self.price, "Dollars; Max Speed:", self.max_speed, "MPH; Miles:", self.miles return self def ride(self): print "Riding" self.miles += 10 return self def reverse(self): if (self.miles > 0): print "Reversing" self.miles -= 5 return self else: print "Cannot Reverse!" return self motorbike = Bike(1000, 100) bicycle = Bike(200, 25) tricycle = Bike (500, 20) motorbike.ride().ride().ride().reverse().displayInfo() bicycle.ride().ride().reverse().reverse().displayInfo() tricycle.reverse().reverse().reverse().displayInfo()
true
740de0cb3d6afbb7c3b28752d15a1e7bdb751a12
Breenori/Projects
/FH/SKS3/Units/urlParser/sqlite/sqlite.py
570
4.15625
4
import sqlite3 connection = sqlite3.connect('people.db') cursor = connection.cursor() cursor.execute("create table if not exists user(id integer primary key autoincrement, name text, age integer)") cursor.execute("insert into user values (NULL, 'sebastian pritz', 22)") #1 cursor.execute("select * from user") row = cursor.fetchone() print(row[0]) print(row[1]) print(row[2]) #2 for rows in cursor.execute("select * from user"): print(rows) #3 liste = cursor.execute("select * from user").fetchall() print(liste) cursor.close() connection.commit() connection.close()
true
32d6d978ce4af56dd6ce8870450a4abe1addfd7e
MaxBI1c/afvinkopdracht-3-goed
/afvinkopdracht 3 opdracht 2 opdracht 2.py
762
4.21875
4
lengthrectangle_one = int(input('What is the length of the first rectangle?')) widthrectangle_one = int(input('What is the width of the first rectangle?')) lengthrectangle_two = int(input('What is the length of the second rectangle?')) widthrectangle_two = int(input('What is the width of the second rectangle?')) area_rectangle_one = lengthrectangle_one * widthrectangle_one area_rectangle_two = lengthrectangle_two * widthrectangle_two if area_rectangle_one > area_rectangle_two : print('The first rectangle has a bigger area than the second rectangle') elif area_rectangle_two < area_rectangle_one : print('The second rectangle has a bigger area than the first rectangle') else: print('Both rectangles have the same area')
true
b6f58732445c87338e5722342ab1cb8b26965886
mac95860/Python-Practice
/working-with-zip.py
1,100
4.15625
4
list1 = [1,2,3,4,5] list2 = ['one', 'two', 'three', 'four', 'five'] #must use this syntax in Python 3 #python will always trunkate and conform to the shortest list length zipped = list(zip(list1, list2)) print(zipped) # returns # [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')] unzipped = list(zip(*zipped)) print(unzipped) # returns # [(1, 2, 3, 4, 5), ('one', 'two', 'three', 'four', 'five')] # for (l1 , l2) in zip(list1, list2): # print(l1) # print(l2) items= ['Apple', 'Banana', 'Orange'] counts = [3,2,5] prices = [0.99, 0.25, 0.50] sentences = [] for (item, count, price) in zip(items, counts, prices): item, count, price = str(item), str(count), str(price) sentence = "I bought " + count + ' ' + item + 's at ' + price + '.' sentences.append(sentence) # by not indenting the print statement, the statement has been moved outside of the for loop print(sentences) # returns # [ # 'I bought 3 Apples at 0.99.', # 'I bought 2 Bananas at 0.25.', # 'I bought 5 Oranges at 0.5.' # ] for sentence in sentences: print(sentence)
true
e6edf7e821959e69ebfbd514bfd6ebed4d6a3504
taozhenting/python_introductory
/name_cases.py
542
4.3125
4
#练习 name="eric" print('"Hello '+name.title()+',would you like to learn some Python today?"') print(name.title()) print(name.upper()) print(name.lower()) print('Albert Einstein once said, "A person who never made a mistake never tried anything new."') famous_person='Albert Einstein' message=famous_person + ' once said, "A person who never made a mistake never tried anything new."' print(message) name='\teric\t' print(name.lstrip()) print(name.rstrip()) print(name.strip()) name='\neric\n' print(name.lstrip()) print(name.rstrip()) print(name.strip())
true
78de74417139d34d6197348884cc2fb504b37223
taozhenting/python_introductory
/6-3/favorite_languages.py
1,303
4.15625
4
favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } #遍历字典 for name,language in favorite_languages.items(): print(name.title() + "'s favorite language is" + language.title() + ".") #遍历字典中的所有键 for name in favorite_languages.keys(): print(name.title()) #判断朋友并打印 friends = ['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print("Hi " + name.title() + ",I see your favorite language is " + favorite_languages[name].title() + "!") #判断某人是否接受调查 if 'erin' not in favorite_languages.keys(): print("Erin,please take our poll!") #字典的键排序 for name in sorted(favorite_languages.keys()): print(name.title() + ",thank you for taking the poll.") #遍历字典中的所有值 favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } print("The following languages have been mentioned:") for language in favorite_languages.values(): print(language.title()) #剔除重复的值(set集合) print("The following languages have been mentioned:") for language in set(favorite_languages.values()): print(language.title())
true
60a3272b25d14ce17af91e2ba41803ba7e48e2c7
IgorGarciaCosta/SomeExercises
/pyFiles/linkedListCycle.py
1,354
4.15625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new # node at the beginning def push(self, new_data): new_node = ListNode(new_data) new_node.next = self.head self.head = new_node # Utility function to print it # the linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next def hasCycle(self) -> bool: s = set() temp = self.head while(temp): if(temp in s): return True s.add(temp) temp = temp.next return False # Driver program for testing llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(10) # Create a loop for testing llist.head.next.next.next.next = llist.head if(llist.hasCycle()): print("Loop found") else: print("No Loop ") # class Solution: # def hasCycle(self, head: ListNode) -> bool: # s = set() # temp = head # while(temp): # if(temp in s): # return True # s.add(temp) # temp = temp.next # return False
true
870dbcb30b9da785f1d82032c62171974f1fc6c0
cdhutchings/csv_read_write
/csv_example.py
796
4.125
4
import csv # Here we load the .csv """ -open file -read line by line -separate by commas """ # with open("order_details.csv", newline='') as csv_file: # csvreader = csv.reader(csv_file, delimiter = ",") # print(csvreader) # # for row in csvreader: # print(row) # # iter() creates an iterable object # next() goes to the next line # with open("order_details.csv", newline='') as csv_file: # csvreader = csv.reader(csv_file, delimiter=",") # # iterable = iter(csvreader) # headers = next(iterable) # # for row in iterable: # print(row) # # list() with open("order_details.csv", newline='') as csv_file: csvreader = csv.reader(csv_file, delimiter=",") for list in list(csvreader): print(list) # Transforming and writing to CSV
true
b27ac5eca6442e9a0b09ef30d9836475deb593c3
mzkaoq/codewars_python
/5kyu Valid Parentheses/main.py
297
4.1875
4
def valid_parentheses(string): left = 0 right = 0 for i in string: if left - right < 0: return False if i == "(": left += 1 if i == ")": right += 1 if left - right == 0: return True else: return False
true
211faf6de66a218395512c29d17865aa5d5b38a3
PhiphyZhou/Coding-Interview-Practice-Python
/Cracking-the-Coding-Interview/ch9-recursion-DP/s9-1.py
763
4.3125
4
# 9.1 A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 # steps at a time. Implement a method to count how many possible ways the child can run up # the stairs. def count(n): mem = [None]*n return count_hop_ways(n, mem) def count_hop_ways(n, mem): if n == 0: return 1 counter = 0 for i in range(1,4): if n >= i: if mem[n-i] == None: mem[n-i] = count_hop_ways(n-i,mem) counter += mem[n-i] return counter print count(0) # 1 print count(1) # 1 print count(2) # 2 print count(3) # 4 print count(4) # 7 print count(100) # 180396380815100901214157639 # The count for step n is just the sum of the previous 3 counts.
true
220d4effabcc190fcd8690810724521ef9641da6
PhiphyZhou/Coding-Interview-Practice-Python
/HackerRank/CCI-Sorting-Comparator.py
1,213
4.25
4
# Sorting: Comparator # https://www.hackerrank.com/challenges/ctci-comparator-sorting # Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below; it has two fields: # # A string, . # An integer, . # Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return (self.name, self.score) def comparator(a, b): return cmp((-a.score,a.name), (-b.score,b.name)) n = int(raw_input()) data = [] for i in range(n): name, score = raw_input().split() score = int(score) player = Player(name, score) data.append(player) data = sorted(data, cmp=Player.comparator) for i in data: print i.name, i.score
true
d7de4f27b05171c1a29e6fd4f1b0fab5e872dbaf
AnshumanSinghh/DSA
/Sorting/selection_sort.py
864
4.28125
4
def selection_sort(arr, n): for i in range(n): min_id = i for j in range(i + 1, n): if arr[min_id] > arr[j]: min_id = j arr[min_id], arr[i] = arr[i], arr[min_id] return arr # Driver Code Starts if __name__ == "__main__": arr = list(map(int, input("Enter the array elements: ").split())) print(selection_sort(arr, len(arr))) """ Time Complexity: O(n2) as there are two nested loops. Auxiliary Space: O(1) The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. Exercise : Sort an array of strings using Selection Sort Stability : The default implementation is not stable. However it can be made stable. Please see stable selection sort for details. In Place : Yes, it does not require extra space. """
true
d124e426fc4a6f6f42c2942a8ce753e31c07ba56
AnniePawl/Tweet-Gen
/class_files/Code/Stretch_Challenges/reverse.py
1,036
4.28125
4
import sys def reverse_sentence(input_sentence): """Returns sentence in reverse order""" reversed_sentence = input_sentence[::-1] return reversed_sentence def reverse_word(input_word): """Returns word in reverse order""" reversed_word = input_word[::-1] return reversed_word def reverse_reverse(input): """Returns words AND sentence in reverse order""" # Call reverse_sentence func, put words in new variable (type list) reverse_input = reverse_sentence(input) # Initialize new list to hold reversed newly words reverse_list = [] # Iterate over each word in list, call reverse_word func for word in reverse_input: backwards_word = reverse_word(word) reverse_list.append(backwards_word) return " ".join(reverse_list) if __name__ == '__main__': # input_word = sys.argv[1:] # print(reverse_word(input_word)) # input_sentence = sys.argv[1:] # print(reverse_sentence(input_sentence)) input = sys.argv[1:] print(reverse_reverse(input))
true
5428b2f9dce1f91420c57963dcd1e80275e3c6cb
AnniePawl/Tweet-Gen
/class_files/Code/rearrange.py
864
4.125
4
import sys import random def rearrange_words(input_words): """Randomly rearranges a set of words provided as commandline arguments""" # Initiate new list to hold rearranged words rearranged_words = [] # Randomly place input words in rearranged_words list until all input words are used while len(rearranged_words) < len(input_words): rand_index = random.randint(0, len(input_words) - 1) rand_word = input_words[rand_index] # Skip words that have already been seen if rand_word in rearranged_words: continue rearranged_words.append(rand_word) # Turn list into a nicely formatted string result = ' '.join(rearranged_words) return result if __name__ == '__main__': # remember argument one is file name! input_words = sys.argv[1:] print(rearrange_words(input_words))
true
f76a969859f8cdbfedb6a147d505ae1fc788dc19
Chris-Valenzuela/Notes_IntermediatePyLessons
/4_Filter.py
664
4.28125
4
# Filter Function #4 # Filter and map are usually used together. The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not. # filter(function, iterable) - takes in the same arguements as map def add7(x): return x+7 def isOdd(x): return x % 2 != 0 a = [1,2,3,4,5,6,7,8,9,10] # this is useful because we can do this instead of running a for loop with conditions b = list(filter(isOdd, a)) print(b) # here we are adding 7 to each filterd list c = list(map(add7, filter(isOdd, a))) print(c) # Use Case: We can use filter to return things that have a certain digit or string etc..
true
df1920f69ffd2cab63280aa8140c7cade46d6289
bhavyanshu/PythonCodeSnippets
/src/input.py
1,297
4.59375
5
# Now let us look at examples on how to ask the end user for inputs. print "How many cats were there?", numberofcats = int(raw_input()) print numberofcats # Now basically what we have here is that we take user input as a string and not as a proper integer value as # it is supposed to be. So this is a major problem because you won't be able to apply any kind of math operation on string type value. # Now in the next example i will show you how to accept a string from user and let python convert it to an integer type value. print "How many kittens were there?", numberofkittens = int(raw_input()) print numberofkittens # What's the difference between input() and raw_input()? # The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it. #There is an easier way to write the above input prompter in single line. Let's take a look" numberofDogs= int(raw_input("Total number of Dogs?")) #Easy, isn't it? print numberofDogs print "*********************Let us now print the input data******************" print "*Number of cats are %d, number of kittens are %d & number of dogs are %d"%(numberofcats,numberofkittens,numberofDogs)+"*" print "**********************************************************************"
true
c0c986476ddb5849c3eb093487047acb2a8cadec
jlassi1/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
413
4.34375
4
#!/usr/bin/python3 """module""" def append_write(filename="", text=""): """function that appends a string at the end of a text file (UTF8) and returns the number of characters added:""" with open(filename, mode="a", encoding="UTF8") as myfile: myfile.write(text) num_char = 0 for word in text: for char in word: num_char += 1 return num_char
true
8583fccda88b05dd25b0822e1e403de2ad64af11
Sisyphus235/tech_lab
/algorithm/tree/lc110_balanced_binary_tree.py
2,283
4.40625
4
# -*- coding: utf8 -*- """ Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_balanced_recursive1(root: TreeNode) -> bool: if root is None: return True left = get_depth(root.left) right = get_depth(root.right) if abs(left - right) > 1: return False return is_balanced_recursive1(root.left) and is_balanced_recursive1(root.right) def get_depth(node: TreeNode) -> int: if node is None: return 0 return 1 + max(get_depth(node.left), get_depth(node.right)) def is_balanced_recursive2(root: TreeNode) -> bool: if check_depth(root) == -1: return False return True def check_depth(node: TreeNode) -> int: if node is None: return 0 left = check_depth(node.left) if left == -1: return -1 right = check_depth(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 else: return 1 + max(left, right) def test_is_balanced(): root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) assert is_balanced_recursive1(root) is True assert is_balanced_recursive2(root) is True root = TreeNode(1) assert is_balanced_recursive1(root) is True assert is_balanced_recursive2(root) is True root = TreeNode(1) root.right = TreeNode(2) assert is_balanced_recursive1(root) is True assert is_balanced_recursive2(root) is True root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) assert is_balanced_recursive1(root) is False assert is_balanced_recursive2(root) is False if __name__ == '__main__': test_is_balanced()
true
3c7c978a4d753e09e2b12245b559960347972b37
Sisyphus235/tech_lab
/algorithm/tree/lc572_subtree_of_another_tree.py
1,623
4.3125
4
# -*- coding: utf8 -*- """ Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. Example 1: Given tree s: 3 / \ 4 5 / \ 1 2 Given tree t: 4 / \ 1 2 Return true, because t has the same structure and node values with a subtree of s. Example 2: Given tree s: 3 / \ 4 5 / \ 1 2 / 0 Given tree t: 4 / \ 1 2 Return false. """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def subtree_of_another_tree(s: TreeNode, t: TreeNode) -> bool: if not s: return False if is_same_tree(s, t): return True return subtree_of_another_tree(s.left, t) or subtree_of_another_tree(s.right, t) def is_same_tree(s: TreeNode, t: TreeNode) -> bool: if not s and not t: return True if not s or not t: return False if s.val != t.val: return False return is_same_tree(s.left, t.left) and is_same_tree(s.right, t.right) def test_subtree_of_another_tree(): s_root = TreeNode(3) s_root.left = TreeNode(4) s_root.right = TreeNode(5) s_root.left.left = TreeNode(1) s_root.left.right = TreeNode(2) t_root = TreeNode(4) t_root.left = TreeNode(1) t_root.right = TreeNode(2) assert subtree_of_another_tree(s_root, t_root) is True if __name__ == '__main__': test_subtree_of_another_tree()
true
1651e397c9fb56f6c6b56933babc60f97e830aac
Sisyphus235/tech_lab
/algorithm/array/find_number_occuring_odd_times.py
1,177
4.25
4
# -*- coding: utf8 -*- """ Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3} Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5} Output : 5 """ def odd_times_n_space(array: list) -> int: """ space complexity: O(n) :param array: :return: """ hash_space = {} for e in array: if e in hash_space: del hash_space[e] else: hash_space[e] = e return list(hash_space.values())[0] def odd_times_1_space(array: list) -> int: """ space complexity: O(1) XOR method, comply with commutative property :return: """ for i in range(len(array) - 1): array[i + 1] = array[i] ^ array[i + 1] return array[-1] def test_odd_times(): array = [1, 2, 3, 2, 3, 1, 3] assert odd_times_n_space(array) == 3 assert odd_times_1_space(array) == 3 array = [5, 7, 2, 7, 5, 2, 5] assert odd_times_n_space(array) == 5 assert odd_times_1_space(array) == 5 if __name__ == '__main__': test_odd_times()
true
3cc965eda451b01a9c0f8eee2f80f64ea1d902a3
Sisyphus235/tech_lab
/algorithm/tree/lc145_post_order_traversal.py
1,363
4.15625
4
# -*- coding: utf8 -*- """ Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [3,2,1] Follow up: Recursive solution is trivial, could you do it iteratively? """ from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None BUFFER = [] def post_order_traversal_recursive(root: TreeNode): if root is not None: post_order_traversal_recursive(root.left) post_order_traversal_recursive(root.right) BUFFER.append(root.val) def post_order_traversal_iterative(root: TreeNode) -> List[int]: ret = [] stack = [(root, False)] while stack: root, is_visited = stack.pop() if root is None: continue if is_visited: ret.append(root.val) else: stack.append((root, True)) stack.append((root.right, False)) stack.append((root.left, False)) return ret def test_post_order_traversal(): root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) post_order_traversal_recursive(root) assert BUFFER == [3, 2, 1] assert post_order_traversal_iterative(root) == [3, 2, 1] if __name__ == '__main__': test_post_order_traversal()
true
d7eda822fb84cd5abd4e7a66fa76eec506b09599
omarfq/CSGDSA
/Chapter14/Exercise2.py
960
4.25
4
# Add a method to the DoublyLinkedList class that prints all the elements in reverse order class Node: def __init__(self, data): self.data = data self.next_element = None self.previous_element = None class DoublyLinkedList: def __init__(self, head_node, last_node): self.head_node = head_node self.last_node = last_node def print_in_reverse(self): current_node = self.last_node while current_node.previous_element: print(current_node.data, end=' -> ') current_node = current_node.previous_element print(current_node.data, '-> None') node_1 = Node(1) node_2 = Node(2) node_3 = Node(3) node_4 = Node(4) node_1.next_element = node_2 node_2.previous_element = node_1 node_2.next_element = node_3 node_3.previous_element = node_2 node_4.previous_element = node_3 doubly_linked_list = DoublyLinkedList(node_1, node_4) doubly_linked_list.print_in_reverse()
true
3f13fa57a9d0e51fd4702c7c7814e0e277cb8f36
omarfq/CSGDSA
/Chapter13/Exercise2.py
277
4.125
4
# Write a function that returns the missing number from an array of integers. def find_number(array): array.sort() for i in range(len(array)): if i not in array: return i return None arr = [7, 1, 3, 4, 5, 8, 6, 9, 0] print(find_number(arr))
true
63226638939260126c5d1ee013b0f76e9d5f5812
Temujin18/trader_code_test
/programming_test1/solution_to_C.py
506
4.3125
4
""" C. Write a ​rotate(A, k) ​function which returns a rotated array A, k times; that is, each element of A will be shifted to the right k times ○ rotate([3, 8, 9, 7, 6], 3) returns [9, 7, 6, 3, 8] ○ rotate([0, 0, 0], 1) returns [0, 0, 0] ○ rotate([1, 2, 3, 4], 4) returns [1, 2, 3, 4] """ from typing import List def rotated_array(input_arr: List[int], key) -> List[int]: return input_arr[-key:] + input_arr[:-key] if __name__ == "__main__": print(rotated_array([3, 8, 9, 7, 6], 3))
true
ea13ba0ca0babd500a0b701db9693587830a4546
cryoMike90s/Daily_warm_up
/Basic_Part_I/ex_21_even_or_odd.py
380
4.28125
4
"""Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.""" def even_or_odd(number): if (number % 2 == 0) and (number > 0): print("The number is even") elif number == 0: print("This is zero") else: print("The number is odd") number = 5 even_or_odd(number)
true
4bb88de5f9de506d24fe0ff4acf2c43bb4bc7bca
momentum-team-3/examples
/python/oo-examples/color.py
1,888
4.3125
4
def avg(a, b): """ This simple helper gets the average of two numbers. It will be used when adding two Colors. """ return (a + b) // 2 # // will divide and round all in one. def favg(a, b): """ This simple helper gets the average of two numbers. It will be used when adding two Colors. Unlike avg, it does not round the result. """ return (a + b) / 2 def normalize_rgb(color_value: int) -> int: if color_value < 0: return 0 elif color_value > 255: return 255 else: return color_value def normalize_alpha(alpha_value: float) -> float: if alpha_value < 0.0: return 0.0 elif alpha_value > 1.0: return 1.0 else: return alpha_value class Color: """ This class represents a color in RGBA format. Because colors can be mixed to produce a new color, this class implements __add__. The __init__ method will ensure that r, g, and b are between 0 and 255, and a is between 0 and 1. """ def __init__(self, r, g, b, a=1.0): # Make sure r, g, and b are between 0 and 255 and # make sure alpha is between 0.0 and 1.0 self.r = normalize_rgb(r) self.g = normalize_rgb(g) self.b = normalize_rgb(b) self.a = normalize_alpha(a) def liked_by_bob_ross(self): return True def __add__(self, other): if not isinstance(other, Color): raise TypeError("Cannot add Color and non-Color.") else: r = avg(self.r, other.r) g = avg(self.g, other.g) b = avg(self.b, other.b) a = favg(self.a, other.a) return Color(r,g,b,a) def __repr__(self): # Delegate to __str__ return self.__str__() def __str__(self): return f"<Color r={self.r} g={self.g} b={self.b} a={self.a}>"
true
26f77ff9d2e26fe9e711f5b72a4d09aed7f45b16
gaoshang1999/Python
/leetcod/dp/p121.py
1,421
4.125
4
# 121. Best Time to Buy and Sell Stock # DescriptionHintsSubmissionsDiscussSolution # Discuss Pick One # Say you have an array for which the ith element is the price of a given stock on day i. # # If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. # # Example 1: # Input: [7, 1, 5, 3, 6, 4] # Output: 5 # # max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) # Example 2: # Input: [7, 6, 4, 3, 1] # Output: 0 # # In this case, no transaction is done, i.e. max profit = 0. import sys class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ lowest = sys.maxsize highest = 0; n = len(prices) for i in range(n): if prices[i] < lowest: lowest = prices[i] elif prices[i] - lowest > highest : highest = prices[i] - lowest return highest s = Solution() # p =[7, 1, 5, 3, 6, 4] # print s.maxProfit(p) # p =[7, 1, 5, 3, 6, 4, 7] # print s.maxProfit(p) p =[7, 1, 4, 7, 0, 2, 10] print(s.maxProfit(p)) # p = [7, 6, 4, 3, 1] # print s.maxProfit(p) # # p = [2,4,1] # print s.maxProfit(p) # # p = [3,2,6,5,0,3] # print s.maxProfit(p)
true
fe82dce52d79df152dc57e93ae6e97e9efa722e5
keerthiballa/PyPart4
/fibonacci_linear.py
856
4.3125
4
""" Exercise 3 Create a program called fibonacci_linear.py Requirements Given a term (n), determine the value of x(n). In the fibonacci_linear.py program, create a function called fibonnaci. The function should take in an integer and return the value of x(n). This problem must be solved WITHOUT the use of recursion. Constraints n >= 0 Answer below: """ n = int(input("Provide a number greater than or equal to 0: ")) def fibonacci(n): first_num=0 second_num=1 if n>=0: for i in range(1,n,1): third_num = first_num + second_num first_num = second_num second_num = third_num print(third_num) else: print("You need to provide a valid input to run the function") if n>=0 and n<=30: fibonacci(n) else: print("You need to provide a valid input to run the function")
true
fcfcbf9381003708979b90a0ca204fe54fe747cc
amit-shahani/Distance-Unit-Conversion
/main.py
1,193
4.25
4
def add_unit(list_of_units, arr): unit = str(input('Enter the new unit: ').lower()) conversion_ratio = float( input('Enter the conversion ration from metres: ')) list_of_units.update({unit: conversion_ratio}) # arr.append(unit) return list_of_units, arr def conversion(list_of_units, arr): length = float(input("Length: ")) unit = input('Unit: ').lower() if unit not in list_of_units.keys(): print("Invalid Unit.") return print([x for x in arr][:len(arr)]) targeted_unit = str(input('Targeted Unit: ')) if targeted_unit not in list_of_units.keys(): print("Invalid Unit") return else: print(float(length)*list_of_units[targeted_unit]) if __name__ == '__main__': n = int(input( 'Press 1 : For Conversion.\nPress 2 : For For adding a unit.\nPress 3 : To Exit.\n')) list_of_units = {'metres': 1, 'yard': 1.094, 'inches': 2.54, 'feet': 2.80840, 'kilometre': 0.001} arr = ['metres', 'yard', 'inches', 'feet', 'kilometre'] if(n == 1): conversion(list_of_units, arr) elif (n == 2): add_unit(list_of_units, arr) else: exit
true
a5f7e54bd93e3445690ab874805e4e57005cecde
galhyt/python_excercises
/roads.py
2,852
4.125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'numberOfWays' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY roads as parameter. # # returns the number of ways to put 3 hotels in three different cities while the distance between the hotels is equal def numberOfWays(roads): # Write your code here print(roads) dist_dict = {} def set_dist_dict(new_key, key): dist_dict[new_key] = dist_dict[key] + 1 if new_key not in dist_dict.keys() else min(dist_dict[new_key], dist_dict[key] + 1) def check_key(r): keys = [(min(key), max(key)) for key in dist_dict.keys()] new_keys = [] for key in keys: if r[0] not in key and r[1] not in key: continue if r[0] == key[1]: if key[0] != r[1]: new_key = (min(key[0], r[1]), max(key[0], r[1])) set_dist_dict(new_key, key) new_keys.append(new_key) if r[0] == key[0]: if key[1] != r[1]: new_key = (min([key[1], r[1]]), max([key[1], r[1]])) set_dist_dict(new_key, key) new_keys.append(new_key) if r[1] == key[0]: if r[0] != key[1]: new_key = (min([r[0], key[1]]), max([r[0], key[1]])) set_dist_dict(new_key, key) new_keys.append(new_key) if r[1] == key[1]: if r[0] != key[0]: new_key = (min([r[0], key[0]]), max([r[0], key[0]])) set_dist_dict(new_key, key) new_keys.append(new_key) return new_keys for _ in range(len(roads)): for r in map(lambda x: (min(x), max(x)), roads): dist_dict[r] = 1 check_key(r) print(dist_dict) def distance(a, b): return dist_dict[(a,b)] ret = 0 n = len(roads)+1 for i in range(1,n-1): for j in range(i+1,n): for k in range(j+1, n+1): dist_ij = distance(i, j) if dist_ij == distance(i, k) and dist_ij == distance(j, k): ret += 1 return ret if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') with open("input1_roads.txt") as file: lines = file.readlines() roads_rows = int(lines[0].strip()) roads_columns = int(lines[1].strip()) roads = [] for i in range(2, len(lines)): roads.append(list(map(int, lines[i].rstrip().split()))) result = numberOfWays(roads) print(result) # fptr.write(str(result) + '\n') # # fptr.close()
true
5c23070568b655b41f55e81f65a2d5840bd9b9c8
WesRoach/coursera
/specialization-data-structures-algorithms/algorithmic-toolbox/week3/solutions/7_maximum_salary/python/largest_number.py
979
4.3125
4
from typing import List from functools import cmp_to_key def compare(s1: str, s2: str) -> int: """Returns orientation of strings producing a smaller integer. Args: s1 (str): first string s2 (str): second string Returns: int: one of: (-1, 0, 1) -1: s1 first produces smaller int 0: No difference 1: s2 first produces smaller int """ s1_first = int(s1 + s2) s2_first = int(s2 + s1) if s1_first > s2_first: return 1 elif s2_first > s1_first: return -1 else: return 0 def largest_number(a: List[str]) -> str: """Compose the largest number out of a set of integers. Args: a (List[str]): list of integers Returns: str: largest number that can be composed of `a` """ return "".join(sorted(a, reverse=True, key=cmp_to_key(compare))) if __name__ == "__main__": _ = input() print(largest_number(input().split()))
true
0b52e4ad1eef997e3a8346eb6f7ea30c4a591bb9
JankaGramofonomanka/alien_invasion
/menu.py
1,794
4.21875
4
from button import Button class Menu(): """A class to represent a menu.""" def __init__(self, screen, space=10): """Initialize a list of buttons.""" self.buttons = [] self.space = space self.height = 0 self.screen = screen self.screen_rect = screen.get_rect() #Number of selected button. self.selected = -1 def add(self, button, n = 'default'): """Add a button to menu.""" if n == 'default': n = len(self.buttons) if self.buttons: if self.selected >= n: self.selected += 1 else: self.selected = 0 self.buttons.insert(n, button) self.height = self.get_height() def remove(self, n): """Remove a button from the menu.""" self.buttons[self.selected].selected = False del self.buttons[n] self.height = self.get_height() self.selected = self.selected % len(self.buttons) self.select(self.selected) def select(self, n=0): """Select a button.""" if self.buttons: self.buttons[self.selected].selected = False self.selected = n self.buttons[n].selected = True else: self.selected = -1 def get_height(self): """Return height of all buttons.""" height = 0 if self.buttons: for button in self.buttons: height += button.height + self.space height -= self.space return height def get_top(self): """Return top of first button .""" return self.screen_rect.centery - (self.height / 2) def prep_buttons(self): """Place buttons in a right position.""" prev_button_bot = self.get_top() - self.space for button in self.buttons: button.rect.y = prev_button_bot + self.space button.prep_msg() prev_button_bot = button.rect.bottom def draw_buttons(self): """Draw all buttons from 'self.buttons'.""" self.prep_buttons() for button in self.buttons: button.draw_button()
true
ee19f685bf59a801596b6f4635944680ada27bc9
MateuszSacha/Iteration
/development exercise 1.py
317
4.3125
4
# Mateusz Sacha # 05-11-2014 # Iteration Development exercise 1 number = 0 largest = 0 while not number == -1: number = int(input("Enter a number:")) if number > largest: largest = number if number == -1: print("The largest number you've entered is {0}".format(largest))
true
8995e16a70f94eddc5e26b98d51b1e03799ef774
MateuszSacha/Iteration
/half term homework RE3.py
302
4.1875
4
# Mateusz Sacha # Revision exercise 3 total = 0 nofnumbers = int(input("How many number do you want to calculate the average from?:")) for count in range (0,nofnumbers): total = total + int(input("Enter a number:")) average = total / nofnumbers print("The average is {0}".format(average))
true
5cbed6cdc2549ec225e478fb061deeff30cf5666
lleonova/jobeasy-algorithms-course
/4 lesson/Longest_word.py
305
4.34375
4
# Enter a string of words separated by spaces. # Find the longest word. def longest_word(string): array = string.split(' ') result = array[0] for item in array: if len(item) > len(result): result = item return result print(longest_word('vb mama nvbghn bnb hjnuiytrc'))
true
04e373740e134f7b71f655c44b76bba0c51bd6a1
lleonova/jobeasy-algorithms-course
/3 lesson/Count_substring_in_the_string.py
720
4.28125
4
# Write a Python function, which will count how many times a character (substring) # is included in a string. DON’T USE METHOD COUNT def substring_in_the_string(string, substring): index = 0 count = 0 if len(substring) > len(string): return 0 elif len(substring) == 0 or len(string) == 0: return 0 while index <= len(string) - len(substring): if substring == string[index:len(substring)+ index]: count +=1 index += len(substring) index += 1 return count # s1 = input("please enter a string of characters:") # s2 = input("please enter a substring of characters:") s1 = "aabbaaabba" s2 = "aa" print(substring_in_the_string(s1, s2))
true
66db39164628280219e3849c8cddeed370915ccb
pragatirahul123/practice_folder
/codeshef1.py
206
4.1875
4
# Write a program to print the numbers from 1 to 20 in reverse order. # Output: 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 var=20 while var>=1: print(var," ",end="") var=var-1
true
a1acd77a9c1adbe44056a532909bc9378681122a
OnoKishio/Applied-Computational-Thinking-with-Python
/Chapter15/ch15_storyTime.py
781
4.1875
4
print('Help me write a story by answering some questions. ') name = input('What name would you like to be known by? ') location = input('What is your favorite city, real or imaginary? ') time = input('Is this happening in the morning or afternoon? ') color = input('What is your favorite color? ') town_spot = input('Are you going to the market, the library, or the park? ') pet = input('What kind of pet would you like as your companion? ') pet_name = input('What is your pet\'s name? ') print('There once was a citizen in the town of %s, whose name was %s. %s loved to hang \ with their trusty %s, %s.' % (location, name, name, pet, pet_name)) print('You could always see them strolling through the %s \ in the %s, wearing their favorite %s attire.' % (town_spot, time, color))
true
3cca295b200f107f100923509c3a31077be52995
akashbaran/PyTest
/github/q6.py
635
4.25
4
"""Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 """ import math C = 50 H = 30 D = raw_input("enter the values for D: ") lst = D.split(',') val = [] #print(lst) for d in lst: val.append(str(int(round(math.sqrt(2*C*float(d)/H))))) print(','.join(val))
true
b0b2d09c383a9d1354caf54eedc9d0df4a0e9d6a
akashbaran/PyTest
/github/q21.py
1,077
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed May 30 15:34:34 2018 @author: eakabar A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 """ import math l,r=0,0 while True: s = input("enter direction ") if not s: break lst = s.split(" ") dir=lst[0] pos=int(lst[1]) if dir == 'UP': r = r + pos elif dir == 'DOWN': r = r - pos elif dir == 'LEFT': l = l - pos elif dir == 'RIGHT': l = l + pos else: pass res = int(math.sqrt((l**2) + (r**2))) print(res)
true
c6e7af5146e9bcacd925ea9579dd15a8f571bfed
akashbaran/PyTest
/github/re_username1.py
405
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu May 31 12:25:27 2018 @author: eakabar Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. """ import re emailAddress = input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print(r2.group(1))
true
b761d29007cc6ccf91f4c838e7fb2f4ebc972e8f
JimNastic316/TestRepository
/DictAndSet/challenge_simple_deep_copy.py
1,020
4.375
4
# write a function that takes a dictionary as an argument # and returns a deep copy of the dictionary without using # the 'copy' module from contents import recipes def my_deepcopy(dictionary: dict) -> dict: """ Copy a dictionary, creating copies of the 'list' or 'dict' values :param dictionary: The dictionary to copy :return: a copy of dictionary, with values being copies of the original values """ # dictionary_copy = {} for key, value in dictionary.items(): new_value = value.copy() dictionary_copy[key] = new_value return dictionary_copy # create a new, empty dictionary # iterate over the keys and values of the dictionary # for each key, copy the value, # then add a copy of the value to the dictionary # test data recipes_copy = my_deepcopy(recipes) recipes_copy["Butter chicken"]["ginger"] = 300 #value is '3' in recipes print(recipes_copy["Butter chicken"]["ginger"]) print(recipes["Butter chicken"]["ginger"])
true
42455a07e117cf79b631630e7fe65f6cceaf5911
micmoyles/hackerrank
/alternatingCharacters.py
880
4.15625
4
#!/usr/bin/python ''' https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings You are given a string containing characters and only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string. Your task is to find the minimum number of required deletions. For example, given the string , remove an at positions and to make in deletions ''' s = 'AABBABAB' s = 'AAAA' s = 'AAABBB' def alternatingCharacters(s): count = i = 0 while i < len(s) - 1: j = i+1 print('Comparing element %d - %s and %d - %s' % (i,s[i],j,s[j])) while s[i] == s[j]: print('remove') count+=1 j+=1 if j >= len(s): break i = j return count print alternatingCharacters(s)
true
3a53c4f41bf1a8604ea073a17762e2dcfc39c8d8
jbsec/pythonmessagebox
/Message_box.py
598
4.21875
4
#messagebox with tkinter in python from tkinter import * from tkinter import messagebox win = Tk() result1 = messagebox.askokcancel("Title1 ", "Do you really?") print(result1) # yes = true no = false result2 = messagebox.askyesno("Title2", "Do you really?") print(result2) # yes = true no = false result3 = messagebox.askyesnocancel("Title3", "Do you really?") print(result3) # yes = true, no = false, cancel = none messagebox.showinfo("Title", "a Tk MessageBox") messagebox.showwarning("warning", "a Tk warning") messagebox.showerror("error", "a Tk error") win.mainloop()
true
a993b0b69e113eefbf033a5a6c4bbebd432ad5e9
cs-fullstack-2019-fall/codeassessment2-insideoutzombie
/q3.py
1,017
4.40625
4
# ### Problem 3 # Given 2 lists of claim numbers, write the code to merge the 2 # lists provided to produce a new list by alternating values between the 2 lists. # Once the merge has been completed, print the new list of claim numbers # (DO NOT just print the array variable!) # ``` # # Start with these lists # list_of_claim_nums_1 = [2, 4, 6, 8, 10] # list_of_claim_nums_2 = [1, 3, 5, 7, 9] # ``` # Example Output: # ``` # The newly created list contains: 2 1 4 3 6 5 8 7 10 9 # ``` # empty array to pass the data into merge_array = [] list_of_claim_nums_1 = [2, 4, 6, 8, 10] list_of_claim_nums_2 = [1, 3, 5, 7, 9] # declare a function def someFun(): # loop to cycle through the list1 array for x in list_of_claim_nums_1: # adds the array to the empty array merge_array.append(x) # loop to cycle through the list2 array for y in list_of_claim_nums_2: # adds the array to the empty array merge_array.append(y) return merge_array print(someFun())
true
af3dd2583562a8fa5f2a45dacb6eea900f1409f5
JiungChoi/PythonTutorial
/Boolean.py
402
4.125
4
print(2 > 1) #1 print(2 < 1) #0 print(2 >= 1) #1 print(2 <= 2) #1 print(2 == 1) #0 print(2 != 1) #1 print( 2 > 1 and "Hello" == "Hello") # 1 & 1 print(not True) #0 print(not not True) #1 #True == 1 print(f"True is {int(True)}") x = 3 print(x > 4 or not (x < 2 or x == 3)) print(type(3)) print(type(True)) print(type("True")) def hello(): print("Hello!") print(type(hello)) print(type(print))
true
7a93dfe5082ef046d45f4526081c317063641b66
rafal1996/CodeWars
/Remove exclamation marks.py
434
4.3125
4
#Write function RemoveExclamationMarks which removes all exclamation marks from a given string. def remove_exclamation_marks(s): count=s.count("!") s = s.replace('!','',count) return s print(remove_exclamation_marks("Hello World!")) print(remove_exclamation_marks("Hello World!!!")) print(remove_exclamation_marks("Hi! Hello!")) print(remove_exclamation_marks("")) print(remove_exclamation_marks("Oh, no!!!"))
true
4d32c35fbc001223bf7def3087a5e0f02aef8f09
rafal1996/CodeWars
/Merge two sorted arrays into one.py
597
4.3125
4
# You are given two sorted arrays that both only contain integers. # Your task is to find a way to merge them into a single one, sorted in asc order. # Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays. # # You don't need to worry about validation, since arr1 and arr2 must be arrays' \ # ' with 0 or more Integers. If both arr1 and arr2 are empty, then just return an empty array. def merge_arrays(arr1, arr2): return sorted(set(arr1 + arr2)) print(merge_arrays([1,2,3,4], [5,6,7,8])) print(merge_arrays([1,3,5,7,9], [10,8,6,4,2]))
true
9998009659bc70720c63ab399c45fb8adafe5e2b
sam-calvert/mit600
/problem_set_1/ps1b.py
1,827
4.5
4
#!/bin/python3 """ Paying Debt Off In a Year Problem 2 Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. We will not be dealing with a minimum monthly payment rate. Take as raw_input() the following floating point numbers: 1. the outstanding balance on the credit card 2. annual interest rate as a decimal Print out the fixed minimum monthly payment, number of months (at most 12 and possibly less than 12) it takes to pay off the debt, and the balance (likely to be a negative number). Assume that the interest is compounded monthly according to the balance at the start of the month (before the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme. In short: Monthly interest rate = Annual interest rate / 12.0 Updated balance each month = Previous balance * (1 + Monthly interest rate) – Minimum monthly payment """ # Gather user input balance = float(input("Enter the outstanding balance on your credit card: ")) interest_rate = float(input("Enter the anual credit card interest rate as a decimal: ")) # Set payment to $10 and test whether this will pay off the balance # Increase payment by $10 until the correct answer is found set_balance = balance payment = 10 while True: balance = set_balance for month in range(1,13): balance *= interest_rate/12 + 1 balance -= payment if balance <= 0: break if balance <= 0: break payment += 10 print("RESULT \nMonthly payment to pay off debt in 1 year: %d \ \nNumber of months needed: %d \nBalance: %.2f" \ % (payment, month, balance))
true
c806a5d9275a6026fb58cc261b8bfd95c1d66b90
keshavkummari/python-nit-7am
/Operators/bitwise.py
1,535
4.71875
5
'''--------------------------------------------------------------''' # 5. Bitwise Operators : '''--------------------------------------------------------------''' """ Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows : a = 0011 1100 b = 0000 1101 # Note: Python's built-in function bin() can be used to obtain binary representation of an integer number. For example, 2 is 10 in binary and 7 is 111. In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary) # Bitwise operators in Python : Operator Meaning Example 1. & Bitwise AND x & y = 0 (0000 0000) 2. | Bitwise OR x | y = 14 (0000 1110) 3. ~ Bitwise NOT ~x = -11 (1111 0101) 4. ^ Bitwise XOR x ^ y = 14 (0000 1110) 5. >> Bitwise right shift x>> 2 = 2 (0000 0010) 6. << Bitwise left shift x<< 2 = 40 (0010 1000) """ #!/usr/bin/python3 a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 print ('a=',a,':',bin(a),'b=',b,':',bin(b)) c = 0 c = a & b # 12 = 0000 1100 print ("result of AND is ", c,':',bin(c)) c = a | b # 61 = 0011 1101 print ("result of OR is ", c,':',bin(c)) c = a ^ b # 49 = 0011 0001 print ("result of EXOR is ", c,':',bin(c)) c = ~a # -61 = 1100 0011 print ("result of COMPLEMENT is ", c,':',bin(c)) c = a << 2 # 240 = 1111 0000 print ("result of LEFT SHIFT is ", c,':',bin(c)) c = a >> 2 # 15 = 0000 1111 print ("result of RIGHT SHIFT is ", c,':',bin(c))
true
910fe52e3d7eafcec15c6d5e31cc8d33bd087942
keshavkummari/python-nit-7am
/DataTypes/Strings/unicodes.py
2,461
4.1875
4
Converting to Bytes. The opposite method of bytes.decode() is str.encode(), which returns a bytes representation of the Unicode string, encoded in the requested encoding. The errors parameter is the same as the parameter of the decode() method but supports a few more possible handlers. UTF-8 is one such encoding. The low codepoints are encoded using a single byte, and higher codepoints are encoded as sequences of bytes. Python's unicode type is a collection of codepoints. The line ustring = u'A unicode \u018e string \xf1' creates a Unicode string with 20 characters. Python's str type is a collection of 8-bit characters. The English alphabet can be represented using these 8-bit characters, but symbols such as ±, ♠, Ω and ℑ cannot. Unicode is a standard for working with a wide range of characters. Each symbol has a codepoint (a number), and these codepoints can be encoded (converted to a sequence of bytes) using a variety of encodings. UTF-8 is one such encoding. The low codepoints are encoded using a single byte, and higher codepoints are encoded as sequences of bytes. Python's unicode type is a collection of codepoints. The line ustring = u'A unicode \u018e string \xf1' creates a Unicode string with 20 characters. When the Python interpreter displays the value of ustring, it escapes two of the characters (Ǝ and ñ) because they are not in the standard printable range. The line s = unistring.encode('utf-8') encodes the Unicode string using UTF-8. This converts each codepoint to the appropriate byte or sequence of bytes. The result is a collection of bytes, which is returned as a str. The size of s is 22 bytes, because two of the characters have high codepoints and are encoded as a sequence of two bytes rather than a single byte. When the Python interpreter displays the value of s, it escapes four bytes that are not in the printable range (\xc6, \x8e, \xc3, and \xb1). The two pairs of bytes are not treated as single characters like before because s is of type str, not unicode. The line t = unicode(s, 'utf-8') does the opposite of encode(). It reconstructs the original codepoints by looking at the bytes of s and parsing byte sequences. The result is a Unicode string. The call to codecs.open() specifies utf-8 as the encoding, which tells Python to interpret the contents of the file (a collection of bytes) as a Unicode string that has been encoded using UTF-8.
true
c81ca7b213c5b8f442f5a1169be00a72874ecd7a
mirajbasit/dice
/dice project.py
1,152
4.125
4
import random # do this cuz u have to def main(): # .lower makes everything inputted lowercase roll_dice = input("Would you like to roll a dice, yes or no? ").lower() # add the name of what is being defined each time if roll_dice == "no" or roll_dice == "n": print("Ok, see you later ") elif roll_dice == "yes" or roll_dice == "y": yeppers = True #you do not have to put the == true, still put the colon cuz loop while yeppers == True: outcome = random.randint(1,6) print(f"The result is {outcome}") re_roll = input("Will you roll again? ").lower() if re_roll == "no" or re_roll == "n": print("Ok, thanks for playing ") yeppers = False elif re_roll == "yes" or re_roll == "y": yeppers = True else: print("Please enter yes or no! ") #place for each condition yeppers = False else: print("Please try again ") # do this cuz u have to if __name__ == "__main__": main()
true
f58b89d169650839c43e0b716b877f6661245f48
vnBB/python_basic_par1_exersises
/exercise_5.py
283
4.375
4
# Write a Python program which accepts the user's first and last name and print them in # reverse order with a space between them. firstname = str(input("Enter your first name: ")) lastname = str(input("Enter your last name: ")) print("Your name is: " + lastname + " " + firstname)
true
4f1db5440a48a15f126f4f97439ef197c0c380ab
mynameischokan/python
/Strings and Text/1_4.py
1,915
4.375
4
""" ************************************************************ **** 1.4. Matching and Searching for Text Patterns ************************************************************ ######### # Problem ######### # We want to match or search text for a specific pattern. ######### # Solution ######### # If the text you’re trying to match is a simple literal, # we can often just use the basic string methods, # such as `str.find()`, `str.endswith()`, `str.startswith()`. # For more complicated matching, use regular expressions and the `re` module. """ import re text = 'yeah, but no, but yeah, but no, but yeah' # TODO # Search for the location of the first occurrence of word `no` in `text` above # INFO # \d+ means match one or more digits text1 = '11/27/2012' text2 = 'Nov 27, 2012' # TODO # Write an `if/else` clause that determines `true/false` of `text1` # and `text2` match using `re` # TODO # Precompile the regular expression pattern into a pattern object first # DO the previous `TODO` with compiled version text3 = 'Today is 11/27/2012. PyCon starts 3/13/2013.' # TODO # `match` searches only starts with occurrence in the string # but you need to FIND ALL matches in text, find them # INFO # When defining regular expressions, it is common to introduce `capture groups` # by enclosing parts of the pattern in parentheses. # TODO # Compile `\d+/\d+/\d+` pattern with capture groups # Print out `groups`(from 0, 3) # Extract them to `month, day, year` # Find all matches from `text3` using pattern with compiled groups # Loop over them and print items in format: `month-day-year` # TODO # Loop over matches found using `findall`, # but this time iteratively using `finditer()` # INFO # If you want an exact match, # make sure the pattern includes the end-marker `$` text4 = '12/23/2020awdaw' # TODO # Try to find exact match of date in `text4` if __name__ == '__main__': pass
true
2005dfcd3969edb4c38aba4b66cbb9a5eaa2e0f2
mynameischokan/python
/Data Structures and Algorithms/1_3.py
1,459
4.15625
4
''' ************************************************* **** Keeping the Last N Items ************************************************* ######### # Problem ######### # You want to keep a limited history of the last few items seen during iteration # or during some other kind of processing. ######### # Solution ######### # Keeping a limited history is a perfect use for a `collections.deque` ''' # For example, the following code performs a simple text match on a sequence of lines # noqa # and yields the matching line along with the previous N lines of context when found: # noqa from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) # TODO # Open a file `file_1_3.txt`. # Loop over each line # print current line and prev lines # When writing code to search for items, # it is common to use a generator function involving `yield`. # This decouples the process of searching from the code that uses the results q = deque() # TODO # Add item to `q` # Add item to the begginning of `q` # Remove item to `q` # Remove item to the begginning of `q` # Adding or popping items from either end of a queue has O(1) complexity. # This is unlike a list where inserting or removing items from the front of the list is O(N). # noqa if __name__ == '__main__': pass
true
383dbeb58575c030f659e21cfe9db4de0f3b4043
mynameischokan/python
/Files and I:O/1_3.py
917
4.34375
4
""" ************************************************************* **** 5.3. Printing with a Different Separator or Line Ending ************************************************************* ######### # Problem ######### - You want to output data using print(), but you also want to change the separator character or line ending. ######### # Solution ######### - Use the `sep` and `end` keyword arguments to print(), to change the output as you wish. # TODO: - Print it by separating comma: 'ACME', 50, 91.5 - " " and by adding `!!\n` at the end. - Print nums in range(5) one by one and in one line. - Try to print `join` of `row` below and face an error. - Try to print `row` below by using `join` and separator comma(,) - Now print `row` using `sep` key of `print`. """ row = ('ACME', 50, 91.5) if __name__ == '__main__': pass
true
6dfbf466e6a2697a3c650dd7963e8b446c3ebbdd
paulprigoda/blackjackpython
/button.py
2,305
4.25
4
# button.py # for lab 8 on writing classes from graphics import * from random import randrange class Button: """A button is a labeled rectangle in a window. It is enabled or disabled with the activate() and deactivate() methods. The clicked(pt) method returns True if and only if the button is enabled and pt is inside it.""" def __init__(self, win, center, width, height, label): """ Creates a rectangular button, eg: qb = Button(myWin, centerPoint, width, height, 'Quit') """ w,h = width/2.0, height/2.0 #w and h are the width and the height x,y = center.getX(), center.getY() #x and y are the coordinates self.xmax, self.xmin = x+w, x-w #creates top left point of rect self.ymax, self.ymin = y+h, y-h #creates top right point of rect p1 = Point(self.xmin, self.ymin)#stores first point p2 = Point(self.xmax, self.ymax) #stores second point self.rect = Rectangle(p1,p2) #creates rect self.rect.setFill('lightgray') #color of rect self.rect.draw(win) #draws rect self.label = Text(center, label) #puts text in button center self.label.draw(win) #draws text self.activate() #this line was not there in class today def getLabel(self): """Returns the label string of this button.""" return self.label.getText() def activate(self): """Sets this button to 'active'.""" self.label.setFill('black') #color the text "black" self.rect.setWidth(2) #set the outline to look bolder self.active = True #set the boolean variable that tracks "active"-ness to True def deactivate(self): """Sets this button to 'inactive'.""" ##color the text "darkgray" self.label.setFill("darkgray") ##set the outline to look finer/thinner self.rect.setWidth(1) ##set the boolean variable that tracks "active"-ness to False self.active = False def isClicked(self,p): """Returns true if button active and Point p is inside""" x,y = p.getX(),p.getY() if self.xmin < x and x < self.xmax and self.ymin < y and y < self.ymax and self.active == True: return True return False if __name__ == "__main__": main()
true
bf694c58e1e2f543f3c84c41e32faa3301654c6e
akshat-52/FallSem2
/act1.19/1e.py
266
4.34375
4
country_list=["India","Austria","Canada","Italy","Japan","France","Germany","Switerland","Sweden","Denmark"] print(country_list) if "India" in country_list: print("Yes, India is present in the list.") else: print("No, India is not present in the list.")
true
f04933dd4fa2167d54d9be84cf03fa7f9916664c
akshat-52/FallSem2
/act1.25/3.py
730
4.125
4
def addition(a,b): n=a+b print("Sum : ",n) def subtraction(a,b): n=a-b print("Diffrence : ",n) def multiplication(a,b): n=a*b print("Product : ",n) def division(a,b): n=a/b print("Quotient : ",n) num1=int(input("Enter the first number : ")) num2=int(input("Enter the second number : ")) print(""" Choice 1 - SUM Choice 2 - DIFFERENCE Choice 3 - PRODUCT Choice 4 - QUOTIENT """) choice=int(input("Enter the number of your choice : ")) if choice==1: addition(num1,num2) elif choice==2: subtraction(num1,num2) elif choice==3: multiplication(num1,num2) elif choice==4: division(num1,num2) else: print("Invalid Choice !!! Please choose 1/2/3/4 only .")
true
bda09e5ff5b572b11fb889b929daddb9f4e53bb9
rhps/py-learn
/Tut1-Intro-HelloWorld-BasicIO/py-greeting.py
318
4.25
4
#Let's import the sys module which will provide us with a way to read lines from STDIN import sys print "Hi, what's your name?" #Ask the user what's his/her name #name = sys.stdin.readline() #Read a line from STDIN name = raw_input() print "Hello " + name.rstrip() #Strip the new line off from the end of the string
true
795d075e858e3f3913f9fc1fd0cb424dcaafe504
rhps/py-learn
/Tut4-DataStructStrListTuples/py-lists.py
1,813
4.625
5
# Demonstrating Lists in Python # Lists are dynamically sized arrays. They are fairly general and can contain any linear sequence of Python objects: functions, strings, integers, floats, objects and also, other lists. It is not necessary that all objects in the list need to be of the same type. You can have a list with strings, numbers , objects; all mixed up. # Constructing a basic list # This list purely has integers test_list = [1,2,3,4,5,6,7,8,9] print test_list # Constructing a mixed list # This list has integers as well as strings test_mixed_list = [1,2,3,"test list"] print "Displaying test_list" print test_list print "Displaying test_mixed_list" print test_mixed_list # Appending to a list test_list.append(10) # Now the test_list = [1,2,3,4,5,6,7,8,9,10] print "After appending 10 to the test_list" print test_list test_list = test_list + [13,12,11] # Now the test_list = [1,2,3,4,5,6,7,8,9,10,13,12,11] print "After adding [13,12,11] to the test list" print test_list # Delete from the test_list del test_list[2] print "Deleted element at index 2 in the test_list" # new test list is [1,2,4,5,6,7,8,9,10,13,12,11] print test_list # Sorting a list print "Sorting the test list" test_list.sort() print test_list # This will display [1,2,4,5,6,7,8,9,10,11,12,13] # Reverse a list print "Reversting the test_list" test_list.reverse() print test_list # This will display [13,12,11,10,9,8,7,6,5,4,2,1] # Now we will demonstrate "Multiplying" a list with a constant. I.e, the # list will be repeatedly concatenated to itself list_to_multiply = ['a','b','c'] print "list to multiply" print list_to_multiply print "After multiplying this list by 3, i.e. repeating it 3 times:" product_list = 3 * list_to_multiply print product_list # This will display ['a','b','c','a','b','c','a','b','c']
true
ec823610ba821cd62f067b8540e733f46946de34
thaycacac/kids-dev
/PYTHON/lv2/lesson1/exercise2.py
463
4.15625
4
import random number_random = random.randrange(1, 100) numer_guess = 0 count = 0 print('Input you guess: ') while number_random != numer_guess: numer_guess = (int)(input()) if number_random > numer_guess: print('The number you guess is smaller') count += 1 elif number_random < numer_guess: print('The number you guess is bigger') count += 1 else: print('Congratulations you\'ve guessed correctly') print('You guessed wrong:', count)
true
011d9ac704c3705fd7b6025c3e38d440a30bf59a
Saskia-vB/Eng_57_2
/Python/exercises/108_bizzuuu_exercise.py
1,540
4.15625
4
# Write a bizz and zzuu game ##project user_number= (int(input("please enter a number"))) for i in range(1, user_number + 1): print(i) while True: user_number play = input('Do you want to play BIZZZUUUU?\n') if play == 'yes': user_input = int(input('what number would you like to play to?\n')) for num in range(1, user_input + 1): if num % 15 == 0: print('bizzzuu') elif num % 3 ==0: print('bizzz') elif num % 5 ==0: print("zzuuu") else: print(num) break # as a user I should be able prompted for a number, as the program will print all the number up to and inclusing said number while following the constraints / specs. (bizz and buzz for multiples or 3 and 5) number= int(input("Choose a number:")) if (number % 5) == 0: print("buzz") elif (number % 3)== 0: print("bizz") else: print("You lost") # As a user I should be able to keep giving the program different numbers and it will calculate appropriately until you use the key word: 'penpinapplespen' # write a program that take a number # prints back each individual number, but # if it is a multiple of 3 it returns bizz # if a multiple of 5 it return zzuu # if a multiple of 3 and 5 it return bizzzzuu # EXTRA: # Make it functional # make it so I can it so it can work with 4 and 9 insted of 3 and 5. # make it so it can work with any number! # print ("I'm going to print the numbers!") # i = int(input("Enter the number: ")) # func(i)
true
b572d0bda55a6a4b9a3bbf26b609a0edc026c0a3
Saskia-vB/Eng_57_2
/Python/dictionaries.py
1,648
4.65625
5
# Dictionaries # Definition and syntax # a dictionary is a data structure, like a list, but organized with keys and not index. # They are organized with 'key' : 'value' pairs # for example 'zebra' : 'an African wild animal that looks like a horse but has black and white or brown and white lines on its body' # This means you can search data using keys, rather than index. #syntax # {} # my_dictionary={'key':'value'} # print(type(my_dictionary)) # i.e.: {'zebra': 'A horse with stripes'} # Defining a dictionary # allows you to store more data, the value can be anything, it can be another data structure. # i.e. for stingy landlords list, we need more info regarding the houses they have and contact details. stingy_landlord1 = { 'name':'Alfredo', 'phone_number':'0783271192', 'property':'Birmingham, near Star City' } # printing dictionary print(stingy_landlord1) print(type(stingy_landlord1)) # getting one value out print(stingy_landlord1['name']) print(stingy_landlord1['phone_number']) # re-assigning one value stingy_landlord1['name'] = "Alfredo de Medo" print(stingy_landlord1) # new key value pair stingy_landlord1['address']="house 2, Unit 29 Watson Rd" print(stingy_landlord1) stingy_landlord1['number_of_victimes']=0 print(stingy_landlord1) stingy_landlord1['number_of_victimes']+=1 print(stingy_landlord1) stingy_landlord1['number_of_victimes']+=1 print(stingy_landlord1) # get all the values out # special dictionary methods # (methods are functions that belong to a specific data type) # .keys() print(stingy_landlord1.keys()) # .values() print(stingy_landlord1.values()) # .items() print(stingy_landlord1.items())
true
d0625cb91921c28816cd5ab06a100cb3ae9e4bbb
alveraboquet/Class_Runtime_Terrors
/Students/cleon/Lab_6_password_generator_v2/password_generator_v2.py
1,206
4.1875
4
# Cleon import string import random speChar = string.hexdigits + string.punctuation # special characters print(" Welcome to my first password generator \n") # Welcome message lower_case_length = int(input("Please use the number pad to enter how many lowercase letters : ")) upper_case_length = int(input("How many uppercase letters : ")) number_length = int(input("How many numbers : ")) special_length = int(input("How many special characters : ")) gP = "" while True: while lower_case_length > 0: gP += random.choice(string.ascii_lowercase) lower_case_length = lower_case_length - 1 while upper_case_length > 0: gP += random.choice(string.ascii_uppercase) upper_case_length = upper_case_length - 1 while number_length > 0: gP += random.choice(string.digits) number_length = number_length - 1 while special_length > 0: gP += random.choice(speChar) special_length = special_length - 1 break gP = (random.sample(gP, len(gP))) # Can't randomly sort string elements.Use this function it returns as a list gP= ''.join(gP) # Then you must use join function to convert back to string print(gP)
true
5a89444d7b72175ba533b87139a5a611a11a89a7
alveraboquet/Class_Runtime_Terrors
/Students/Jordyn/Python/Fundamentals1/problem1.py
224
4.3125
4
def is_even(value): value = abs(value % 2) if value > 0: return 'Is odd' elif value == 0: return 'Is even' value = int(input('Input a whole number: ')) response = is_even(value) print(response)
true
59bc2af7aeef6ce948184bb1291f18f81026ed9c
alveraboquet/Class_Runtime_Terrors
/Students/Jordyn/Python/Fundamentals2/problem3.py
296
4.1875
4
def latest_letter(word): length = len(word) length -= 1 word_list = [] for char in word: word_list += [char.lower()] return word_list[length] word = input("Please input a sentence: ") letter = latest_letter(word) print(f"The last letter in the sentence is: {letter}")
true
627275ef1f88b1c633f0114347570dc62a16f175
alveraboquet/Class_Runtime_Terrors
/Students/cadillacjack/Python/lab15/lab15.py
1,306
4.1875
4
from string import punctuation as punct # Import ascii punctuation as "punct". # "punct" is a list of strings with open ('monte_cristo.txt', 'r') as document: document_content = document.read(500) doc_cont = document_content.replace('\n',' ') # Open designated file as "file". "file" is a string for punc in punct: doc_cont = doc_cont.replace(punc, "") # Remove all punctuation from string doc_cont = doc_cont.lower() # Lowercase all words doc_cont = doc_cont.split(' ') # Convert string to list of strings word_count = {} # Create empty dictionary for word in doc_cont: # Scan "doc_cont", check every word. if word not in word_count: # If scanned word not in "word_count"... word_count[word] = 1 # Add word to "word_count" as a key with the value 1 elif word in word_count: # If scanned word is in "word_count"... word_count[word] +=1 # Increase value of key "word" by 1 words = list(word_count.items()) # Convert dict "word_count" to a list of tuples. # Save list as "words" # Tuples are key, value pairs words.sort(key = lambda tup: tup[1],reverse = True) # Sort list "words" using the value of each tuple # Reverse the order of list fro highest value to lowest print(f"The top ten words are ; {words[:10]})") # print the first 10 words of list "words"
true
0c31b359da41c800121e7560fceac30836e2daec
alveraboquet/Class_Runtime_Terrors
/Students/tom/Lab 11/Lab 11, make change, ver 1.py
1,903
4.15625
4
# program to make change # 10/16/2020 # Tom Schroeder play_again = True while play_again: money_amount = input ('Enter the amount amount of money to convert to change: \n') float_convert = False while float_convert == False: try: money_amount = float(money_amount) float_convert = True except ValueError: money_amount = input ('Your entry is not a valid entry. Enter the amount amount of money to convert to change: \n') quarters = money_amount // .25 # print (f'{quarters} quartes') money_amount_less_quarters = round(money_amount % .25, 2) # print (f'{money_amount_less_quarters} money_amount_less_quarters') dimes = money_amount_less_quarters // .1 # print (f'{dimes} dimes') money_amount_less_dimes = round(money_amount_less_quarters % .1, 2) # print (f'{money_amount_less_dimes} money_amount_less_dimes') nickles = money_amount_less_dimes // .05 # print (f'{nickles} nickles') money_amount_less_nickles = round(money_amount_less_dimes % .05, 2) # print (f'{money_amount_less_nickles} money_amount_less_nickles') pennies = money_amount_less_nickles / .01 quarters = int(quarters) dimes = int(dimes) nickles = int(nickles) pennies = int(pennies) print(f'${money_amount} is made up of {quarters} quarters, {dimes} dimes, {nickles} nickles, {pennies} pennies.') play_again_input = input ('Would you like to do another one? "Y" or "N"').capitalize() while play_again_input != 'Y' and play_again_input != 'N': play_again_input = input ('You made an incorrect entry. Would you like to do another one? "Y" or "N"').capitalize() if play_again_input == 'Y': play_again = True elif play_again_input == 'N': play_again = False
true
bd89d612e7e9d15153ad804f85dfe64245c365a6
DanielY1783/accre_python_class
/bin/06/line_counter.py
1,440
4.71875
5
# Author: Daniel Yan # Email: daniel.yan@vanderbilt.edu # Date: 2018-07-25 # # Description: My solution to the below exercise posed by Eric Appelt # # Exercise: Write a command line utility in python that counts the number # of lines in a file and prints them. to standard output. # # The utility should take the name of a file as an argument. To do this use # import sys and then sys.argv[1] will be the first argument given. # # By trial and error, determine the type of exception raised when the user # fails to run the program with an argument, the file specified does not # exist, or the user does not have permission to read the file specified. # # Using try/except blocks, handle each of these exception types separately # and send an appropriate message to the user in each case. import sys if __name__ == '__main__': try: file_name = sys.argv[1] count = 0 with open(file_name, "r") as read_file: for _ in read_file: count += 1 print("{} has {} line(s)".format(file_name, count)) except IndexError: print("No file specified. Specify file in first command line argument") except FileNotFoundError: print("File does not exist. Make sure that directory and extension of " "file are included.") except PermissionError: print("You do not have permission to read the file. Please obtain " "read permission to file and try again.")
true
b4d3854aea11e1cac0cece0b4dbd708b6d95d184
DanielY1783/accre_python_class
/bin/01/fib.py
1,338
4.53125
5
# Author: Daniel Yan # Email: daniel.yan@vanderbilt.edu # Date: 2018-06-07 # # Description: My solution to the below exercise posed by Eric Appelt # # Exercise: Write a program to take an integer that the user inputs and print # the corresponding Fibonacci Number. The Fibonacci sequence begins 1, 1, 2, 3, # 5, 8, 13, so if the user inputs 7, the user should see the 7th Fibonacci # number printed, which is 13. If the user inputs a negative number the # program should print an error message. if __name__ == '__main__': # Get user input user_input = input( "Enter in a positive integer 'n' such that the 'nth' Fibonacci Number " "will be printed: ") fib_num = int(user_input) # Print error if number is not positive if fib_num < 0: print("Value is not positive. Exiting.") exit(-1) elif fib_num == 0: print("The Fibonacci Number in the 0 position is: 0") else: # Set the two previous Fibonacci Numbers. f1 = 0 f2 = 0 # Set the current Fibonacci Number to print. cur = 1 # Get the user choice. while fib_num > 1: f1 = f2 f2 = cur cur = f1 + f2 fib_num = fib_num - 1 print( "The Fibonacci Number in the '" + user_input + "' position is: " + str(cur))
true
64739565dd86b5b36fdbe203c3f6beeb2c78b847
anthony-marino/ramapo
/source/courses/cmps130/exercises/pe01/pe1.py
651
4.5625
5
############################################# # Programming Excercise 1 # # Write a program that asks the user # for 3 integers and prints the # largest odd number. If none of the # three numbers were odd, print a message # indicating so. ############################################# x = int(input("Enter x: ")) y = int(input("Enter y: ")) z = int(input("Enter z: ")) max_odd = float("-inf") if x % 2 != 0 and x > max_odd: max_odd = x if y % 2 != 0 and y > max_odd: max_odd = y if z % 2 != 0 and z > max_odd: max_odd = z if max_odd != float("-inf") : print("The largest odd number was", max_odd) else: print("There were no odd numbers!")
true
9dbffbb4195dfe02d90e4f2bd2813cc2a7d993a6
anthony-marino/ramapo
/source/courses/cmps130/exercises/pe10/pe10-enumeration.py
1,047
4.40625
4
############################################################################## # Programming Excercise 10 # # Find the square root of X using exhaustive enumeration ############################################################################# # epsilon represents our error tolerance. We'll # accept any answer Y where Y squared is within epsilon # of X epsilon = 0.001 # step is based on epsilon for convenience, but doesn't # have to be. Its just the increment that we'll check in. # It should be rather small relative to epsilon step = epsilon ** 2 # we'll also keep track of how many turns around the loop # this takes, so we can compare against other techniques. num_iterations = 0 x = float(input("Please enter a real number: ")) ans = 0.0 while abs(ans**2 - x) > epsilon: ans += step num_iterations += 1 print ("Completed in", num_iterations, " iterations") if abs(ans**2 - x ) > epsilon: print("Exhaustive enumeration could not determine the square root of", x) else: print("The square root of", x, "is", ans, "!")
true
f279a594a986076b96993995f5072bcc383244d6
singh-vijay/PythonPrograms
/PyLevel3/Py19_Sets.py
288
4.15625
4
''' Sets is collection of items with no duplicates ''' groceries = {'serial', 'milk', 'beans', 'butter', 'bananas', 'milk'} ''' Ignore items which are given twice''' print(groceries) if 'pizza' in groceries: print("you already have pizza!") else: print("You need to add pizza!")
true
96ee1777becc904a39b140c901522881b2942cee
WavingColor/LeetCode
/LeetCode:judge_route.py
1,034
4.125
4
# Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. # The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. # Example 1: # Input: "UD" # Output: true # Example 2: # Input: "LL" # Output: false class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ rs, ls, us, ds = [], [], [], [] for string in moves: if string == 'D': ds.append(string) elif string == 'R': rs.append(string) elif string == 'U': us.append(string) elif string == 'L': ls.append(string) return not bool((len(rs)+len(us) - len(ls) - len(ds)))
true
f084aa9b24edc8fe1b0d87cd20beee21288946ad
mattandersoninf/AlgorithmDesignStructures
/Points/Python/Point.py
1,083
4.15625
4
# python impolementation of a point # a point in 2-D Euclidean space which should contain the following # - x-coordinate # - y-coordinate # - moveTo(new_x,new_y): changes the coordinates to be equal to the new coordinates # - distanceTo(x_val,y_val): this function returns the distance from the current point to some other point as a float class Point: def __init__(self,x,y): self._x = x self._y = y @property def x(self): print("get x-coordinate") return self._x @x.setter def x(self,val): print("set x-coordinate") self._x = val @property def y(self): print("get y-coordinate") return self._x @y.setter def y(self,val): print("set y-coordinate") self._x = val @property def coordinates(self): print("get coordinates") return (self._x,self._y) def moveTo(self,new_x,new_y): self._x = new_x self._y = new_y def distanceTo(self,x_val,y_val): return ((self._x-x_val)**2+(self._y-y_val)**2)**.5
true
91eb26b11d3a5839b3906211e3e10a636ac0277b
Exia01/Python
/Self-Learning/testing_and_TDD/basics/assertions.py
649
4.28125
4
# Example1 def add_positive_numbers(x, y): # first assert, then expression, message is optional assert x > 0 and y > 0, "Both numbers must be positive! -> {}, {}".format( x, y) return x + y # test cases print(add_positive_numbers(1, 1)) # 2 add_positive_numbers(1, -1) # AssertionError: Both numbers must be positive! # Example 2 def eat_junk(food): assert food in [ # truth or false "pizza", "ice cream", "candy", "fried butter" ], "food must be a junk food!" return f"NOM NOM NOM I am eating {food}" #test case food = input("ENTER A FOOD PLEASE: ") print(eat_junk(food))
true
dbdf00041078931bec33a443fbd330194cf60ec0
Exia01/Python
/Self-Learning/lists/slices.py
361
4.28125
4
items = [1, 2, 3, 4, 5, 6, ['Hello', 'Testing']] print(items[1:]) print(items[-1:]) print(items[::-1])# reverses the list print(items[-3:]) stuff = items[:] # will copy the array print(stuff is items) # share the same memory space? print(stuff[0:7:2]) print(stuff[7:0:-2]) stuff[:3] = ["A", "B", "C"] print(stuff) x =[ "Hello World!", "Testing HEre"]
true
64878d4e5e228f2c45c578ea44614fcb5dc67e1b
Exia01/Python
/Self-Learning/built-in_functions/abs_sum_round.py
712
4.125
4
#abs --> Returns the absolute value of a number. The argument may be an integer or a floating point number #Example print(abs(5)) #5 print(abs(3.5555555)) print(abs(-1324934820.39248)) import math print(math.fabs(-3923)) #treats everything as a float #Sum #takes an iterable and an optional start # returns the sum of start and the items of an iterable from left to right and returns the total. # starts default to 0 print(sum([1,2,3])) print(sum([1, 2, 3,], 10)) # will start at 10 and add #round #Return number rounded to ndigits precision after the decimal point. #If ndigits is omitted or is None, it returns the nearest integer to input print(round(10.2)) #10 print(round(1.24323492834, 2))#1.24
true
278dd78ed805a27e0a702bdd8c9064d3976a2f78
Exia01/Python
/Python OOP/Vehicles.py
2,884
4.21875
4
# file vehicles.py class Vehicle: def __init__(self, wheels, capacity, make, model): self.wheels = wheels self.capacity = capacity self.make = make self.model = model self.mileage = 0 def drive(self, miles): self.mileage += miles return self def reverse(self, miles): self.mileage -= miles return self # file vehicles.py class Vehicle: def __init__(self, wheels, capacity, make, model): self.wheels = wheels self.capacity = capacity self.make = make self.model = model self.mileage = 0 def drive(self, miles): self.mileage += miles return self def reverse(self, miles): self.mileage -= miles return self class Bike(Vehicle): def vehicle_type(self): return "Bike" class Car(Vehicle): def set_wheels(self): self.wheels = 4 return self class Airplane(Vehicle): def fly(self, miles): self.mileage += miles return self v = Vehicle(4, 8, "dodge", "minivan") print(v.make) b = Bike(2, 1, "Schwinn", "Paramount") print(b.vehicle_type()) c = Car(8, 5, "Toyota", "Matrix") c.set_wheels() print(c.wheels) a = Airplane(22, 853, "Airbus", "A380") a.fly(580) print(a.mileage) class Parent: # parent methods and attributes here class Child(Parent): # inherits from Parent class so we define Parent as the first parameter # parent methods and attributes are implicitly inherited # child methods and attributes def varargs(arg1, *args): print("Got " + arg1 + " and " + ", ".join(args)) varargs("one") # output: "Got one and " varargs("one", "two") # output: "Got one and two" varargs("one", "two", "three") # output: "Got one and two, three" class Wizard(Human): def __init__(self): super().__init__() # use super to call the Human __init__() method # every wizard starts off with 10 intelligence, overwriting the 3 from Human self.intelligence = 10 def heal(self): self.health += 10 # all wizards also get a heal() method class Ninja(Human): def __init__(self): super().__init__() # use super to call the Human __init__() method # every Ninja starts off with 10 stealth, overwriting the stealth of 1 from Human self.stealth = 10 def steal(self): self.stealth += 5 # all ninjas also get a steal() method class Samurai(Human): def __init__(self): super().__init__() # use super to call the Human __init__() method # every Samurai starts off with 10 strength, overwriting the 2 from Human self.strength = 10 def sacrifice(self): self.health -= 5 # all samurais also get a sacrifice() method
true
65a6a75a451031ae2ea619b3b8b2210a44859ca3
Exia01/Python
/Self-Learning/Algorithm_challenges/three_odd_numbers.py
1,607
4.1875
4
# three_odd_numbers # Write a function called three_odd_numbers, which accepts a list of numbers and returns True if any three consecutive numbers sum to an odd number. def three_odd_numbers(nums_list, window_size=3): n = window_size results = [] temp_sum = 0 #test this check if window_size > len(nums_list): return False # first sum for i in range(window_size): temp_sum += nums_list[i] #can implement quick short circuit here results.append(temp_sum % 2 != 0) for i in range(window_size, len(nums_list)): temp_sum = temp_sum - nums_list[i - n] + nums_list[i] results.append(temp_sum % 2 != 0) return any(results) ##Test Cases print(three_odd_numbers([1,2])) # True print(three_odd_numbers([1,2,3,4,5])) # True print(three_odd_numbers([0,-2,4,1,9,12,4,1,0])) # True print(three_odd_numbers([5,2,1])) # False print(three_odd_numbers([1,2,3,3,2])) # False #Here be dragons # https://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/ # def maxSubArraySum(arr, n): # tempSum = 0 # maxSum = 0 # dic = {} # try: # n > len(arr) # except: # return None # for num in range(n): # maxSum += arr[num] # # print(maxSum) # tempSum = maxSum # for i in range(n, len(arr)): # # print(arr[i-n], arr[i], tempSum) # tempSum = tempSum - arr[i - n] + arr[i] # maxSum = max(maxSum, tempSum) # # if (tempSum > maxSum): # # maxSum = tempSum # return maxSum # print(maxSubArraySum(arr, n))
true
66ebbe4465ff1a433f5918e7b20f019c60b496ae
Exia01/Python
/Self-Learning/lambdas/basics/basics.py
725
4.25
4
# A regular named function def square(num): return num * num # An equivalent lambda, saved to a variable but has no name square2 = lambda num: num * num # Another lambda --> anonymous function add = lambda a,b: a + b #automatically returns #Executing the function print(square(7)) # Executing the lambdas print(square2(7)) print(add(3,10)) # Notice that the square function has a name, but the two lambdas do not print(square.__name__) print(square2.__name__) print(add.__name__) #Adding add_values = lambda x, y: x + y #Multiplying multiply_values = lambda x, y: x * y #dividing divide_values = lambda x, y: x / y #subtract subtract_values = lambda x, y: x - y # Cube cube = lambda a: a ** 3 print(cube(8))
true
40be281781c92fc5417724157b0eebb2aefb8160
Exia01/Python
/Self-Learning/functions/operations.py
1,279
4.21875
4
# addd def add(a, b): return a+b print(add(5, 6)) # divide def divide(num1, num2): # num1 and num2 are parameters return num1/num2 print(divide(2, 5)) # 2 and 5 are the arguments print(divide(5, 2)) # square def square(num): # takes in an argument return num * num print(square(4)) print(square(8)) #return examples def sum_odd_numbers(numbers): total = 0 for num in numbers: if num % 2 != 0: total += num return total # Returning too early :( # OLD-VERSION----OLD-VERSION----OLD-VERSION----- # NEW AND IMPROVED VERSION :) def sum_odd_numbers_2(numbers): total = 0 for num in numbers: if num % 2 != 0: total += num return total print(sum_odd_numbers_2([1, 2, 3, 4, 5, 6, 7])) # cleaner code example def is_odd_number(num): if num % 2 != 0: return True else: # This else is unnecessary return False def is_odd_number_2(num): if num % 2 != 0: return True return False # We can just return without the else print(is_odd_number_2(4)) print(is_odd_number_2(9)) def count_dollar_signs(word): count = 0 for char in word: if char == '$': count += 1 return count print(count_dollar_signs("$uper $size"))
true
44697f20d48ba5522c2b77358ad1816d6af2bb96
Exia01/Python
/Self-Learning/built-in_functions/exercises/sum_floats.py
611
4.3125
4
#write a function called sum_floats #This function should accept a variable number of arguments. #Should return the sum of all the parameters that are floats. # if the are no floats return 0 def sum_floats(*args): if (any(type(val) == float for val in args)): return sum((val for val in args if type(val)==float)) return 0 #Test Cases print(sum_floats(1.5, 2.4, 'awesome', [], 1))# 3.9 print(sum_floats(1, 2, 3, 4, 5)) # 0 #Explanation: # First check to see if there are "any" float pass in the args through a loop. #if there float we loop to find them and only add those, then returning it
true
f8b7cd07614991a3ae5580fd2bd0458c730952ee
Exia01/Python
/Self-Learning/functions/exercises/multiple_letter_count.py
428
4.3125
4
#Function called "multiple_letter_count" # return dictionary with count of each letter def multiple_letter_count(word = None): if not word: return None if word: return {letter: word.count(letter) for letter in word if letter != " "} #Variables test_1 = "Hello World!" test_2 = "Gotta keep Pushing!" #Test cases print(multiple_letter_count(test_1)) print(multiple_letter_count(test_2))
true
bea429f7de9a604e1d92b4506038dd17fef4c7eb
shvnks/comp354_calculator
/src/InterpreterModule/Tokens.py
936
4.28125
4
"""Classes of all possible types that can appear in a mathematical expression.""" from dataclasses import dataclass from enum import Enum class TokenType(Enum): """Enumeration of all possible Token Types.""" "Since they are constant, and this is an easy way to allow us to know which ones we are manipulating." NUMBER = 0 PLUS = 1 MINUS = 2 MULTIPLICATION = 3 DIVISION = 4 POWER = 5 FACTORIAL = 6 TRIG = 7 LOGARITHMIC = 8 STANDARDDEVIATION = 9 GAMMA = 10 MAD = 11 PI = 12 E = 13 SQUAREROOT = 14 LEFTP = 15 RIGHTP = 16 LEFTB = 17 RIGHTB = 18 COMMA = 19 @dataclass class Token: """Stores the Type of Token and it value if any.""" type: TokenType value: any = None def __repr__(self): """Output the Token (Debugging Purposes).""" return self.type.name + str({f'{self.value}' if self.value is not None else ''})
true