blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6ef6acc1c6c365f082c551708635ebd79d1f849a
Yobretaw/AlgorithmProblems
/Py_leetcode/032_longestValidParentheses.py
2,145
4.125
4
import sys import math """ Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. """ def longest_valid_parentheses(s): if not s or len(s) < 2: return 0 # stack st = [] # every when st gets empty, we update start_pos start_pos = 0 max_len = 0 n = len(s) for i in range(0, n): if s[i] == '(': st.append(i) elif not st: start_pos = i + 1 else: st.pop() if not st: max_len = max(max_len, i - start_pos + 1) else: max_len = max(max_len, i - st[-1]) return max_len # Space: O(1) def longest_valid_parentheses2(s): if not s or len(s) == 1: return 0 n = len(s) depth = 0 start = 0 max_len = 0 for i in range(0, n): if s[i] == '(': depth += 1 else: depth -= 1 if depth < 0: start = i + 1 depth = 0 elif depth == 0: max_len = max(max_len, i - start + 1) start = n - 1 depth = 0 for i in reversed(range(0, n)): if s[i] == ')': depth += 1 else: depth -= 1 if depth < 0: start = i - 1 depth = 0 elif depth == 0: max_len = max(max_len, start - i + 1) return max_len #s = ')()())' #print longest_valid_parentheses(s) #print longest_valid_parentheses2(s) #s = ')()()())' #print longest_valid_parentheses(s) #print longest_valid_parentheses2(s) #s = '(()' #print longest_valid_parentheses(s) #print longest_valid_parentheses2(s)
true
1ac5ce236e29fd29f2146d64a7482264e9afc531
Yobretaw/AlgorithmProblems
/Py_leetcode/150_evaluateReversePolishNotation.py
1,546
4.28125
4
import sys import os import math """ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 """ def evalRPN(s): n = len(s) if n < 2: return int(s[0]) if n else 0 st = [] for c in s: try: st.append(int(c)) except: second = st[-1] first = st[-2] st.pop() st.pop() st.append(evalHelp(first, second, c)) return st[-1] def evalHelp(a, b, op): return { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: int(1.0 * x / y) }[op](a, b) #print evalRPN(["2", "1", "+", "3", "*"]) #print evalRPN(['3', '-4', '+']) #print evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]) #print evalRPN(["-78","-33","196","+","-19","-","115","+","-","-99","/","-18","8","*","-86","-","-","16","/","26","-14","-","-","47","-","101","-","163","*","143","-","0","-","171","+","120","*","-60","+","156","/","173","/","-24","11","+","21","/","*","44","*","180","70","-40","-","*","86","132","-84","+","*","-","38","/","/","21","28","/","+","83","/","-31","156","-","+","28","/","95","-","120","+","8","*","90","-","-94","*","-73","/","-62","/","93","*","196","-","-59","+","187","-","143","/","-79","-89","+","-"])
false
f21356398a5e226ef2c8aa70ed53a3a34e8f1385
kraftea/python_crash_course
/Chap_7/7-4_pizza_toppings.py
270
4.1875
4
prompt = "List what toppings you want on your pizza: " prompt += "When you're done adding toppings, type 'quit.' " toppings = "" while toppings != 'quit': toppings = input(prompt) if toppings != 'quit': print("I'll add " + toppings + " to your pizza.")
true
2ddd1c05cfec4691ef71a0b444991ce7908bd3c8
andreplacet/reiforcement-python-tasks
/exe11.py
443
4.25
4
# Exericio 11 from math import pow num1 = int(input('Informe um número inteiro: ')) num2 = int(input('Informe o segundo número inteiro: ')) num3 = float(input('Informe um número real: ')) a = (num1 * 2) + (num2 / 2) b = (num1 * 3) + (num3 * 3) c = pow(num3, 3) print(f'O produto do dobro do primeiro com metade do segundo {a:.2f}') print(f'A soma do triplo do primeiro com terceiro {b:.2f}') print(f'O Terceiro elevado ao cubo {c:.2f}')
false
441c611474f45cb2a4300f7bae33f8e80087c059
attacker2001/Algorithmic-practice
/Codewars/Number climber.py
1,076
4.40625
4
# coding=utf-8 """ For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1. For example, given N = 13, the sequence is [1, 3, 6, 13]. Write a function that returns this sequence given a number N. Try generating the elements of the resulting list in ascending order, i.e., without resorting to a list reversal or prependig the elements to a list. """ # def climb(n): # seq = [n] # while n != 1: # if n % 2 == 0: # seq.append(n / 2) # n /= 2 # else: # seq.append((n-1) / 2) # n -= 1 # n /= 2 # return sorted(seq) def climb(n): if n == 1: return [1] else: return climb(n/2) + [n] if __name__ == "__main__": print climb(13) """ def climb(n): result = [] while n: result.append(n) n /= 2 return result[::-1] def climb(n): return [1] if n == 1 else climb(int(n/2)) + [n] """
true
3a1e27e4bf95753641b933cdee233462c11e11bc
attacker2001/Algorithmic-practice
/Codewars/[5]Sum of Pairs.py
1,998
4.125
4
# coding=utf-8 """ https://www.codewars.com/kata/sum-of-pairs/train/python Sum of Pairs Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2. == None/nil/undefined (Based on the language) sum_pairs([10, 5, 2, 3, 7, 5], 10) # ^-----------^ 5 + 5 = 10, indices: 1, 5 # ^--^ 3 + 7 = 10, indices: 3, 4 * # * entire pair is earlier, and therefore is the correct answer == [3, 7] Negative numbers and duplicate numbers can and will appear. NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out. """ # def sum_pairs(ints, s): # firstly_finished = len(ints) # for x in ints: # temp = ints[:] # y = s - x # temp.remove(x) # if y in temp and max(temp.index(y), ints.index(x)) < firstly_finished: # firstly_finished = temp.index(y) + 1 # if firstly_finished == len(ints): # return None # return [s-ints[firstly_finished], ints[firstly_finished]] def sum_pairs(ints, s): tmp_ints = sorted(ints) while tmp_ints: current = tmp_ints.pop() if current <= s and s - current in tmp_ints: tmp_ints.remove(s - current) location_a, location_b = ints.index(current), ints.index(s-current) print location_a, location_b if __name__ == "__main__": print sum_pairs([10, 5, 2, 3, 7, 5], 10) """ to be continued """
true
2df60ffb99ecac399ac959168224e58f96372bb2
attacker2001/Algorithmic-practice
/Codewars/Find the odd int.py
672
4.25
4
# coding=UTF-8 ''' Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times. test.describe("Example") test.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5) 即找出列表中 出现次数为奇数的元素 ''' def find_it(seq): for i in seq: if seq.count(i) % 2 != 0: return i return None def main(): numbers = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5] print find_it(numbers) if __name__ == "__main__": main() ''' Other Soluntion: import operator def find_it(xs): return reduce(operator.xor, xs) '''
true
356d4accbfb6562795dc85a76257f8e44e1b91e0
attacker2001/Algorithmic-practice
/leetcode/43. Multiply Strings.py
1,309
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @file: 43. Multiply Strings.py @time: 2019/11/05 Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly. """ class Solution: def multiply(self, num1: str, num2: str) -> str: return str(int(num1) * int(num2)) if __name__ == '__main__': a = Solution() print(a.multiply('456', '5416456')) print(int(a.multiply('45456555555556', '5416456')) == 45456555555556*5416456) """ def multiply(self, num1, num2): res = 0 carry1 = 1 for n1 in num1[::-1]: carry2 = 1 for n2 in num2[::-1]: res += int(n1)*int(n2)*carry1*carry2 carry2 *= 10 carry1 *= 10 return str(res) i think it's not work at "res += int(n1)*int(n2)carry1carry2" when res is vary large. you should turn res to a string then do the ''+''. """
true
f701c3ec7108cbd939b6440753180c9bdea1e932
attacker2001/Algorithmic-practice
/Codewars/Sexy Primes.py
582
4.28125
4
# coding=UTF-8 ''' Sexy primes are pairs of two primes that are 6 apart. In this kata, your job is to complete the function sexy_prime(x, y) which returns true if x & y are sexy, false otherwise. Examples: sexy_prime(5,11) --> True sexy_prime(61,67) --> True sexy_prime(7,13) --> True sexy_prime(5,7) --> False ''' def isprime(x): return x > 1 and all(x % i != 0 for i in xrange(2, int(x**0.5) + 1)) def sexy_prime(x, y): return isprime(x) and isprime(y) and abs(x-y)==6 def main(): x, y = 13, 19 print sexy_prime(x, y) if __name__ == '__main__': main()
true
351027c7112eddd41a40383cf9707aa282daa42c
attacker2001/Algorithmic-practice
/Codewars/[8]Square(n) Sum.py
551
4.15625
4
# coding=utf-8 """ Complete the squareSum method so that it squares each number passed into it and then sums the results together. For example: square_sum([1, 2, 2]) # should return 9 """ def square_sum(numbers): sum_num = 0 for i in numbers: sum_num += i*i return sum_num if __name__ == '__main__': print square_sum([1, 3, 5]) print square_sum([1, 2]) """ Other solution: def square_sum(numbers): return sum(x ** 2 for x in numbers) def square_sum(numbers): return sum(map(lambda x: x**2,numbers)) """
true
77fa8e4bc4cff43f7b7601d0870b671156d983d2
attacker2001/Algorithmic-practice
/leetcode/70. Climbing Stairs.py
2,959
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @file: 70. Climbing Stairs.py @time: 2019/04/28 You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step """ class Solution: def climbStairs_by_steps(self, i, n, memo): if i > n: return 0 if i == n: return 1 if memo[i] > 0: return memo[i] memo[i] = self.climbStairs_by_steps(i + 1, n, memo) + self.climbStairs_by_steps(i + 2, n, memo) return memo[i] def climbStairs(self, n: int) -> int: m = [0] * (n + 1) return self.climbStairs_by_steps(0, n, m.copy()) if __name__ == '__main__': a = Solution() print(a.climbStairs(35)) """ Explanations: Same simple algorithm written in every offered language. Variable a tells you the number of ways to reach the current step, and b tells you the number of ways to reach the next step. So for the situation one step further up, the old b becomes the new a, and the new b is the old a+b, since that new step can be reached by climbing 1 step from what b represented or 2 steps from what a represented. 说白了就是斐波那契数列,只不过是换了一种说法。 Other solutions: def climbStairs(self, n): a = b = 1 for _ in range(n): a, b = b, a + b return a Dynamic Programming: https://leetcode.com/articles/climbing-stairs/ https://leetcode.com/problems/climbing-stairs/discuss/163347/Python-3000DP-or-tm # Solution 1: Recursion (TLE) class Solution(object): def climbStairs(self, n): if n == 1: return 1 if n == 2: return 2 return self.climbStairs(n - 1) + self.climbStairs(n - 2) # Solution 2: Top-Down (using array) class Solution(object): def climbStairs(self, n): if n == 1: return 1 res = [-1 for i in range(n)] res[0], res[1] = 1, 2 return self.dp(n-1, res) def dp(self, n, res): if res[n] == -1: res[n] = self.dp(n - 1, res) + self.dp(n - 2, res) return res[n] # Solution 3: Bottom-Up (using array) class Solution(object): def climbStairs(self, n): if n == 1: return 1 res = [0 for i in range(n)] res[0], res[1] = 1, 2 for i in range(2, n): res[i] = res[i-1] + res[i-2] return res[-1] # Solution 3: Bottom-Up (Constant Space) class Solution(object): def climbStairs(self, n): if n == 1: return 1 a, b = 1, 2 for _ in range(2, n): a, b = b, a + b return b """
true
043a596f123ae6c98391f29df36ee1316b283bf9
hiyounger/sdet05_demo
/WYF/popsoting/paixu.py
776
4.21875
4
# coding:utf-8 # 1、对list进行排序 # pop_list=[6,8,10,1,7,3,9] # pop_list.sort() # # print pop_list # 2、编写一个listsorting方法,接收一个list参数,返回该list参数的排序结果 def listsorting(list): for a in range(len(list)): for b in range(0,len(list)-a-1): if list[b]>list[b+1]: list[b],list[b+1]=list[b+1],list[b] list = [6, 8, 10, 1, 7, 3, 9] listsorting(list) print list # 3、编写一个listsorting方法,接收一个list参数和sort参数(desc, asc),返回该list参数的对应排序结果 def listsorting(list,sort): for a in range(len(list)): for b in range(0,len(list)-a-1): if list[b]>list[b+1]: list[b],list[b+1]=list[b+1],list[b]
false
c7ca3175043bf370551e6e193e484dd733843183
ritwiktiwari/AlgorithmsDataStructures
/Stack/LinkedListImplementation.py
1,367
4.125
4
class Node: def __init__(self, value=None): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def __iter__(self): current = self.head while current: yield current current = current.next class Stack: def __init__(self): self.stack = LinkedList() def is_empty(self): if self.stack.head is None: return True else: return False def push(self, value): node = Node(value) node.next = self.stack.head self.stack.head = node def pop(self): if self.is_empty(): raise ValueError("Stack is already empty") else: temp = self.stack.head.value self.stack.head = self.stack.head.next return temp def peek(self): if self.is_empty(): raise ValueError("Stack is empty") else: return self.stack.head.value def delete(self): self.stack.head = None def __str__(self): values = [str(x.value) for x in self.stack] return ' '.join(values) stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack) print("------") print(stack.pop()) print(stack.pop()) print(stack.pop()) print("------") stack.push(1) print(stack.peek())
false
77f7a48858b463f00c310fcef4388410c89d3659
ritwiktiwari/AlgorithmsDataStructures
/archive/linked_list/link_list_reversal.py
1,419
4.1875
4
class Node(object): def __init__(self,data): self.data = data self.nextNode = None class LinkedList(object): def __init__(self): self.head = None def insert(self,data): newNode = Node(data) if self.head == None: self.head = newNode else: newNode.nextNode = self.head self.head = newNode def print_list(self): current = self.head while current: print(current.data) current = current.nextNode def reverse(self): reverse_link_list = LinkedList() current = self.head while current: reverse_link_list.insert(current.data) current = current.nextNode reverse_link_list.print_list() def reverse_inplace(self): # init previous and current as none; current as last previous = None current = self.head next = None while current is not None: next = current.nextNode # Store next node current.nextNode = previous # Update the reference of current node # Increment previous and current previous = current current = next self.head = previous link = LinkedList() link.insert(20) link.insert(4) link.insert(15) link.insert(10) link.print_list() link.reverse() link.reverse_inplace() link.print_list()
true
c4a7cf3914e30fe219eebd359c529659dc00060e
facufrau/beginner-projects-solutions
/solutions/rockpaperscissors.py
2,305
4.3125
4
# Beginner project 5. # Rock-paper-scissors game. from random import randint import time print("Rock, paper and scissors game") # Create a moves list and a score. moves = ["R","P","S"] score = {"Player": 0 , "Computer": 0, "Ties": 0} # Function to evaluate winner and add score. def play(player, computer): """ Evaluate the winner of the R-P-S game and update score. Player wins return 1, computer wins return 2, ties return 3. """ if (player == "R"): if (computer == "S"): score["Player"] = score["Player"] + 1 return 1 elif (computer == "P"): score["Computer"] = score["Computer"] + 1 return 2 elif (computer == "R"): score["Ties"] = score["Ties"] + 1 return 3 elif (player == "P"): if (computer == "S"): score["Computer"] = score["Computer"] + 1 return 2 elif (computer == "P"): score["Ties"] = score["Ties"] + 1 return 3 elif (computer == "R"): score["Player"] = score["Player"] + 1 return 1 elif (player == "S"): if (computer == "S"): score["Ties"] = score["Ties"] + 1 return 3 elif (computer == "P"): score["Player"] = score["Player"] + 1 return 1 elif (computer == "R"): score["Computer"] = score["Computer"] + 1 return 2 # Main loop while True: while True: player_move = input("Choose your move: (R) Rock, (P) Paper or (S) Scissors\n").upper() if (player_move in moves): break computer_move = moves[randint(0,2)] print(f"Your move is {player_move}") time.sleep(1) print(f"The computer move is {computer_move}") time.sleep(1) result = play(player_move, computer_move) if result == 1: print("You won!!") elif result == 2: print("The computer won") elif result == 3: print("It is a tie") print(f"Scoreboard: \n\tPlayer {score['Player']} \n\tComputer {score['Computer']} \n\tTies {score['Ties']}") flag = input("Play again? 'Yes'/'No'\n") if flag.upper() == 'YES' or flag.upper() == 'Y': continue elif flag.upper == 'NO' or flag.upper() == 'N': break
true
eee31bafc8faf23461d003b3123788816619a517
facufrau/beginner-projects-solutions
/solutions/num_generator_functions.py
1,371
4.25
4
# Generates a 5 digit random number until reach a goal number and count the qty of tries. from random import randint from time import sleep def countdown(): ''' Counts down from 3 and prints to the screen ''' for i in [3, 2, 1]: print(f'{i}...') sleep(1) def ask_number(): ''' Prompts the user for a 5 digit number and checks the input. ''' while True: goal_num = input('Enter goal number: ') try: goal_num = int(goal_num) if goal_num > 10000 and goal_num < 100000: return goal_num print('Please enter a 5 digit integer number') except: print('That is not an integer number') def find_number(goal): ''' Generates random number until the goal is generated. Count number of tries required. ''' tries = 0 while True: tries += 1 random_num = randint(10000,99999) print(random_num) if random_num == goal: return random_num, tries def main(): goal_num = ask_number() print('This program will generate random numbers until reached the input number.') countdown() found_num, tries = find_number(goal_num) print(f'Your goal number was {found_num} and needed {tries} tries.') if __name__ == '__main__': main()
true
75a32476ded737b570551260a8d9950b90d66faf
facufrau/beginner-projects-solutions
/solutions/countdown.py
2,120
4.34375
4
#Beginner project 22 - Countdown timer. ''' Create a program that allows the user to choose a time and date, and then prints out a message at given intervals (such as every second) that tells the user how much longer there is until the selected time. Subgoals: If the selected time has already passed, have the program tell the user to start over. If your program asks for the year, month, day, hour, etc. separately, allow the user to be able to type in either the month name or its number. TIP: Making use of built in modules such as time and datetime can change this project from a nightmare into a much simpler task ''' from time import sleep from datetime import datetime from dateutil import parser, tz from dateutil.relativedelta import relativedelta def time_amount(time_unit: str, countdown: relativedelta) -> str: """Return the time amount formatted with unit if not null.""" t = getattr(countdown, time_unit) if t != 0 : return f"{t} {time_unit}" else: return "" def main(): """Calculates time delta and prints the countdown every 5 seconds.""" units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] print('------Countdown------') event = input("Enter the name of the event you want to track: \n") while True: date_input = input("Enter date in format YYYY-MM-DD HH:MM:SS: ") try: DATE = parser.parse(date_input) DATE = DATE.replace(tzinfo=tz.tzlocal()) except: continue if DATE > datetime.now(tz=tz.tzlocal()): break else: print("Date already passed, please enter another date.") print('Press ctrl + c to stop') while True: now = datetime.now(tz=tz.tzlocal()) countdown = relativedelta(DATE, now) output = [] for tu in units: t = time_amount(tu, countdown) if t: output.append(t) output_string = ", ".join(output) print(f"Countdown to {event}: " + output_string) sleep(5) if __name__ == "__main__": main()
true
badd05c91d29aa690abaf492d18d1be96a18bb59
joebrainy/Lab-1-Data
/hello_world.py
256
4.1875
4
name = input("What is your name?") birth_year = int(input("When were you born?")) print(f"Hello, {name}") from datetime import datetime this_year = datetime.now().year age = this_year - (birth_year) print(f"You must be {age}") print(f"goodbye, {name}")
true
9a598ff515f8fdb50499ea91d23778103e917cd5
SrilakshmiMaddali/PycharmProjects
/devops/github/food_question.py
2,829
4.125
4
#!/usr/bin/env python3 # Dictionary to keep track of food likes counter = {} # Open up the favorite foods log and count frequencies using the dictionary with open("favorite_foods.log", "r") as f: for line in f: item = line.strip() if item not in counter: counter[item] = 1 else: counter[item] += 1 # Print out all the available liked foods print("Select your favorite food below:") for item in counter: print(item) # Ask which food is the user's favorite answer = input("Which of the foods above is your favorite? ") answer = answer.lower() # Print out how many others like the user's favorite food, otherwise say it can't be found try: print("{} of your friends like {} as well!".format(counter[answer], answer)) exit(0) except KeyError: print("Hmm we couldn't find anyone who also likes \"{}\".".format(answer)) print("Did you enter one of the foods listed above?") exit(0) """ In this section, we'll fix the script food_question.py, which displayed an error when executing it. You can run the file again to view the error. ./food_question.py Output: 5079d715c2f97126.png This script gives us the error: "NameError: name 'item' is not defined" but your colleague says that the file was running fine before the most recent commit they did. In this case, we'll revert back the previous commit. For this, check the git log history so that you can revert back to the commit where it was working fine. git log Output: e89b58d398338a9d.png Here, you'll see the commits in reverse chronological order and find the commit having "Rename item variable to food_item" as a commit message. Make sure to note the commit ID for this particular commit. Enter q to exit. To revert, use the following command: git revert [commit-ID] Replace [commit-ID] with the commit ID you noted earlier. This creates a new commit again. You can continue with the default commit message on the screen or add your own commit message. Then continue by clicking Ctrl-o, the Enter key, and Ctrl-x. Now, run food_question.py again and verify that it's working as intended. ./food_question.py Output: cedea93d17157044.png Merge operation Before merging the branch improve-output, switch to the master branch from the current branch improve-output branch using the command below: git checkout master Merge the branch improve-output into the master branch. git merge improve-output Output: f1ea7fd1a1500f03.png Now, all your changes made in the improve-output branch are on the master branch. ./food_question.py Output: 5216220ceb4627f1.png To get the status from the master branch, use the command below: git status Output: c18b4c4d4dd08623.png To track the git commit logs, use the following command: git log Output: b78661eaf4c93cf1.png """
true
9c91c98c2f7f83b781becae042cf1be890479a9f
DmitryTsybulkin/adaptive-python
/lesson1/task2/task.py
593
4.25
4
# put your python code here one = float(input()) two = float(input()) operator = input() if operator == "+": print(one + two) elif operator == "-": print(one - two) elif operator == "/": if two == 0: print("Division by 0!") else: print(one / two) elif operator == "*": print(one * two) elif operator == "mod": if two == 0: print("Division by 0!") else: print(one % two) elif operator == "pow": print(one ** two) elif operator == "div": if two == 0: print("Division by 0!") else: print(one // two)
false
2bd4cba118f79c1ba3ddec7cdf4a83c080375dd1
thiagorente/pythonchallenge
/challenge_1.py
1,531
4.15625
4
def calc_char(charactere): #check if char is a letter, if yes advance two letters if it's not y or z #if y or z return to a and b respectively new_char = charactere if(charactere.isalpha()): if(charactere == 'y' or charactere == 'z'): new_char = chr(ord(charactere) - 24) else: new_char = chr(ord(charactere) + 2) return new_char def challenge_1(text_to_convert): #the answer to this challenge is get the text from the website and decode it by #changing the letter for the second letter after that new_string = '' for line in text_to_convert: for char in line: #check if the char is a letter new_string = new_string + calc_char(char) print(new_string + '\n') def new_challenge_1(text_to_convert): dict = {"a" : "c", "b": "d", "c" : "e", "d": "f", "e" : "g", "f" : "h", "g" : "i", "h" : "j", "i" : "k", "j": "l", "k" : "m", "l" : "n", "m" : "o", "n" : "p", "o" : "q", "p" : "r", "q" : "s", "r" : "t", "s" : "u", "t" : "v", "u" : "w", "v" : "x", "w" : "y", "x" : "z", "y" : "a", "z" : "b"} new_text = '' for line in text_to_convert: mktrans = (line.maketrans(dict)) new_text = new_text + line.translate(mktrans) print(new_text + '\n') if __name__ == '__main__': challenge_1('map') challenge_1(open('./resources/challenge_1.txt', 'r')) new_challenge_1('map') new_challenge_1(open('./resources/challenge_1.txt', 'r'))
false
f5edfe34e10d69825125b811e97f011b3a487874
Aayush-Kasurde/python-attic
/regex/Exercise6.py
426
4.1875
4
#!/usr/bin/env python # Exercise 6 - repeatition cases import re line = "123456" #matchObj = re.search(r'\d{3}', line, re.M|re.I) # Match exactly 3 digits #matchObj = re.search(r'\d{3,}', line, re.M|re.I) # Match 3 or more digits matchObj = re.search(r'\d{3,5}', line, re.M|re.I) # Match 3, 4, or 5 digits if matchObj: print "matchObj.group() : ", matchObj.group() else: print "No Match found"
false
31cb120639053a12c374f44dea0b7209cf0d2e4e
Aayush-Kasurde/python-attic
/puzzles/perpetual_calendar.py
513
4.125
4
#!/usr/bin/env python def dayofweek(year,month,day): t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4] a = {0 : "Sunday", 1 : "Monday", 2 : "Tuesday", 3 : "Wednesday", 4 : "Thursday", 5 : "Friday", 6 : "Saturday"} if month < 3 : year = year - 1 answer = (year + year / 4 - year / 100 + year / 400 + t[month-1] + day ) answer = answer % 7 return a[answer] print "12/05/2000 is " + dayofweek(2000,05,12) print "01/01/2012 is " + dayofweek(2012,01,01) print "01/04/2012 is " + dayofweek(2012,04,01)
false
eae2d1d244b241449a9527f223f6f16313a8f534
laodearissaputra/data-structures
/trees/inorderPredecessorAndSuccessor.py
2,099
4.1875
4
# Python program to find predecessor and successor in a BST # A BST node class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None def findPredecessorAndSuccessor(self, data): global predecessor, successor predecessor = None successor = None if self is None: return if self.data == data: if self.left is not None: temp = self.left if temp.right is not None: while(temp.right): temp = temp.right predecessor = temp if self.right is not None: temp = self.right while(temp.left): temp = temp.left successor = temp return if data < self.data: print('Left') self.left.findPredecessorAndSuccessor(data) else: print('Right') self.right.findPredecessorAndSuccessor(data) def insert(self, data): if self.data == data: return False elif data < self.data: if self.left: return self.left.insert(data) else: self.left = Node(data) return True else: if self.right: return self.right.insert(data) else: self.right = Node(data) return True if __name__ == '__main__': root = Node(50) root.insert(30) root.insert(20) root.insert(40) root.insert(70) root.insert(60) root.insert(80) # following BST is created # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 root.findPredecessorAndSuccessor(70) if (predecessor is not None) and (successor is not None): print('Predecessor:', predecessor.data, 'Successor:', successor.data) else: print('Predecessor:', predecessor, 'Successor:', successor)
true
7e7a349797423223117102900bc7d866f2bec532
Wolfant/EspePython
/Labs/error1.py
929
4.125
4
def transformar_int(x): """Funcion que trasforma un objeto a int Args: x: objeto a transformar Returns: Valor del objeto en int Raises: ValueError: En caso de que sea str TypeError: en caso de que sea un objeto contenedor """ try: return (int(x)) except (ValueError, TypeError) as e: raise e def main(): numero = input('Ingrese un numero: ') print(transformar_int(numero)) def test_funcion(): entero = 34 cadena = '56' lista = [1, 2, 34] palabra = "hola" try: print(transformar_int(entero)) print(transformar_int(cadena)) print(transformar_int(lista)) print(transformar_int(palabra)) print ('esto nunca va a mostrarse') except (ValueError, TypeError): print('error') print ('esto siempre se ejecuta') if __name__ == '__main__': test_funcion()
false
4d06682ad0fd3e950b727b5303571168599e7875
KarstenLi/Learning-Python
/nameIntro.py
239
4.125
4
''' hello = input ("hello") monkey = 'hi' if hello == "monkey": print ("BANANA") else: print ("You dissapoint me.") ''' name = input ("Hi, what is your name?") print ("That is the worst name ever, " + name + ".")
false
5dd0c7f05a570a43d8702857d7db847762cd1b64
Raul-Morales-Martinez/Proyect_python
/archgit.py
2,047
4.40625
4
# comandos y ejemplos coding dojo analizar comando por separado en al consola first_name = "Zen" last_name = "Coder" age = 27 print(f"mi nombre es {first_name} {last_name} y tengo {age} años") ## first_name = "Zen" last_name = "Coder" age = 27 print("Mi nombre es {} {} y tengo {} años.".format(first_name, last_name, age)) # output: My name is Zen Coder and I am 27 years old. print("Mi nombre es {} {} y tengo {} años.".format(age, first_name, last_name)) # output: My name is 27 Zen and I am Coder years old. ## hw = "Hola %s" % "mundo" # con valores literales py = "Me encanta Python %d" % 3 print(hw, py) # salida: Hola mundo Me encanta Python 3 name = "Zen" age = 27 print("Mi nombre es %s y soy %d" % (name, age)) # o con variables # Salida: Mi nombre es Zen y tengo 27 ## x = "hola mundo" print(x.title()) # Salida: "Hello World" ## ## #funciones def add(a,b):#nombre de la función: 'add', parámetros: a y b  x = a + b# proceso return x# retorno value: x #variables de la funcion new_val = add(3, 5) # llamando a la función add, con los argumentos 3 y 5 copy print(new_val) # el resultado de la función add se devuelve y se guarda en new_val, por lo que veremo #ejemplos de funciones def say_hi(name): return "Hi " + name greeting = say_hi("Michael") # el valor devuelto por la función se asigna a la variable print(greeting) # mostrará 'Hi Michael' ## # def beCheerful(name='', repeat=2): # set defaults when declaring the parameters print(f"good morning {name}\n" * repeat) beCheerful() # output: good morning (repeated on 2 lines) beCheerful("tim") # output: good morning tim (repeated on 2 lines) beCheerful(name="john") # output: good morning john (repeated on 2 lines) beCheerful(repeat=6) # output: good morning (repeated on 6 lines) beCheerful(name="michael", repeat=5) # output: good morning michael (repeated on 5 lines) # NOTE: argument order doesn't matter if we are explicit when sending in our arguments! beCheerful(repeat=3, name="kb") # output: good morning kb (repeated on 3 lines)
false
88f039201cd0c170d00c82e17f56362d5a598b37
gitmocho/fizzbuzz
/fizzbuzz.py
446
4.46875
4
""" Write a program - prints the numbers from 1 to 100. - But for multiples of three print 'Fizz' instead of the number - and for the multiples of five print Buzz. - numbers which are multiples of both three and five print FizzBuzz. Sample output: """ x = 0 for x in range(0,100): if x % 3 == 0 and x % 5 == 0: print ('Fizz Buzz') elif x % 3 == 0: print ('Fizz') elif x % 5 == 0: print ('Buzz') else: print (x) x = x + 1
true
7a5e0ef2c7f0d7f6227751954f98abaaba7c3219
saedislea/forritun
/sequence.py
604
4.21875
4
#Algorithm #Print the following sequence: 1,2,3,6,11,20,37... #Sum first 3 numbers (1,2,3=6) #Then num1 becomes num2 and continue #Input number from user n = int(input("Enter the length of the sequence: ")) # Do not change this line sum = 0 num1 = 1 num2 = 2 num3 = 3 for i in range(1,n+1): if i == 1: print(i) continue elif i == 2: print(i) continue elif i == 3: print(i) continue #Numer one becomes number 2, num2 -> num3 and num3 -> sum sum = (num1 + num2 + num3) num1 = num2 num2 = num3 num3 = sum print(sum)
true
fd5d6d42e68cbc29c741a8114e5a6e8262a358b6
MyVeli/ohjelmistotekniikka-harjoitustyo
/src/logic/investment_costs.py
1,122
4.34375
4
class YearlyCosts: """Class used to hold list of costs for a particular year. Used by InvestmentPlan class """ def __init__(self, cost): """constructor for yearly costs Args: cost (tuple): description, value, year """ self.year = cost[2] self.costs = list() self.cost_sum = 0.0 self.add_cost(cost) def add_cost(self, cost): """add a new cost item to the object Args: cost (tuple): description, value, year """ self.costs.append((cost[0], cost[1], cost[2])) self.cost_sum += float(cost[1]) def remove_cost(self, cost): self.costs.remove(cost[0],cost[1], cost[2]) def get_costs(self): """used to get list of costs Returns: list of tuples: returns all cost items for the year in list (description, value, year) """ return self.costs def get_cost_sum(self): """used to get the sum of all costs for the year Returns: float: sum of costs """ return self.cost_sum
true
3e1c37b7b610a94a31be79ef8ba92e7a7133b7ad
dnbadibanga/Python-Scripts
/Pattern.py
1,585
4.4375
4
## #Assignment 6 - Pattern.py #This program creates a pattern of asterisks dependant on a number given #by the user # #By Divine Ndaya Badibanga - 201765203 # #define the recursive function that will write out a pattern def repeat(a, b): #the base case that ensures the function ends once the pattern #is complete if abs(a) > b: return #the recursive case that continuously calls on the function #in order to print out the pattern else: #the condition statement the function follows to print out the #descending part of the pattern if a > 0: #print the number of asterisks, with each iteration, decrease #the number of asterisks printed print('*' * a) #call on the function again, with a decreased input number return repeat(a-1, b) #write the condition statement the function follows to print out the #ascending part of the pattern else: #print the number of asterisks, with each iteration, increase the #number of asterisks to be printed, using the absolute funtion #to print appropriately if a != 0: print('*' * abs(a)) #call on the function again, with a decreased input number return repeat(a-1, b) #prompt the user for input regarding the size of the pattern to be printed a = int(input('Please enter an integer value to start the pattern: ')) #invoke the function with the input given by the user repeat(a, a) #FIN
true
3bbfc8abdfcd57d2bd42c918710d5d6bd32869ff
dnbadibanga/Python-Scripts
/NLProducts.py
1,589
4.34375
4
## #This program calculates price ish # #Set cost to produce per unit ITEMA_COST = 25 ITEMB_COST = 55 ITEMC_COST = 100 #markup MARKUPTEN = 1.1 MARKUPFIFTEEN = 1.15 #enter data itemA_num = int(input('Please enter the number of ItemA sold: ')) itemB_num = int(input('Please enter the number of ItemB sold: ')) itemC_num = int(input('Please enter the number of ItemC sold: ')) #compute selling price itemA_Price = ITEMA_COST * MARKUPTEN itemB_Price = ITEMB_COST * MARKUPTEN itemC_Price = ITEMC_COST * MARKUPFIFTEEN #compute total cost to produce total_Cost = (ITEMA_COST * itemA_num) + (ITEMB_COST * itemB_num) + (ITEMC_COST * itemC_num) #compute total sales total_Sales = (itemA_Price * itemA_num) + (itemB_Price * itemB_num) + (itemC_Price * itemC_num) #compute profit profit = total_Sales - total_Cost #calculate percentage total_Items = itemA_num + itemB_num + itemC_num itemA_perc = itemA_num / total_Items * 100 itemB_perc = itemB_num / total_Items * 100 itemC_perc = itemC_num / total_Items * 100 #Display data print('The selling price of ItemA is $', '%.2f' %itemA_Price) print('The selling price of ItemB is $', '%.2f' %itemB_Price) print('The selling price of ItemC is $', '%.2f' %itemC_Price) print('Total Cost to Produce (all items sold) is $', '%.2f' %total_Cost) print('Total Sales (all items sold) is $', '%.2f' %total_Sales) print('Profit is $', '%.2f' %profit) print('Percentage of ItemA sold is ', itemA_perc, '%') print('Percentage of ItemB sold is ', itemB_perc, '%') print('Percentage of ItemC sold is ', itemC_perc, '%')
true
8d479521727e008011feceab37f1d921afa5a17a
108krohan/codor
/hackerrank-python/learn python/standardize-mobile-number-using-decorators - decorators mobile numbers.py
1,535
4.3125
4
"""standardize mobile number using decorators at hackerrank.com """ """ Problem Statement Lets dive into decorators! You are given N mobile numbers. Sort them in ascending order after which print them in standard format. +91 xxxxx xxxxx The given mobile numbers may have +91 or 91 or 0 written before the actual 10 digit number. Alternatively, there maynot be any prefix at all. Input Format An integer N followed by N mobile numbers. Output Format N mobile numbers printed in different lines in the required format. Sample Input 3 07895462130 919875641230 9195969878 Sample Output +91 78954 62130 +91 91959 69878 +91 98756 41230 """ def standardize(strNum) : lstNum = list(strNum) lstNum = lstNum[-10:] ## strNum = str(lstNum) ## print strNum result = '+91 ' for digit in lstNum : if len(result) == 9 : result += ' ' result += digit return result numCases = int(raw_input()) record = [] for _ in range(numCases) : record.append(standardize((raw_input()))) record.sort() for i in record : print i """ def standardize(record) : for oneRecord in record : result = '+91 ' for elem in str(oneRecord)[:] : if len(result) == 9 : result += ' ' result += elem print result numCases = int(raw_input()) record = [] for _ in range(numCases) : record.append(int(raw_input()[-10:])) record.sort() standardize(record) """
true
8c8b4e17b90c88882d4a986847fa7ede8c6eb906
108krohan/codor
/hackerrank-python/learn python/map-and-lambda-expression - cube a factorial by mapping it.py
1,721
4.3125
4
"""map and lambda expression at hackerrank.com Problem Statement Let's learn some new python concepts! You have to generate a list of the first N fibonacci numbers, 0 being the first number. Then, apply the map function and a lambda expression to cube each fibonacci number and print the list. Input Format An integer N Output Format A list containing cubes of first N fibonacci numbers. Constraints 0<=N<=15 Sample Input 5 Sample Output [0, 1, 1, 8, 27] The first 5 fibonacci numbers are [0, 1, 1, 2, 3] and their cubes are [0, 1, 1, 8, 27] Concept The map() function applies a function to every member of an iterable and returns the result. It takes two parameters, first the function which is to be applied and second the iterables like a list. Let's say you are given a list of names and you have to print a list which contains length of each name. >> print (list(map(len, ['Tina', 'Raj', 'Tom']))) [4, 3, 3] Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function which has only one line in its body. It proves very handy in functional and GUI programming. >> sum = lambda a, b, c: a + b + c >> sum(1, 2, 3) 6 Note: Lambda functions cannot use the return statement and can only have a single expression. Unlike def, which creates a function and assigns it a name, lambda creates a function and returns the function itself. Lambda can be used inside list and dictionary. """ fibo = [] nums = int(raw_input()) for i in range(nums) : if i in (0,1) : fibo.append(i) else : fibo.append(fibo[-2] + fibo[-1]) print map( lambda x : x**3, fibo)
true
5486cbf6316d70c3e9097ba40ca562ca0594d70e
108krohan/codor
/hackerrank-python/learn python/regex - regular expressions, phone number checking validity.py
1,655
4.90625
5
# -*- coding: cp1252 -*- """ Problem Statement Let's dive into the interesting topic of regular expressions! You are given some inputs and you are required to check whether they are valid mobile numbers. A valid mobile number is a ten digit number starting with 7, 8 or 9. Input Format The first line contains an integer N followed by N lines, each containing some string. Output Format For every string listed, print YES if it is a valid mobile number and NO if it isnt. Constraints 1 <= N <= 10 Mobile Number contains valid alpha-numeric characters 2 <= len(Number) <= 15 Sample Input 2 9587456281 1252478965 Sample Output YES NO Concept A valid mobile number is a ten digit number starting with 7, 8 or 9. Regular expressions are a key concept in any programming language. A quick explanation with python examples is available here. You could also go through the link below to read more about regular expressions in python. https://developers.google.com/edu/python/regular-expressions """ ##numCases = int(raw_input()) ##result = [] ##for _ in range(numCases) : ## oneNum = raw_input() ## if len(oneNum) is not 10 : ## print 'NO' ## elif oneNum[0] not in ('7', '8', '9') : ## print 'NO' ## else : ## try : ## oneNum = int(oneNum) ## print 'YES' ## except : ## print 'NO' ## import re meta = re.compile(r'(7|8|9)\d{9,9}$') numCases = int(raw_input()) for _ in range(numCases) : num = (raw_input()) if meta.match(num) : print 'YES' else : print 'NO'
true
c9c2dfb39da519c66735e1a52099f508b41bbcc4
108krohan/codor
/hackerrank-python/algorithm/strings/funnyString - reverse string and ord check.py
1,532
4.15625
4
# -*- coding: utf-8 -*- """funny string at hackerrank.com """ """ Problem Statement Suppose you have a string S which has length N and is indexed from 0 to N−1. String R is the reverse of the string S. The string S is funny if the condition |Si−Si−1|=|Ri−Ri−1| is true for every i from 1 to N−1. (Note: Given a string str, stri denotes the ascii value of the ith character (0-indexed) of str. |x| denotes the absolute value of an integer x) Input Format First line of the input will contain an integer T. T testcases follow. Each of the next T lines contains one string S. Constraints 1<=T<=10 2<=length of S<=10000 Output Format For each string, print Funny or Not Funny in separate lines. Sample Input 2 acxz bcxz Sample Output Funny Not Funny Explanation Consider the 1st testcase acxz here |c-a| = |x-z| = 2 |x-c| = |c-x| = 21 |z-x| = |a-c| = 2 Hence Funny. """ testCases = int(raw_input()) for _ in range(testCases) : string = raw_input() reverse = string[::-1] #reverse = ''.join(reversed(string)) also works #str[::-1] is an order times faster, however result = 'Funny' for i in range(1, len(string)) : if abs(ord(string[i]) - ord(string[i - 1])) is not \ abs(ord(reverse[i]) - ord(reverse[i - 1])) : result = 'Not Funny' break if result == 'Not Funny' : print result else : print result
true
cabf3a7e5c654e72fad14c3177cb20552f7e6682
108krohan/codor
/MIT OCW 6.00.1x python/inputOps.py
218
4.3125
4
y=float(raw_input("Enter a number\t")) print y print y+y x= float(raw_input("Enter a number x\t")) print x if x / 2 == 0 : print 'Even' else : print 'Odd' if x % 3 != 0 : print 'And not divisible by 3'
false
bf70462b8a25e767c0336a420dea9b43de95d671
108krohan/codor
/hackerrank-python/learn python/defaultdicts.py
2,305
4.1875
4
# -*- coding: utf-8 -*- """ Problem Statement DefaultDict is a container in the collections class of Python. It is almost the same as the usual dictionary (dict) container but with one difference. The value fields' data-type is specified upon initialization. A basic snippet showing the usage follows: from collections import defaultdict d = defaultdict(list) d['python'].append("awesome") d['something-else'].append("not relevant") d['python'].append("language") for i in d.items(): print i This prints: ('python', ['awesome', 'language']) ('something-else', ['not relevant']) In this challenge, you will be given 2 integers (n and m) and n words which might repeat, say they belong to a word group A. Then you'll be given m other words belonging to word group B. For each of these m words, you have to check whether the word has appeared in A or not. If it has then you have to print indices of all of its occurences. If it has not then just print −1. Constraints 1≤n≤10000 1≤m≤100 1≤ length of each word in the input≤100 Input Format The first line contains n and m. The next n lines contain the words belonging to A. The next m lines contain the words belonging to B. Output Format Output m lines. The ith line should contain the 1 indexed positions of occurences of the ith word, separated by spaces, of the last m lines of the input. Sample Input 5 2 a a b a b a b Sample Output 1 2 4 3 5 Explanation 'a' appeared 3 times in positions 1, 2 and 4. 'b' appeared 2 times in position 3 and 5. Hence the output. For the same word group A, had the appearances of 'c' been asked about in the word group B, you would have had to print −1 instead. from collections import defaultdict """ from collections import defaultdict N,M = map(int, raw_input().split()) result = defaultdict(list) record = [] checker = [] for i in range(N) : record.append(raw_input()) for i in range(M) : checker.append(raw_input()) if checker[i] in record : for j in range(N) : if record[j] == checker[i] : result[i].append(j) else : result[i].append(-2) for i in range(M): for j in result[i] : print j+1, print ''
true
115322603ea25e037e0672875eae1221cced3a67
108krohan/codor
/MIT OCW 6.00.1x python/memoryAndSearchMethodsSorting.py
2,558
4.1875
4
"""Recorded lecture 9. =Selection sort =Merge sort =String Merge sort =Function within function """ ## ####Selection Sort ##def selSort(L): ## ##ascending order ## for i in range (len(L)-1): ## ##Invariant : the list L[:] is sorted ## minIndex = i ## minVal = L[i] ## j = i + 1 ## while j < len(L) : ## if minVal > L[j]: ## minIndex = j ## minVal = L[j] ## j += 1 ## temp = L[i] ## L[i] = L[minIndex] ## L[minIndex] = temp ## print 'partially sorted list = ', L ## ##L = [35, 4, 5, 29, 17, 58, 0] ##selSort(L) ##print 'Sorted List = ', L ## """merge sort techinque""" def merge (left, right, lt): result = [] i,j = 0,0 while i < len(left) and j < len(right): if lt(left[i], right[j]) : result.append(left[i]) ## print 'merging ', left[i], result i += 1 else : result.append(right[j]) j += 1 ## print 'merging ', right[i], result while i < len(left) : result.append(left[i]) i += 1 while j < len(right) : result.append(right[j]) j += 1 return result def sort (L, lt = lambda x,y : x < y): if len(L) < 2 : return L[:] else : middle = int(len(L)/2) left = sort (L[:middle],lt) right = sort (L[middle:],lt) print 'About to merge', left, 'and', right return merge (left, right, lt) ##L = [35, 4, 5, 29, 17, 58, 0] ##newL = sort(L) ##print 'SortedList = ', newL ##L = [1.0, 2.25, 24.5, 12.0, 2.0, 23.0, 19.125, 1.0] ##newL = sort(L, float.__lt__) ##gt descending order ##print 'SortedList = ', newL """lastname and first name""" ###use this program with the merge sort function given above. def lastNameFirstName(name1,name2): import string name1 = string.split(name1, ' ') name2 = string.split(name2, ' ') if name1[1] is not name2[1] : return name1[1] < name2[1] else : return name1[0] < name2[0] def firstNameLastName (name1, name2) : import string name1 = string.split (name1, ' ') name2 = string.split (name2, ' ') if name1[0] is not name2[0] : return name1[0] < name2[0] else : return name1[1] < name2[0] L = ["John Guttag", "Ronit Kumar", "Rohan Awesome Kumar", "Kanishka Kumar", \ "Taurooshya Yadav"] newL = sort(L, lastNameFirstName) ##acts as lt now, for strings. print 'SortedList = ', newL
true
efdac446b4f2fc678c0ebdef33124b46fc3acd49
108krohan/codor
/hackerrank-python/learn python/piling up, traversing list from both sides to reach common point.py
2,936
4.15625
4
# -*- coding: utf-8 -*- """piling up at hackerrank.com Problem Statement There is a horizontal row of n cubes. Side length of each cube from left to right is given. You need to create a new vertical pile of cubes. The new pile should be such that if cubei is on cubej then sideLengthj≥sideLengthi. But at a time, you can only pick either the leftmost or the rightmost cube only. Print "Yes" if its possible, " No" otherwise. Input Format First line contains a single integer T, denoting the number of test cases. For each testcase, there are 2 lines. First line of each test case contains n. Second line of each test case contains n space separated integers, the sideLengths of the cubes in that order. Constraints 1≤T≤5 1≤n≤105 1≤sideLength<231 Output Format For each testcase, output a single line containing a single word, either a "Yes" or a "No". Sample Input 2 6 4 3 2 1 3 4 3 1 3 2 Sample Output Yes No Explanation In the first sample, pick in this order: left, right, left, right, left, right. In the second sample no order gives an appropriate arrangement since 3 will always come after either 1 or 2. """ result = [] record = [] try : numCases = int(raw_input()) except : pass for _ in range(numCases) : oRLen = int(raw_input()) oneRecord = map(int, raw_input().split()) left = 0 right = oRLen - 1 while (oneRecord[left] >= oneRecord[left+1] or \ oneRecord[right] >= oneRecord[right - 1]) and \ oneRecord[left] is not oneRecord[right] and \ left < right: if oneRecord[left] >= oneRecord[left+1] : left += 1 if oneRecord[right] >= oneRecord[right - 1] : right -= 1 if oneRecord[left] == oneRecord[right] : print left, oneRecord[left] print right, oneRecord[right] result.append('Yes') else : print left, oneRecord[left] print right, oneRecord[right] result.append('No') for i in result : print i """ Shit another Solution : from collections import deque import sys for _ in range(input()): n = input() arr = map(int,raw_input().split()) lst = deque(arr) curr = 9999999999999999 flag = 0 if (len(lst)<=2): print "Yes" continue left = lst.popleft() right = lst.pop() latest = -1 while (len(lst)>0): flag = 0 if (left >= right and left <= curr): curr = left left = lst.popleft() latest = left flag = 1 elif (right> left and right <= curr): curr = right right = lst.pop() latest = right flag = 1 if flag == 0: break if len(lst)>0 or latest > curr: print "No" else: print "Yes" """
true
fe4e651dc4bfe552af76448e23cc6ff03861f5c0
LizaChelishev/class2010
/circum_of_a_rectangle.py
282
4.40625
4
def circum_of_a_rectangle(height, width): _circum = height * 2 + width * 2 return _circum width = float(input('Enter the width: ')) height = float(input('Enter the height: ')) circum = circum_of_a_rectangle(height, width) print(f'The circum of the rectangle is {circum}')
true
15204536853cfb1c049bedfe6775bcbff045ba6e
AnushavanAleksanyan/data_science_beyond
/src/second_month/task_2_3.py
1,005
4.125
4
import numpy as np from numpy import newaxis # task_2_3_1 # Write a NumPy program to find maximum and minimum values of an array def min_max(arr): mx = np.max(arr) mn = np.min(arr) return mn, mx # task_2_3_2 # Write a NumPy program to find maximum and minimum values of the secont column of an array def min_max_second_col(arr): mx = np.max(arr[:,1]) mn = np.min(arr[:,1]) return mn, mx # task_2_3_3 # Write a NumPy program to find median of an array def mediana(arr): return np.median(arr) # task_2_3_4 # Create one dimention and two dimention arrays and multiply them def mult(arr1, arr2): return arr1[:,newaxis]*arr2 def main(): arr = np.random.randint(2,20, size=(10,5)) a = np.array([2, 5, 7, 4]) b = np.array([[3, 2, 4],[1,2,5],[2,1,3],[4,1,5]]) print(arr) print(arr[:,1]) print(min_max(arr)) # task_2_3_1 print(min_max_second_col(arr)) # task_2_3_2 print(mediana(arr)) # task_2_3_3 print(mult(a,b)) # task_2_3_4 main()
true
dc8141598f1afe6eec21121c1e1e839f92f388f3
gadamslr/A-Level-Year-1
/GroupU/gtin_Task1.py
1,648
4.125
4
#GTIN challenge # Initialise variables GTINcheck = False gtinList = [] checkDigit = 0 # Checks that the GTIN number entered is valid while GTINcheck == False: gtinNum = input("Please enter a 7 or 8 digit GTIN number!!") try: # Validation check to ensure the value entered is numeric. if int(gtinNum) and (6 < len(gtinNum) < 9 ): gtinList = list(gtinNum) GTINcheck = True except ValueError: #If value entered is non-numeric then inform user print("GTIN should be numeric") print("Try again") print("GTIN number entered is: ",gtinList) # Counter to perform the main algorithm for task 1 counter = 0 calc = 0 for counter in range(0,7): # Loops from 0 upto, not including the 7th GTIN digit x = int(gtinList[counter]) if (counter % 2) == 1: calc +=(x * 1) else: calc +=(x * 3) print("Sum of GTIN7 digits is is: {}".format (calc)) # To calculate the nearest multiple of 10 I have used a counter while (calc + checkDigit) %10!=0: checkDigit += 1 print("Nearest multiple of 10 is: {}".format (calc + checkDigit)) print("Therefore check digit is: {}".format (checkDigit)) # Test to see if the eigth digit is present. if len(gtinNum) == 8: # If GTIN num entered = 8 digits print("Validation check on eight digit of GTIN 8 number.") if int(checkDigit) == int(gtinNum[7]): print("GTIN8 checkDigit is valid: {} ".format (checkDigit)) else: print("GTIN8 checkDigit is not valid: {}".format (gtinNum[7]))
true
b6e6c8c5b2a05659231dc08455d1f6c321f7909e
cfxmys/cpython
/game/sample_game1.py
328
4.1875
4
"""--- 第一个小游戏 ---""" temp = input("猜一下小甲鱼现在心里想的哪个数字") guess = int(temp) if guess == 8: print("你是小甲鱼心里的蛔虫吗") print("就是才中了也没有奖励,哈哈") else: print("猜错了,小甲鱼心里想的是 8") print("游戏结束了,不玩了")
false
8b7fb945d5a66792d6bc7613114b4a2d6e84f8aa
susanmpu/sph_code
/python-programming/learning_python/date_converter.py
644
4.34375
4
#!/usr/bin/env python def main(): """ Takes a short formatted date and outputs a longer format. """ import sys import string months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] short = raw_input("Please enter the date (mm/dd/yyyy): ") month_s, day_s, year_s = string.split(short, "/") month = int(month_s) month_l = months[month - 1] print "The date is: %s %s, %s." % (month_l, day_s, year_s) if raw_input("Press RETURN to exit."): sys.exit(0) if __name__ == '__main__': main()
true
30c43127770096540cf10c087a9bc901b6dbb0ce
susanmpu/sph_code
/python-programming/learning_python/ascii_to_plain.py
574
4.15625
4
#!/usr/bin/env python # by Samuel Huckins def main(): """ Print the plain text form of the ASCII codes passed. """ import sys import string print "This program will compute the plain text equivalent of ASCII codes." ascii = raw_input("Enter the ASCII codes: ") print "Here is the plaintext version:" plain = "" for a in string.split(ascii): ascii_code = eval(a) plain = plain + chr(ascii_code) print "" print plain if raw_input("Press RETURN to exit."): sys.exit(0) if __name__ == '__main__': main()
true
ca292ea53fa1ca32820061f1891393d063e9106b
susanmpu/sph_code
/python-programming/learning_python/hydrocarbon_weight.py
1,060
4.15625
4
#!/usr/bin/env python # by Samuel Huckins def hydrocarbon_weight(hydrogen, carbon, oxygen): """ Calculates the weight of a hydrocarbon atom containing the passed number of atoms present per type. hydrogen -- Number of hydrogen atoms. carbon -- Number of carbon atoms. oxygen -- Number of oxygen atoms. """ h_weight = 1.0079 * hydrogen c_weight = 12.011 * carbon o_weight = 15.9994 * oxygen mol_weight = h_weight + c_weight + o_weight return mol_weight def main(): """ Controls main program flow. """ h = int(raw_input("What is the number of hydrogen atoms? ")) c = int(raw_input("What is the number of carbon atoms? ")) o = int(raw_input("What is the number of oxygen atoms? ")) mol_weight = hydrocarbon_weight(h, c, o) print "The hydrocarbon containing %s hydrogen atoms, %s carbon atoms, and \ %s oxygen atoms has a molecular weight of %s." % (h, c, o, mol_weight) if __name__ == '__main__': main() if raw_input("Press RETURN to exit."): sys.exit(0)
true
a292a52811e08fc803e02ce315635fd34ff4c752
susanmpu/sph_code
/python-programming/learning_python/find_distance.py
759
4.21875
4
#!/usr/bin/env python # by Samuel Huckins import math def find_distance(point1, point2): """ Find the distance between the points passed. point1 -- X and Y coordinates of the first point. point2 -- X and Y coordinates of the second point. """ distance = math.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) **2) return distance def main(): """ Provides main flow control. """ point1 = input("Coordinates for point 1 (x, y): ") point2 = input("Coordinates for point 2 (x, y): ") dist = find_distance(point1, point2) print "The distance between %s and %s is %0.2f." % (point1, point2, dist) if __name__ == '__main__': main() if raw_input("Press RETURN to exit."): sys.exit(0)
true
a56363e486fe4bf9d7795a274b220cfbf81e7eab
susanmpu/sph_code
/python-programming/learning_python/bmi_calc.py
644
4.40625
4
#!/usr/bin/env python import math def main(): """ Asks for height and weight, returns BMI and meaning. """ height = raw_input("What is your height (FEET INCHES)? ") height = int(height.split(" ")[0]) * 12 + int(height.split(" ")[1]) weight = int(raw_input("What is your weight (lbs)? ")) w_part = weight * 720 h_part = math.sqrt(height) bmi = w_part / h_part print "Being %s inches tall and weighing %s pounds, your BMI is: %s" % \ (height, weight, bmi) if bmi in range(19, 26): print "This is considered healthy." else: print "This is considered unhealthy." main()
true
971fd0f327e8e2243ee8b2d3875c1707c214bffe
ashifujjmanRafi/code-snippets
/python3/data-structures/array/array.py
1,289
4.15625
4
# import array module import array # declare an array arr = array.array('i', [1, 2, 3]) # print the original array using for loop for i in range(3): print(arr[i], end=' ') print('\r') print(arr.itemsize) # return the length of a item in bytes print(arr.typecode) # return the type code print(arr.buffer_info()) # return a tuple (address, length) print(arr.buffer_info()[1] * arr.itemsize) # 3 * 4 => 12 print(arr.count(3)) # return the number of occurrence of 3 in the array. # array append(value) arr.append(4) print(arr) # array insert(index_position, value) arr.insert(2, 10) # insert 10 in 3rd postion print(arr) # insert in last position. if index_position is greater then length size then insert in last position like append method arr.insert(100, 20) print(arr) # array pop(position) : remove the element at that postion and return the value ret_value = arr.pop(2) print(ret_value) print(arr) # array remove(value) : remove the first occurrence value in this array, if element not found raise a ValueError arr.remove(1) print(arr) # array index(value): return the first occurrence of the given value in the array if not found raise an ValueError. print(arr.index(4)) # array reverse(): reverse the array items arr.reverse() print(arr) arr.reverse() print(arr)
true
f6bae3bb7208e83faf06ed7cd445da0c05062aca
ashifujjmanRafi/code-snippets
/python3/learn-python/built-in-functions/complex.py
627
4.3125
4
""" The complex() method returns a complex number when real and imaginary parts are provided, or it converts a string to a complex number. complex([real[, imag]]) * real - real part. If real is omitted, it defaults to 0. * imag - imaginary part. If imag is omitted, it defaults to 0. """ z = complex(2, -3) print(z) z = complex(1) print(z) z = complex() print(z) z = complex('5-9j') print(z) a = 2+3j print('a =', a) print('Type of a is', type(a)) b = -2j print('b =', b) print('Type of b is', type(a)) c = 0j print('c =', c) print('Type of c is', type(c)) print(z) print(z.real) print(z.imag)
true
74476693637542a54c8de52f81a82ece64d0a5bb
ashifujjmanRafi/code-snippets
/python3/learn-python/metaprogramming/practice.py
677
4.28125
4
# class Person: # def __init__(self, name, age): # self.name = name # self.age = age # def __str__(self): # return f'{self.name} is {self.age} years old.' # def __len__(self): # return len(self.name) + 10 # person = Person('Mahin', 23) # print(len(person)) # class Test: # """ cls: class Test itself. Not object of class Test. It class itself """ # def __new__(cls, x): # print(f'__new__, cls={cls}') # return super().__new__(cls) # def __init__(self, x): # print(f'__init__, self={self}') # self.x = x # def __repr__(self): # return f'name is name' # test = Test(2)
false
1dca731536c7d93cd74cf8ffd256aadc96226fb7
ashifujjmanRafi/code-snippets
/linear-algebra/inner-product.py
1,172
4.5625
5
# 6.1 David C. Lay Inner Product # An inner product is a generalization of the dot product. In a vector space, it is a # way to multiply vectors together, with the result of this multiplication being a scalar. ''' Example: Compute u.v and v.u for u = col(2, -5, -1), v = col(3, 2, -3) u.v = transpose(u).v = (3 * 2) + (- 5 * 2) + (-1 * -3) = -1 v.u = 10 Because u.v = v.u ''' u, v = [2, -5, -1], [4, 2, -3] inner_prod = 0 for i in range(len(u)): inner_prod += u[i] * v[i] print(inner_prod) # numpy library import numpy as np u = np.array([2, -5, -1]); v = np.array([4, 2, -3]); inner_prod = np.inner(v, u) print(inner_prod) # for 1-d array np.inner(u, v) is same as sum(u[:] * v[:]) inner_prod = sum(u[:] * v[:]) print(inner_prod) # or simply inner_prod = u * v inner_prod = sum(inner_prod) print(inner_prod) x = np.array([[1], [2]]) x_trans = np.transpose(x) out = np.dot(x_trans, x) print(sum(out)[0]) # for multi-dimentional array a = np.array([[1,2], [3,4]]) b = np.array([[11, 12], [13, 14]]) print(np.inner(a, b)) ''' In the above case, the inner product is calculated as − 1*11+2*12, 1*13+2*14 3*11+4*12, 3*13+4*14 '''
false
45a3228f62c9e74a9cce37f4218aa49ab0e0ed3a
awzeus/google_automation_python
/01_Crash_Course_on_Python/Week 2/05_Practice_Quiz_03.py
1,435
4.25
4
# Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is "Taylor". def greeting(name): if name == "Taylor": return "Welcome back Taylor!" else: return "Hello there, " + name print(greeting("Taylor")) print(greeting("John")) # If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. # A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. # Knowing this, can you fill in the gaps in the calculate_storage function below, # which calculates the total number of bytes needed to store a file of a given size? def calculate_storage(filesize): block_size = 4096 # Use floor division to calculate how many blocks are fully occupied full_blocks = filesize // block_size # Use the modulo operator to check whether there's any remainder partial_block_remainder = filesize % block_size # Depending on whether there's a remainder or not, return # the total number of bytes required to allocate enough blocks # to store your data. if partial_block_remainder > 0: return full_blocks*4096 + 4096 return 4096 print(calculate_storage(1)) # Should be 4096 print(calculate_storage(4096)) # Should be 4096 print(calculate_storage(4097)) # Should be 8192 print(calculate_storage(6000)) # Should be 8192
true
7080bbaff17d9b8b5789dedda43f03e9373161df
LucasGVallejos/Master-en-MachineLearning-y-RedesNeuronales
/01-PrincipiosYFundamentosDePython/POO/14.06-HerenciaMultiple.py
1,363
4.1875
4
#La capacidad de una subclase de heredar de múltiples superclases. #Esto conlleva un problema, y es que si varias superclases tienen los mismos atributos o métodos, #la subclase sólo podrá heredar de una de ellas. #En estos casos Python dará prioridad a las clases más a la izquierda en el momento de la declaración de la subclase class Primera: def __init__(self): print("\nSoy la Primer Clase\n") def metodoA(self): print("Soy un metodo de la Primer Clase") class Segunda: def __init__(self): print("\nSoy la Segunda Clase\n") def metodoB(self): print("Soy un metodo de la Segunda Clase") ################################################################### # Tanto la primer como la segunda superclase tienen mismos metodos# # Es por ese motivo que si se heredan ambas superclases, Python # # prioriraza los metodos de la clase que se encuentre en la Izq. # ################################################################### class Tercera(Primera,Segunda): def metodoC(self): print("Soy un metodo de la Tercer Clase") tercera = Tercera() tercera.metodoA() tercera.metodoB() tercera.metodoC() class Cuarta(Segunda,Primera): def metodoD(self): print("Soy un metodo de la Cuarta Clase") cuarta = Cuarta() cuarta.metodoA() cuarta.metodoB() cuarta.metodoD()
false
34d00da742e866e6456553c6e58e95cab1c50ff4
suganthi2612/python_tasks
/24_jul/program15.py
785
4.59375
5
from sys import argv #importing argv function from sys module, in order to get the user input script, filename = argv #assigning argv to the var "filename" and initializing script txt = open(filename) #opening "filename" which should be a file from user and storing it in "txt" print "Here's your file %r:" % filename #printing the filename print txt.read() #reading the file stored in "txt" var print "Type the filename again:" #printing a line file_again = raw_input("> ") #getting another filename from user using raw_input() but this works with python2 and input() should work with python3, storing it in var "file_again" txt_again = open(file_again) #opening the latter file and storing in a var print txt_again.read() #reading the file stored in txt_again
true
b0c1455ef5d5e0fc3abc4d78cba8a3f6e180cb98
craffas/Faculdade-UniCEUB
/controle_estoque.py
808
4.15625
4
print('Olá, sejam bem vindos ao meu programa!\n') #Criando Função para converter arquivo em dicionário. def file_to_dict(file_name): #Open file file = open(file_name, 'r') #Init a dict dict = {} #Run a file for line in file: #Remove \n line = line.strip() #Split Line list = line.split(';') #Separate list itens product_name = list[0].replace('"', '') product_quant = int(list[1]) product_value = float(list[2]) #Fill the dict dict[product_name] = [product_quant, product_value] #Close file file.close() #Return dict return dict #Use function estoque = file_to_dict('estoque.txt') print(estoque) venda = [["Tomate", 5], ["Batata", 10], ["Feijao", 243]]
false
adb489a31b399721a19ed6342a8f21fe6b9e3bad
jmjjeena/python
/advanced_set/code.py
854
4.28125
4
# Create a list, called my_list, with three numbers. The total of the numbers added together should be 100. my_list = [25, 25, 50] r = my_list[0] + my_list[1] + my_list[2] print(r) # Create a tuple, called my_tuple, with a single value in it my_tuple = ('a',) print(len(my_tuple)) ''' --> When generating a one-element tuple, if you write only one object in parentheses (), the parentheses () are ignored and not considered a tuple. --> To generate a one-element tuple, a comma , is required at the end. --> If you just you () --> python thinks is for mathematical () --> also can assign tuple without () --> 'a', --> python will understand its a tuple ''' # Modify set2 so that set1.intersection(set2) returns {5, 77, 9, 12} set1 = {14, 5, 9, 31, 12, 77, 67, 8} set2 = {5, 77, 9, 12, 1} result = set1.intersection(set2) print(result)
true
793a4b1adc1127552dc7d22d1861eef2d1267cb2
o-power/python-intro
/assignment3_task2.py
2,943
4.5625
5
# A dealership stocks cars from different manufacturers. # They have asked you to write a program to manage the different manufacturers they stock. # a. Create an appropriately named list and populate it with at least 10 manufacturers, # making sure you don’t add them in alphabetical order manufacturers = ['Nissan','Skoda','Volkswagen','Toyota','Hyundai','Honda' ,'Ford','Lada','Ferrari','Dacia','Volvo','Fiat','Isuzu','Rover'] # b. Display the entire list in one go using the sorted() method print(sorted(manufacturers)) # c. Display the entire list again for comparison, this time without calling any methods on it print(manufacturers) # d. Display the list in reverse. Note that the list is only to be reversed, not sorted manufacturers.reverse() print(f'Reversed list: {manufacturers}') manufacturers.reverse() # e. The dealership wants a “live” backup copy of their list, create a backup list that # updates with any changes made to the original list manufacturers_backup = manufacturers # f. To test the backup list, add a new manufacturer to the original list, then display the # backup list to confirm that it reflects the changes to the original list manufacturers.append('Aston Martin') print(manufacturers_backup) # g. The dealership also wants a copy of the original list that they can manipulate without # changing the original list. Make a copy of the entire list manufacturers_copy = manufacturers[:] # h. Permanently sort the new copy of the list, then display it and the original list using # the same print statement, but make sure the two lists print on different lines. # This is to allow you to compare the two lists, confirming the original list wasn’t modified along with the copy manufacturers_copy.sort() print(f'Sorted copy: {manufacturers_copy}') print(f'Original list: {manufacturers}') # i. The dealership decide they want three subsets of the sorted list. Slice the sorted # list into three alphabetically grouped lists, for example A to H, I to Q, R to Z # method 1 a_to_h = manufacturers_copy[:7] i_to_q = manufacturers_copy[7:10] r_to_z = manufacturers_copy[10:] #print(a_to_h) #print(i_to_q) #print(r_to_z) # method 2 a_to_h = [] i_to_q = [] r_to_z = [] for manufacturer in manufacturers_copy: if manufacturer[0].lower() < 'i': a_to_h.append(manufacturer) elif manufacturer[0].lower() < 'r': i_to_q.append(manufacturer) else: r_to_z.append(manufacturer) # print(a_to_h) # print(i_to_q) # print(r_to_z) # j. Display the three subset lists as part of a formatted string. If you think the output is too messy, # try using whitespace character combinations to make it more readable. Note: if your VS Code terminal # is getting too cluttered, click in the terminal and type clear, then press enter. This will give you a clear area in your terminal print(f'\nA to Z: {a_to_h}\nI to Q: {i_to_q}\nR to Z: {r_to_z}')
true
cc9fead76d2b970d753c926a045822e8931d7a82
o-power/python-intro
/assignment6_task1.py
735
4.59375
5
# 1. Create three lists of car models, each list should only have the models for a particular manufacturer. # For example, you could have one list of Fords, one of Toyotas, and one of Reanults. Give the lists # appropriate names nissan_models = ['Micra','Leaf','Qashqai','Juke'] toyota_models = ['Yaris','Corolla','RAV4','C-HR','Prius'] volkswagen_models = ['Polo','Golf','Passat','Jetta'] # 2. Create a list called car_models with the three lists of car models as items in the new list car_models = [nissan_models, toyota_models, volkswagen_models] #print(car_models) # 3. Iterate over the list to print each nested list of car models, the output would look similar to this: for car_model in car_models: print(car_model)
true
ba2727bac22e06d7e71e038c3eef748f119d49cf
aceFlexxx/Algorithms
/Algorithms Course/CS3130Pr1_prgm3.py
712
4.3125
4
# An example of a non-recursive function to # calculate the Fibonacci Numbers. import math import time def Fibo(n): """This is a recursive function to calculate the Fibinocci Numbers""" fLess2 = 0; fLess1= 1; fVal = fLess1 + fLess2 for i in range(2, n+1): fVal = fLess1 + fLess2 fLess2 = fLess1 fLess1 = fVal return fVal num1 = raw_input("Enter n for the Fibonacci #:") if num1.isdigit() == False: num1 = 10000 else: num1 = int(num1) start = time.time() print "The", num1," Fibonacci number in the sequence: \n", Fibo(num1) end = time.time() print "To calculate this with the improved algorithm,", \ "It took me", 1000*(end - start), "msecs"
true
edb4bdab58f7303a69c2d59b0edbb698305b0f83
michdcode/Python_Projects_Book
/Math_Python/chp_one_prac.py
2,036
4.46875
4
from fractions import Fraction def factors(num): """Find the factors of a given number.""" for numbers in range(1, num+1): if num % numbers == 0: print(numbers) your_num = input('Please enter a number: ') your_num = float(your_num) if your_num > 0 & your_num.is_integer(): factors(int(your_num)) else: print('Please enter a positive integer.') def multiplication_table(num): """"Prints out multiples for a number up to 10.""" for numbers in range(1, 11): print('{0} x {1} = {2}'.format(num, numbers, num*numbers)) user_number = input("Enter a number: ") multiplication_table(float(user_number)) def fahrenheit_to_celsius(): """Converts fahrenheit to Celsius.""" fahrenheit = float(input('Please enter the degrees in fahrenheit: ')) celsius = (fahrenheit - 32) * Fraction(5, 9) print('Temperature in Celsius is: {0:.2f}'.format(celsius)) def celsius_to_fahrenheit(): """Converts Celsius to Fahrenheit.""" celsius = float(input('Please enter the degrees in celsius: ')) fahrenheit = (celsius * Fraction(9, 5)) + 32 print('Temperature in Fahrenheit is: {0:.2f}'.format(fahrenheit)) def inches_to_meters(): """Converts inches to meters.""" inches = float(input('Please enter the number of inches: ')) meters = (inches * 2.54)/100 print('Distance in meters is: {0}'.format(meters)) def miles_to_kilometers(): """Converts miles to kilometers.""" miles = float(input('Please enter the number of miles: ')) KM = (miles * 1.609) print('Distance in kilometers is: {0}'.format(KM)) def calc_quadratic_equ_root(a, b, c): """Finds the roots in a quadratic equation""" D = (b*b - 4*a*c)**0.5 x1 = (-b + D)/(2*a) x2 = (-b - D)/(2*a) print('x1: {0}'.format(x1)) print('x2: {0}'.format(x2)) def gather_root_data(): a = input('Enter a: ') b = input('Enter b: ') c = input('Enter c: ') calc_quadratic_equ_root(float(a), float(b), float(c))
true
034f54d21418d137bf4337bccff3cced66268f3b
adaxing/leetcode
/design-linked-list.py
2,060
4.15625
4
class Node: def __init__(self, val): self.val = val self.next = None class MyLinkedList: def __init__(self, val, next=None): """ Initialize your data structure here. """ self.val = val self.next = next def get(self, index): """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int """ if index < len(self.val): return self.val[index] else: return -1 def addAtHead(self, val): """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. :type val: int :rtype: void """ self.val.insert(0,val) def addAtTail(self, val): """ Append a node of value val to the last element of the linked list. :type val: int :rtype: void """ self.val.insert(len(self.val), val) def addAtIndex(self, index, val): """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. :type index: int :type val: int :rtype: void """ if index < len(self.val): self.val.insert(index, val) elif index == len(self.val): self.addAtTail(val) def deleteAtIndex(self, index): """ Delete the index-th node in the linked list, if the index is valid. :type index: int :rtype: void """ if index < len(self.val): self.val.pop(index) # Your MyLinkedList object will be instantiated and called as such: obj = MyLinkedList([1,2,4]) param_1 = obj.get(2) obj.addAtHead(5) obj.addAtTail(8) obj.addAtIndex(6,7) obj.deleteAtIndex(4) print(obj.val)
true
020aecb13c8f16367f1ce6d37d453884ae1c17f2
carlinpeton/callycodespython
/Random.py
2,879
4.15625
4
import random # CHALLENGES # 052 # num = random.randint(1, 100) # print(num) # 053 # fruit = random.choice(["apple", "pear", "orange", "grapes", "watermelon"]) # print(fruit) # 054 # coin = random.choice(["heads", "tails"]) # guess = input("Heads or tails (heads/tails) : ") # # if guess == coin: # print("You win!") # else: # print("Bad luck") # # print("It was a", coin, "!") # 055 This one required initiative in deciding that for loops could be used. # num = random.randint(1, 5) # guess = int(input("Pick a number between 1 and 5: ")) # # # for i in range(0, 1): # if num != guess: # if guess < num: # print("Too low.") # guess = int(input("Pick a number between 1 and 5: ")) # else: # print("Too high.") # guess = int(input("Pick a number between 1 and 5: ")) # # if num != guess: # print("You lose!") # else: # print("Correct!") # 056 # whole = random.randint(1, 10) # guess = int(input("I'm thinking of a number between 1 and 10. Enter this number: ")) # # while whole != guess: # guess = int(input("Try again: ")) # # print("Well done my G!") # 057 This is a fun game. # whole = random.randint(1, 10) # guess = int(input("I'm thinking of a number between 1 and 10. Enter this number: ")) # # while whole != guess: # if guess < whole: # print("Too low!") # else: # print("Too high!") # guess = int(input("Try again: ")) # # print("Well done my G!") # 058 dope # question_number = 1 # score = 0 # # for i in range(0, 5): # num1 = random.randint(1, 10) # num2 = random.randint(1, 10) # question_ans = num1 + num2 # print("Question", question_number, ":", num1, "+", num2, "= ?") # ans = int(input("Ans: ")) # question_number += 1 # if ans == question_ans: # score += 1 # # print("You scored", score, "out of 5!") # 059 colour = ["blue", "purple", "green", "orange", "red"] rand_col = random.choice(colour) choice = input("Guess the colour I am thinking of: ") while rand_col != choice: if rand_col == "blue": print("You are probably feeling quite blue right now.") choice = input("Guess the colour I am thinking of again: ") elif rand_col == "purple": print("A purple heart is better than a black heart.") choice = input("Guess the colour I am thinking of again: ") elif rand_col == "green": print("If you want grass, just water your own.") choice = input("Guess the colour I am thinking of again: ") elif rand_col == "orange": print("Only plumbs think they can rhyme orange.") choice = input("Guess the colour I am thinking of again: ") else: print("I don't know what you've RED, but it's not what it looks like.") choice = input("Guess the colour I am thinking of again: ") print("Well done champ.")
false
1e6dd7d2e4889307d7e3299e427515cdaa47e454
TrevorCunagin/fizzbuzzpython
/fizzBuzzPython/fizzBuzzPython/fizzBuzzPython.py
399
4.34375
4
#created by: Trevor Cunagin #this program prints numbers from 1 to 100, where every multiple of 3 prints #"Fizz" and every multiple of 5 prints "Buzz". It prints "FizzBuzz" when a #number is a multiple of 3 and 5 for i in range(1, 101): if (i % 3 == 0 and i % 5 == 0): print("FizzBuzz") elif (i % 3 == 0): print("Fizz") elif (i % 5 == 0): print("Buzz") else: print(i)
false
4777821a747d9810b49350bb7caba98301c638ce
Thestor/RanDomRepoSitory
/Practice1.py
409
4.125
4
# -*- coding: utf-8 -*-' """ Name: Exercise 1 @author: Matthew """ print("Enter your height.") try: heightinfeet = eval(input("Feet: ")) heightininches = eval(input("Inches: ")) except: print("That is an invalid input.") else: heightincm = (heightinfeet * 30.48) + (heightininches * 2.54) length = heightincm * 0.88 print ("\nSuggested board length:", length, "cm")
true
cbd2a896c08ca4401888a9a8699a3d079f0e27b3
madanaman/leetCodeSolutions
/arrays/inserting_in_arrays/merge_sorted_array.py
1,905
4.125
4
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. """ class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ num1_write_pointer = len(nums1) - 1 startm = m - 1 startn = n - 1 # print("input", nums1, nums2) while num1_write_pointer >= 0: # print("nums1", nums1, "nums2", nums2) # print(num1_write_pointer, startm, startn, nums1[startm], nums2[startn]) if startm >= 0 and startn >= 0: if nums2[startn] >= nums1[startm]: # print("inside first if") nums1[num1_write_pointer] = nums2[startn] startn -= 1 else: # print("inside else") nums1[num1_write_pointer] = nums1[startm] startm -= 1 elif startm >= 0: break elif startn >= 0: nums1[num1_write_pointer] = nums2[startn] startn -= 1 num1_write_pointer -= 1 # print(nums1) return nums1 def testing(): nums1 = [1, 2, 3, 0, 0, 0] m = 3 nums2 = [2, 5, 6] n = 3 solve = Solution() assert solve.merge(nums1, m, nums2, n) == [1, 2, 2, 3, 5, 6] print("test successful") nums1 = [1] m = 1 nums2 = [] n = 0 assert solve.merge(nums1, m, nums2, n) == [1] print("test successful") testing() def test(): pass # ip1 = [0, 1, 7, 6, 0, 2, 0, 7] # ip2 = [1,0,2,3,0,4,5,0] # solve = Solution() # solve.duplicateZeros(ip) # print(solve) test()
true
d2f96b6a2763deceefd38207aa08877d9115f7e9
RosemaryDavy/Python-Code-Samples
/leapyear.py
377
4.125
4
#Rosemary Davy #March 4, 2021 #This function takes a es a year as a parameter and #returns True if the year is a leap year, False if it is otherwise year = int(input("Please enter a year:")) def checkLeap(year): leap = False if year % 400 == 0 : leap = True elif year % 4 == 0 and year % 100 != 0: leap = True return leap print(checkLeap(year))
true
06c2c1377c5cc6c299c6e2def9a703f936c877fa
RosemaryDavy/Python-Code-Samples
/davy_print_new_line.py
362
4.28125
4
#Rosemary Davy #February 13, 2021 #This program prints each number in list #on its own line num = [12, 10 , 32 , 3 , 66 , 17 , 42 , 99 , 20] for x in num: print(x) #and also prints the given numbers along with their square #on a new line squared = [ ] for x in num: sqr = x * x squared.append(sqr) print("The square of {} is {}".format(x, sqr))
true
21696cbcd0318f7c0aadddd126c04653c36cd6c6
RosemaryDavy/Python-Code-Samples
/mpg.py
518
4.65625
5
string_miles = input("How many miles did you travel?") float_miles = float(string_miles) string_gallons = input("How many gallons of gas did you use?") float_gallons = float(string_gallons) mpg = float_miles // float_gallons print("Your car can travel approximately" , mpg , "miles per gallon of gasoline.") #Rosemary Davy #January 28, 2021 #This program asks the user for the number of miles they drove and the number of gallons of gasoline used. #It then converts that into miles per gallon and tells the user the result.
true
d8b33e98ef5d4e8894764376f6254af24529ac63
jdbrowndev/hackerrank
/algorithms/strings/sherlock-and-anagrams/Solution.py
733
4.25
4
""" Author: Jordan Brown Date: 8-13-16 Solves the sherlock and anagrams problem by counting all unordered, anagrammatic pairs in all substrings of each input string. Link to problem: https://www.hackerrank.com/challenges/sherlock-and-anagrams """ def count_anagrammatic_pairs(str): anagrams = {} for start in range(len(str)): for end in range(start + 1, len(str) + 1): anagram = "".join(sorted(str[start:end])) if anagram in anagrams: anagrams[anagram] += 1 else: anagrams[anagram] = 1 return sum((int(count*(count - 1)/2) for (str, count) in anagrams.items())) for _ in range(int(input())): print(count_anagrammatic_pairs(input()))
true
bd60aa0314779cda8ff7ade34189fe1da8356f91
jdbrowndev/hackerrank
/algorithms/strings/funny-string/Solution.py
500
4.125
4
""" Author: Jordan Brown Date: 9-3-16 Solves the funny string problem. Link to problem: https://www.hackerrank.com/challenges/funny-string """ def is_funny_string(s): for i in range(1, len(s)): originalDiff = abs(ord(s[i]) - ord(s[i - 1])) reverseDiff = abs(ord(s[len(s) - i - 1]) - ord(s[len(s) - i])) if originalDiff != reverseDiff: return False return True t = int(input()) for _ in range(t): print("Funny" if is_funny_string(input()) else "Not Funny")
true
5e75e9bc56b991569a883d04228502e8c81b7cad
JonathanTTSouza/GuessTheNumber
/main.py
1,553
4.21875
4
''' Guess the number program. The objective is to guess a random number from 1 to 100. ''' import random def maingame(): print("Welcome to Guess the number") print("I'm thinking of a random number from 1-100.") print("Try guessing it!\n") random_number = random.randint(1,100) #print(f"(Testing: number is {random_number})") while True: difficulty = input("Choose your difficulty(easy/hard): ") if difficulty == 'easy': print("Easy difficulty selected. You have 10 guesses.") n_of_guesses = 10 break elif difficulty == 'hard': print("Hard difficulty selected. You have 5 guesses.") n_of_guesses = 5 break else: print("Invalid input, try again") continue guess = 0 while n_of_guesses > 0: try: guess = int(input("\nMake a guess: ")) except: print("Invalid input") continue if guess > random_number: n_of_guesses -= 1 print(f"Too high. {n_of_guesses} guesses remaining.") elif guess < random_number: n_of_guesses -= 1 print(f"Too low. {n_of_guesses} guesses remaining.") elif guess == random_number: print("You got it! Congratulations.") break replay = input("Want to play again?(y/n): ") if replay == 'n': print("Goodbye") else: print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n') maingame() maingame()
true
69282fd3dc835c735dd4495bc8891c33077a7321
juhuahaoteng/jianzhi-offer
/二叉搜索树与双向链表.py
2,467
4.1875
4
""" 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: """ 二叉搜索树的特点是:左节点的值 < 根节点的值 < 右节点的值,不难发现,使用二叉树的中序遍历出来的数据的排序就是排序的顺序 把二叉搜索树看成三部分:根节点,左子树和右子树,在把左、右子树都转换成排序的双向链表之后,再和根节点连接起来,从而形成一个排序的双向链表 """ def Convert(self, head): # 特判 if not head: return None # 当只有一个根节点时,直接返回根节点即可 if not head.left and not head.right: return head # 递归调用根节点的左节点 self.Convert(head.left) # left指针指向根节点的左节点 left = head.left # 当left节点存在时 if left: # 当left节点存在右节点 while left.right: # left指针指向它的右节点,因为在根节点的左节点中,此时的右节点是最大的 left = left.right # 根节点的右节点指向left head.left = left # 根节点指向left指针的右节点(双向指针),形成双向指针,即双向链表 left.right = head self.Convert(head.right) # right指针指向根节点的右节点 right = head.right # 当右节点存在时 if right: # 当右节点存在子左节点时 while right.left: # 循环直至找到最右节点的左节点 right = right.left # 将根节点的右节点与这个节点相连 head.right = right # 反向相连,形成双向指针(双向链表) right.left = head # 当根节点存在左节点时 while head.left: # 递归调用,直至找到最左的节点,即将head指针指向根节点的最左的节点,而不是根节点 # 因为根节点的最左的节点时最小的值,这样就形成了一个排好序的双向链表 head = head.left return head
false
d5eb4c0ba4c7abf4c4a52d80c7d32c374fa7c1af
rosharma09/PythonFromScratch
/printPatter1.py
494
4.125
4
i = 1 while i <= 3: print('Hello' , end = "") j = 1 while j <=3: print('World', end = "") j += 1 print() i += 1 # to print the number from 1-100 excluding numbers that are divisible bu 3,5 i = 1 while i <= 100: if(i % 3 == 0 or i % 5 ==0): i += 1 continue else: print(i) i += 1 i = 1 j = 5 while i <= 5: print("*" , end = "") while(j >= 1): print("*" , end = "") j -= 1 print() i += 1
false
e49f5ca625fc5920b983696915e98294d97e9b5f
rosharma09/PythonFromScratch
/PassList.py
717
4.125
4
# pass list as an arg to a fn # create a function which takes list of numbers as an input and returns the number of even and odd number in the lsit # define a list numberList = [] print(type(numberList)) # ask user to enter the length of the lsit listLength = int(input('Enter the list length: ')) for i in range(0,listLength): val = int(input('Enter the next value:')) numberList.append(val) print(numberList) def count(inputList): eCount = 0 oCount = 0 for i in inputList: if i % 2 == 0: eCount += 1 else: oCount += 1 return eCount , oCount oddCount , evenCount = count(numberList) print("Even : {} and Odd : {}".format(evenCount,oddCount))
true
50ad644f1e4570ba99159ae2da1a983d28c1a8e1
rosharma09/PythonFromScratch
/numpyArray.py
1,064
4.34375
4
from numpy import * # this program is to illusrtate the different ways of creating array using numpy # method 1: using the array function --> we can give the array values and provide the type intArray = array([1,2,3,4] , int) print(intArray) floatArray = array([1,2,3,4] , float) print(floatArray) charArray = array(['a','b','c']) print(charArray) # method2: using the linspace function --> we can create an array by providing the start and end of the array # and specify the number of parts splitArray = linspace(0,15,16) # sytax : linspace(start,end,splitCount) print(splitArray) # method3: using the logspace function --> we can create an array with the logs of the range and divided into equal parts logArray = logspace(1,40,10) print(logArray) print('%.2f' %logArray[0]) # method3: arange function --> to specify an array of range of numbers rangeArray = arange(0,10,2) print(rangeArray) # mehtod4: to create an array with zeros zeroArray1 = zeros(5, int) print(zeroArray1) # method5: to create an aray of 1s onesArray = ones(5) print(onesArray)
true
aa30ffbd0682e82a4c9a60ddbb45e7d00774b489
6ftunder/open.kattis
/py/Quadrant Selection/quadrant_selection.py
234
4.15625
4
# user inputs two numbers/coordinates (x,y) which tells us which quadrant the point is in x = int(input()) y = int(input()) if x > 0 and y > 0: print(1) elif x < 0 < y: print(2) elif x < 0 > y: print(3) else: print(4)
true
91c86708915f6838f38c0fcd522abe7a49e513df
MateuszSacha/Variables
/first name.py
348
4.4375
4
#Mateusz Sacha #10-09-2014 #exercise 1.1 - Hello World print ("Hello World") #get a name from the user and store it into a variable first_name = input ("please enter you first name") #print out the name stored in the variable first_name print (first_name) #print out the name as part of the message print("hello {0}1".format(first_name)
true
ec15abe213878f787dda0118c53f4ffd8d6c1f74
AgusRoble/Python
/Comparacion Edades.py
637
4.15625
4
print("Ingrese un nombre: ") Nombre1 = input() print("Ingrese un apellido: ") Apellido1 = input() print("Ingrese su edad: ") Edad1 = input() print("Ingrese otro nombre: ") Nombre2 = input() print("Ingrese un apellido: ") Apellido2 = input() print("Ingrese su edad: ") Edad2 = input() if Nombre1 == Nombre2 or Apellido1 == Apellido2: print("no pueden haber mismos nombres y apellidos") else: if Edad1 < Edad2: print(f"{Nombre1} es menor que {Nombre2}") elif Edad1 > Edad2: print(f"{Nombre1} es mayor que {Nombre2}") elif Edad1 == Edad2: print(f" {Nombre1} y {Nombre2} tienen la misma edad") else: print("Datos no validos")
false
e9a125dc93125afe135099dfe1df6cd99a9d325d
lucasdealmeidadev/Python
/Calculadora/index.py
916
4.15625
4
def menu() : print("\n\n\t\t\t>>> MENU PRINCIPAL <<<\n\n"); print('(1) - Adição\n'); print('(2) - Subtração\n'); print('(3) - Multiplicação\n'); print('(4) - Divisão\n'); print("\n\t\t\t>>> ------ X ------ <<<\n"); def operacao(n1, n2, op) : if (op == 1): return print('Adição = ', n1 + n2); elif (op == 2): return print('Subtração = ', n1 - n2); elif (op == 3): return print('Multiplicação = ', n1 * n2); elif (op == 4): return print('Divisão = ', n1 / n2); else: return print('Erro : informe uma opção válida'); def main() : import os; n1 = float(input('Informe o 1° número : ')); n2 = float(input('Informe o 2° número : ')); os.system('cls'); menu(); op = int(input('Informe uma opção : ')); os.system('cls'); operacao(n1, n2, op); main();
false
d486e86f158860f487fa6a1659cf36422f4530fe
Maria105/python_lab
/lab7_10.py
277
4.28125
4
#!/usr/bin/env python3 # -*- codding:utf-8 -*- def input_text() -> str: """Input message: """ text = input('enter you text: ') return (text) def min_word(text: str) -> str: """Find smallest word""" return min(text.split()) print(min_word(input_text()))
false
97ba0e6836c625362df5ffe9479dfcc44450928b
Maria105/python_lab
/lab7_13.py
398
4.1875
4
#!/usr/bin/env python3 #-*- cpdding: utf-8 -*- def input_text() -> str: """Input needed two text""" text_1 = input('Enter first text: ') text_2 = input('Enter second text: ') return [text_1, text_2] def check(text_1, text_2: str) -> bool: """Check is anagram two text""" return not[0 for _ in text_1 if text_1.count(_) > text_2.count(_)] print(check (input_text ( ) ) )
false
3e14d07c77dedaa0ca27bd1f6295d88d4cca9ea9
Maria105/python_lab
/lab7_12.py
319
4.3125
4
#!/usr/bin/env python3 # -*- codding:utf-8 -*- def input_text() -> str: """Input message: """ text = input('enter you text: ') return (text) def remove_spaces(text: str) -> str: """Remove all unnecessary spaces from the string""" return ' '.join (text.split()) print(remove_spaces(input_text()))
true
e266ad7bd05c070b2b7efa411a8005b81e5d6980
eddycaldas/python
/12-Lists-Methods/the-index-method.py
419
4.40625
4
# it returns the first index position of the element in question. the first argument is the element looking for, the second one is the index at where we can to start the search. pizza_toppings = [ 'pineapple', 'pepperoni', 'sausage', 'olive', 'sausage', 'olive' ] print(pizza_toppings.index('pepperoni')) print(pizza_toppings.index('olive')) print() print(pizza_toppings.index('olive', 3))
true
dd7369b3182f776031cf5896be7ddbe2b899c21b
eddycaldas/python
/11-Lists-Mutation/the-extend-method.py
459
4.375
4
# extend method adds any amount at the end of a list, it will mutate it. color = ['black', 'red'] print(color) print() color.extend(['blue', 'yellow', 'white']) print(color) print() extra_colors = ['pink', 'green', 'purple'] color.extend(extra_colors) print(color) print() # this methos ( + ) will not mutate them: steak = ['t-bone', 'ribeye'] more_steak = ['ney york strip', 'tenderloid'] print(steak + more_steak) print() print(steak) print(more_steak)
true
237516a4b16ddf4e5fbc04127e6cfc5b584a5b9d
eddycaldas/python
/08-Control-Flow/the-if-statement.py
1,408
4.59375
5
# # zero or empty string are falsie values, all other numbers are not # if 3: # print('Yes!') # if 0: # print("humm...") # print() # print(bool(0)) # print(bool(-1)) # print(bool("")) # print(bool(" ")) # Define a even_or_odd function that accepts a single integer. # If the integer is even, the function should return the string “even”. # If the integer is odd, the function should return the string “odd”. # # even_or_odd(2) => "even" # even_or_odd(0) => "even" # even_or_odd(13) => "odd" # even_or_odd(9) => "odd" def even_or_odd(int): if (int%2 == 0): print("even") elif (int%2 != 0): print('odd') even_or_odd(2) even_or_odd(0) even_or_odd(13) even_or_odd(9) print() # Define a truthy_or_falsy function that accepts a single argument. # The function should return a string that reads "The value _____ is ______" # where the first space is the argument and the second space # is either truthy or falsy. # # truthy_or_falsy(0) => "The value 0 is falsy" # truthy_or_falsy(5) => "The value 5 is truthy" # truthy_or_falsy("Hello") => "The value Hello is truthy" # truthy_or_falsy("") => "The value is falsy" def truthy_or_falsy(arg): if arg == 0 or arg == '': print("The value ", arg, ' is falsy' ) else: print('The value ', arg, ' is truthy') truthy_or_falsy(0) truthy_or_falsy(5) truthy_or_falsy("Hello") truthy_or_falsy("")
true
57f0867a7c856dd63d4675f502489a45bbd0e3f9
eddycaldas/python
/08-Control-Flow/nested-if-statements.py
1,746
4.28125
4
ingredient1 = 'pasta' ingredient2 = 'meatballs' if ingredient1 == 'pasta': if ingredient2 == 'meatballs': print('make some pasta with meatballs') else: print('make plain pasta') else: print('I have no recommendation') print() if ingredient1 == 'pasta' and ingredient2 == 'meatballs': print('make some pasta with meatballs') elif ingredient1 == 'pasta': print('make plain pasta') else: print('I have no recommendation') print() # Define a divisible_by_three_and_four function # that accepts a number as its argument. # It should return True if the number is evenly # divisible by both 3 and 4 . It should return False otherwise. # divisible_by_three_and_four(3) => False # divisible_by_three_and_four(4) => False # divisible_by_three_and_four(12) => True # divisible_by_three_and_four(18) => False # divisible_by_three_and_four(24) => true def divisible_by_three_and_four(num): if (num % 3 == 0) and (num % 4 == 0): print(True) else: print(False) divisible_by_three_and_four(3) divisible_by_three_and_four(4) divisible_by_three_and_four(12) divisible_by_three_and_four(18) divisible_by_three_and_four(24) print() # Declare a string_theory function that accepts # a string as an argument. # It should return True if the string has # more than 3 characters and starts with a # capital “S”. It should return False otherwise. # string_theory("Sansa") => True # string_theory("Story") => True # string_theory("See") => False # string_theory("Fable") => False def string_theory(str): if len(str) > 3 and str[0] == 'S': print(True) else: print(False) string_theory("Sansa") string_theory("Story") string_theory("See") string_theory("Fable")
true
e74021b6d8ef203951fb3bc32d9e5866b939353e
eddycaldas/python
/07-Strings-Methods/the-find-and-index-methods.py
851
4.3125
4
# browser = "Google Chrome" # print(browser.find("C")) # print(browser.find("Ch")) # print(browser.find("o")) # print('\n') # print(browser.find("R")) # -1 means that the character or string is not # on the original string itself # ----------------------------> # print() # print(browser.find('o', 2)) # print(browser.find('o', 5)) # in this case, a second argument is where the # search of the character or string starts. # -----------------------------> # print() # print(browser.index('C')) #print(browser.index("Z")) # index method is the same as the find one, # but instead it'll return a ValueError instead # of the -1 as the find method does. # --------------------------------> print() my_string = "los pollitos dicen pio pio pio" print(my_string.rfind('l')) print(my_string.rfind('l',7)) print(my_string.rfind('l', 15, 22))
true
815153c3097f2cbebd1eb59e6766d227bdcfd70b
Sheikh-A/Python_Lessons
/demonstration_04.py
368
4.34375
4
""" Challenge #4: Create a function that takes length and width and finds the perimeter of a rectangle. Examples: - find_perimeter(6, 7) ➞ 26 - find_perimeter(20, 10) ➞ 60 - find_perimeter(2, 9) ➞ 22 """ def find_perimeter(length, width): return ((2*length) + (2*width)) print(find_perimeter(6,7)) print(find_perimeter(20,10)) print(find_perimeter(2,9))
true
fc5a01f2d8db49961f1aa677509940f1ab87306d
meytala/SheCodes
/lesson4/exercise.py
630
4.15625
4
## functins with STR: #isalnum x='meytal' print(x.isalnum())#checks whether the string consists of alphanumeric characters (no space). y='meytal avgil' print(y.isalnum()) ##there is a space #split print(y.split())#Split the argument into words #replace #returns a copy of the string in which the occurrences of old have been replaced with new #str.replace(old, new[,max]) #if the max argument is givven, only the first count occurrences are replaced. str = "this is string example....wow!!! this is really string" print(str) print (str.replace("is", "was")) ##replace all the "is" in "was" print (str.replace("is", "was", 3)) #join
true
1954d865a393378e5b860e788ea9fd452d0c9514
LawrenceDiao/python-XJY
/py_7.2.py
634
4.25
4
''' 创建集合 1:用大括号括起来 2:使用 set() set() 唯一 就是重复的会自动删除** ''' set1 = {1,2,3,4,5,6} set2 = set([1,2,3,4,5,6,]) # 去除重复元素 # 方法一 list1 = [1,2,3,4,5,5,3,1,0] temp = list1[:] list1.clear() for each in temp: if each not in list1: list1.append(each) # 方法2 list1 = [1,2,3,4,5,5,3,1,0] list1 = list(set(list1)) # 访问 循环出来 set1 = {1,2,3,4,5,6,7,8,9} for each in set1: print(each,end=",") # 1,2,3,4,5,6,7,8,9, # 冰冻集合 frozen() set1 = frozenset({1,2,3,4,5}) set1.add(6)
false
a3ed486093bd5c6587cc01542c5dae4ae9f46f10
kbrennan711/SoftDesSp15
/toolbox/word_frequency_analysis/frequency.py
1,960
4.46875
4
""" Kelly Brennan Software Design Professors Paul Ruvolo and Ben Hill Spring 2015 Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. All words are converted to lower case. >>> get_word_list('doc_test.txt') ['cat', 'dog', 'moo'] """ full_text = open(file_name) lines = full_text.readlines() line_begin = 0 line_end = len(lines)-1 while lines[line_begin].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1: line_begin += 1 while lines[line_end].find('END OF THIS PROJECT GUTENBERG EBOOK') == -1: line_end -= 1 text = lines[line_begin+1:line_end-1] #Plus and minus one to get rid of header comment words_list = [] for line in text: if line == '\n': pass else: for word in line.split(): word = word.strip(string.punctuation + string.whitespace) word = word.lower() words_list.append(word) return words_list def get_top_n_words(word_list, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequentlyoccurring >>> get_top_n_words(['a', 'a', 'b'], 2) [(2, 'a'), (1, 'b')] """ d = dict() most_common = [] for word in word_list: if word not in d: d[word] = 1 else: d[word] += 1 for key, value in d.items(): most_common.append((value, key)) most_common.sort(reverse = True) return most_common[0:n] # print get_top_n_words(get_word_list('persuasion.txt'), 10) if __name__ == "__main__": import doctest doctest.testmod()
true
a72169d59cc2a01d2b1b914e5f9972c05f669510
saijadam/PythonTraining
/Day2_Collections/listdemo.py
352
4.125
4
#List - Mutable list1 = [1,2,3,1,5] #so that I can add, remove, etc list1.append(6) sum=0 for item in list1: sum=sum+item #comment #TO COMMENT MULTIPLE LINES - CTRL+/ print("Sum of list: ",sum) #list duplicate of occurances here 2, only ONE occueanc of 1 print(list1.count(1)) #Data type conversion print("converted to tuple :", tuple(list1))
true
20ce616fef83b7723792853e65d07a5d3a7dbae4
jingji6/test1
/base.py
1,468
4.21875
4
""" python的语法 所有方法都是小括号结尾,比如,print()、input() 元组、数组、字典的取值,都是用中括号,比如a[0] 元组、数组、字典的定义,分别是()、[]、{} """ # #字符串 # print("你好!") # #数字 # print(23333) # #小数 # print(2.333) # #布尔值 # print(True or False) # #元组 # print(()) # #数组 # print([]) # #字典 # print({}) # #注释 # 'haha' # ''' # 锄禾日当午 # 汗滴禾下土 # ''' # #打印多个字符串 # print("哈哈",2333) # #字符串拼接 # print('哈哈'+'嘻嘻') # #运算符(+-*\) # print('哈哈'*10) # print((2+1)*10-9) #input方法 # #变量 # #赋值 # a = "张三" #把张三这个值赋值给了名字叫a的这个变量 # print(a) # a = input("请输入:") # print("input获取的数据:",a) #type方法 数据类型 # print(type("2333")) # print(type(2333)) # print(type(23.33)) # print(type(True)) # print(type(())) # print(type([])) # print(type({})) #转换数据类型 # print(type(int(2.33))) # a = float(input("请输入:")) # b = float(input("请输入:")) # print("a+b=",a+b) #len()方法 长度 # a = "1.2333333333333" # print(len(a)) #练习:通过代码获取两段内容,并且计算他们的长度 #1: # a = len(input("请输入:")) # b = len(input("请输入:")) # print("a+b=",a+b) #2: # a = input("请输入:") # b = input("请输入:") # print("两段字符的长度:",len(a)+len(b)) print(6)
false
251f24c743bb0d13124d917bac1c6c403ad5ab5d
andrewviren/Udacity_Programming_for_Data_Science
/Part 4/match_flower_name.py
542
4.15625
4
# Write your code here flower_dict = {} def file_to_dict(filename): with open(filename) as f: for line in f: #print(line[3:].rstrip()) flower_dict[line[0]]=line[3:].rstrip() file_to_dict("flowers.txt") # HINT: create a function to ask for user's first and last name user_input = input("Enter your First [space] Last name only:") first_init = user_input[0].upper() # print the desired output yourFlower = str(flower_dict[first_init]) print("Unique flower name with the first letter: " + yourFlower)
true
a52cb5d452339e373045b1a218c1853bb4ea3e61
DavidNovo/ExplorationsWithPython
/ExploratonsInPythonGUI.py
1,685
4.28125
4
# tkinter and tcl # making windows # lesson 39 of beginning python # lesson 40 making buttons # lesson 41 tkinter event handling from tkinter import * # making a Window class # this class is for creating the window class Window(Frame): # defining the initialize method # this is run first by container def __init__(self, master = NONE): # creating the frame in the window Frame.__init__(self,master) self.master = master self.init_window() # this method adds buttons to the frame def init_window(self): self.master.title("GUI") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) # creating a button # adding event handling to a button lesson 41 quitButton = Button(self,text="Quit",command = self.client_exit) quitButton.place(x=0,y=0) # make a main menu menuBar = Menu(self.master) self.master.config(menu=menuBar) fileDropDown = Menu(menuBar) menuBar.add_cascade(label='File', menu=fileDropDown) fileDropDown.add_command(label='Exit', command=self.client_exit) editDropDown = Menu(menuBar) menuBar.add_cascade(label='Edit', menu=editDropDown) editDropDown.add_command(label='Undo') def client_exit(self): exit() # # naming the root root = Tk() # size off the window root.geometry("400x300") # using the Window class with our defined root # the self variable is set to root # the second variable is left as the default # in this case the default is master = None app = Window(root) # the execution happens here root.mainloop()
true
dfd43aeb7478e6e4401e7a8a551ef1b2dec5d1ad
1aaronscott/Sprint-Challenge--Graphs
/graph.py
2,273
4.15625
4
""" Simple graph implementation """ from util import Stack, Queue # These may come in handy class Graph: """Represent a graph as a dictionary of rooms.""" def __init__(self): self.rooms = {} def add_room(self, room): """ Add a room to the graph. """ # create a dict for the new room self.rooms[room.id] = {} # populate it with the room's exits per the map for r in room.get_exits(): self.rooms[room.id][r] = '?' def add_hall(self, this_room, next_room, direction): """ Add a non-directed edge to the graph. """ reverse_direction = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'} self.rooms[this_room.id][direction] = next_room.id self.rooms[next_room.id][reverse_direction[direction]] = this_room.id def get_neighbors(self, room): """ Get all neighbors (edges) of a room. """ # print("current room is: ", room) return self.rooms[room] def bfs(self, starting_room): """ Return a list containing the shortest path from starting_room to other rooms in breath-first order. """ # Create an empty queue and enqueue A PATH TO the starting vertex ID q = Queue() q.enqueue([starting_room]) # Create a Set to store visited vertices visited = set() # While the queue is not empty... while q.size() > 0: # Dequeue the first PATH path = q.dequeue() # Grab the last room from the PATH last_room = path[-1] # found an exit with a '?' as the value if last_room == "?": return path # If that vertex has not been visited... if last_room not in visited: # Mark it as visited... visited.add(last_room) # Then add A PATH TO its neighbors to the back of the queue for edge in self.get_neighbors(last_room).values(): # COPY THE PATH path_copy = list(path) # APPEND THE NEIGHOR TO THE BACK path_copy.append(edge) q.enqueue(path_copy)
true
8404bf0fe83e56c17a18ad1a9ba0eeec0d7cf3b1
iampaavan/Pure_Python
/Exercise-77.py
307
4.15625
4
import sys """Write a Python program to get the command-line arguments (name of the script, the number of arguments, arguments) passed to a script.""" print(f"This is the path of the script: {sys.argv[0]}") print(f"Number of arguments: {len(sys.argv)}") print(f"List of arguments: {str(sys.argv)}")
true
6d435a78210841598cc4f66f182b0d1cb871793d
iampaavan/Pure_Python
/Exercise-96.py
564
4.1875
4
"""Write a Python program to check if a string is numeric.""" def check_string_numeric(string): """return if string is numeric or not""" try: i = float(string) except (ValueError, TypeError): print(f"String is not numeric") else: print(f"String {i} is numeric") print(f"********************************************************") check_string_numeric('1a23') print(f'********************************************************') check_string_numeric('123') print(f'********************************************************')
true