blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7a1cdf1af372986d74d8b8d7c5da1db0d4cbf231
annikathiele/mappython
/map.py
1,168
4.125
4
import time def sort_a(word_list): """ Recursive implementation of quick- or mergesort. Parameter --------- word_list : list of str list to be sorted Returns ------- int sum of all swaps and comparisons float time used in ms """ # return mergesort_or_quicksort(word_list) start = time.time() sorted_list = quicksort(word_list + [0]) ende = time.time() comparisons = sorted_list.pop() time_ms = (ende-start)*1000 return [comparisons] + [time_ms] + sorted_list def quicksort(word_list): length = len(word_list) if length <=1: return word_list comparisons = word_list.pop() pivot = word_list.pop() lower = [] higher = [] for item in word_list: comparisons += 1 if item < pivot: lower.append(item) else: higher.append(item) sorted_lower = quicksort(lower+ [comparisons]) # print(sorted_lower) comp_lower = sorted_lower.pop() sorted_higher = quicksort(higher+ [0]) comp_higher = sorted_higher.pop() return sorted_lower + [pivot] + sorted_higher + [comp_lower+comp_higher]
true
f7fbaf7d026ece3fcf32abe32aaa86e38ea9ef62
PQCuongCA18A1A/Ph-m-Qu-c-C-ng_CA18A1A
/PhamQuocCuong_44728_CH04/Exercise/page_109_exercise_03.py
680
4.125
4
""" Author: Phạm Quốc Cường Date: 22/9/2021 Problem: You are given a string that was encoded by a Caesar cipher with an unknown distance value. The text can contain any of the printable ASCII characters. Suggest an algorithm for cracking this code Solution: """ def decoded(s): for i in range(1,95): string = "" for char in s: if(ord(char) + i > 126): charc = (ord(char) + i) - 94 string = string + chr(charc) else: charc = ord(char) + i string = string + chr(charc) print(string) decoded("T! x$r&'}r&z! %21j!'1~zxy&1\"r%%1TZedBEAB?")
true
574990b7a33979586402dbb0c7c1add1d3f777a8
PQCuongCA18A1A/Ph-m-Qu-c-C-ng_CA18A1A
/PhamQuocCuong_44728_CH03/Exercise/page_85_exercise_03.py
277
4.28125
4
""" Author: Phạm Quốc Cường Date: 8/9/2021 Problem: Write a loop that counts the number of space characters in a string. Recall that the space character is represented as ' '. Solution: """ a=input("How to use a for loop in Python") for i in a: print(i.count(' ') + 1)
true
c77c3dff6b5509d49e04e6b59f780e740a1ee0a9
kushckwl/python_project
/guess_number.py
484
4.125
4
import random def guess(x): random_number = random.randint(1, x) guess = 0 while guess != random_number: guess = int(input(f"Guess a number between 1 and {x}:")) if guess < random_number: print('Sorry , again guess, too low') elif guess > random_number: print('Sorry, again guess, too high') print(f'Yepeee! you guess right number. you win the game!{random_number} is correct.') guess(100)
true
b8221fd9e4d6c21951d3db47378cbb240709bd46
anselmos/coding-problem
/solutions/2019_10_29.py
1,210
4.125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 [Anselmos](github.com/anselmos) <anselmos@users.noreply.github.com> # # Distributed under terms of the MIT license. """ Given a list of numbers and a number k, return whether any two numbers from the list add up to k.abs For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? """ import unittest import unittest def problem(number_list, k): for elt in number_list: if k - elt in number_list: return True return False class TestNumbers(unittest.TestCase): """ Testing""" def test_example(self): example_list = [10, 15, 3, 7] k = 17 self.assertTrue(problem(example_list, k)) example_list = [10, 7] k = 17 self.assertTrue(problem(example_list, k)) example_list = [10] k = 17 self.assertFalse(problem(example_list, k)) example_list = [-1, 25, 2, 46] k = 26 self.assertFalse(problem(example_list, k)) example_list = [-1, -5, 2, 46] k = 7 self.assertFalse(problem(example_list, k)) if __name__ == '__main__': unittest.main()
true
d6331e71856771b33e5d69ddaf18b10ee03be5a6
ThomsonTang/python-tutorials
/python-cookbook/src/data-structures-algorithms/1-3-kepping-last-items.py
1,477
4.46875
4
"""1.3 Keeping the last N items The following code performs a simple text match on a sequence of lines and yields the matching line along with the previous N lines of context when found. When writing code to search for items, it is common to use a generator function involving yield, as shown in this recipe's solution. """ from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line) # example use on a file if __name__ == '__main__': with open('1-3-test-file.txt') as f: for line, prevlines in search(f, 'python', 5): for pline in prevlines: print(pline, end='') print(line, end='') print('-' * 20) # using dequeue(maxlen=N) creates a fixed-sized queue. q = deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(q) """ More generally, a deque can be used whenever you need a simple queue structure. If you don't give it a maximum size, you get an unbounded queue that lets you append and pop items on either end. Adding or popping items from either end of a queue has O(1) complexity. This is unlike a list where inserting or removing items from the front of the list is O(N). """ q = deque() q.append(1) q.append(2) q.append(3) print(q) q.appendleft(4) print(q) print(q.pop()) print(q) print(q.popleft()) print(q)
true
aa6c4f363adbf3ed4e9d11cd8d36fa413d30d599
one-last-time/python
/controlFlow/ConditionalStatement.py
1,995
4.4375
4
# ''' # You decide you want to play a game where you are hiding # a number from someone. Store this number in a variable # called 'answer'. Another user provides a number called # 'guess'. By comparing guess to answer, you inform the user # if their guess is too high or too low. # Fill in the conditionals below to inform the user about how # their guess compares to the answer. # ''' answer = 9 guess = 9 if answer>guess: result = "Oops! Your guess was too low." elif answer<guess: result = "Oops! Your guess was too high." elif answer==guess: result = "Nice! Your guess matched the answer!" print(result) # ''' # Depending on where an individual is from we need to tax them # appropriately. The states of CA, MN, and # NY have taxes of 7.5%, 9.5%, and 8.9% respectively. # Use this information to take the amount of a purchase and # the corresponding state to assure that they are taxed by the right # amount. # ''' state = "CA" purchase_amount = 5 if state=="CA": tax_amount = .075 total_cost = purchase_amount*(1+tax_amount) result = "Since you're from {}, your total cost is {}.".format(state, total_cost) elif state=="MN": tax_amount = .095 total_cost = purchase_amount*(1+tax_amount) result = "Since you're from {}, your total cost is {}.".format(state, total_cost) elif state=="NY": tax_amount = .089 total_cost = purchase_amount*(1+tax_amount) result = "Since you're from {}, your total cost is {}.".format(state, total_cost) print(result) #complex boolean expression weight = 72 height = 1.8 if 18.5 <= weight / height**2 < 25: print("BMI is considered 'normal'") is_raining = True is_sunny = True if is_raining and is_sunny: print("Is there a rainbow?") unsubscribed = False location ='USA' if (not unsubscribed) and (location == "USA" or location == "CAN"): print("send email") errors = 3 if errors: print("You have {} errors to fix!".format(errors)) else: print("No errors to fix!")
true
283667a72bf6107d54cf1f6f1c09af1577b2f9e7
one-last-time/python
/functions/function.py
746
4.125
4
#Write a function named population_density that takes two arguments, population and land_area, and returns #a population density calculated from those values. I've included two test cases that you can use to verify #that your function works correctly. Once you've written your function, use the Test Run button to test your code. def population_density(population, land_area): ans=population/land_area return ans # test cases for your function test1 = population_density(10, 1) expected_result1 = 10 print("expected result: {}, actual result: {}".format(expected_result1, test1)) test2 = population_density(864816, 121.4) expected_result2 = 7123.6902801 print("expected result: {}, actual result: {}".format(expected_result2, test2))
true
01aa1b0165b4533b6869071f5885fd4874bc9392
one-last-time/python
/list.py
392
4.34375
4
animal=["tiger","lion","dog","cat"] #shows full list print(animal) #get size print(len(animal)) #show an element print(animal[0]) #show an element from last print(animal[-4]) print(animal[-3]) #delete an element in list del animal[2] print(animal) #sort animal.sort() print(animal) #sort animal.sort(reverse = True) print(animal) for x in animal: print(x)
true
165662dd2df0759cb43172f690558cdd2b62e9cc
one-last-time/python
/Data Types and Operators/ArithmeticOperators.py
665
4.1875
4
#addtion,subtraction,multiplication,division,mod are same as other language print(((1+2+3)*(4/2)-5)%3) #power #get 2^3 print(2**3) #integer divison #it rounds the result print(8//3) print(-8//3) """ Quiz: Calculate In this quiz you're going to do some calculations for a tiler. Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long. Tiles come in packages of 6. 1.How many tiles are needed? 2.You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over? """ #1 total=(7*9)+(7*5) print("total tiles need=",total) #2 print("tiles remain =",(6*17)%total)
true
46ca34ac7cff4689deb3f0acbede5503534c2ca6
FinchyG/Python_testing_fridge_temperatures
/Testing_fridge_temperatures.py
920
4.28125
4
# Test whether fridge temperatures are between 1 and 5 degrees Celsius # function with one parameter, temperatures: a list of numbers def test_temperature(temperatures): # initialise empty list to store temperatures outside of range 1 to 5 unacceptable_temperatures = [] # iterate through input list for temperature in range(len(temperatures)): # filter unacceptable temperatures outside of range 1 to 5 if temperatures[temperature] < 1 or temperatures[temperature] > 5: # append temperature to list of unacceptable temperatures unacceptable_temperatures.append(temperatures[temperature]) # output list of unacceptable temperatures print(unacceptable_temperatures) # check that test_temperatues works def check_test_temperatures(): assert test_temperatures([1,2,3,4,5]) == [] assert test_temperatures([-1,2,4,6]) == [-1,6]
true
c7f864ea1b3915f64b2b083754ef288b7214c329
DeepankJain/Python-Programs
/Prog17.py
430
4.1875
4
#Python function to check whther a string is palindrome or not str = input("Enter any string: ") def checkPalindrome(teststring): i = 0 j = len(teststring)-1 while i < j: if teststring[i] != teststring[j]: print("Not a palindrome") break else: i = i+1 j = j-1 if i >= j: print("It is a palindrome") print(checkPalindrome(str))
false
b9dac96e603a2af6b4db973904175d7e808dc9c8
DeepankJain/Python-Programs
/Prog3.py
238
4.3125
4
#To check whether a number is postive, negative or Zero num1 = int(input("Enter any number:")) if num1 > 0: print("Number is positive") elif num1 == 0: print("Number entered is Zero") else: print("Number is negative")
true
42838d219ffd6d447c796649fe4cc9579a1348d4
raezir/The-Hoodrat-Repository
/test1.py
551
4.125
4
#!/usr/bin/env python #import sys ''' Created on Jan 28, 2017 This code opens a text file and reads it, saving it to line and then printing it. @author: rkbergsma ''' f = open('Article1.txt','r') #open to read line = f.readlines() #reads all lines in file #line = [x.strip() for x in line] #strip gets rid of newline characters #print(line) #prints as list with bad formatting print(*line, end='\n') #print the text only in a list, can replace '\n' with ' ' f.close()
true
fc36149cf8ad326668e5aba6ddc55bc2e135a5b0
theLAZYmd/challenges
/easy/leapyears.py
930
4.21875
4
# https://www.hackerrank.com/challenges/write-a-function/problem import datetime def is_leap(year): return (1900 <= year <= 10 ** 5) and ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)) now = datetime.datetime.now() for i in range(now.year): #all years up to present year if is_leap(i): #that pass the leap year test print(i) #get printed def is_leap_brokendown(year): if year < 1900: #get limitations out the way first return False if year > 10**5: return False if year % 400 == 0: #if the year is a multiple of 400 it's definitely leap return True if year % 100 == 0: #all years that are multiples of 400 but NOT 100 aren't leap return False if year % 4 == 0: #all remaining years that are multiples of 4 ARE leap return True return False #all remainig years after that aren't
false
296e3317f545906b0194e5e049a35dda9fb16ae9
graysonjclark1/comp110-21f-workspace
/exercises/ex01/relational_operators.py
572
4.125
4
"""Input 2 variables and demonstrate how relational operators work.""" __author__ = "730481947" left: int = int(input("Left-hand variable: ")) right: int = int(input("Right-hand variable: ")) result_1: bool = left < right print(str(left) + " < " + str(right) + " is " + str(result_1)) result_2: bool = left >= right print(str(left) + " >= " + str(right) + " is " + str(result_2)) result_3: bool = left == right print(str(left) + " == " + str(right) + " is " + str(result_3)) result_4: bool = left != right print(str(left) + " != " + str(right) + " is " + str(result_4))
false
08f6f7b1c7fa5c063ce5be8f1d8e7213ac9c7b01
Melwyn12/Python-Projects
/simpleAdditionQuiz.py
2,166
4.125
4
# Math game quiz # prompts users to answer simple addition problems using random numbers from 0-100 # added subtraction, multiplication, and division def printBanner(): print("\t\t\t ##################### ") print("\t\t\t Math Quiz ") print("\t\t\t By Falconscrest123 ") print("\t\t\t #####################\n\n\n") def calculateAverage(): sum = num1 + num2 return sum def calculateDiffernce(): difference = num1 - num2 return difference def multiplyNumber(): product = num1 * num2 return product def divideNumber(): divide = float(num1 / num2) divide = round(divide, 2) return divide import random printBanner() counter = 0 while True: num1 = random.randrange(0,100) num2 = random.randrange(0,100) quizType = input("Do you want to add,subtract,multiply or divide:") quizType = quizType.lower() if quizType == "add" or quizType == "addition": answer = calculateAverage() userInput = input("What is the answer to %i + %i or press (done) to quit:" %(num1,num2)) userInput = userInput.lower() elif quizType == "subtract" or quizType == "subtraction": answer = calculateDiffernce() userInput = input("What is the answer to %i - %i or press (done) to quit:" %(num1,num2)) userInput = userInput.lower() elif quizType == "multiply" or quizType == "multiplication": answer = multiplyNumber() userInput = input("What is the answer to %i * %i or press (done) to quit:" %(num1,num2)) userInput = userInput.lower() elif quizType == "divide" or quizType == "division": answer = divideNumber() userInput = input("What is the answer to %i / %i or press (done) to quit:" %(num1,num2)) userInput = userInput.lower() else: print("Invalid input") continue if userInput == "done": print("Good-Bye") break try: userInput = float(userInput) except: userInput = input("Bad input Please enter an integer only:") if userInput == answer: counter += 1 print("\nThe answer is %4.2f" %(answer)) print("Good Job! Your score is %i\n" %(counter)) elif userInput != answer: print("Wrong Answer You got 0 points for this question") print("The right answer is %4.2f" %(answer)
true
e8f4e29b97a0adeca5cdccd8c33b4063cfa9b516
teosss/HomeWorkPyCore
/lesson_6/task_1.py
1,212
4.34375
4
def func_1(): """ Function 1 find the even, odd, div23 numers classic method """ even = [] odd = [] div23 = [] for i in range(1,10): if i % 2 == 0: even.append(i) if i % 3 == 0: odd.append(i) if i % 2 != 0 and i % 3 != 0: div23.append(i) print(func_1.__doc__) print("Even numbers: ", even) print("Odd numbers: ", odd) print("Numbers div 2 and 3: ", div23) def func_2(): """ Function 2 find the even, odd, div23 numers list comprehension """ print(func_2.__doc__) print("Even numbers: ", list(i for i in range(1,10) if i % 2 == 0)) print("Odd numbers: ", list(i for i in range(1,10) if i % 3 == 0)) print("Numbers not div 2 and 3: ", list(i for i in range(1,10) if i % 2 != 0 and i % 3 != 0)) def func_3(*arg): """ Function 3 find the even, odd, div23 numers with tuples """ print(func_3.__doc__) print("Even numbers: ", list(i for i in arg if i % 2 == 0)) print("Odd numbers: ", list(i for i in arg if i % 3 == 0)) print("Numbers not div 2 and 3: ", list(i for i in arg if i % 2 != 0 and i % 3 != 0)) func_1() func_2() func_3(1,2,3,4,5,6,7,8,9)
false
4c73f3903714e956a47065cfb51c2438159bcfa9
teosss/HomeWorkPyCore
/lesson_8/task_1.py
938
4.25
4
import super_module_t1 def input_area(value): """" This function determines the type of figure Input: value(str) Result: (int,float) """" if value is '1': s = int(input("Enter first side: ")) b = int(input("Enter second side: ")) return super_module_t1.rectangle_area(s,b) elif value is '2': s = int(input("Enter the base of the triangle: ")) h = int(input("Enter the height of the triangle: ")) return super_module_t1.triangle_area(s,h) elif value is '3': r = int(input("Enter radius of circle: ")) return super_module_t1.circle_area(r) else: value = input("You have entered incorrect data, please try again (1,2,3): ") return input_area(value) value = input("The area of which figure you want to count: \n 1 - rectangle \n 2 - triangle \n 3 - circle \n Enter number: ") print(input_area(value))
true
dae37bc59b17b2e7e9b6118b19a3bcac1fadc43b
Panic-point1/Algorithmia
/python/binary_search.py
857
4.25
4
''' In binary search, - Compare x with the middle element. - If x matches with the middle element, we return the mid index. - Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray after the mid element. Then we apply the algorithm again for the right half. - Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the left half. ''' def binary(a,f,l,x): if l >= f: m = (l+f) // 2 if a[m] == x: return m elif a[m] > x: return binary(a,m+1,l,x) else: return binary(a,m+1,l,x) else: return -1 a = [560,50000,55773,88883,672728] x = int(input("Enter the number you want to search:-")) result = binary(a,0,len(a)-1,x) if result != -1: print("Element is present at "+str(result)+"th index") else: print("Sorry! element is not present")
true
57ba2c2cfe3ab44fc716e148322c16268f2204a3
JessicaJang/cracking
/Chapter 3/q_3_5.py
1,185
4.15625
4
# Chapter 3 Stacks and Queues # 3.5 Sort Stack # Write a program to sort a stack such that the smallest items are on the top # You can use an additiona temporary stack, but you may not copy the elements # into any other data structure (such as an array). The stack supports # the following operations: push, pop, peek and isEmpty import os from stack import Stack class sortStack: def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def push(self, item): flag = True while not self.stack2.isEmpty(): tmp = self.stack2.pop() if tmp >= item: self.stack1.push(item) self.stack1.push(tmp) flag = False else: self.stack1.push(tmp) if flag == True: self.stack1.push(item) while not self.stack1.isEmpty(): self.stack2.push(self.stack1.pop()) def pop(self): if self.stack2.isEmpty(): return return self.stack2.pop() def isEmpty(self): return self.stack2.isEmpty() def peek(self): if self.stack2.isEmpty(): return return self.stack2.peek() if __name__=="__main__": print("test") sstack = sortStack() sstack.push(3) sstack.push(2) sstack.push(5) sstack.push(1) print(sstack.pop()) print(sstack.peek())
true
0e447a93b2db7926b93b73bad2ea46111e7a493e
JessicaJang/cracking
/Chapter 2/q_2_3.py
453
4.28125
4
# Chapter 2 Linked Lists # Interview Questions 2.3 # Delete middle node: # Implement an algorithm to delete a node in the middle import os from LinkedList import LinkedList from LinkedList import LinkedListNode def delete_middle_node(node): node.value = node.next.value node.next = node.next.next ll = LinkedList() ll.add_multiple([1, 2, 3, 4]) middle_node = ll.add(5) ll.add_multiple([7, 8, 9]) print(ll) delete_middle_node(middle_node) print(ll)
true
9baa2091eff6073b7f0642899a0ee3f07fbf96c0
Cosmo767/Practice
/Udemy_Python_refresher/review_2_getting_input.py
304
4.1875
4
# name = input("Enter your name: ") # print(name) # input gives you a string, not a number size_input = input("How big your house in sq feet?:" ) square_feet = int(size_input) sqr_meters = square_feet /10.8 string = f"{square_feet} square feet is equal to {sqr_meters:.2f} square meters" print(string)
true
1114f176bb5c3b78c22c54aad4c61f258b5a1579
Cosmo767/Practice
/jason_algos_one/most_common_letter.py
1,906
4.25
4
def most_common_letter(text): """Returns the letter of the alphabet that occurs most frequently. If there is a tie, choose the letter that comes first in the alphabet. If there are no letters, return the empty string""" ''' create a dictionary with a value for each key that counts how many time the letter appears. keep track of the max value and the respective key as we iterate over the string. return the letter at the end. ''' lower_case_text = text.lower() my_dict = {} current_largest = "" my_dict[current_largest] = 0 for char in lower_case_text: if char >= "a" and char <= "z": #the char is a letter if char in my_dict: #the letter is already in the dict my_dict[char] += 1 else: #the letter is not in the dict my_dict[char] = 1 if (my_dict.get(char) > my_dict.get(current_largest)): current_largest = char elif (my_dict.get(char) == my_dict.get(current_largest)): current_largest = current_largest if char > current_largest else char #ternary expression # print(current_largest, "Current Largest") # print(my_dict, "my dict") return current_largest ''' test cases input expected vs output ''' def test(my_input, expected_output): actual_output = most_common_letter(my_input) successful_test = actual_output == expected_output success_notification = "PASS" if successful_test else "FAIL" output_message = ("{}: \n INPUT: {}\n OUTPUT: \n\t expected: {} \n\t actual: {}". format(success_notification, my_input, expected_output, actual_output)) print(output_message) # test("aab", "a") # test("beta", "a" ) # test("", "") #test("5,2,3,3,3","") #21 # test("2,2,2z", "z") #21 # test("TaeaTt","t") test("ABCabc","a")
true
0d4a3ed33566dd1980674c2ad18336f3c3b6b597
Cosmo767/Practice
/Udemy_Python_refresher/33_unpacking_args.py
748
4.28125
4
def add(*args): total = 0 for arg in args: total = total + arg return total def mutliphy(*args): # print(args) total = 1 for arg in args: total = total*arg return total # print(mutliphy(1,3,5)) def apply(*args, operator): # creates a named operator at the end, must pass in a named arg at end if operator == "*": return mutliphy(*args) elif operator == "+": return add(*args) else: return "No valid operator" print(apply(1,3,5,2,operator="+")) ######################### # def add(x,t): # return x+t # nums = [3,5] # print(add(*nums)) # # or # nums ={"x":15, "t": 25} # print(add(x=nums["x"], t=nums["t"])) # # same as this # print(add(**nums))
true
0906b7cc9dda5c140134c5a68fde84daa6453166
100sun/python_programming
/chp5_ex.py
1,340
4.28125
4
# 5.1 Capitalize the word starting with m: song = """ When an eel grabs your arm, ... And it causes great harm, ... That's - a moray!""" song = song.replace('m', ' M') print(song) # 5.2 Print each list question with its correctly matching answer in the form: Q: question A: answer > > > questions = [ "We don't serve strings around here. Are you a string?", "What is said on Father's Day in the forest?", "What makes the sound 'Sis! Boom! Bah!'?" ] answers = [ "An exploding sheep.", "No, I'm a frayed knot.", "' Pop!' goes the weasel." ] for i in range(0, 3): print(f'Q: {questions[i]}\nA: {answers[i]}') # 5.3 Write the following poem by using old-style formatting. Substitute the strings 'roast beef', 'ham', 'head', and 'clam' into this string: poem = '''My kitty cat likes %s, My kitty cat likes %s, My kitty cat fell on his %s And now thinks he's a %s''' args = ('roast beef', 'ham', 'head', 'claim') print(poem % args) # ∵ must be immutable values.. -> set names = ['duck', 'gourd', 'spitz'] # 5.6 old style for name in names: print("%sy Mc%sface" % (name.capitalize(), name.capitalize())) # 5.7 new style for name in names: print("{}y Mc{}face".format(name.capitalize(), name.capitalize())) # 5.8 newest tysle for name in names: print(f"{name.capitalize()}y Mc{name.capitalize()}face")
true
c4f3dbc5ab71c5fb6c5f3bd36fcb0eb469d2f27b
ulillilu/MachineLearning-DeepLearning
/03-02.Database/sqlite3_test.py
785
4.40625
4
import sqlite3 # sqlite 데이터베이스 연결 dbpath = "test.sqlite" conn = sqlite3.connect(dbpath) # 테이블을 생성하고 데이터 넣기 cur = conn.cursor() cur.executescript(""" /* items 테이블이 이미 있다면 제거하기 */ DROP TABLE IF EXISTS items; /* 테이블 생성하기 */ CREATE TABLE items( item_id INTEGER PRIMARY KEY, name TEXT UNIQUE, price INTEGER ); /* 데이터 넣기 */ INSERT INTO items(name, price)VALUES('Apple', 800); INSERT INTO items(name, price)VALUES('Orange', 780); INSERT INTO items(name, price)VALUES('Banana', 430); """) # 데이터베이스에 반영 conn.commit() # 데이터 추출 cur = conn.cursor() cur.execute("SELECT item_id,name,price FROM items") item_list = cur.fetchall() for it in item_list: print(it)
false
41f2085568658b304f233161dceae20dfc7bf21d
zndemao/PythonStudy
/note19函数与过程.py
937
4.21875
4
# 函数 与 过程 # 函数:有返回值 # 过程:没有返回值 # Python只用函数没有过程 def hello(): print('hello world') temp = hello() print(type(temp)) # 有返回值,返回返回值,没有返回NoneType def back(): return [1, 'love', 3.14] print(back()) # 函数变量的作用域 def discounts(price, rate): final_price = price * rate # print(old_price) old_price = 200 print(old_price) return final_price old_price = float(input('请输入')) rate = float(input('请输入折扣率')) new_price = discounts(old_price, rate) print('打折后的价格' + str(new_price)) # 不能使用+ 二者无法进行算数运算 print("打折后的价格", new_price) # print('这里试图打印final_price的值:',final_price) # 局部变量,出来函数无效 print(old_price) # 如果在函数内如果试图修改全局变量,python会创建一个局部变量,名字虽然相同
false
e5eccbc671e5225f8da0c3dbf9666ef6b81ec8c2
tomasvalda/dt211-3-cloud
/Euler/solution7.py
616
4.21875
4
#!/usr/bin/python def is_prime(num): # function for check if the number is prime, returns true or false if num == 2: return true if num < 2: return false if not num & 1: return false # for x in range # number is prime when we can divide it only by the exact number or 1 ################# return true def main(): isprime = true # prime check number = 1 prime_count = 1 # primes count while isprime == true: if is_prime(number): prime_count = prime_count + 1 if prime_count == 10001: # 10001st prime number print number isprime = false number = number + 2 # next prime number
true
4189cbe031375dd974083eb6e006b04852b29392
Snehal2605/Technical-Interview-Preparation
/ProblemSolving/450DSA/Python/src/string/MinimumSwapsForBracketBalancing.py
1,674
4.3125
4
""" @author Anirudh Sharma You are given a string S of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balanced. Note - Strings S1 and S2 can be empty. """ def minimumNumberOfSwaps(S): # Number of swaps required swaps = 0 # Special case if S is None or len(S) == 0: return swaps # Variable to track open brackets openBrackets = 0 # Loop through the string for c in S: # If we encounter the left bracket, # we will increment the count if c == '[': openBrackets += 1 # If we encounter the right bracket, # then any of the two conditions can # happen else: # If there are open brackets to the # left of the current bracket, # close the last encountered open # bracket if openBrackets != 0: openBrackets -= 1 # If not, we will have to perform # swap else: swaps += 1 # Reset the count of open brackets openBrackets = 1 # We will need n/2 inversions for extra open brackets # to make the string balanced return swaps + openBrackets // 2 if __name__ == "__main__": S = "[]][][" print(minimumNumberOfSwaps(S)) S = "[[][]]" print(minimumNumberOfSwaps(S)) S = "][][][" print(minimumNumberOfSwaps(S))
true
3ea12eeb1275db5ca2a730ad5cd55e8f9da5e755
Snehal2605/Technical-Interview-Preparation
/ProblemSolving/450DSA/Python/src/binarytree/LevelOrderTraversal.py
1,314
4.21875
4
""" @author Anirudh Sharma Given a binary tree, find its level order traversal. Level order traversal of a tree is breadth-first traversal for the tree. Constraints: 1 <= Number of nodes<= 10^4 1 <= Data of a node <= 10^4 """ def levelOrderTraversal(root): # Special case if root is None: return None # List to store the result result = [] # Queue to store nodes of the tree nodes = [] # Add root node to the queue nodes.append(root) # Loop until the queue is empty while nodes: # Get the current node current = nodes.pop(0) # Add this node to the result result.append(current.data) # Check if the left child exists if current.left: nodes.append(current.left) # Check if the right child exists if current.right: nodes.append(current.right) return result class Node: def __init__(self, data): self.data = data self.left = None self.right = None if __name__ == "__main__": root = Node(1) root.left = Node(3) root.right = Node(2) print(levelOrderTraversal(root)) root = Node(10) root.left = Node(20) root.right = Node(30) root.left.left = Node(40) root.left.right = Node(60) print(levelOrderTraversal(root))
true
355c5ba49e9a5ee0d5862f1155800456b10fdb6c
Snehal2605/Technical-Interview-Preparation
/ProblemSolving/450DSA/Python/src/dynamicprogramming/MobileNumericKeypad.py
1,471
4.28125
4
""" @author Anirudh Sharma Given the mobile numeric keypad. You can only press buttons that are up, left, right, or down to the current button. You are not allowed to press bottom row corner buttons (i.e.and # ). Given a number N, the task is to find out the number of possible numbers of the given length. """ def getCount(N): # Array to store the allowed keys which can # be pressed before a certain key allowedKeys = [ [0, 8], [1, 2, 4], [1, 2, 3, 5], [2, 3, 6], [1, 4, 5, 7], [2, 4, 5, 6, 8], [3, 5, 6, 9], [4, 7, 8], [5, 7, 8, 9, 0], [6, 8, 9] ] # Lookup table to store the total number of # combinations where i represents the total # number of pressed keys and j represents the # actual keys present lookup = [[0 for y in range(10)] for x in range(N + 1)] # Populate the table for i in range(1, N + 1): for j in range(10): if i == 1: lookup[i][j] = 1 else: # Loop for all the allowed previous keys for previous in allowedKeys[j]: lookup[i][j] += lookup[i - 1][previous] # Total sum totalSum = 0 for value in lookup[N]: totalSum += value return totalSum if __name__ == "__main__": print(getCount(1)) print(getCount(2)) print(getCount(3)) print(getCount(4)) print(getCount(5)) print(getCount(16))
true
a0faf6dc0aaddd8e0cfbf57ff9ed2a53b47a380c
Snehal2605/Technical-Interview-Preparation
/ProblemSolving/450DSA/Python/src/dynamicprogramming/LongestIncreasingSubsequence.py
1,346
4.125
4
""" @author Anirudh Sharma Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Constraints: 1 <= nums.length <= 2500 -10^4 <= nums[i] <= 10^4 """ def lengthOfLIS(nums): # Special case if nums is None or len(nums) == 0: return 0 # Length of the array n = len(nums) # Lookup table to store the longest increasing # subsequence until a certain index. # lookup[i] => length of longest increasing sub # -sequence endding at index i # Since every element is an increasing sequence of # length 1. lookup = [1] * n # Loop through the array for i in range(n): for j in range(i): if nums[i] > nums[j] and lookup[i] < lookup[j] + 1: lookup[i] = lookup[j] + 1 # Find the maximum value in the lookup table longest = 0 for x in lookup: longest = max(longest, x) return longest if __name__ == "__main__": nums = [10,9,2,5,3,7,101,18] print(lengthOfLIS(nums)) nums = [0,1,0,3,2,3] print(lengthOfLIS(nums)) nums = [7,7,7,7,7,7,7] print(lengthOfLIS(nums))
true
e7d9e7d85e9e3912415fb2947c392157ab7414e3
mdcowan/SSL
/Lecture_Files/Wk1_2/python.py
722
4.375
4
# To get user input, you must first import system functionality import sys # You can then use 'raw user input' to get data from the user name = raw_input("What is your name?") # From there you can use the variable with the user input data # Writing to a file # a = append, w = overwrite # Template to open a file to write: declaredVariable = ("nameOfFile", "aOrW") # Step one - open the file f = open("myfile.txt","w") # Step two - write data f.write("Here is my text " + name + ".") # Step three - close the file f.close() # Reading from a file # r = read # Template to read from a file: declaredVariable = ("nameOfFile", "r") f = open("myfile.txt","r") # ouput what was read print(f.read()) #close the name f.close()
true
185a1af3665c4fdc6582968114478154861e6789
kaory-china/python
/CC1_2 Week/square_area_perimeter.py
303
4.34375
4
'it calculates square perimeter and area based on user int input of the square side size' MedidaLadoQuadrado = int(input("Digite o valor correspondente ao lado de um quadrado:")) Perimetro = MedidaLadoQuadrado * 4 Area = MedidaLadoQuadrado ** 2 print("perímetro:", Perimetro,"-","área:", Area)
false
c6a687f92ae05d2411702febf255dd02ca34d561
ishitach/AI-and-PyTorch
/Neural network using relu.py
714
4.15625
4
#Creating a neural network with 128,64 hidden layers and 10 output layers and ReLU activation import torch.nn.functional as F class Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden1 = nn.Linear(784, 128) self.hidden2 = nn.Linear(128, 64) # Output layer, 10 units - one for each digit self.output = nn.Linear(64, 10) def forward(self, x): # Hidden layer with relu function x = self.hidden1(x) x= relu(x) x = self.hidden2(x) x= relu(x) x = F.softmax(self.output(x), dim=1) return x model = Network() model
true
0a61e216e7bbade2dd5090e75285384bc92159f3
clagunag/Astr-119
/HW_1_1.py
489
4.1875
4
# -*- coding: utf-8 -*- ''' Cesar Laguna Python 3.6.1 ''' import numpy as np ''' # 1 Takes inputs (b, c) and provides output of A (area of a rectangle) Rectangle = rec ''' b = int(input('Base (rec) :')) #input allows for user to input their own data/ numbers c = int(input('Height (rec) :')) A_rec = b*c print ('Area of Rectangle', A_rec) ''' # 1 For area of a triangle ''' h0 = int(input('Base (tri) :')) B = int(input('Height (tri) :')) A_tri = 0.5*h0*B print ('Area of Triangle', A_tri)
true
f33007c902b9ffd40cf7bf86d2f53895fbca3aec
ricardoquijas290582/PythonCourse
/metodos_listas.py
1,668
4.375
4
#metodos de listas lista = ["Juan", "Luis", "Pedro"] print(lista) print("-----------") #nos regresa el indice del elemento que queremos buscar en una lista, si es que existe luis_index = lista.index("Luis") #1 print(luis_index) print("-----------------") #agregar un elemento al final de la lista lista.append("Pablito") print(lista) print("------------------") #agregar otra lista a la lista lista_extra = ["Melo", "Topi", "Arturo"] lista.extend(lista_extra) print(lista) print("------------------") #agregar un dato a la lista lista.insert(luis_index, "Luis") print(lista) #Regresa el numero de veces que hay un elemento print(lista.count("Luis")) print("---------------") #elimiar el primer elemento de la lista que concuerde con el parametro recibido lista.remove("Pablito") print(lista) print("---------------------------") #elimina el ultimo elemento de la lista elemento_quito = lista.pop() #lista.pop() print(lista) print(elemento_quito) print("---------------------") #elimina el elemento del indice que digamos lista.pop(luis_index) print(lista) print("------------------") #invierte el orden de los elementos es una lista lista.reverse() print(lista) print("---------------------") #Ordenar una lista alfabeticamente: ASCENDENTO O DESCENDENTE lista.sort() print(lista) lista.sort(reverse=True) print(lista) print("--------------------------") #copia todo lo que tiene lista hasta el momento copia = lista.copy() print(copia) print("--------------------") #comprobamos que no se modifico la copia lista.append("Yagel") print(lista) print(copia) print("---------------------") #elimina todos los elementos de una lista lista.clear() print(lista)
false
b84e10fbca2bba78cad0cd936f4902e5cd06af8d
Data-Winnower/Python-Class-Projects
/Turtle Star Drawing.py
2,866
4.40625
4
# Kale Perry # Programming Concepts and Applications # CSC1570-4914 Fall 2020 # 01 October 2020 # Repeating Turtle # Repeating Turtle # Repeating Turtle # Did I remember to say, Repeating Turtle? import turtle turtle.speed(5) again = "Yes" print ("LET'S DRAW A STAR!") while again =="Yes" or again == "Y" or again == "yes" or again =="y": points = int(input("How many points would you like on your star? Pick 5 - 30: ")) print ("") if points >=5 and points <= 30: print ("OK, a ",points,"-pointed star it is.") else: print ("What part of pick a number from 5 to 30 did you not understand?") # Set the turning angle for each possible point count if points == 5: angle = 36 elif points==7: angle = 180/7 elif points == 8: angle = 45 elif points == 9: angle = 20 elif points == 10: angle = 72 elif points == 11: angle = 180/11 elif points == 12: angle = 30 elif points ==13: angle = 180/13 elif points == 14: angle = 540/10.5 elif points == 15: angle = 12 elif points == 16: angle = 22.5 elif points == 17: angle=180/17 elif points == 18: angle = 40 elif points == 19: angle = 180/19 elif points == 20: angle = 18 elif points == 21: angle = 180/21 elif points == 22: angle = 360/11 elif points == 23: angle = 180/23 elif points == 24: angle = 15 elif points == 25: angle = 7.2 elif points == 26: angle = 90-(180/26) elif points == 27: angle = 180/27 elif points == 28: angle = 540/14 elif points == 29: angle = 180/29 elif points == 30: angle = 24 # I could keep going and add as many more # as I feel like figuring out the angle for turtle.clear() if points >=5 and points <= 30 and points!=6: for x in range (points): turtle.pencolor("magenta") turtle.forward(250) turtle.left(angle+180) elif points == 6: for x in range (6): turtle.pencolor("blue") turtle.forward(80) turtle.right (60) turtle.forward (80) turtle.left(120) again = input("Would you like to draw another?") # Don't judge me - this was fun for me! # Figuring out the angles was quite the challenge. # And yeah, I cheated a little by not making all of them # really pointy - # compare 25 points to 26 points. # Once I got it to work - # Pointy or not, I called it good! # And I had to go a whole other route # to make a 6 pointed star. # But, hey.....geometry wasn't the point # of the assignment.
true
0276d2004f3ec6f8ac3fa40257e53460485caf46
RaspiKidd/PythonByExample
/Challenge44.py
542
4.28125
4
# Python By Example Book # Challenge 044 - Ask how many people the user wants to invite to a party. If they enter a number below 10. # ask for the names and after each name display "(name) has to be invited to the party". If they enter a number which is # 10 or higher display the message "Too many people". invite = int(input("How many people are coming to the party? ")) if invite < 10: for i in range (0, invite): name = input("what is their name? ") print(name, "has been invited") else: print("Too many people")
true
75ba36c9c802dfbdb8f96e10a7a417a6f99c338e
RaspiKidd/PythonByExample
/Challenge72.py
448
4.5
4
# Python By Example Book # Challenge 072 - Create a list of six school subjects. Ask the user which of these subjects they # don't like. Delete the subject they have chosen from the list before you display the list again. subjects = ["maths", "english", "p.e", "computing", "science", "history"] print (subjects) print () dislike = input("Which subject do you not like? ") delete = subjects.index(dislike) del subjects [delete] print (subjects)
true
4a139d8ec093a78e7f7dad5bc47fbd67c4edc808
RaspiKidd/PythonByExample
/Challenge92.py
615
4.28125
4
# Python By Example Book # Challenge 092 - Create two arrays (one containing three numbers that the user enters and # one containing a set of five random numbers). Join these two arrays together into one large array. # Sort this large array and display it so that each number appears on a seperate line. from array import * import random num1 = array('i', []) num2 = array('i', []) for i in range (0,3): num = int(input("Enter a number: ")) num1.append(num) for y in range (0,5): num = random.randint(1, 100) num2.append(num) num1.extend(num2) num1 = sorted(num1) for i in num1: print (i)
true
2113eeb68b5b660c78d568123082b411750f3a4a
RaspiKidd/PythonByExample
/Challenge54.py
552
4.4375
4
# Python By Example Book # Challenge 054 - Randomly chose heads or tails ("h" or "t"). Ask the user to make their choice. # If their choice is the same as the randomly selected value, display the message "You win", # otherwise display "bad luck". At the end, tell the user if the computer selected heads or tails. import random coin = random.choice(["h", "t"]) guess = input("Enter (h)eads or (t)ails: ") if guess == coin: print ("You win") else: print ("Bad luck") if coin == "h": print ("It was heads") else: print ("It was tails")
true
40c6fccf41c2424e1d787d59e3c42bf8724004d0
RaspiKidd/PythonByExample
/Challenge87.py
402
4.4375
4
# Python By Example Book # Challenge 087 - Ask the user to type in a word and then display it backwards on seperate lines. # For instance, if they type in "Hello" it should display as shown below: ''' Enter a word: Hello o l l e H ''' word = input("Enter a word: ") length = len(word) num = 1 for x in word: position = length - num letter = word[position] print (letter) num = num + 1
true
a4264a9c28edd71030c523ff9f18de6f01e76e38
RaspiKidd/PythonByExample
/Challenge83.py
462
4.375
4
# Python By Example Book # Challenge 083 - Ask the user to type a word in uppercase. If they type it in lowercase, ask them to try again. # Keep repeating this until they type in a message all in uppercase. msg = input("Enter a message in uppercase: ") tryAgain = False while tryAgain == False: if msg.isupper(): print ("thank you") tryAgain = True else: print ("Try again") msg = input("Enter a message in uppercase: ")
true
ab858ab774b8f552cd18e61d31dae22f7d2de6b0
RaspiKidd/PythonByExample
/Challenge17.py
574
4.21875
4
# Python By Example Book # Challenge 017 - Ask the users age. If they are 18 or over , display the message "You can vote", if they are aged 17, display the # message "You can learn to drive", if they are 16 , display the message "You can buy a lottery ticket", if they are under 16, display # the message "You can go trick or treating". age = int(input("How old are you? ")) if age >= 18: print("You can vote") elif age == 17: print("You can learn to drive") elif age == 16: print("You can buy a lottery ticket") else: print("You can go trick or treating")
true
663de86686531f0522892249b03b0169d46cdb62
gomsvicky/PythonAssignmentCaseStudy1
/Program13.py
318
4.28125
4
list1 = [] num = input("Enter number of elements in list: ") num = int(num) for i in range(1, num + 1): ele = input("Enter elements: ") list1.append(ele) print("Entered elements ", list1) max1 = list1[0] for x in list1: if x > max1: max1 = x print("Biggest number is ", max1)
true
a3c327eacdfddf49ddaaff474414f2eaffae397c
brittany-morris/Bootcamp-Python-and-Bash-Scripts
/python/learndotlab/evenorodd.py
272
4.15625
4
#!/usr/bin/env python3 import sys list = sys.argv[1] with open(list, 'r') as f: for num in f: num = num.strip() value = int(num) if value % 2 == 0: print(num, True) # True means number is Even else: print(num, False) # False means number is Odd
true
bfa6ad316c5a87c2b3c724ed7e1129c01e0a193f
Sam-stiner/science-fairproject
/science fair.py
1,697
4.15625
4
def convertString(str): try: returnValue = int(str) except ValueError: returnValue = float(str) return returnValue print 'welcome to satilite tracker 0.2.1' print 'what object would you like find the orbit around?' print ' 1: earth' print ' 2: the sun' print ' 3: a custom object (beta)' print ' *note as of now this is not 100% accurate*' menue = raw_input() if a == '1': print 'what is the mass of the satilite (kg):' m=input() print 'what is the vilosity of the satilite (m/s):' v=input() print 'how far is the satilite from earth (km):' d=input() print 'how long has the object been in orbit (days):' t=input() r=d+6378.1 f=(m*v**2)/r print 'the net centripital force is:', f, 'newtons' G=6.673*10**(0-11)*r**2/m**2 l=(4*3.14**2)/G*(5.97219*10**24) k=l/r**3 T=k**.5 e=T/365 print 'the orbital period of the object is:', e, 'days' F=(e*k)*t h=2*3.14*r H=h*F print 'the object has traveled', H , 'km' if a == '2': print 'what is the mass of the satilite (kg):' m=input() print 'what is the vilosity of the satilite (m/s):' v=input() print 'how far is the satilite from the sun (km):' d=input() print 'how long has the object been in orbit (days):' t=input() r=d+695500 f=(m*v**2)/r print 'the net centripital force is:', f, 'newtons' G=6.673*10**(0-11)*r**2/m**2 l=(4*3.14**2)/G*(1.1891*10**30) k=l/r**3 T=k**.5 e=T/365 print 'the orbital period of the object is:', T, 'days' F=(e*k)*t h=2*3.14*r H=h*F print 'the object has traveled', H , 'km' if menue == '3'
true
40e018205dbc3671f3751ab5d0f359282f3150a4
DivyangPDev/automate-Boring-Stuff-With-Python
/Chapter 6/Chapter_6.py
2,374
4.1875
4
#! /usr/bin/env python3 #Practice Questions # 1. What are escape characters? # Escape characters lets you use characters that otherwise impossible to put into a string. An escape character # consists of a backslash (\n) followed by the character you want to add to the string # 2. What do the \n and \t escape characters represent? # \n escape character represents new newlines # \t escape characters represents tab # 3. How can you put a \ backslash character in a string? # You can put a \backslash character in a string by making it a raw string. # 4. The string value "Howl's Moving Castle" is a valid string. Why isn’t it #a problem that the single quote character in the word Howl's isn’t escaped? # Because it is enclosed by double quotes # 5. If you don’t want to put \n in your string, how can you write a string with newlines in it? # By using triple quotes # 6. What do the following expressions evaluate to? # • 'Hello world!'[1] # 'e' # • 'Hello world!'[0:5] # 'Hello' # • 'Hello world!'[:5] # 'Hello' # • 'Hello world!'[3:] # 'lo world!' # 7. What do the following expressions evaluate to? # • 'Hello'.upper() # 'HELLO' # • 'Hello'.upper().isupper() # True # • 'Hello'.upper().lower() # 'hello' # 8. What do the following expressions evaluate to? # • 'Remember, remember, the fifth of November.'.split() # ['Remember,', 'remember,', 'the', 'fifth', 'of', 'November.'] # • '-'.join('There can be only one.'.split()) # 'There-can-be-only-one' # 9. What string methods can you use to right-justify, left-justify, and center a string? # right-justify - rjust() # left-justify - ljust() # center a string - center() # 10. How can you trim whitespace characters from the beginning or end of a string? # beginning - lstrip() # end - rstrip() # Practise Project tableDataList = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(tableData): colWidths = [0] * len(tableData) for i in range(len(tableData)): del colWidths[i] colWidths.insert(i,len(max(tableData[i], key=len))) maxWidth = max(colWidths) tableLength = len(tableData[0]) for i in range(tableLength): for j in range(len(tableData)): print(tableData[j][i].rjust(maxWidth),end=" ") print("") printTable(tableDataList)
true
1bfb612ed8408426e7cc5c6a28ad3393e797844d
ardenercelik/Python
/convert_to_alt_caps.py
1,093
4.40625
4
""" Write a function named convert_to_alt_caps that accepts a string as a parameter and returns a version of the string where alternating letters are uppercase and lowercase, starting with the first letter in lowercase. For example, the call of convert_to_alt_caps("Pikachu") should return "pIkAcHu". """ def convert_to_alt_caps(word): wordList = list(word) for i in range(len(word)): if i % 2 == 0: wordList[i] = wordList[i].lower() else: wordList[i] = wordList[i].upper() print("".join(wordList)) # convert_to_alt_caps("Pikacu") # convert_to_alt_caps("arden") # convert_to_alt_caps("isbank") """ Write a function named count_words that accepts a string as its parameter and returns the number of words in it. A word is a sequence of one or more non-space characters. For example, the call of count_words("What is your name?") should return 4. """ def count_words(sentence): sList = sentence.split() print("There are {} words in this sentence.".format(len(sList) ) ) count_words("What is your name?")
true
5ae848cedbd3dd5b0cc94f0404dd7e9daf40b638
Bashir63/pands
/code/Week02/bmi.py
454
4.28125
4
# This is my first weekly problem solving program for this course # This program calculates the user's BMI using their inputs # Author : Bashir Ahammed # inputs for user's height and weight weight = float (input ("Enter weight: ")) height = float (input ("Enter height: ")) # Conversion of centimeters to meter squared metersquared = (height / 100) **2 # Calculation of BMI BMI = round(weight / metersquared, 2) #BMI output print("BMI is {}". format(BMI))
true
a6589717a9591f153892ead3989283aa4e676401
PriyankaSahu1/Practise-Python
/handson/handson15.py
409
4.125
4
#handson 15 list=["abc","bcd","jkl","xyz","mno"] #using membership operator if("abc" in list): print("abc is available") else: print("abc is not present") #without using membership operator for i in range(5): if(list[i]=="abc"): print("available") break else: print("not available") #printing list in reverse direction list.reverse() print(list)
true
2d0d8ff19d55b823a7fbc84a7276da650f24f1a9
Spekks/python-SEAS-Ejercicios
/Ejercicios/Unidad 3/Caso/UD03_EG1.py
1,838
4.15625
4
# Ejercicio guiado 1. Unidad 3 # a) Escribir algo parecido a un menú para elegir una entre varias opciones. Última línea muestra el resultado: letter = input("Escriba la letra 'a', 'b' o 'c': ") if letter == 'a': print("Opción a") elif letter == 'b': print("Opción b") elif letter == 'c': print("Opción c") else: print("No has seleccionado una de las opciones válidas.") # b) Vamos a introducir un conjunto de números enteros que van a ser elementos de un conjunto, de forma que # automáticamente se eliminen los repetidos. Tras eso, el conjunto se va a convertir en una lista en la que no haya # elementos repetidos. num = set() print("Introduce 5 números:") for i in range(5): num.add(int(input())) lNum = list(num) print(lNum, type(lNum), sep=", ") # c) Vamos a introducir por teclado los elementos de una lista y vamos a crear otra con dichos elementos que quede # ordenada de mayor a menor. Para ello se obtendrá el mayor, se introducirá en una lista y se eliminará de la primera. # Así se hará hasta tener todos los componentes en la segunda lista. A continuación, se escribirán en pantalla con los # símbolos > o = adecuados en cada caso. n, lst1, lst2, sep, lst3 = None, [], [], [], [] n = int(input("Cuántos números quieres introducir? ")) print("Números: ") for i in range(n): lst1.append(int(input())) print("Lista 1:", lst1, "lista 2:", lst2) for i in range(n): c = max(lst1) lst1.remove(c) lst2.append(c) print("lista 1:", lst1, "lista 2:", lst2) for i in range(n-1): if lst2[i] != lst2[i+1]: sep.append(">") else: sep.append("=") print(sep) for i in range(n): if i < n-1: lst3.extend([lst2[i], sep[i]]) else: lst3.append(lst2[i]) print(lst3) print("lista ordenada: ", ' '.join(str(i) for i in lst3))
false
f3eefe168776c1173fe236992812a1736c9464fd
Spekks/python-SEAS-Ejercicios
/Ejercicios/Unidad 4/Caso/UD04_EG1.py
2,129
4.28125
4
# Ejercicio guiado. Unidad 4. # a) Vamos a dibujar cuadrados rellenos utilizando el carácter car que se pasará como argumento. Se pasan también el # desplazamiento de cada línea (valor de a) y el número de caracteres que se escriben (valor de b) que es igual al # número de líneas que se escriben. Todos ellos son de entrada (pasados por valor). comprobar = False while not comprobar: caracter = input("Escribe un carácter: ") if len(caracter) > 1: print("inténtalo otra vez.") else: comprobar = True x = int(input("Escribe un número:")) y = int(input("Escribe un número:")) def cuadrado(a, b, car): # Lo que pide el ejercicio for i in range(b): print(" " * a, (car + " ") * b) def cuadrado2(a, b, car): # Lo que para mí tendría sentido for i in range(a): print((car + " ") * b) cuadrado(x, y, caracter) cuadrado2(x, y, caracter) # b) En este ejercicio se utiliza en la izquierda una variable local s cuyo valor se quiere imprimir antes de haberle # asignado un valor. Genera un error. def f(): global s # Si no asignamos la variable s como global, que traeremos luego en ámbito global, no funciona. print(s) s = "Hola, ¿quién eres?" # Al haber definido s como global, esta instancia de s NO es local, es la variable global. print(s) s = "Hola, soy Pepe" f() print(s) # Imprimirá el nuevo valor de s instanciado dentro de la función f(), pues esta utiliza s global. # c) Vamos a usar parámetros mutables para ver el efecto del procedimiento sobre estos parámetros. Para ello, vamos a # pasar una lista de enteros a la función y vamos a hacer que devuelva la lista ordenada. Lo hacemos como ejercicio, ya # que en la práctica existe un método (sort) que realiza esta operación. lNumeros = [30, 1, 43, 2, 45, 1, 4, 4, 13] def ordenar(lst): for z in range(len(lst)-1): iControl = lst[z] for i in range(len(lst)-1): if lst[i] > lst[i+1]: iControl = lst[i+1] lst[i+1] = lst[i] lst[i] = iControl print(lst) ordenar(lNumeros)
false
baea71029f36481b204178ffded7ddf70da664d5
treedbox/python-3-basic-exercises
/list/multi-dimensional/app.py
375
4.40625
4
# list two-dimensional # list inside the list foo = [[5, 6], [6, 7], [7, 2], [8, 4]] print(foo) # [[5, 6], [6, 7], [7, 2], [8, 4]] # list multi-dimensional # list inside the list inside the list bar = [[5, 6], [6, 7], [7, [2, 6]], [[8, 5], 4]] print(bar) # [[5, 6], [6, 7], [7, [2, 6]], [[8, 5], 4]] print(bar[0]) # [5, 6] print(bar[0][1]) # 6 print(bar[3][0][0]) # 8
false
d425842338650746eb7de3fc1a2ad7d922c0deaa
stellakaniaru/simple-python-games
/tictactoe.py
1,375
4.125
4
''' Tic Tac Toe game. ''' import random def drawBoard(board): # This function prints out the board that it was passed. # "board" is a list of 10 strings representing the board (ignore index 0) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') drawBoard([''] * 10) def inputPlayerLetter(): # Lets the player type which letter they want to be. # Returns a list with the player’s letter as the first item, and the computer's letter as the second. letter = '' while not (letter == 'X' or letter == 'O'): print('Do you want to be X or O?') letter = input().upper() # the first element in the list is the player’s letter, the second is the computer's letter. if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): # Randomly choose the player who goes first. if random.randint(0, 1) == 0: return 'computer' else: return 'player' def playAgain(): # This function returns True if the player wants to play again,otherwise it returns False. print('Do you want to play again? (yes or no)') return input().lower().startswith('y')
true
3821a69333bbbe017c04c25f68df88c3b3c61706
ramesh1990/Python
/Easy/stock.py
894
4.28125
4
''' Stock Buy Sell to Maximize Profit The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all. ''' def stock(lst): if ( len(lst) < 2) : return 0 min_val = lst[0] min_ind = 0 for i in range(len(lst)): if ( lst[i] < min_val ) : min_val = lst[i] min_ind = i max_val = lst[min_ind] for j in range(min_ind+1,len(lst)): if ( lst[j] > max_val ): max_val = lst[j] return max_val - min_val print (" Stock : ",stock([5,2,6,1,7,8,10,3]))
true
aa9e99206b9458bbb76c6e2d557d63301e5662ce
lavenderLatte/python_practice
/word_autoCorrection/edit_distance.py
2,024
4.28125
4
""" Function to compute edit distance between two words. Edit distance -- the minimum number of +, -, r operations that are needed to convert str2 to str1. +, -, r are addition, subtraction and replacement. For example: str1 = "abc", str2 = "ac". edit distance is 1 --> addition of b str2. str1 = "abc", str2 = "axc". edit distance is 1 --> replace x with b in str2. str1 = "a", str2 = "xc". edit distance is 2 --> remove c, replace x with a. str1 -- first input string. str2 -- second input string. out -- edit distance. usage: from edit_distance import edit_distance edit_distance(str1, str2) """ import numpy as np def edit_distance(str1, str2): """ edit_distance("", "") == 0 """ """ edit_distance("a", "") == 1 """ """ edit_distance("", "a") == 1 """ """ edit_distance("b", "a") == 1 """ """ edit_distance("xyz", "abc") == 3 """ # get length of str1 and str2 n1 = len(str1) n2 = len(str2) #create a 2d array dp = np.zeros(shape=(n2+1, n1+1)).astype('int') #dp[0][0] is the distance between two empty strings. Hence 0. dp[0][0] = 0 # redundant but for clarity #initialize the dp array for i1 in range(1, n1+1): # edit distance of empty string to another string of length i1 is i1. dp[0][i1] = i1 for i2 in range(1, n2+1): # edit distance of a string of length i2 to be converted to empty is i2 dp[i2][0] = i2 # dp for non trivial strings for i1 in range(1, n1+1): for i2 in range(1, n2+1): if(str1[i1-1] == str2[i2-1]): # if the characters are the same, then get the distance from prefixes of both str1 and str2 dp[i2][i1] = dp[i2-1][i1-1] else: dp[i2][i1] = np.min([ dp[i2-1][i1-1] +1, # replacing str2[i2] with str1[i1] dp[i2-1][i1] +1, # remove str2[i2] dp[i2][i1-1] +1 ]) # add str1[i1] at the end out = dp[n2][n1] return out
true
c8acc4486cb24f3219cda93255d5c0a822483cf9
GeburtstagsTorte/Homework
/Projects/Genetic Algorithm/Bubble Arena/Populations.py
1,105
4.46875
4
""" Step 1: Initialize: Create a population of N elements, each with randomly generated DNA (genes) (drawing) Step 2: Selection: Evaluate the fitness of each element of the population and create a pool (mating pool) Step 3: Reproduction: a) Pick two parents with probability according to their relative fitness b) Replicate: create a child by combining the DNA of these two parents c) Mutation: mutate the child's DNA based on a given probability d) add new child to a new population Step 4: New generation: Replace the old population with the new population and return to Step 2 until task is accomplished """ class Populations: population = [] generation = 0 # best = object # average_fitness = 0 def __init__(self): pass def update(self): pass def calc_fitness(self): pass def calc_average_fitness(self): pass def calc_best_individual(self): pass def selection(self): pass def reproduction(self): pass def mutation(self): pass
true
45b58f45a716e59aea24bf7b11b81b1815a408e9
riadassir/MyFirstRepository
/ex_06_02.py
973
4.5
4
############################################################# # Riad Assir - Coursera Python Data Strucutres Class - ex_06_02.py # Dealing with Files ############################################################# #FileHandle = open('mbox-short.txt') FileName = input('Enter the file name: ') try: FileHandle = open(FileName) except: print('File cannot be opened: ', FileName) quit() for line in FileHandle: print((line.rstrip()).upper()) #content = FileHandle.read() #UpperCaseContent = content.upper() #print (UpperCaseContent) #################################### testing code for previous work #count = 0 #for line in FileHandle: # line.rstrip() # if line.startswith('Subject:'): # count = count + 1 # if not line.startswith('From:'): #If you don't see the word From in the line, skip it.. # continue # print(line) # #print('There were', count, 'subject lines in', FileName) ######################################
true
92e6e640eca88f65c651ef4b156992b7fb8c52fb
dtauxe/hackcu-ad
/plot.py
2,690
4.15625
4
#!/bin/python # From: # https://stackoverflow.com/questions/6697259/interactive-matplotlib-plot-with-two-sliders from numpy import pi, sin import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons import math # Draw the plot def do_plot(sigstr): def signal(t): return eval(sigstr) axis_color = 'lightgoldenrodyellow' fig = plt.figure() ax = fig.add_subplot(111) # Adjust the subplots region to leave some space for the sliders and buttons fig.subplots_adjust(left=0.25, bottom=0.25) x_axis = 2*pi #t = np.arange(0.0, x_axis, x_axis/1000) t = np.linspace(0, x_axis, num=1000) # Draw the initial plot # The 'line' variable is used for modifying the line later [line] = ax.plot(t, signal(t), linewidth=2, color='red') ax.set_xlim([0, x_axis]) ax.set_ylim([-10, 10]) # Add two sliders for tweaking the parameters # Define an axes area and draw a slider in it xax_slider_ax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axis_color) xax_slider = Slider(xax_slider_ax, 'X-Axis', pi/64, 64*pi, valinit=x_axis) # Draw another slider #freq_slider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axis_color) #freq_slider = Slider(freq_slider_ax, 'Freq', 0.1, 30.0, valinit=freq_0) # Define an action for modifying the line when any slider's value changes def sliders_on_changed(val): x_axis = val #t = np.arange(0.0, x_axis, x_axis/1000) t = np.linspace(0, x_axis, num=1000) [line] = ax.plot(t, signal(t), linewidth=2, color='red') print (x_axis) ax.set_xlim([0, x_axis]) line.set_ydata(signal(t)) fig.canvas.draw_idle() xax_slider.on_changed(sliders_on_changed) #freq_slider.on_changed(sliders_on_changed) # Add a button for resetting the parameters reset_button_ax = fig.add_axes([0.8, 0.025, 0.1, 0.04]) reset_button = Button(reset_button_ax, 'Reset', color=axis_color, hovercolor='0.975') def reset_button_on_clicked(mouse_event): #freq_slider.reset() xax_slider.reset() reset_button.on_clicked(reset_button_on_clicked) # Add a set of radio buttons for changing color color_radios_ax = fig.add_axes([0.025, 0.5, 0.15, 0.15], axisbg=axis_color) color_radios = RadioButtons(color_radios_ax, ('red', 'blue', 'green'), active=0) def color_radios_on_clicked(label): line.set_color(label) fig.canvas.draw_idle() color_radios.on_clicked(color_radios_on_clicked) plt.show() ### MAIN if __name__ == '__main__': while (True): sigstr = input("---> ") do_plot(sigstr)
true
8bf9e58c2d775db3e3c77f7e852de92dc521be55
jjennas/web-ohjelmointi
/assignment2/2.py
621
4.21875
4
import re, statistics #function finds numbers in string def finding_numbers(s): return re.findall(r"-?\d+",s) answer = input("Give integers, can be separated by any character") if not answer: print("Please input integers separated by any character") else: numbers = finding_numbers(answer) # Tries to convert string of numbers into list of integers try: int_list = [int(i) for i in numbers] print(f"Sum is {sum(int_list)}, mean is {statistics.mean(int_list):.1f} and median is {statistics.median(int_list):.1f}") except ValueError: print("Error! No integers was given")
true
98eb13251a8780adc7acdb61c5db8fec32e1a741
lw2533315/leetcode
/uniquePaths_test.py
876
4.40625
4
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? # 递归法超时,只是用来测验和查找规律 class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ l = [0] self.move(1,1,m,n,l) return l[0] def move(self, row,col,m,n,l): if row == m and col == n: l[0] += 1 elif row > m or col > n: pass else: self.move(row + 1, col,m,n,l) self.move(row, col + 1, m,n, l) s = Solution() print (s.uniquePaths(3,2))
true
9346d7d92949c4037d1bf5a76b65b48b2a398276
newmayor/pythonlearning
/selectionSort.py
666
4.1875
4
def selSort(L): """Assumes that L is a list of elements that can be compared using >. Sorts L in ascending order. """ suffixStart = 0 while suffixStart != len(L): #look at each element in suffix for i in range(suffixStart, len(L)): if L[i] < L[suffixStart]: #swap position of elements L[suffixStart], L[i] = L[i], L[suffixStart] suffixStart += 1 #this program consists of two loops that increment thru a length of list. The inside one is O(len(L)) and the outside one is O(len(L)). Therefore, this program has complexity O(len(L^2)). This is known as quadratic time complexity.
true
c947b7d0e412238a284ce7a8ca8515b77ff454a6
newmayor/pythonlearning
/ex_IO.py
2,724
4.1875
4
def print_numbers(numbers): print("These are the currently stored phone numbers: ") for k, v in numbers.items(): print("Name:", k, "\tNumber:", v) print() def add_number(numbers, name, number): numbers[name] = number #use a dict to define name as the dict key and the associated number as the dict value def remove_number(numbers, name): if name in numbers: del numbers[name] else: print(name, " was not found") def lookup_number(numbers, name): if name in numbers: return "The number belonging to " + name + "is " + numbers[name] else: return name + " was not found." def load_numbers(numbers, filename): in_file = open(filename, "rt") while True: in_line = in_file.readline() if not in_line: break in_line = in_line[:-1] name, number = in_line.split(",") numbers[name] = number in_file.close() def save_numbers(numbers, filename): out_file = open(filename, "wt") for k, v in numbers.items(): out_file.write(k + ", " + v + "\n") out_file.close() def print_menu(): print("1. Print phone numbers") print("2. Add a phone number") print("3. Remove a phone number") print("4. Lookup a phone number") print("5. Load phone numbers FROM txt file") print("6. Save phone numbers INTO txt file") print("7. Quit program") print() phone_list = {} menu_choice = 0 print_menu() while True: menu_choice = int(input("Type in menu selection number (1-7):")) if menu_choice == 1: print_numbers(phone_list) elif menu_choice == 2: print("Adding a name and number to the phonebook.") name = input("Name?: ") phone = input("Enter the phone number: ") add_number(phone_list, name, phone) elif menu_choice == 3: print("Remove a name and associated number.") name = input("Name of the phone number to remove? ") remove_number(phone_list, name) elif menu_choice == 4: print("Looking up a number") name = input("Enter the name of the person whose phone number you want to lookup: ") print(lookup_number(phone_list, name)) elif menu_choice == 5: print("Loading phone numbers from a txt file...") filename = input("Please enter the file name or path to load:") load_numbers(phone_list, filename) elif menu_choice == 6: print("Saving the numbers to a txt file...") filename = input("Enter the filename or path to which you'd like to save these numbers to: ") save_numbers(phone_list, filename) elif menu_choice == 7: break else: print_numbers print("Goodbye!")
true
a4ce076b6389af67d906657b1653cdaad0e5996e
the-aerospace-corporation/ITU-Rpy
/tiler.py
1,472
4.25
4
# -*- coding: utf-8 -*- """ Turns a rectangle into a number of square tiles. Created on Thu Oct 15 17:24:31 2020 @author: MAW32652 """ def tiler(m, n, dimList = []): """ Tiler outputs the size of the tiles (squares), that are required to fill a rectangle of arbitrary dimension. Note: It does not find the minimum number of squares, but finds a number of squares. m = len of horz dimension n = len of vert dimension output = dimList, a list of the dimensions of the squares that are required to fill the rectangle. """ #if the input lists are of the same length if len(m) == len(n): #add the length of either dimension to the list. dimList.append(len(m)) #return the lsit of results. return dimList #case where the m dimension is larger than the n dimension elif len(m) > len(n): #append the length of the smaller dimension, n. dimList.append(len(n)) #do tiler on the rest of the rectangle #start at len(n) to the end and all of n. return tiler(m[len(n):], n, dimList) #case where the n dimension is larger than the m dimension. elif len(n) > len(m): #append the length of the smaller dimension, m. dimList.append(len(m)) #do tiler on the rest of the rectangle #start at all of m and at len(m) return tiler(m, n[len(m):], dimList)
true
a429f0cf76e5617d958e23514f1a4ba2d67d6e4f
rock-chock/leetcode
/412_fizzbuzz.py
804
4.125
4
""" https://leetcode.com/problems/fizz-buzz/ Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. """ def main(): n = 30 res = fizzbuzz(n) for i in res: print(i) def fizzbuzz(n): r =[] for i in range(1, n+1): div_by_3 = (i % 3 == 0) div_by_5 = (i % 5 == 0) if div_by_3 and div_by_5: r.append('FizzBuzz') elif div_by_3: r.append('Fizz') elif div_by_5: r.append('Buzz') else: r.append(str(i)) return r if __name__ == "__main__": main()
true
e3551871af7f069111a413ee63db06796503aa90
Tylerman90/PythonPractice
/odd_even_funk.py
821
4.375
4
#Write a program that reads a list of integers, #and outputs whether the list contains #all even numbers, odd numbers, or neither. #The input begins with an integer #indicating the number of integers that follow. def user_values(): my_list = [] num_in_list = int(input()) for num in range(num_in_list): my_list.append(int(input())) return my_list def is_list_even(my_list): for i in my_list: if (i % 2 == 1): return False return True def is_list_odd(my_list): for i in my_list: if (i % 2 == 0): return False return True if __name__ == '__main__': user_list = user_values() if is_list_even(user_list): print('all even') elif is_list_odd(user_list): print('all odd') else: print('not even or odd')
true
f145873536f4f3fcdec1bfc5fcc8cb065f5742f6
kapiltiwari1411/python-lab
/kapil4reverse.py
246
4.25
4
#program to find reverse of enterd number. num=int(input("please enter any number")) reverse=0. while(num>0): reminder=num%10 reverse=(reverse*10)+reminder num=num//10. print(" reverse of the entered number\n", reverse)
true
651b8fba4e4f3bd3ee41aa4f4ee792988e3526ac
ArthurBrito1/MY-SCRIPTS-PYTHON
/Desafios/desafio37.py
634
4.1875
4
numero = int(input('Digite um numero inteiro qualquer:')) print('''ESCOLHA UMA DAS BASES PARA CONVERSÃO: [ 1 ] PARA CONVERTER PARA BINARIO: [ 2 ] PARA CONVERTER PARA OCTAL: [ 3 ] PARA CONVERTER PARA HEXADECIMAL:''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para binario é igual a {}'.format(numero, bin(numero)[2:])) elif opção == 2: print('{} converito para octal é igual a {}'.format(numero,oct(numero)[2:])) elif opção == 3: print('{} convertido para hexadecimal é igual a {}'.format(numero, hex(numero)[2:])) else: print('Opção invalida tente novamente')
false
60dd32a7b8c2906552b82b012c1e4e3a1914bbdd
ArthurBrito1/MY-SCRIPTS-PYTHON
/Exemplos/ex007.1aula.py
355
4.1875
4
nome = str(input('Qual é seu nome?')) if nome == 'Arthur': print('Que nome bonito!') elif nome == 'Pedro' or nome == 'Maria' or nome == 'João': print('Seu nome é bem popular no Brasil.') elif nome in 'Ana Claudia Jessika Juliana': print('Que belo nome feminino.') else: print('Seu nome é bem normal.') print('Tenha um bom dia, {}!'.format(nome))
false
a37d0bfdb5defc86998701657f9c11ff27113a1a
ItsPepperpot/hangman
/hangman.py
2,362
4.125
4
# Hangman. # Made by Oliver Bevan in July 2019. import random print("Welcome to hangman!") menu_choice = 0 while menu_choice != 3: print("Please pick an option.") print("1. Begin game") print("2. Show rules") print("3. Exit") menu_choice = int(input()) if menu_choice == 1: # Begin game. print("Thinking of a word...") dictionary = open("words.txt", "r") word_list = [] for line in dictionary: word_list.append(line) dictionary.close() word_to_guess = word_list[random.randint(0, len(word_list) - 1)] print("Let's begin.") user_has_won = False lives_remaining = 8 matched_characters = [" "] * len(word_to_guess) while not user_has_won and lives_remaining > 0: for i in range(0, len(word_to_guess)): if matched_characters[i] is not " ": print(matched_characters[i], end=" ") else: print("_", end=" ") print( f"\n Please enter a guess. ({lives_remaining} lives remaining)") guess = input() if len(guess) > 1: # User is guessing the word. if guess == word_to_guess: user_has_won = True else: lives_remaining -= 1 print("Sorry, that's not the correct word.") else: # User is guessing a letter. if guess in word_to_guess: for i in range(0, len(word_to_guess)): if word_to_guess[i] == guess: matched_characters[i] = guess else: print("Sorry, that's not in the word.") lives_remaining -= 1 if user_has_won: print("Congratulations! You got it.") else: print("Sorry, you lose!") print(f"The word was {word_to_guess}") elif menu_choice == 2: # Show rules. print("How to play:") print("Hangman is a simple guessing game.") print("The computer thinks of a word. To win, you simply guess the word by suggesting letters.") print( "If you cannot guess the word within the maximum number of guesses, you lose.") print("Good luck!")
true
cbd3e856cce1ba5c088408c9722989b82ee30709
JamieBort/LearningDirectory
/Python/Courses/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section3ConditionalsLoopsFunctionsAndABitMore/22ExerciseLoops.py
1,226
4.28125
4
# First of two. # Create a program that asks a user for 8 names of people. # Store them in a list. # When all the names have been given, pick a random one and print it. # Second of two. # Create a guess game with the names of colors. # At each round pick a random color and let the user guess it. # After a successful guess, ask the user if they want to play again. # Keep playing until the user types "no" import random #used for both # First of two. mylist = [] while len(mylist) < 8: another = input("One by one, please type the name of a person.\n") mylist.append(another) print("Your list of people is: ", mylist) print("Here is the name from your list that has been picked randomly: ", random.choice(mylist)) # Second of two. guess = "yes" listOfColors = ["red", "orange", "blue", "green"] while guess != "no": guess = input("Make a guess. Type 'red', 'orange', 'blue', or 'green'. If it matches the computer, you win. The game will be over. If not, guess again.\n") print("You guessed: ", guess) if random.choice(listOfColors) == guess: print("They guessed correctly. Game over.") break else: print("They guessed incorectly. Guess again.") print("Out of while loop.")
true
7096d9987e86cdc601fa4d2fbb6f748b69a4eb00
Youngjun-Kim-02/ICS3U-Assignment2-python
/volume_of_cone.py
726
4.40625
4
#!/usr/bin/env python3 # Created by: Youngjun Kim # Created on: April 2021 # This program calculates the volume of a cone # with radius and height inputted from the user import math def main(): # this function calculates the volume of a cone # main function print("We will be calculating the area of a cone. ") # input radius_of_cone = int(input("Enter radius of a cone (mm): ")) height_of_cone = int(input("Enter height of a cone (mm): ")) # process volume_of_cone = 1/3 * math.pi * radius_of_cone * radius_of_cone * height_of_cone # output print("") print("Volume is {0} mm³.".format(volume_of_cone)) print("") print("Done.") if __name__ == "__main__": main()
true
e9ef8fd3021f0790cfd9d5b0895ac23f3aad980a
juanPabloCesarini/cursoPYTHON2021
/Ejercicios Sección 4/Punto3.py
362
4.375
4
""" Escribir un programa que pregunte al usuario su edad y muestre por pantalla todos los años que ha cumplido (desde 1 hasta su edad). """ def pedirEdad(): return int(input("Tu edad: ")) def mostrarEdades(edad): i=1 while i<=edad: print("Tu edad es: ", i) i+=1 def main(): edad = pedirEdad() mostrarEdades(edad) main()
false
6fcc046029e432c4919bb48b6005dfe3799068c3
juanPabloCesarini/cursoPYTHON2021
/Seccion 11/metodos_cadenas.py
507
4.3125
4
nombre = input("Ingresa tu nombre: ") print("el nombre es: ", nombre.upper()) nombre = input("Ingresa tu nombre: ") print("el nombre es: ", nombre.lower()) nombre = input("Ingresa tu nombre: ") print("el nombre es: ", nombre.capitalize()) frase= input("Ingresa una frase: ") letra= input("Letra a buscar: ") print(letra, "se encuentra: ",frase.count(letra), "veces") print(letra, "se encuentra en la posicion: ",frase.find(letra)) print(frase.split(" ")) ## HAY MAS BUSCARLAS EN LA DOCU DE PYTHON
false
7bf07e28f7377b6b735b33f387d83f03b641b9db
ArmandoRuiz2019/Python
/Funciones/Funciones.txt
1,789
4.1875
4
Este mini proyecto te permitirá practicar un poco con funciones, listas, y la traducción de formulas matemáticas a sentencias de programación. A fin de usar las notas en nuestro programa, necesitaremos que estén incluidas en un contenedor, específicamente una lista. La rutina presenta los siguientes resultados a partir de una entrada de calificaciones: Imprime lo siguiente: el total de calificaciones suma de las calificaciones calificación promedio varianza desviación estándar ''' calificaciones = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_calificaciones(calificaciones): #Imprime la lista de calificaciones for calificacion in calificaciones: print calificacion def calificaciones_sum(lista): #Suma la calificaciones suma = 0.0 for i in lista: suma += i return suma def calificaciones_promedio(lista): #Calcula el promedio de las calificaciones suma = calificaciones_sum(lista) return suma / len(lista) def calificaciones_varianza(lista, promedio): #Obtiene la valiranza n = len(lista) s2 = 0 for i in lista: s2 += (i - promedio) ** 2 s2 = s2 / n return s2 def calificaciones_std_deviacion(varianza): #Calcula la desviación estándar s = varianza ** (0.5) return s #print calificaciones No se pide, pero sino se imprime no nos deja pasar de módulo. print calificaciones print print_calificaciones(calificaciones) print calificaciones_sum(calificaciones) print calificaciones_promedio(calificaciones) print calificaciones_variaza(calificaciones, calificaciones_promedio(calificaciones)) print calificaciones_std_deviacion(calificaciones_varianza(calificaciones, calificaciones_promedio(calificaciones)))
false
fc06cad0a5e98e8ea0acce7a20bf4e0725794df6
ArmandoRuiz2019/Python
/Colecciones/Tuplas02.py
1,028
4.125
4
# -*- coding: utf-8 -*- # Autor: Armando Ruiz # Tuplas en Python mi_tupla = (1,'Enmanuel') print ('Mostrando un elemento de la tupla:',mi_tupla[1]) print ('Tupla:',mi_tupla) # convierte una lista en tupla # método list mi_lista = list(mi_tupla) print ('Tupla convertida en Lista:',mi_lista) # convierte una tupla en lista # método tuple lista = [2,1992,2,'Alexander'] tupla = tuple(lista) print ('Lista convertida en Tupla:',tupla) # comprobar si hay elemento en la tupla print ('Alexander' in tupla) # para saber cuantos veces se encuentra un elemento en la tupla # count print ('Cuantas veces se encuentra un elemento en la tupla:',tupla.count(2)) # longitud de una tupla # len print ('Longitud de la tupla:',len(tupla)) # tuplas unitarias tupla_unitaria = 'Luz', print ('Tupla unitaria:',len(tupla_unitaria)) # desempaquetado de tupla d_tupla = ('Enmanuel',4,4,1994) nombre, dia, mes, ano = d_tupla print ('\nDesempaquetado de tupla:') print ('Nombre:',nombre) print ('Dia:',dia) print ('Mes:',mes) print ('Año:',ano)
false
4b80e51dc0a98003cf82bc271886b0b61ff284e7
sinugowde/PythonWorkSpace
/PP_006.py
433
4.21875
4
# PythonPractice_006: Polindrome def checkPolindrome(stringVar): for i in range(0, len(stringVar)//2): if stringVar[i] != stringVar[-i-1]: resVar = False break resVar = True return resVar # Main Function/Method stringVar = input() resVar = checkPolindrome(stringVar) if resVar: print("the Entered string: " + stringVar + ", is a POLINDROME") else: print("the Entered string: " + stringVar + ", is not a POLINDROME")
true
a2cbae5516ae86338884900c57ea0a60433b8260
bradweeks7/CPE202
/Labs/Lab1/lab1/lab1.py
933
4.3125
4
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list == None: raise ValueError # An empty list should return None if len(int_list) == 0: return None for number in range(len(int_list)): maximum = 0 new_max = int_list[number] if new_max > maximum: maximum = new_max return maximum def reverse_rec(int_list): # must use recursion """recursively reverses a list of numbers and returns the reversed list If list is None, raises ValueError""" pass def bin_search(target, low, high, int_list): # must use recursion """searches for target in int_list[low..high] and returns index if found If target is not found returns None. If list is None, raises ValueError """ pass
true
170f0f24b96c69417a0a2af693bdd53b7a00d88b
jeffersonsouza/computer-engineering-degree
/fundamentos-python/AT/03.py
1,364
4.21875
4
# Usando o Thonny, escreva uma função em Python chamada potencia. # Esta função deve obter como argumentos dois números inteiros, # A e B, e calcular AB usando multiplicações sucessivas # (não use a função de python math.pow) e retornar o resultado da operação. # Depois, crie um programa em Python que obtenha dois números inteiros do # usuário e indique o resultado de AB usando a função. # # Também disponível em https://github.com/jeffersonsouza/computer-engineering-degree/blob/master/fundamentos-python/AT/ campos = [ {'label': 'Informe um número inteiro a ser usado como base:', 'valor': 0}, {'label': 'Informe um número inteiro a ser usado como expoente:', 'valor': 0}, ] def potencia(base, expoente): base, expoente = int(base), int(expoente) resultado = base for n in range(1, expoente): resultado *= base return resultado for campo in campos: while True: campo['valor'] = input(f"{campo['label']} ") or '' if not campo['valor'].isnumeric(): print("O valor informado é inválido.") elif not int(campo['valor']) > 0: print(f"O valor precisa ser maior que zero.") else: break print( f"A potenciação da base {campos[0]['valor']} e expoente {campos[1]['valor']} é: {potencia(campos[0]['valor'], campos[1]['valor'])}")
false
d6c8cd38a45fbe47c95aeb01ce7387d4202dbdaf
jeffersonsouza/computer-engineering-degree
/fundamentos-python/TP3/01.py
843
4.21875
4
# Usando Python, faça o que se pede (código e printscreen): # - Crie uma lista vazia; # - Adicione os elementos: 1, 2, 3, 4 e 5, usando append(); # - Imprima a lista; # - Agora, remova os elementos 3 e 6 (não esqueça de checar se eles estão na lista); # - Imprima a lista modificada; # - Imprima também o tamanho da lista usando a função len(); # - Altere o valor do último elemento para 6 e imprima a lista modificada. # # Também disponível em https://github.com/jeffersonsouza/computer-engineering-degree/blob/master/fundamentos-python/TP3/ # item "a" lista = [] # item "b" for n in range(1, 6): lista.append(n) # item "c" print(lista) # item "d" for n in [3, 6]: if n in lista: lista.remove(n) # itens "e" e "f" print(lista, '-> Tamanho:', len(lista), 'itens') # item "g" lista[-1] = 6 print(lista)
false
a93d3bd1ef9fee237e33689359553aef83b26b22
sdawn29/cloud-training
/list_ex.py
1,317
4.375
4
#list -> class l1 = list([10, 20, 30]) # a list of 3 elements l2 = [10, 12.5, 'python', ['a','b']] #shortcut of creating a list print(l2) print(l2[1]) print(l2[2][1]) print(l2[-1:1:-1]) #add element ot the list l2.append(200) print('append=',l2) l2.insert(2,300) print('Insert=',l2) l3 = [10,20] l4 = ['a', 'b'] l5 = l3 + l4 l6 = l3 * 10 print(l5, l6, sep = '\n') l3.extend(l4) print('extends =', l3) #remove elements from list r1 = l5.pop() print('r1=', r1, l5) r2 = l5.pop(2) print('r2 =', r2, l5) r3 = l5.remove(20) #in this case we are passing the value, it will remove the first occurance of the value print('remove=', r3, l5) del l5[0] print('After del=', l5) #update elements to the list print('l3=',l3) l3[1] = 'Java' print('after update=',l3) #some other methods l6 =[10, 30, 20] l6.sort() #ascending order print('sort ascend =', l6) l7 = ['z','a','b'] l7.sort(reverse = True) #descending order print('sort desc =', l7) l8 = [10, 'a', 20, 'b'] l8.reverse() # print the reverse of the list print('reverse=',l8) l8.clear() print('l8=',l8) #copy l = [10, ['a', 'b']] m = l # Reference copy n =l.copy() #shallow copy #copy module -> copy(), deepcopy() import copy p = copy.deepcopy(l) print(id(l[0]), id(p[0])) print(id(l[1]), id(p[1]))
true
8eb9843678140e25e75f2a9030c2480d0fdd649c
SafiyatulHoque/Bootcamp-NSU
/Bootcamp 11/Pre Bootcamp Contest 11 (1)/Q.py
436
4.625
5
# Python3 code to demonstrate # to extract words from string # using split() # initializing string test_string = 'Adventures in Disneyland Two blondes were going to Disneyland when they came to a fork in the road. The sign read: "Disneyland Left." So they went home.' # printing original string print ("The original string is : " + test_string) # using split() # to extract words from string res = test_string.split() print (res)
true
66ea622dc4018f5849cb4a2f938a7837ae418635
shreyansh-tyagi/leetcode-problem
/power of 2.py
808
4.25
4
''' Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Example 4: Input: n = 4 Output: true Example 5: Input: n = 5 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you solve it without loops/recursion? '''' import math class Solution: def isPowerOfTwo(self, n: int) -> bool: a,b=0,0 if n==0: return False while(a!=n and a<n): a=2**b b+=1 if a==n: return True else: return False
true
0c121b96785c7586221dd6a08d0a5ec24ee5abaf
shreyansh-tyagi/leetcode-problem
/wildcard matching.py
1,248
4.28125
4
''' Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb", p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb", p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb", p = "a*c?b" Output: false Constraints: 0 <= s.length, p.length <= 2000 s contains only lowercase English letters. p contains only lowercase English letters, '?' or '*'. ''' class Solution: def isMatch(self, s: str, p: str) -> bool: if p=='*' and p=='?': p.remove('*') p.remove('?') if p in s : return 'true' else: return 'false'
true
926c7b7076a25daef60b3d3b300670b30e73e575
shreyansh-tyagi/leetcode-problem
/backspace string compare.py
1,175
4.125
4
''' Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: s = "ab#c", t = "ad#c" Output: true Explanation: Both s and t become "ac". Example 2: Input: s = "ab##", t = "c#d#" Output: true Explanation: Both s and t become "". Example 3: Input: s = "a##c", t = "#a#c" Output: true Explanation: Both s and t become "c". Example 4: Input: s = "a#c", t = "b" Output: false Explanation: s becomes "c" while t becomes "b". Constraints: 1 <= s.length, t.length <= 200 s and t only contain lowercase letters and '#' characters. Follow up: Can you solve it in O(n) time and O(1) space? ''' class Solution: def backspaceCompare(self, s: str, t: str) -> bool: a,b=[],[] for i in s: if i!='#': a.append(i) else: if a!=[]: a.pop() for j in t: if j!='#': b.append(j) else: if b!=[]: b.pop() return a==b
true
4d5d7368ff9248788d9fbd3acf136b51a8f35c00
shreyansh-tyagi/leetcode-problem
/planning a meeting.py
1,748
4.25
4
''' You have to organize meetings today. There are meetings for today. Meeting must start at time and end at time . Unfortunately, there are only two meeting rooms available today. Consider meetings and intersecting in time if . You cannot conduct two meetings in the same room at the same time. Your task is to determine whether it is possible to hold all meetings using only two rooms. If yes, then print . Otherwise, print . Function description Complete the isPossible function in the editor. It contains the following parameters: Parameter name: Type: INTEGER Description: Number of meetings Parameter name: Type: INTEGER ARRAY Description: Start time of meetings Parameter name: Type: INTEGER ARRAY Description: End time of meetings Return The function must return an INTEGER denoting the answer to the problem. If it is possible to hold all the meetings using only two rooms, then it is . Otherwise, it is . Input format The first line contains an integer denoting the number of elements in . Each line of subsequent lines (where ) contains an integer describing . Each line of subsequent lines (where ) contains an integer describing . Constraints SAMPLE INPUT 3 1 2 4 2 3 5 SAMPLE OUTPUT 1 Explanation Hold the first ([1; 2]) and the third ([4; 5]) meetings in the first room. Hold the second meeting ([2; 3]) in the second room. ''' def isPossible(n,s,e): # Write your code here for i in range(n): if max(s)>=min(e): return 1 else: return 0 return # Write your code here n = int(input()) start = [] end = [] for _ in range(n): start.append(int(input())) for i in range(n): end.append(int(input())) out_ = isPossible(n, start, end) print(out_)
true
18e31179f424c66e561bcd7d88536f73381c423e
shreyansh-tyagi/leetcode-problem
/permutations.py
662
4.125
4
''' Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: 1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique. ''' from itertools import permutations class Solution: def permute(self, nums: List[int]) -> List[List[int]]: b=(list(permutations(nums))) c=[] for i in range(len(b)): c.append(list(b[i])) return c
true
cc19150ea53ef523c336039b30c3d79dfd12fdd2
ElizabethRoots/python_practice
/mini_projects/ft_converter.py
711
4.40625
4
#!/usr/bin/env python3 import sys height = float(input("Enter your height in the format: ft.in ")) inches = height * 12 dvd = 7.48 creditCard = 3.375 iPadAir = 9.4 select = int( input("Select unit of measurement: 1 = DVD case, 2 = Credit Cards, 3 = iPad Air Gen-One ")) def divide(inches, select): formatted_float = "{:.2f}".format(inches / select) return formatted_float if select == 1: print("You are", divide(inches, dvd), "DVD cases tall.") if select == 2: print("You are", divide(inches, creditCard), "Credit cards tall.") if select == 3: print("You are", divide(inches, iPadAir), "iPad Air gen-one's tall.") else: print("Not a valid input.")
true
351ecae3df591709bba7a5ad0e0c44005338b615
calebhews/Ch.08_Lists_Strings
/8.0_Jedi_Training.py
1,650
4.46875
4
# Sign your name: Caleb Hews ''' 1.) Write a single program that takes any of the three lists, and prints the average. Use the len function. There is a sum function I haven't told you about. Don't use that. Sum the numbers individually as shown in the chapter. Also, a common mistake is to calculate the average each time through the loop to add the numbers. Finish adding the numbers before you divide. ''' a_list = [3,12,3,5,3,4,6,8,5,3,5,6,3,2,4] b_list = [4,15,2,7,8,3,1,10,9] c_list = [5,10,13,12,5,9,2,6,1,8,8,9,11,13,14,8,2,2,6,3,9,8,10] a_total = 0 b_total = 0 c_total = 0 for item in a_list: a_total += item a_num=len(a_list) for item in b_list: b_total += item b_num=len(b_list) for item in c_list: c_total += item c_num=len(c_list) a_ave=a_total/a_num b_ave=b_total/b_num c_ave=c_total/c_num print(a_ave) print(b_ave) print(c_ave) ''' 2.) Write a program that will strip the username (whatever is in front of the @ symbol) from any e-mail address and print it. First ask the user for their e-mail address. ''' # done=False # while True: # email=input("What is your email address? ") # username=" " # for item in email: # if item=="@": # done=True # break # username += item # print(username) ''' TEXT FORMATTING: 3.) Make following program output the following: Score: 41,237 High score: 1,023,407 Do not use any plus sign (+) in your code. You should only have two double quotes in each print statement. ''' # score = 41237 # highscore = 1023407 # print("Score: " + str(score) ) # print("High score: " + str(highscore) )
true
fa2880ed5dfb7e0fe4986a84097af2ca38aa0eb4
FazeelUsmani/Scaler-Academy
/017 String Algorithm/A3 reverseString.py
1,038
4.28125
4
/* Reverse the String Problem Description Given a string A of size N. Return the string A after reversing the string word by word. NOTE: A sequence of non-space characters constitutes a word. Your reversed string should not contain leading or trailing spaces, even if it is present in the input string. If there are multiple spaces between words, reduce them to a single space in the reversed string. Problem Constraints 1 <= N <= 105 Input Format The only argument given is string A. Output Format Return the string A after reversing the string word by word. Example Input Input 1: A = "the sky is blue" Input 2: A = "this is ib" Example Output Output 1: "blue is sky the" Output 2: "ib is this" Example Explanation Explanation 1: We reverse the string word by word so the string becomes "the sky is blue". */ class Solution: # @param A : string # @return a strings def solve(self, A): A = A.split() A = A[::-1] return ' '.join(A)
true
37209057e5842fb3a827b0588918d4ee291bcdfd
k4u5h4L/algorithms
/leetcode/Symmetric_Tree.py
935
4.34375
4
''' Symmetric Tree Easy Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Input: root = [1,2,2,3,4,4,3] Output: true Example 2: Input: root = [1,2,2,null,3,null,3] Output: false ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root == None: return True return self.is_symmetric(root.left, root.right) def is_symmetric(self, left, right): if left == None or right == None: return left == right if left.val != right.val: return False return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left)
true
a8ffbc2d433ae45bf4f87875e663b4853be83cc2
k4u5h4L/algorithms
/nuclei/max_profit.py
486
4.15625
4
''' For the given array of length and price find the maximum profit that can be gained. ''' def maxProfit(prices): max_profit = 0 min_price = prices[0] for price in prices: min_price = min(price, min_price) max_profit = max(max_profit, price - min_price) return max_profit def main(): prices = [2,4,2,5,8,2,3] res = maxProfit(prices) print(f"Max profit of {prices} is {res}") if __name__ == "__main__": main()
true
fb775e5361af5b84e1b1be3bae5f526bab67ea19
k4u5h4L/algorithms
/leetcode/ZigZag_Conversion.py
1,955
4.34375
4
''' ZigZag Conversion Medium The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" ''' class Solution: def convert(self, s: str, numRows: int) -> str: if len(s) == 1 or numRows == 1: return s zig_zag = [] for _ in range(numRows): zig_zag.append([" "] * (len(s))) i = 0 j = 0 point = 0 down_or_slant = True while point < len(s): if down_or_slant: while i < numRows and point < len(s): zig_zag[i][j] = s[point] i += 1 point += 1 down_or_slant = not down_or_slant j += 1 else: i -= 2 while i >= 0 and point < len(s): zig_zag[i][j] = s[point] i -= 1 j += 1 point += 1 i += 2 down_or_slant = not down_or_slant res = "" for i in range(len(zig_zag)): for j in range(len(zig_zag[i])): if zig_zag[i][j] != " ": res += zig_zag[i][j] return res
true
f6846b1ccb90f6eb86bee2970132941cf498c102
k4u5h4L/algorithms
/leetcode/Second_Largest_Digit_in_a_String.py
1,017
4.28125
4
''' Second Largest Digit in a String Easy Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits. Example 1: Input: s = "dfa12321afd" Output: 2 Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2. Example 2: Input: s = "abc1111" Output: -1 Explanation: The digits that appear in s are [1]. There is no second largest digit. ''' class Solution: def secondHighest(self, s: str) -> int: max_num = 0 for char in s: try: max_num = max(max_num, int(char)) except ValueError: pass s = s.replace(str(max_num), "") max_num = -1 for char in s: try: max_num = max(max_num, int(char)) except ValueError: pass return max_num
true
0a7df1ce50f54435c9a653bd0c4c5bc54e6179a9
k4u5h4L/algorithms
/leetcode/Rotate_Image.py
1,123
4.46875
4
''' Rotate Image Medium You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]] Example 2: Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] Example 3: Input: matrix = [[1]] Output: [[1]] Example 4: Input: matrix = [[1,2],[3,4]] Output: [[3,1],[4,2]] ''' # Intuition is to take transpose and then reverse each row class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ res = [] for i in range(len(matrix)): res.append(matrix[i].copy()) for i in range(len(res)): for j in range(len(res[i])): matrix[i][j] = res[j][i] matrix[i].reverse()
true
cc9934f6d827570fd8bb3ad05b6acc36b3c37495
k4u5h4L/algorithms
/leetcode/Add_to_Array-Form_of_Integer.py
508
4.1875
4
''' Add to Array-Form of Integer Easy The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. ''' class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: res = [str(n) for n in num] res = str(int(''.join(res)) + k) return [int(char) for char in res]
true
f2da2236b2af5e8cc428d8bc6dac3e08b19e574c
k4u5h4L/algorithms
/leetcode/Set_Matrix_Zeroes.py
926
4.28125
4
''' Set Matrix Zeroes Medium Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix. You must do it in place. Example 1: Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]] Example 2: Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] ''' class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ res = [] for i in range(len(matrix)): res.append(matrix[i].copy()) for i in range(len(res)): for j in range(len(res[i])): if res[i][j] == 0: for k in range(len(res)): matrix[k][j] = 0 for k in range(len(res[i])): matrix[i][k] = 0
true