blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
289cc536fb1d4a594155fd8f2ae37bb669feba57
vishwasanavatti/Interactive-Programming-with-python
/Interactive Programming with python/second_canvas.py
397
4.21875
4
# Display an X ################################################### # Student should add code where relevant to the following. import simplegui # Draw handler def draw(canvas): canvas.draw_text("X",[96, 96],48,"Red") # Create frame and assign callbacks to event handlers frame=simplegui.create_frame("Test", 200, 200) frame.set_draw_handler(draw) # Start the frame animation frame.start()
true
fd503ae0aae52dff9f8d209d72ff86af9943ec63
j0sht/checkio
/three_words.py
467
4.21875
4
# You are given a string with words and numbers separated by whitespaces. # The words contains only letters. # You should check if the string contains three words in succession. import re def checkio(s): return re.search(r'[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+', s) != None print(checkio("Hello World hello") == True) print(checkio("He is 123 man") == False) print(checkio("1 2 3 4") == False) print(checkio("bla bla bla bla") == True) print(checkio("Hi") == False)
true
c2991ed8c969b799c5458bac865e478122ec04af
panmari/nlp2014
/ex1/task3.py
334
4.15625
4
#!/usr/bin/python3 print("Please enter an integer") try: input_int = eval(input()) except NameError as e: print("Oops, that was not an integer!") exit(1) print("The first {} numbers of the fibonacci sequence are: ".format(input_int)) fib = [1,1] for i in range(input_int): fib.append(fib[-1] + fib[-2]) print(fib)
true
52d504ec91089e3b0eb747b99bf580e08883dc73
cesarg01/AutomateBoringPythonProjects
/collatz.py
973
4.4375
4
# This program take any natural number n. If n is even, divide it by 2 to get n/2, # if n is odd multiply it by 3 and add 1 to obtain 3n+1. Repeat the process indefinitely. # The conjecture is that no matter what number you start with, you will always eventually reach 1. # This is known as the Collatz conjecture. def collatz(number): """ # Take the user's input and apply the Collatz conjecture """ if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 == 1: print(3 * number + 1) return 3 * number + 1 # Keep asking the user for a natural number until they input a natural number. while True: try: user_input = int(input('Please enter a number: \n')) break except ValueError: print('Error: Enter a integer') # Save the first collatz value value = collatz(user_input) # Keep calling collatz() until value becomes 1 while value != 1: value = collatz(value)
true
729f00cf4e463f39588ac965b873b52ba9baf5c4
CWMe/Python_2018
/Python_Learn_Night/Python_Dictionaries.py
729
4.46875
4
# Dictionaries in Python # { } # Map data type in Python # key : value paris for data. my_dictionary = {"name": "CodeWithMe", "location": "library", "learning": "Python"} # dictionaries may not retain the order in which they were created (before python 3.6.X). # print(my_dictionary) # accessing VALUES from a dictionary. print(my_dictionary["learning"]) # we can add new key value pairs. my_dictionary["date"] = "April" del my_dictionary["date"] # only 1 value per key # the keys must be IMMUTABLE (strings, numbers, or tuples) # useful methods for dictionaries # .items() # .keys() # .values() for key in my_dictionary.keys(): if key == "location": continue else: print(key, my_dictionary[key])
true
ac4062b52a08a61400ae7eb41b1554b907b23887
thewchan/python_oneliner
/ch3/lambda.py
637
4.28125
4
"""Lambda function example. Create a filter function that takes a list of books x and a minimum rating y and returns a list of potential bestsellers that have higher than minimum rating, y' > y. """ import numpy as np books = np.array([['Coffee Break Numpy', 4.6], ['Lord of the Rings', 5.0], ['Harry Potter', 4.3], ['Winnie-the-Pooh', 3.9], ['The Clown of God', 2.2], ['Coffee Break Python', 4.7]]) predict_bestseller = (lambda x, y: x[x[:, 1].astype(float) > y])(books, 3.9) print(books) print('Predicted bestsellers:') print(predict_bestseller)
true
b9f437acb644e63dbebc2aba451e5f90d7d8c854
Oyanna/Decode_Python59
/homeworks/hw_GUI_Zhuldyz.py
1,269
4.125
4
from math import pi from tkinter import * window = Tk() def square(r): S = pi*r*r text = "Площадь круга равна %s \n " %(S) return text def inserter(value): output.delete("0.0", "end") output.insert("0.0", value) def handler(): try: r_val = float(r.get()) inserter(square(r_val)) except ValueError: inserter("Убедитесь, что вы ввели радиус круга") window.title("Площадь круга") window.minsize(350, 250) #устанавливаем минимальный размер окна window.resizable(width=False, height=False) #выключаем возможность изменять окно frame = Frame(window) frame.grid() r = Entry(frame, width = 5) r.grid(row = 0, column = 1) r.configure(font=("Courier", 14, "bold")) lbl_r = Label(frame, text = "Введи радиус круга: ") lbl_r.grid(row = 0, column = 0, padx = 10) lbl_r.configure(font=("Courier", 14, "bold")) btn = Button(frame, text = "Найти",command = handler) btn.grid(row = 0, column = 6) btn.configure(font=("Courier", 14, "italic")) output = Text(frame, bg="lightgreen", font = "Arial 14", width = 60, height = 20) output.grid(row = 2, columnspan=8) window.mainloop()
false
14f266de9648b45e70a6d58b35e3f44be4611047
Adriana-ku06/programming2
/pythom/exercise26.py
2,959
4.125
4
#Adriana ku exercise 26 from sys import argv print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') tall=input() #undeclared tall variable print("How much do you weigh?", end=' ')#first error missing closing parentheses weight = input() print(f"So, you're {age} old, {tall} height and {weight} heavy.")#variable declaration error script, filename = argv #error. import from argv txt = open(filename)#variable write error print(f"Here's your file {filename}:") print(txt.read())#variable write error is txt print("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print(txt_again.read())#function call error is "." no " _" print("Let's practice everything.")#error two, single quotes in a print print("You \d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")#error three, line break and single quotes poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print("--------------")#error 4 missing closing quote print(poem) print("--------------")#error 5, a start quote is required five = 10 - 2 + 3 - 6 #error 6 sign without variable to subtract print(f"This should be five: {five}") def secret_formula (started): #error 8, missing ":" in the function declaration jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 # error 9, missing division operation symbols return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) # remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) # it's just like with an f"" string print(f"We'd have {beans} beans, {jars} jars and {crates} crates.") start_point = start_point / 10 print("We can also do that this way:") formula = secret_formula(start_point)##variable write error # this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates.".format(*formula)) people = 20 cats = 30 ##variable write error dogs = 15 if people < cats: print ("Too many cats! The world is doomed!") #Error 10, parenthesis in missing print if people < cats: print("Not many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: ##error 11, missing ":" in the declaration print("The world is dry!") dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs:#error 12, missing ":" in the function declaration print("People are less than or equal to dogs.") #error 8, missing " in the function declaration if people == dogs: #error 13, missing "==" in the function declaration print("People are dogs.")
true
b70e39bcc40473503c1a2cf169c3a7d28d552c92
Vladigors/pycharm_new
/package1/nums1.py
211
4.15625
4
range(10) list(range(1, 10)) for i in range(10): print(i, end= '') for i in range(3, 20): print(i, end= '') for i in range (5, 25, 3): print(i, end= '') for i in range(10, 20): print(i, end= '')
false
b7d01a00f0161216a6e5205b31638c9a8ac0a8ca
DavidM-wood/Year9DesignCS4-PythonDW
/CylinderVolCon.py
377
4.21875
4
import math print("This program calculates the volume of") print("a cylinder given radius and height") r = input("what is the radius: ") r = float(r) h = input("what is the height: ") h = float(h) v = math.pi*r*r*h v = round(v,3) print("Given") print(" radius = ",r," units") print(" height = ",h," units") print("The volume is: ",v," units cubed") print("END PROGRAM")
true
1a49be8a93de2ed7e8f6136933bcb194d62c168a
DavidM-wood/Year9DesignCS4-PythonDW
/LoopDemo.py
1,509
4.25
4
#A loop is a programjnf structure that can repeat a section of code. #A loop can run the same coede exactly over and over or #with domr yhought it can generate a patter #There are two borad catagories of loops #Conditional loops: These loop as long as a conditon is true #Counted Loops (for): These loop usikng a counter to keep teack of how many the loop has run # you can use any loop in any situation,but usually from a design #perspectie there is a better loop in terms of coding #If you know in advance how many times a loop should run a COUNTED LOOP \ #is usually the better choice. #If you don't know how many times a loop should run a CONDITIONAL LOOP #is usually the better choice print("**************************************************************************") #TAKING INPUTS word = "" #We have to declaire and inialize word so it fails the while loop #A while loop evaluates a condition when it is first reached.while #If the condition is true it enters the loop block while len(word) <6 or word.isalpha() == False: #Loop block word = input("Please input a word longer than 5 letters: ") if len(word) <6: print("Buddy, I said more than 5 letters ") if (word.isalpha() == False): print("Buddy I said a real word") #When we reach the bottom of the loop block we check the condtion #again. If it is true, we g back to the top of the block and run it again print(word+" is a seriosly long word!") #CAUTION: DO NOT USE WHILE LOOPS TO CONTROL INPUT WITH GUI PROGRAMS
true
42959799e73a040a42e2757b422b45313ff4c848
marcelo-py/Exercicios-Python
/exercicios-Python/desaf033.py
844
4.15625
4
#maior e menor numero v1 = int(input('digite um numero ')) v2 = int(input('digite o segundo numero ')) v3 = int(input('digite o terceiro numero ')) if v1<v2 and v1<v2: menor = v1 print('O menor é', v1) if v2<v1 and v2<v3: menor = v2 print('O menor é', v2) if v3<v1 and v3<v2: menor = v3 print('O menor é', v3) #verificando o maior... if v1>v2 and v1>v3: maior = v1 print('O maior é ',v1) if v2>v1 and v2>v3: maior = v2 print('O maior é ',v2) if v3>v1 and v3>v2: maior = v3 print('O maior é ',v3) """primeiro = int(input('Primeiro numero ')) segundo = int(input('Segundo numero ')) terceiro = int(input('Terceiro numero ')) numeros = [primeiro, segundo, terceiro] print('O maior numero digitado foi {}'.format(max(numeros))) print('O menor numero digitado foi {}'.format (min(numeros)))"""
false
9b7fa70f9b7c0cf967d63a5ea24afdaa38e5acdd
shach934/leetcode
/leet114.py
974
4.21875
4
114. Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if root is None: return None dummy = TreeNode(0) tail = dummy stack = [] while stack or root: while root: tail.left = None tail.right = root tail = tail.right stack.append(root.right) root = root.left root = stack.pop() root = dummy.right
true
5cfb176a07bdb5473c6317586573525306cba589
shach934/leetcode
/leet403.py
2,213
4.1875
4
403. Frog Jump A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. Note: The number of stones is ≥ 2 and is < 1,100. Each stone's position will be a non-negative integer < 231. The first stone's position is always 0. Example 1: [0,1,3,5,6,8,12,17] There are a total of 8 stones. The first stone at the 0th unit, second stone at the 1st unit, third stone at the 3rd unit, and so on... The last stone at the 17th unit. Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: [0,1,2,3,4,8,9,11] Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. 动态规划做的,也不算慢,超过了百分之五十的。可能dfs会更快一些吧。 class Solution(object): def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ stone = {} for idx, pos in enumerate(stones): stone[pos] = idx step = [set() for i in range(len(stones))] step[0].add(0) for i in range(len(stones)): for j in step[i]: if stones[i]+j+1 in stone: step[stone[stones[i]+j+1]].add(j+1) if j-1>0 and stones[i]+j-1 in stone: step[stone[stones[i]+j-1]].add(j-1) if stones[i]+j>0 and stones[i]+j in stone: step[stone[stones[i]+j]].add(j) return True if len(step[-1]) else False
true
65dc7d8c342a8da41493e7dfc1459e1d468359d6
Larry-Volz/python-data-structures
/17_mode/mode.py
1,038
4.21875
4
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. SEE TEACHER'S SOLUTION He uses a dictionary, {}.get(num, 0)+1 to ad them up then max()... convoluted but clever - worth seeing a different way to do it """ mode = 0 for ea in nums: if nums.count(ea) > nums.count(mode): mode = ea return mode print("1 = ",mode([1, 2, 1])) print("2 = ",mode([2, 2, 3, 3, 2])) #Teacher's solution (worth reviewing): # for num in nums: # counts[num] = counts.get(num, 0) + 1 #0 is default - adds one if none exist # # returns {2:3, 3:2} # # find the highest value (the most frequent number) # max_value = max(counts.values()) # # now we need to see at which index the highest value is at # for (num, freq) in counts.items(): # if freq == max_value: # return num
true
24f14855d4cc1565f6dc94c9318315b7ea3c25dc
biodataprog/code_templates
/Regexp/Motif_Match_Bsub.py
1,769
4.3125
4
#!/usr/bin/env python3 #Python code to demonstrate pattern matching # import the regular expression library import re # a random DNA sequence generator def read_DNA (file): DNA = "" fasta_pat = re.compile("^>") with open(file, 'r') as f: seenheader = 0 for line in f: if fasta_pat.search(line): if seenheader: return DNA print("Header matches",line); seenheader = 1 else: DNA += line DNA = re.sub("\s+","",DNA) return DNA # lets initialize a pattern we want to match # let's use the PRE motif which is a binding site for # a transcription factor # based on this paper: # EcoRI = "GAATTC" Bsu15I = "ATCGAT" Bsu36I = "CCT[ACGT]AGG" BsuRI = "GGCC" EcoRII = "CC[AT]GG" RestrictionEnzymes = [EcoRI, Bsu15I, Bsu36I, BsuRI, EcoRII] # Now let's search for this element in DNA sequence DNA = read_DNA("B_subtilis_str_168.fasta") print("Bsub DNA is", len(DNA), "bp long") for RE in RestrictionEnzymes: pattern = re.compile(RE) match = pattern.search(DNA) count = pattern.findall(DNA) print(RE,"matches", len(count), "sites") # while match: # print match.group(0), match.start(), match.end() # match = pattern.search(DNA,match.end()+1) print("//") DNA = read_DNA("Ecoli_K-12.fasta") print("Ecoli DNA is", len(DNA), "bp long") for RE in RestrictionEnzymes: pattern = re.compile(RE) match = pattern.search(DNA) count = pattern.findall(DNA) print(RE,"matches", len(count), "sites") # while match: # print match.group(0), match.start(), match.end() # match = pattern.search(DNA,match.end()+1) print("//")
false
843b0e4e5ae83c783df4ddb4518f56bd974a1ccf
abigailshchur/KidsNexus
/hangman_complete.py
2,609
4.125
4
import random # we need the random library to pick a random word from list # Function that converts a list to a string split up be delim # Ex) lst_to_str(["a","b","c"],"") returns "abc" # Ex) lst_to_str(["a","b","c"]," ") returns "a b c" # Ex) lst_to_str(["a","b","c"],",") returns "a,b,c" def lst_to_str(lst, delim): return delim.join(lst) # Function th def replace_with_input(lst_current_guess, user_input, chosen_word): for i in range(len(chosen_word)): if chosen_word[i] == user_input: lst_current_guess[i] = chosen_word[i] return lst_current_guess # Opening text file with 1000 words text_file = open("words.txt", "r") # Making a list of words from that file words = text_file.read().split('\n') # picking random index in list index = random.randint(0, len(words)-1) # picking word chosen_word = words[index] len_chosen_word = len(chosen_word) print("The chosen word has " + str(len_chosen_word) + " characters") # setting up difficulty of game num_guesses = 12 #starting game game_over = False guessed_letters = [] guessed_words = [] player_current_guess = ["?"]*len_chosen_word while (not game_over): print("********************** PLAYER TURN **********************") print("You have " + str(num_guesses) + " guesses left") print("Here are all the characters you guessed so far: " + lst_to_str(guessed_letters, ',')) print("Here are all the words you guessed so far: " + lst_to_str(guessed_words, ',')) print("Your current guess is: " + lst_to_str(player_current_guess, '')) valid_user_input = False while(not valid_user_input): user_input = raw_input("What is your guess?\n") if len(user_input) == 1: valid_user_input = True have_letter_guesses = True player_current_guess = replace_with_input(player_current_guess, user_input, chosen_word) guessed_letters.append(user_input) print(lst_to_str(player_current_guess, '')) elif len(user_input) == len_chosen_word: valid_user_input = True if user_input == chosen_word: player_current_guess = chosen_word.split("(?!^)") else: print("Incorrect Guess") guessed_words.append(user_input) else: print("Invalid input (either 0 characters or too long)") # Handle game over details num_guesses = num_guesses - 1 if (sum([i=='?' for i in player_current_guess]) == 0): print("*********************** GAME OVER ***********************") print("You did it!!! the word was " + chosen_word) game_over = True if num_guesses == 0 and not game_over: print("*********************** GAME OVER ***********************") print("You lost :( the word was " + chosen_word) game_over = True
true
6b45fe344565cb148d4b0baa4b3ed2b6fe75d583
heasleykr/Algorithm-Challenges
/recursion.py
843
4.25
4
# Factorials using recursion def fact(n): # base. If n=0, then n! = 1 if n == 0: return 1 # else, calculate all the way until through return n*fact(n-1) # one liner # return 1 if not n else n*fact(n-1) def fact_loop(n): # base case return n if 0 # if n == 0: # return n # else: sum_ = n # else, calculate all the way until through while n != 1: n = n-1 sum_ *= n return sum_ #Fibonacci sequence. Sum of previous two numbers. def fib(n): #base case if n < 2: return n #Calculate Fn return fib(n-1) + fib(n-2) #homework TODO: How to cut this in half? store previous calculations #homework TODO: Turn fibonaci into iterative fn. if __name__ == '__main__': # print(fact(6)) print(fact_loop(6))
true
abc9a6b5424c0ef2e574c86f995ef66061746af7
amarbecaj/MidtermExample
/zadatak 3.py
1,434
4.15625
4
""" =================== TASK 3 ==================== * Name: Negative and Non-Negative Elements * * Write a script that will populate a list with as * many elements as user defines. For taken number * of elements the script should take the input from * user for each element. You should expect that * user will always provide integer numbers. At the * end, the script should print how many negative * and non-negative numbers there were present in * the list. * * Note: Please describe in details possible cases * in which your solution might not work. =================================================== """ n = int(input("Koliko brojeva unosite? "))# da bi znali kolika ce biti duzina liste(mora biti cijeli broj) lista = [] # na pocetku je data prazna lista nenegativni = negativni = 0 for i in range(n): # koliko lista ima clanova, toliko cemo puta pitati korisnika da unese novi clan liste novi_broj = int(input("Unesite "+ str(i+1)+ ".broj: ")) # stringovi mogu da se spoje sabiranjem lista.append(novi_broj) # svaki od unijetih brojeva dodajemo u listu if novi_broj < 0: # ako je unijeti broj manji od nule, ukupan broj negativnih se uveca za 1 negativni += 1 else: # u suprotnom se uveca broj nenegativnih za 1 nenegativni += 1 print("Vasa lista: ", str(lista)) print("Nenegativnih brojeva u listi ima: ", nenegativni) print("Negativnih brojeva u listi ima: ", negativni)
false
f374c8b57722d4677cbf9cc7cde251df8896b33d
sreerajch657/internship
/practise questions/odd index remove.py
287
4.28125
4
#Python Program to Remove the Characters of Odd Index Values in a String str_string=input("enter a string : ") str_string2="" length=int(len(str_string)) for i in range(length) : if i % 2 == 0 : str_string2=str_string2+str_string[i] print(str_string2)
true
a2807475320a5bb3849a943dbe5dd9f9331254ed
sreerajch657/internship
/practise questions/largest number among list.py
259
4.34375
4
#Python Program to Find the Largest Number in a List y=[] n=int(input("enter the limit of list : ")) for i in range(0,n) : x=int(input("enter the element to list : ")) y.append(x) y.sort() print("the largest number among list is : %d "%(y[-1]))
true
fdd72acf5565bdee962fed5471249461843d01ab
Neil-C1119/Practicepython.org-exercises
/practicePython9.py
1,511
4.28125
4
# This program is a guessing game that you can exit at anytime, and it will # keep track of the amount of tries it takes for the user to guess the number # Import the random module import random # Define the function that returns a random number def random_num(): return random.randint(1, 10) # Self explanatory print("-----The Random Number Game!-----") print("\nType 'exit' at any time to quit.") # Set the random number number = random_num() # Prepare the userGuess and tries variables userGuess = 0 tries = 0 # A loop that runs while the user's guess isn't the number AND their answer isn't exit while userGuess != number and userGuess != "exit": # Get the user's guess userGuess = input("Guess my number between 1 and 9. . . :") # If the user types exit end the loop if userGuess.lower() == "exit": break # If the guess is too high. . . if int(userGuess) > number: print("Try a little lower") # Add a try tries += 1 # If the guess is too low. . . elif int(userGuess) < number: print("It's higher than that") # Add a try tries += 1 # If the guess is correct. . . elif int(userGuess) == number: # Tell the user it is correct and show them how many tries it took print("That's right! It took you", tries,"tries!\n\n") # Reset the random number number = random_num() # Reset the user's tries tries = 0
true
2c67dd011e851c1e79a23004908cf69bc2c34607
ifegunni/Cracking-the-coding-interview
/arrays1.7.py
1,923
4.3125
4
# Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 # bytes, write a method to rotate the image by 90 degrees. Can you do this in place? #This solution is my O(n2) solution def rotate(matrix): newMatrix = [row[:] for row in matrix] #we have to copy the matrix so we don't edit the original a = len(matrix) for i in range(a): #traverse through each row and column for j in range(a): newMatrix[i][j] = matrix[a-j-1][i] # swap clockwise 90 degrees return newMatrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) # Rotating a matrix 180 degrees clockwise from copy import deepcopy # using deepcopy to copy matrix into new matrix def rotate(matrix): oneEightyMatrix = deepcopy(matrix) n = len(matrix) for i in range(n): # algorithm for j in range(n): oneEightyMatrix[i][j] = matrix[n-i-1][n-j-1] return oneEightyMatrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) #In place solution with O(n2) time complexity and O(1) space complexity def rotate(matrix): n = len(matrix) matrix.reverse() for i in range(n): for j in range(n): matrix[i][j] = matrix[j][i] return matrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix)) #In place solution with O(n2) time complexity and O(1) space complexity def rotate(matrix): n = len(matrix) matrix.reverse() for i in range(n): for j in range(i): #only change matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # also changed return matrix if __name__ == '__main__': matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix) print(rotate(matrix))
true
238ac35d263a55d451dfd2b0f3fb1cfe4d12363d
ifegunni/Cracking-the-coding-interview
/arrays1.6.py
2,910
4.25
4
# String Compression: Implement a method to perform basic string compression using the counts # of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the # "compressed" string would not become smaller than the original string, your method should return # the original string.You can assume the string has only uppercase and lowercase letters (a - z). # this solution is O(n2) because we are concatinating a new string and that result to an O(n2) def stringCompression(string): res = "" # create an empty string count = 0 # initialize count for each element in the string to 0 prev = string[0] # to keep record of previous character in the string for char in string: if char == prev: #if the current element in a string equal to the previous element count+=1 # count the occurrence else: res += prev + str(count) #if not equal start adding the string to the new string and prev = char #set previous to current character and take not of occurence count = 1 #by initializing count to 1 res += prev + str(countConsecutive) #this last bit is called the edge case and it is important to capture the last bit of the string. if len(res) < len(string): return(res) else: return(string) if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x)) #A better solution is to use a list rather that creating a new list Making the new solution O(n) def stringCompression(string): res = [] #using list in place of creating a new string is the only difference and changes time complexity to O(n) countConsecutive = 0 prev = string[0] for char in string: if char == prev: countConsecutive += 1 else: res += prev + str(countConsecutive) prev = char countConsecutive = 1 res += prev + str(countConsecutive) res = ''.join(res) if len(res) < len(string): return res else: return string if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x)) # A different approach, comparing the current character with the next element in the string. def stringCompression(string): res = [] count = 1 for i in range(len(string)-1): # len(string) - 1: because we are comparing the value with the next value. if the we compare the last value with the next value(no value) then we get an error if string[i] == string[i+1]: count += 1 else: res += string[i] + str(count) count = 1 res += string[i] + str(count) # return(res) res = "".join(res) if len(res) < len(string): return res else: return string if __name__ == '__main__': x = "aabcccccaaa" print(stringCompression(x))
true
a571e0e9e507b15d778cf7c7210864c47422c138
kehsihba19/MINI-PYTHON-Beginner-Project
/Hangman.py
1,190
4.28125
4
import random def word_update(word, letters_guessed): masked_word = "" for letter in word: if letter in letters_guessed: masked_word += letter else: masked_word += "-" print( "The word:", masked_word) # List of words for the computer to pick from words = ("basketball", "football", "hockey", "lacrosse", "baseball") # Word to be guessed; picked at random word = random.choice(words) print ("="*32) print (" Guess the sport!") print ("You get to guess five letters.") print ("There are %s letters in the word." % (len(word))) print ("="*32) guesses = 5 letters_guessed = [] while guesses != 0: # make the letter lower case with .lower() letter = input("Enter a letter: ").lower() if letter in letters_guessed: print("You already guessed that letter.") else: guesses = guesses - 1 print("You have %d guesses left." % (guesses)) letters_guessed.append(letter) word_update(word, letters_guessed) # again, make input lower case guess = input("Guess the word: ").lower() if guess == word: print ("Congratulations, %s is the word!" % (guess)) else: print( "Nope. The word is %s." % (word))
true
650e6537431e2e52e257f8ba04ee285f9ed06405
UmVitor/python_int
/ex016.py
238
4.15625
4
#Crie um programa que leia um numero real #Qualquer pelo teclado e mostre na tela #a sua porção inteira import math num = float(input('Digite um numero: ')) print('O numero {} tem a parte inteira {}'.format(num,math.floor(num)))
false
8ea2aa3c42278988534f88c66b818b8c25a8ba82
UmVitor/python_int
/ex100.py
758
4.1875
4
#Faça um programa que tenha uma lista chamada numeros e duas funções #chamadas sorteia() e somaPar(). A primeira função vai sortear 5 numeros #e coloca-los dentro de uma lista e a segunda função vai mostrar a soma entre #todos os valores pares sorteados pela função anterior from random import randint lista = list() soma = 0 def sorteia(): print('Sorteando 5 valores ', end=' ') for c in range(0,5): lista.append(randint(0,10)) print(lista[c] , end=' ') print() def somaPar(): soma = 0 print(f'Somando os valores pares de {lista}, temos ', end=' ') for c in range(0,len(lista)): if((lista[c]%2) == 0): soma += lista[c] print(soma) sorteia() somaPar()
false
5137ae95f22550277269ebcaa1d5977f702cf840
UmVitor/python_int
/ex072.py
594
4.3125
4
#Crie um programa que tenha uma tupla totalmente preenchida com uma #contagem por extenso, de zero ate vinte. #Seu programa deverá ler um numero pelo teclado(entre 0 e 20) e mostrálo #por extenso extenso = ('zero', 'um','dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','catorze','quinze','dezesseis','dezessete','dezoito','dezenove','vinte') n1 = int(input('Digite um número entre 0 e 20: ')) while(n1 > 20 or n1 < 0): n1 = int(input('Tente novamente!!\nDigite um numero entre 0 e 20: ')) print(f'você digitou o número {extenso[n1]}!!')
false
0071380236913bd4c168c488e35e4ef229d5d457
UmVitor/python_int
/ex028.py
438
4.125
4
#escreva um programa que faça o computador 'pensar' em um numero inteiro #entre 0 e 5 e peça para o usuario tentar descobrir qual foi o número escolhido #pelo computador. import random from time import sleep n1 = int(input('Digite um numero: ')) n2 = random.randint(1,5) print ('Pensando...') sleep(2) print('O numero escolhido foi {}'.format(n2)) if (n2 == n1): print('Você acertou') else: print('Você errou')
false
9afd9a445eb308c45d00b446d46b9231306217b5
UmVitor/python_int
/ex101.py
641
4.125
4
#Crie um programa que tenha uma função chamada voto() que vai receber como #parametro o ano de nascimento de uma pessoa, retornando um valor literal #indicando se uma pessoa tem voto Negado, opcional ou obrigatorio from datetime import date def voto(i): n1 = date.today().year idade = n1 - i if(idade < 16): return f'Você tem: {idade} anos.\nVOTO NEGADO!!' elif((16 < idade < 18) or (idade>60)): return f'Você tem: {idade} anos.\nVOTO FACULTATIVO!!' else: return f'Você tem: {idade} anos.\nVOTO OBRIGATORIO!!!' a = int(input('Data de nascimento: ')) print(voto(a))
false
236afd3162a72f9c1ee32e4b9f006d77ca2ca4d3
UmVitor/python_int
/ex026.py
577
4.1875
4
#Faca um programa que leia uma frase pelo teclado e mostre #Quantas vezes aparece a letra 'a' #em que posição ela aparece a primeira vez #em que posição ela aparece a ultima vez frase = str(input('Digite uma frase: ')).lower().strip() print(frase) print('Nesta frase a letra a aparece {} vezes!'.format(frase.count('a'))) print('A letra A aparece {} vezes!'.format(frase.count('a'))) print('A primeira ocorrencia dessa letra é na {}° posição'.format(frase.find('a')+1)) print('A ultima ocorrencia dessa letra é na {}° posição'.format(frase.rfind('a')+1))
false
bdd5560416f0615534c7be04edac65b988c804a0
liviaandressa/exercicios-curso-em-video
/Testes_aulas_guanabara/Desafio_jogo_da_adivinhação.py
1,123
4.5
4
'''escreva um programa que faça o computador pensar em um número inteiro entre 0 e 5 e peça para o usuáro tentar descobrir qua foi o número escolhido pelo computador. o programa deverá escrever na tela se o usuário venceu ou perdeu''' ''' 1° solução import random print('Vou pensar em um número entre 0 e 5. Tente adivinhar') numero = int(input('Em que número que pensei? ')) lista = [0, 1, 2, 3, 4, 5] sortear = random.choice(lista) if numero == sortear: print("Parabéns! {} foi o número que eu pensei.".format(sortear)) else: print('Você errou! o número que eu pensei foi o número {}'.format(sortear))''' #Segunda solução from random import randint from time import sleep def linhas(): print('***' * 20) computador = randint(0, 5) linhas() print('Vou pensar entre um número entre 0 e 5. Tente adivinhar...') linhas() jogador = int(input("Em que número eu pensei? ")) print('processando...') sleep(3) if jogador == computador: print('PARABÉNS! Você conseguiu me vencer!') else: print('GANHEI! Eu pensei no número {} e não no número {}'.format(computador, jogador))
false
6c00f55d6f5c28b24afd48cadf14bfee4add3c26
r121196/Python_exercise
/caluclator/simple calculator.py
668
4.1875
4
operation = input(''' type the required maths operation: + for addition - for substraction * for multiplication / for division ''') n1 = int(input('Enter the first number: ')) n2 = int(input('Enter the second number: ')) if operation == '+': print ('{} + {} = '. format(n1, n2)) print (n1 + n2) elif operation == '-': print ('{} - {} = '. format(n1 , n2)) print (n1 - n2) elif operation == '*': print ('{} * {} = '.format (n1, n2)) print (n1 * n2) elif operation == '/': print ('{} /{} = '. format(n1, n2)) print (n1 / n2) else : print (" The operation etered is invalid. Restart the programme.")
true
f32ad9099e69b7a8a70715e988aa2dde959778bf
lengau/dailyprogrammer
/233/intermediate.py
2,816
4.125
4
#!/usr/bin/env python3 # Daily Programmer #233, Intermediate: Conway's Game of Life # https://redd.it/3m2vvk from itertools import product import random import sys import time from typing import List class Cell(object): """A single cell for use in cellular automata.""" def __init__(self, state: str): self.state = state self.neighbours = () self.next_state = self.state def calculate_step(self): if not self.neighbours: raise ReferenceError('No neighbours defined') alive_neighbours = 0 for neighbour in self.neighbours: if neighbour.state and not neighbour.state.isspace(): alive_neighbours += 1 if not self.state or self.state.isspace(): if alive_neighbours == 3: self.next_state = random.choice([ n for n in self.neighbours if not n.state.isspace()]).state else: self.next_state = ' ' return if alive_neighbours not in (2, 3): self.next_state = ' ' def take_step(self): self.state = self.next_state def __str__(self) -> str: return self.state or ' ' def main(): with open(sys.argv[1]) as file: lines = file.read().splitlines() height = len(lines) width = max(len(line) for line in lines) def make_line(width: int, line: str) -> List[Cell]: """Make a line of cells.""" out_line = [] for cell_state in line: out_line.append(Cell(cell_state)) if len(out_line) < width: for _ in range(width - len(out_line)): out_line.append(Cell('')) return out_line grid = [] for line in lines: grid.append(make_line(width, line)) for y, x in product(range(height), range(width)): neighbour_coords = [] for a, b in product((-1, 0, 1), repeat=2): neighbour_coords.append((y+a, x+b)) neighbour_coords.pop(4) # The coordinates of the current cell. neighbours = [] for location in neighbour_coords: if -1 not in location and location[0] != height and location[1] != width: neighbours.append(grid[location[0]][location[1]]) grid[y][x].neighbours = neighbours for i in range(20): print("\033c"); print('Step %d:' % i) for line in grid: print(''.join(cell.state for cell in line)) for line in grid: for cell in line: cell.calculate_step() for line in grid: for cell in line: cell.take_step() if ''.join(''.join(cell.state for cell in line) for line in grid).isspace(): break time.sleep(0.75) if __name__ == '__main__': main()
true
2f395c7039ae26aa8c75b03f3727cd0c9235bcf5
Pavan-443/Python-Crash-course-Practice-Files
/chapter 8 Functions/useralbums_8-8.py
570
4.21875
4
def make_album(artist_name, title, noof_songs=None): """returns info about music album in a dictionary""" album = {} album['artist name'] = artist_name.title() album['song title'] = title.title() if noof_songs: album['no of songs'] = noof_songs return album while True: print('\ntype q to quit at any time') name = input('please enter the Artist name: ') if name.lower() == 'q': break title = input('please enter title of the song: ') if title.lower() == 'q': break print(make_album(name, title))
true
f390c30e06bdacc7e29d38fc519c95fb478bd924
zemery02/ATBS_notes
/Lesson_Code/hello.py
631
4.125
4
#! python3 # This program says hello and asks for my name print('Hello World!') print('What is your name?') #ask for their name myName = input() print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') #ask for their age myAge = input() print('You will be ' + str(int(myAge) + 1) + ' in a year') if myAge == '15': print('You\'re going to be driving in no time!') elif myAge == '17': print('You\'re going to be legal next year!') elif myAge == '20': print('You can drink next year! Bottoms up!') else: print('Time sure does fly doesn\'t it?')
true
4f8383ae5d0439bb9972f2852623552e65a06527
vik13-kr/telyport-submission
/api/build_api/Q-2(Reverse character).py
494
4.3125
4
'''Reverse characters in words in a sentence''' def reverse_character(p_str): rev_list = [i[::-1] for i in p_str] #reversed characters of each words in the array rev_string = " ".join(map(str,rev_list)) #coverted array back to string return rev_string n_str = 'My name is Vikash Kumar' rev_str = reverse_character(n_str.split(' ')) # passing string as an list print('Original Character : {}'.format(n_str)) print('Reversed String : {}'.format(rev_str))
true
ac9e55e127c2972a737cdbdea7db49847381a993
DonLiangGit/Elements-of-Programming
/data_structure/Linkedlist_Node.py
1,161
4.1875
4
# define a Node class for linked list # __name__ & __main__ # http://stackoverflow.com/questions/419163/what-does-if-name-main-do # http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do class Node: def __init__ (self,initdata): self.data = initdata self.next = None def getData (self): return self.data def getNext (self): return self.next def addData(self, addedData): self.data = addedData def addNext(self, nextNode): self.next = nextNode # define an unordered list class UnorderedList: def __init__(self): self.head = None self.last = None def isEmpty(self): print("The List is empty.") return self.head == None def add(self,item): temp = Node(item) if self.head == None: temp.addNext(self.head) self.head = temp self.last = temp print("successful add.") else: self.last.next = temp self.last = temp print("add nodes") def size(self): current = self.head count = 0 print(count) while current != None: count += 1 current.getNext() return count mylist = UnorderedList() mylist.isEmpty() mylist.add(12) mylist.add(13) mylist.add(14) print(mylist.size())
true
12d289806c1323503a8a6040bc0a14f8d440711f
samuelbennett30/FacePrepChallenges
/Lists/Remove Duplicates.py
801
4.40625
4
''' Remove the Duplicate The program takes a lists and removes the duplicate items from the list. Problem Solution: Take the number of elements in the list and store it in a variable. Accept the values into the list using a for loop and insert them into the list. Use a for loop to traverse through the elements of the list. Use an if statement to check if the element is already there in the list and if it is not there, append it to another list. Print the non-duplicate items of the list. Exit. Sample Input: 5 10 10 20 20 20 Sample Output: Non-duplicate items: [10, 20] ''' arr=[] num=int(input()) for x in range(0,num): numbers=int(input()) arr.append(numbers) b=[] unique=[] for x in arr: if x not in b: unique.append(x) b.append(x) print("Non-duplicate items:") print(unique)
true
390aef3387103d3c30e03d19ff5dcf9985abee3b
tushar8871/python
/dataStructure/primeNumber.py
1,689
4.125
4
#generate prime number in range 0-1000 and store it into 2D Array #method to create prime number def primeNumber(initial,end): #create a list to store prime number in 0-100,100-200 and so-on resultList=[] try: #initialize countt because when we generate prime number between 0-100 then we have to initialize #initial from 100 not to 1 countt=1 #loop executed until initial is less than end while initial<end: #initialize temp to stop execution of loop upto 100,200 ,etc to create seperate list temp=100*countt list1=[] #execute loop utp temp and generate number for k in range(1,temp): count=0 for j in range(1,k+1): #check K mod j =0 then increment count #count is incremneted because prime number only divided by itself or one if k%j==0: count+=1 if count==2: #when we add number from 2nd execution already stored number will not be stored if k > initial: list1.append(k) #append list of prime no into main list resultList.append(list1) countt+=1 initial=temp except Exception: print("Modulo divide by error") return resultList #get range from user to find prime number initial=int(input("Enter initial vlaue of range : ")) end=int(input("Enter end vlaue of range : ")) #method call and store into listt listt=primeNumber(initial,end) #print list of prime number print("Prime Number in 2D array are : \n " ,listt)
true
d43783ac3758262be6e636db5da6a2725a1c218a
tushar8871/python
/functioalProgram/stringPermutation.py
1,002
4.28125
4
#Generate permutation of string #function to swap element of string def swap(tempList,start,count): #swapping element in list temp=tempList[start] tempList[start]=tempList[count] tempList[count]=temp #return list of string return tempList #generate permutation of string def strPermutation(Str,start,end): count=0 #if start and equal to length of string then print string if (start==end-1): print(Str) else: for count in range(start,end): #Put String in list to generate permutation tempList=list(Str) #call swap function to swap element of string swap(tempList,start,count) #recursive call until found all string strPermutation("".join(tempList),start+1,end) swap(tempList,start,count) #Get input from user Str=input("Enter string : ") #find length of string strLength=len(Str) #call function to generate permutation of string strPermutation(Str,0,strLength)
true
8973a64b33c9587d2b2f5dd4d1aaffcd54d10e17
bezdomniy/unsw
/COMP9021/Assignment_1/factorial_base.py
775
4.25
4
import sys ## Prompts the user to input a number and checks if it is valid. try: input_integer = int(input('Input a nonnegative integer: ')) if input_integer < 0: raise ValueException except: print('Incorrect input, giving up...') sys.exit() integer=input_integer ## Prints factorial base of 0 as a special case. if integer == 0: print('Decimal 0 reads as 0 in factorial base.') sys.exit() count=2 result=[] ## Generates a list of digits in factorial base. while integer > 0: result.append(str(integer % count)) integer = integer // count count += 1 ## Prints the original input and the reversed generates list for final answer. print('Decimal {} reads as {} in factorial base.'.format(input_integer,''.join(result[::-1])))
true
eb945c57d13c1364f773dd2bf64c3afcacf865ea
gtanubrata/Small-Fun
/return_day.py
1,129
4.125
4
''' return_day(1) # "Sunday" return_day(2) # "Monday" return_day(3) # "Tuesday" return_day(4) # "Wednesday" return_day(5) # "Thursday" return_day(6) # "Friday" return_day(7) # "Saturday" return_day(41) # None ''' days = {1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "Saturday"} def return_day(num): if num in days.keys(): return days[num] None print(return_day(2)) # # LIST VERSION ----------------------------------------------------------------------------------- # def return_day(num): # days = ["Sunday","Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday"] # # Check to see if num valid # if num > 0 and num <= len(days): # # use num - 1 because lists start at 0 # return days[num-1] # return None # # ADVANCED VERSION ------------------------------------------------------------------------------- # def return_day(num): # try: # return ["Sunday","Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday"][num-1] # except IndexError as e: # return None
true
f306b95eff6714bebe60f7b9a3332ec9f1399853
jackh423/python
/CIS41A/CIS41A_UNITC_TAKEHOME_ASSIGNMENT_1.py
2,654
4.25
4
""" Name: Srinivas Jakkula CIS 41A Fall 2018 Unit C take-home assignment """ # First Script – Working with Lists # All print output should include descriptions as shown in the example output below. # Create an empty list called list1 # Populate list1 with the values 1,3,5 # Create list2 and populate it with the values 1,2,3,4 # Create list3 by using + (a plus sign) to combine list1 and list2. Print list3. # Use sequence operator in to test list3 to see if it contains a 3, print True/False result (do with one line of code). # Count the number of 3s in list3, print the result. # Determine the index of the first 3 in list3, print the result. # Pop this first 3 and assign it to a variable called first3, print first3. # Create list4, populate it with list3's sorted values, using the sorted built-in function. # Print list3 and list4. # Slice list3 to obtain a list of the values 1,2,3 from the middle of list3, print the result. # Determine the length of list3, print the result. # Determine the max value of list3, print the result. # Sort list3 (use the list sort method), print list3. # Create list5, a list of lists, using list1 and list2 as elements of list5, print list5. # Print the value 4 contained within list5. list1 = [] for a in 1, 3, 5: list1.append(a) list2 = [1, 2, 3, 4] list3 = list1 + list2 print(f"list3 is: {list3}") print(f"list3 contains a 3: {3 in list3}") print(f"list3 contains {list3.count(3)} 3s") print(f"The index of the first 3 contained in list3 is {list3.index(3)}") first3 = list3.pop(list3.index(3)) print(f"first3 = {first3}") list4 = sorted(list3) print(f"list3 is now: {list3}") print(f"list4 is: {list4}") print(f"Slice of list3 is: {list3[2:5]}") print(f"Length of list3 is {len(list3)}") print(f"The max value of list3 is {max(list3)}") list3.sort() print(f"Sorted list3 is: {list3}") list5 = [list1, list2] print(f"list5 is{list5}") print(f"Value 4 from list5: {list5[1][3]}") # 2 e: Examine the results. Can you see how they were arrived at? # 2 c answer is arrived by performing AND on every bit of 2 numbers. # 2 d answer is arrived by performing OR on every bit of 2 numbers. ''' Execution results: /usr/bin/python3 /Users/jakkus/PycharmProjects/CIS41A/CIS41A_UNITC_TAKEHOME_ASSIGNMENT_1.py list3 is: [1, 3, 5, 1, 2, 3, 4] list3 contains a 3: True list3 contains 2 3s The index of the first 3 contained in list3 is 1 first3 = 3 list3 is now: [1, 5, 1, 2, 3, 4] list4 is: [1, 1, 2, 3, 4, 5] Slice of list3 is: [1, 2, 3] Length of list3 is 6 The max value of list3 is 5 Sorted list3 is: [1, 1, 2, 3, 4, 5] list5 is[[1, 3, 5], [1, 2, 3, 4]] Value 4 from list5: 4 Process finished with exit code 0 '''
true
af8dd324cd12deb2647eb541822000c9b377c99b
xurten/python-training
/tips/tip_54_use_lock_for_threads.py
1,317
4.125
4
# Tip 54 use lock for threads from threading import Thread, Lock HOW_MANY = 10 ** 5 class Counter: def __init__(self): self.count = 0 def increment(self, offset): self.count += offset def worker(index, counter): for _ in range(HOW_MANY): counter.increment(1) def thread_example(): how_many = 10 ** 5 counter = Counter() threads = [] for i in range(5): thread = Thread(target=worker, args=(i, counter)) threads.append(thread) thread.start() for thread in threads: thread.join() expected = how_many * 5 found = counter.count print(f'found= {found}, expected = {expected}') def thread_with_lock_example(): class LockingCounter: def __init__(self): self.lock = Lock() self.count = 0 def increment(self, offset): with self.lock: self.count += offset counter = LockingCounter() threads = [] for i in range(5): thread = Thread(target=worker, args=(i, counter)) threads.append(thread) thread.start() for thread in threads: thread.join() expected = HOW_MANY * 5 found = counter.count print(f'found= {found}, expected = {expected}') thread_example() thread_with_lock_example()
true
a7880e35154bb5b0da2498d2907b60a3ecc3f6bc
rohitkrishna094/Data-Structures-And-Algorithms_old
/Problems/Arrays/ReversingArray.py
851
4.4375
4
''' This is a program to reverse an array or list ''' def reverse(lst): return lst.reverse() # using built in lib functions l = list([1, 2, 3, 4]) r = list(reversed(l)) print(l, r) # lst[::-1] # another way to reverse using slicing # without using built in functions def reverse_mine(lst): endIndex = len(lst) - 1 for i in range(0, len(lst) // 2): temp = lst[i] lst[i] = lst[endIndex] lst[endIndex] = temp endIndex -= 1 l = list([1, 2, 3, 4, 5]) print(l, end=' ') reverse_mine(l) print(l) # a more refined approach found online def reverseAnArray(myArray, start, end): while(start < end): myArray[start], myArray[end - 1] = myArray[end - 1], myArray[start] start += 1 end -= 1 l = list([1, 2, 3, 4, 5, 6]) print(l, end=' ') reverseAnArray(l, 0, len(l)) print(l)
false
5cdb5e79bcf34192624b2ff88d0a585d60406636
saddzoe/insurance-calculator
/README.py
1,348
4.375
4
# insurance-calculator # This is a mini project from codecademy print(middle_element([5, 2, -10, -4, 4, 5])) names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"] insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0] # Add your code here names.append("Priscilla") insurance_costs.append(8320.0) medical_records = list(zip(insurance_costs, names)) print(medical_records) num_medical_records = len(medical_records) print(f"There are {num_medical_records} medical records.") first_medical_record = medical_records[0] print(f"Here is the first medical record: {first_medical_record}.") medical_records.sort() print(f"Here are the medical records sorted by insurance cost: {medical_records}.") cheapest_three = medical_records[:3] print(f"Here are the three cheapest insurance costs in our medical records: {cheapest_three}.") priciest_three = medical_records[-3:] print(f"Here are the most expensive insurance costs in our medical records: {priciest_three}.") occurrences_paul = names.count("Paul") print(f"There are {occurrences_paul} individuals with the name Paul in our medical records.") names_alphabetical_order = list(zip(sorted(names))) print(names_alphabetical_order) middle_five_records = medical_records[3:8] print(middle_five_records)
false
28f778bd069323b1883006a8c69aa9c8864242e1
pengxingyun/learnPython
/basePython/listAndTuple.py
1,216
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # list 有序集合类型 相当于数组Array names = ['aaa', 'bbb', 'ccc'] print(names) # ['aaa', 'bbb', 'ccc'] # len 获取list元素个数 print(len(names)) # 索引访问list元素 print(names[0]) # 第一个 print(names[len(names) - 1]) # 最后一个 print(names[-1]) # 最后一个 print(names[-2]) # 倒数第二个 # 追加元素到末尾 names.append('ddd') print(names) # ['aaa', 'bbb', 'ccc', 'ddd'] # 插入元素到指定位置 names.insert(1, 'insert1') print(names) # ['aaa', 'insert1', 'bbb', 'ccc', 'ddd'] # 删除list指定位置的元素 参数缺省为删除最后一位 names.pop(); # 删除最后一位 names.pop(1); # 删除第二位元素 print(names); # ['aaa', 'bbb', 'ccc'] # 修改元素 直接赋值给指定元素 names[1] = 'bbb' print(names) # ['aaa', 'bbb', 'ccc'] # list里面的数据类型可以不同 L = ['aaa', 1, True] # list里面也可以包含list s = ['aaa', ['bb', 'cc'], True] # 元组: tuple tuple一旦初始化不能修改 classmates = ('aaa', 'bbb', 'ccc') # 不可修改 # 获取元素 classmates[0] print(classmates[0]) # 定义只有一个元素的tuple时 需要加一个,消除歧义 t = (1,)
false
ff37f855eacfc27e1a7b1cd5247facac93f4b3c8
jack-evan/python
/tuples.py
239
4.21875
4
#this is a tuple someval = ("one","two",345,45.5,"summer") #print tuple print someval #prints tuple print someval[0] #prints first element of the tuple print someval[2:] #prints third element and on print someval * 2 #prints tuple twice
true
15498baa6391c1f3976f9ac752e66028ae67c632
jann1sz/projects
/school projects/python/deep copy of 2d list.py
1,215
4.25
4
def deep_copy(some_2d_list): #new_copy list is the list that holds the copy of some_2d_list new_copy = [] #i will reference the lists within some_2d_list, and j will reference the #items within each list. i = 0 j = 0 #loop that creates a deep copy of some 2d list for i in range(len(some_2d_list)): #bracket is an empty list that will append each item in the lists of #some_2d_list. #once all of the numbers in the first list are appended to bracket and #bracket is appended to the new copy list, the bracket list becomes #empty when it moves to the next list within some_2d_list bracket = [] for j in range(len(some_2d_list[i])): #value calls the first list in some 2d list #single_var calls the first item in the first list value = some_2d_list[i] single_var = value[j] #each item in the list is appended to the bracket list, which will #then be appened to the new_copy list bracket.append(single_var) new_copy.append(bracket) return new_copy deep_copy([[1,2],[3,4]])
true
cd6d6f7b6b9b4e5e7fc39d1fb56c0995147d33cc
mskaru/LearnPythonHardWay
/ex15.py
791
4.3125
4
# -*- coding: utf-8 -*- from sys import argv # script = py file name that I want to run # filename = the txt or word or whichever other file type # i want to read the information from script, filename = argv # command that calls the content of the file as txt txt = open(filename) print "Here's your file %r:" % filename # commands to read the txt print txt.read() # alternative way to get the same result print "Type the filename again:" # let's you input the file name and defines that as file_again file_again = raw_input("Write here: ") # command that calls the content of the file as txt txt_again = open(file_again) # commands to read the txt print txt_again.read() # the only difference between the two is writing the file name # in the terminal directly or asking for an input
true
87e1314624ce2cfd7672d3f8781b94135aca3796
rumbuhs/Homeworks
/HW6/hw6_t2.py
1,046
4.4375
4
from math import pi from math import sqrt def calculator(shape): """ This funktion will find the square of a rectangle, triangle or circle. depending on the user's choice. Input: name of shape Otput: the square of the shape """ shape = shape.upper() if shape == "RECTANGLE": a = int(input("Please, enter rectangle's length: ")) b = int(input("Please, enter rectangle's breadth: ")) print ((a*b), ' is a rectangle square') elif shape == 'TRIANGLE': c = int(input("Please, enter triangle's height length: ")) d = int(input("Please, enter triangle's breadth length: ")) print ((0.5*d*c), 'is a triangle square') elif shape == 'CIRCLE': r = int(input("Please, enter circle's radius length: ")) print((sqrt(r)*pi), 'is a circle square') else: print("Sorry! Chose betwen rectangle, triangle or circle") while True: shape = input('Please, enter the name of shape, you want to find a square: ', ) calculator(shape)
true
42959f7f25f93f11e5edf0f200d0f74b2dcf724d
Hunt-j/python
/PP02.py
546
4.15625
4
num = int(input("Pick a number:")) check = int(input("Pick a second number:")) if (num % 2 == 0): print("The number you've chosen is even") else: print("The number you've chosen in odd") if (num % 4 ==0): print("The number you've chose is divisible by 4") else: print("The number you've choses is not divisible by 4") if (num % check ==0): print("The first number you've chose is divisible by the 2nd number you've chosen") else: print("The first number you've chose is not divisible by the 2nd number you've chosen")
true
529662305609ad9c36fb41a6466c7c90fe4590e8
FabioZTessitore/laboratorio
/esercizi/liste/reverse.py
353
4.4375
4
# reverse.py # Riscrive una stringa al contrario print('Reverse the string\n') text = input('Enter the message: ') # crea una lista dalla stringa `text` # quindi inverte l'ordine delle lettere # quindi unisce le lettere in una nuova stringa letters = [letter for letter in text] letters.reverse() textReversed = ''.join(letters) print(textReversed)
false
bd320410d6462d80f43620755a40495baa53bc0b
sshridhar1965/subhash-chand-au16
/FactorialW3D1.py
201
4.34375
4
# Factorial of a number num = int(input("Please Enter a number whose factorial you want")) product=1 while (num>=1): product = num*product num = num-1 print("The Factorial is ",product)
true
77d83b8729fe087a1a38ced864ac363ff53c4165
jeffreyc86/python-practice
/sequenceoperators.py
614
4.21875
4
string1 = "he's " string2 = "probably " string3 = "rooting " string4 = "for the " string5 = "knicks" print(string1 + string2 + string3 + string4 + string5) # above is same as print("he's " "probably " "rooting " "for the " "knicks ") print("hello " * 5) # hello hello hello hello hello # print("Hello " * 5 + 4) - will error out print("hello " * (5+4)) # hello hello hello hello hello hello hello hello hello print("hello " * 5 + "4") # hello hello hello hello hello 4 # check if substring is within string today = "friday" print("day" in today) #True print("fri" in today) #True print("thur" in today) #false
false
771576a2ea6f1e99200c242e3d53ea510e4a51e5
DanielVasev/PythonOnlineCourse
/Beginner/most_common_counter.py
1,244
4.34375
4
""" How to count most common words in text """ from collections import Counter text = "It's a route map, but it's only big enough to get to the starting point. Many businesses have been asking\ when they will be allowed to reopen. Now they have some rough indication, pencilled in to the calendar, but far from\ all of them, and with distancing still required. In contrast with Boris Johnson's approach for England, Nicola\ Sturgeon's statement at Holyrood was not a route map to a late summer of socialising, concerts, sports and travel.\ The plan is far more cautious. Nicola Sturgeon's idea of release, maybe by late April, is to get through the doors\ of a restaurant or bar. Both leaders had said they were putting data ahead of dates, but it was the prime minister's\ dates that the public notice, remember and plan on. Travel bookings soared on Monday and Tuesday." # We split big string to separate list elements. words = text.split() # Creating counter counter = Counter(words) # Most common 3 words we can change the attribute top_three = counter.most_common(3) # Print the result print(top_three) # Counter how many words are in the text # print(words) # sum = 1 # for n in words: # print(n, sum ) # sum +=1
true
4e2005cd521e0d50e46f64e26530224ceedd53c8
515ek/PythonAssignments
/Sample-2-solutions/soln20.py
1,343
4.3125
4
## Name: Vivek Babu G R ## Date: 26-07-2018 ## Assignment: Sample 2 ## Question: A simple substitution cipher is an encryption scheme where each letter in an alphabet to replaced by a different letter in the same alphabet ## with the restriction that each letter's replacement is unique. The template for this question contains an example of a substitution cipher ## represented a dictionary CIPHER_DICTIONARY. Your task is to write a function encrypt(phrase,cipher_dict) that takes a string phrase and a ## dictionary cipher_dict and returns the results of replacing each character in phrase by its corresponding value in cipher_dict. ## Ex: encrypt("cat", CIPHER_DICT) should return ”km “ ############################################################################################################################################################ def encrypt(phrase , cipher_dict): msg = '' for ch in phrase: msg += cipher_dict[ch] return msg CIPHER_DICT = {'e': 'u', 'b': 's', 'k': 'x', 'u': 'q', 'y': 'c', 'm': 'w', 'o': 'y', 'g': 'f', 'a': 'm', 'x': 'j', 'l': 'n', 's': 'o', 'r': 'g', 'i': 'i', 'j': 'z', 'c': 'k', 'f': 'p', ' ': 'b', 'q': 'r', 'z': 'e', 'p': 'v', 'v': 'l', 'h': 'h', 'd': 'd', 'n': 'a', 't': ' ', 'w': 't'} print(CIPHER_DICT) msg = input("Enter the phrase to encrypt\n") print(encrypt(msg, CIPHER_DICT))
true
cd4e8d94167d991aacdc132a2ca3f22a107e4c16
515ek/PythonAssignments
/Sample-1-solutions/soln18.py
385
4.1875
4
## Name: Vivek Babu G R ## Date: 26-07-2018 ## Assignment: Sample 1 ## Question: Python Program to Take in a String and Replace Every Blank Space with Hyphen. ############################################################################################ str1 = input('Enter the string\n') str2 = '' for s in str1.split(' '): if str2 != '': str2 = str2 + '-' + s else: str2 += s print(str2)
true
a455f7a6c96aff192219ef358f796c3f608b52e1
AMANBAIN/First-Github-Repo
/PythonCalculator.py
1,241
4.21875
4
def menu(): print("\nHello User") print("1. ADD") print("2. SUBTRACT") print("3. MULTIPLY") print("4. DIVIDE") print("5. EXIT") pick = int(input("Enter a Choice: ")) return pick def main(): choice = menu() while choice != 5: if choice == 1: # adds two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print(num1, "+", num2, "=", num1 + num2) elif choice == 2: # subtracts two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print(num1, "-", num2, "=", num1 - num2) elif choice == 3: # multiplies two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print(num1, "*", num2, "=", num1 * num2) elif choice == 4: # divides two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print(num1, "/", num2, "=", num1 / num2) else: print("Invalid Entry") choice = menu() main()
false
64d72e038c18c73bcc5ead26b026a6c3d4826e3d
ClntK/PaymentPlanner
/paymentPlanner.py
2,030
4.1875
4
""" File: paymentPlanner.py Author: Clint Kline Last Modified: 5/30/2021 Purpose: To Estimate a payment schedule for loans and financed purchases. """ # input collection price = (float(input("\nPurchase Price: "))) months = (float(input("Loan Duration(in months): "))) # example "12" for one year, "120" for 10 years downPayment = (float(input("Down Payment: "))) interestRate = (float(input("Interest Rate(as a decimal): "))) # example: .045 = 4.5% # other variables subTotal = price - downPayment total = subTotal + (subTotal * interestRate) payment = total / months # comfirm input print("\nprice: $%0.2f" % price) print("months: $%0.2f" % months) print("downPayment: $%0.2f" % downPayment) print("interestRate: $%0.2f" % interestRate) print("subTotal: $%0.2f" % subTotal) print("total w/int after down payment: $%0.2f" % total) print("payment: $%0.2f" % payment, "\n") # print table headers print("%-10s%-18s%-15s%-15s%-15s%-15s" % ("Month #:", "Init. Balance:", "Interest:", "Principal:", "Payment:", "Rem. Balance")) # begin list build if months > 0: duration = [] month = 0 # add values to list "duration" equal to number of months entered while months != 0: month += 1 duration.append(month) months -= 1 # handle no input in months variable else: print("Please enter a Duration.") # begin table build remDur = len(duration) while total > 0 and remDur > 0: # loop through each month in list "duration" to create a table of payments equal to the amount of months entered by user for i in duration: balance = total interest = balance * interestRate / remDur remDur -= 1 remBal = balance - (payment + interest) principal = payment - interest # display table row print("%-10s$%-17.2f$%-14.2f$%-14.2f$%-14.2f$%-14.2f" % (i, balance, interest, principal, payment, remBal)) total = remBal # end
true
9731d705b7cb3fdf08c13bb6790daac74765d754
ManavParmar1609/OpenOctober
/Data Structures/Searching and Sorting/MergeSort.py
1,275
4.34375
4
#Code for Merge Sort in Python #Rishabh Pathak def mergeSort(lst): if len(lst) > 1: mid = len(lst) // 2 #dividing the list into left and right halves left = lst[:mid] right = lst[mid:] #recursive call for further divisions mergeSort(left) mergeSort(right) #iterators for left and right halves i = 0 j = 0 #iterator for main list k = 0 while i < len(left) and j < len(right): #comparing values from left half with the values from right half and inserting the smaller value in the main list if left[i] < right[j]: lst[k] = left[i] i += 1 #incrementing value of iterator for left half else: lst[k] = right[j] j += 1 #incrementing value of iterator for right half k += 1 #incrementing value of iterator for main list #for all the remaining values while i < len(left): lst[k] = left[i] i += 1 k += 1 while j < len(right): lst[k] = right[j] j += 1 k += 1 #an example myList = [5, 7, 6, 1, 9] mergeSort(myList) print(myList) #Time complexity: O(nlogn)
true
b44d519c3cf9f4dd9f741d710eff3447d9991a22
ManavParmar1609/OpenOctober
/Algorithms/MemoizedFibonacci.py
927
4.3125
4
""" @author: anishukla """ """Memoization: Often we can get a performance increase just by not recomputing things we have already computed.""" """We will now use memoization for finding Fibonacci. Using this will not only make our solution faster but also we will get output for even larger values such as 1000 whereas by general recursive approch calculating fibonacci of 40 will also take very large amount of time.""" def fibonacci_memoization(n, d={}): if n in d: return d[n] elif n == 0: ans = 0 elif n == 1: ans = 1 else: ans = fibonacci_memoization(n-1, d) + fibonacci_memoization(n-2, d) d[n] = ans return ans print("Enter number of test cases you want: ") T = int(input()) for i in range(T): print("Input the position for fibonacci value: ") N = int(input()) print("Fibonacci(%d) = " %N , fibonacci_memoization(N))
true
f107b6b4d03e7557bfd26597d75acd953d1e5cda
EvgenyKirilenko/python
/herons_formula.py
320
4.4375
4
#this code calculates the area of triangle by the length of the given sides #by the Heron's formula from math import sqrt a=int(input("Enter side A:")) b=int(input("Enter side B:")) c=int(input("Enter side C:")) p=float((a+b+c)/2) s=float(sqrt(p*(p-a)*(p-b)*(p-c))) print ("Area of the triangle is : ",s)
true
c0e3604aff31861c0e38f030e91b3a5b82c29049
pratikpwr/Python-DS
/strings_6/lenghtOfStrings.py
329
4.34375
4
# length of string can be calculated by len() name = input("Enter string: ") length_of_string = len(name) print("string:", name) print("length of string:", length_of_string) # max and min of String or others maxi = max(name) mini = min(name) print("maximum:", maxi + "\nminimum:", mini) # slicing a String print(name[0:3])
true
427601166ccc5624317e9fea05adc163236321ae
ARAV0411/HackerRank-Solutions-in-Python
/Numpy Shapes.py
257
4.1875
4
import numpy arr= numpy.array(map(int, raw_input().split()) print numpy.reshape(arr, (3,3)) # modifies the shape of the array #print arr.shape() --- prints the rows and columns of array in tuples # arr.shape()= (3,4) --- reshapes the array
true
1c9ab653a40c59ba50f04719d8950a2656fdd6f5
ybharad/DS_interview_prep_python
/prime_factors.py
736
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 26 20:43:26 2020 @author: yash this function calculates the factors of any number which are only prime numbers it reduces the factors of a number to its prime factors """ import math def primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: print (2), n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3, int(math.sqrt(n)) + 1, 2): # while i divides n , print i ad divide n while n % i == 0: print (i), n = n / i # Condition if n is a prime # number greater than 2 if n > 2: print (n)
true
8e132be5f0cc44dd9f44161c9516afd8b61c0e67
Andrey-Gurevich/Course-Python
/lesson_2_Task_1.py
998
4.21875
4
""" Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b на квадраты с наибольшей возможной на каждом этапе стороной. Выведите длины ребер получаемых квадратов и кол-во полученных квадратов """ def square_rec(aa, bb, nn=0): if aa == bb: print("Сторона квадрата ", aa) return nn+1 if aa > bb: print("Сторона квадрата ", bb) return square_rec(aa-bb, bb, nn+1) print("Сторона квадрата ", aa) return square_rec(aa, bb-aa, nn+1) a = int(input("Введите длину стороны A -> ")) b = int(input("Введите длину стороны B -> ")) n = 0 print("Количество квардратов ", square_rec(a, b, n))
false
b687fa59ae247c922fb7cc0ff003ebdba4834443
cbesanao/aprendendo_python
/CursoemVideo/aula07a-Operadores-Aritmeticos.py
1,075
4.15625
4
# 1 () # 2 ** # 3 * / // % # 4 + - ''' nome = input("Qual é o seu nome? ") print('Prazer em te conhecer {:20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços print('Prazer em te conhecer {:>20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços e será alinhado à DIREITA print('Prazer em te conhecer {:<20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços e será alinhado à ESQUERDA print('Prazer em te conhecer {:^20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços e será CENTRALIZADO print('Prazer em te conhecer {:=^20}!\n'.format(nome)) # agora a parte do nome terá 20 espaços e será CENTRALIZADO entre " ''' n1 = int(input('Um valor: ')) n2 = int(input('Outro valor: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma é {}, a multiplicação é {} e a divisão {:.3f}'.format(s, m, d), end=' ') print('A divisão inteira é {} e a potência é {}'.format(di, e)) # para quebrar a linha ou um enter, digita \n # para juntar as linha ou dois prints digita , end=' '
false
77706820160382ec17b7a3f29f2ba2ef6561d4d1
YuryRazhkov/Rozhkov_GB_ALGO
/Rozhkov_GB_ALGO/Rozhkov_Yury_dz_2/task_2_1.py
1,638
4.15625
4
# 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. # Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, # а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа # '0' в качестве знака операции. Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), # то программа должна сообщать ему об ошибке и снова запрашивать знак операции. # Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя. b = 1 while b != 0: a = input('enter value_1: ') while a.isdigit() == 0: a = input('wrong value! enter value_1: ') b = input('enter operation: ') while b not in ('0', '+', '-', '*', '/'): print('wrong operanion') b = input('operation: ') if b == '0': print('stopped by user') break c = input('enter value_2: ') while c == '0' and b == '/': print('error zero division') c = input('value_2: ') while c.isdigit() == 0: c = input('wrong value! enter value_2: ') print(eval(a + b + c))
false
db6ef77f8dd537603785af1ca4ff554cb837e9c7
arshad-taj/Python
/montyPython.py
260
4.28125
4
def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] s = "Geeksforgeeks" print("The original string is : ", end="") print(s) print("The reversed string(using recursion) is : ", end="") print(reverse(s))
true
5a770eec9865f4462e2cb412720b18cb1422829a
CQuinlan1/Programming_Python_Problemset
/Problem7.py
738
4.46875
4
#************************** # Created by Catherine Ann Celeste Quinlan. # This program will take a FLOATING POINT NUMBER as input and output its square root approximation. # QUESTION 7 #************************* import math Selectednumber = input ("Please enter a positive floating number bigger than 0 : \n " ) try: val = float(Selectednumber) if(val > 0): print("Yes,input string is a float number.") root_square = round(math.sqrt(val),2) print("The Square root of this number , rounded to two decimal places is :", root_square) elif (val == 0): print("please enter a float number bigger than 0") else: print("User number is negative.") except ValueError: print("That is not a floating number!")
true
895d715fb433475c1e0bbac0e0de220755191440
kmangub/data-structures-and-algorithms
/python/challenges/multi_bracket_validation/multi_bracket_validation.py
1,571
4.65625
5
def multi_bracket_validation(string): """ This function will check to see if the brackets are matching. It creates an empty list, which is our stack and we will iterate through each character. Any opening brackets will be appended to our stack. When it encounters a closing bracket, it will check if the stack is empty and will return false if it is. If the stack is not empty, it will pop the last element and it will compare to the closing bracket. It will return false it doesn't match right away. Once we are done iterating, it checks the length again and return the appropriate Boolean """ stack = [] for char in string: print(char) if char == '{' or char == '(' or char == '[': stack.append(char) elif char == '}' or char == ')' or char == ']': if len(stack) == 0: return False top_of_stack = stack.pop() if not compare(top_of_stack, char): return False if len(stack) != 0: print('stack not empty...') return False print(stack) return True def compare(opening, closing): """ This function supplements our multi bracket validation. If the statement returns False, the function returns False. """ if opening == '{' and closing == '}': return True if opening == '(' and closing == ')': return True if opening == '[' and closing == ']': return True return False print(multi_bracket_validation('{(})'))
true
42b0c03db3abb4932e1f8d6ff2471c339a8b5c4d
angusb/puzzles
/inversions.py
1,175
4.15625
4
# Inversions can be used to detect how similar two lists are (Kendall's #rank correlcation). This is applicable with search engine testing. Futhermore, # inversions can be used to match a user's preferences with those of others. # # Given a list L = x_1, x_2, ..., x_N of distinct integers between 1 and n # an inversion is defined as any pair (i,j) where 1 <= i < j <= n such that x_i > x_j # # In a list of n numbers there are up to O(n^2) possible inversions. def merge_and_count(a, b): count = 0 a_i, b_j = 0, 0 merge_list = [] while a_i < len(a) and b_j < len(b): merge_list.append(min(a[a_i], b[b_j])) if b[b_j] < a[a_i]: count += len(a) - a_i if a[a_i] <= b[b_j]: a_i += 1 else: b_j += 1 if a_i < len(a): merge_list.extend(a[a_i:]) elif b_j < len(b): merge_list.extend(b[b_j:]) return count, merge_list def sort_and_count(l): if len(l) <= 1: return 0, l mid = len(l)/2 a = l[:mid] b = l[mid:] c_a, a = sort_and_count(a) c_b, b = sort_and_count(b) c, L = merge_and_count(a, b) return c_a + c_b + c, L def inversions(l): return sort_and_count(l)[0] if __name__ == '__main__': assert inversions([1, 3, 0, 2, 4]) == 3
true
f3eee113887465cafb2eebc4c7683489a6581ccb
Charlene-bot/FindAJob
/MoveZeros.py
556
4.1875
4
#Given an array of integers, write a function to move all 0's to the end #while maintaining the relative order of rest of the elements #Algorithm -- moving all numbers ahead #setting the rest of the numbers in the list to 0 def Move_Zeros(arr, length): j = 0 for num in arr: if num != 0: arr[j] = num j = j + 1 print(j) print(length) for num in range(j,length): arr[num] = 0 arr = [1, 0, 4, 0, 12] length = len(arr) print(arr) Move_Zeros(arr, length) print("After the function") print(arr)
true
b73f14ad6adfcb0005a19a66748fe3a594570b4b
Somanathpy/Py4e-Coursera
/Python_Data_Structures/scriptsandoutputs/ex7.2.py
1,558
4.15625
4
## Assignment 7.2 # Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: # X-DSPAM-Confidence: 0.8475 # Count these lines and extract the floating point values from each of the lines and compute the average of those values and # produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. # when you are testing enter mbox-short.txt as the file name. import string fname = input("enter file name:") path = "C:/Users/SomandLily/Documents/GitHub/Py4e-Coursera/Python_Data_Structures/Data/" fname = path+fname try: file = open(fname) except: print("can't open file: "+fname) total = 0 count = 0 for line in file: if line.startswith('X-DSPAM-Confidence:'): m = len(line) pos = line.find(':') num = float(line[pos+1:m]) total += num count += 1 print("Total :"+str(total)) print("count :"+str(count)) print("average: "+str(total/count)) '''****** doing this with regular expressions**********''' import string import re fname = input("enter file name:") path = "C:/Users/SomandLily/Documents/GitHub/Py4e-Coursera/Python_Data_Structures/Data/" fname = path+fname try: file = open(fname) except: print("can't open file: "+fname) total = 0 count = 0 for line in file: if line.startswith('X-DSPAM-Confidence:'): m = re.search(r'.*?([\d+]*\.[\d]+)',line) if m: total += float(m.group(1)) count += 1 else: continue print("Total: "+str(total)) print("count: "+str(count)) print("average: "+str(total/count))
true
ef6fe1c287eb86fa59d09d1d79d854665d35ea43
chalk13/softformance_school_exercises
/module_4/convert_user_name.py
1,638
4.21875
4
"""Програми, які перетворюють ім'я користувача у: - послідовність байтів - unicode code points - бінарне представлення """ USER_NAME = input("Please, enter your name: ") # --------------------------------------------------------------------- # Sequence of bytes # The rules for translating a Unicode string into a sequence of bytes # are called an encoding. # --------------------------------------------------------------------- # UTF-8 uses the following rules: # 1) If the code point is < 128, it’s represented by the corresponding # byte value. # 2) If the code point is >= 128, it’s turned into a sequence of two, # three, or four bytes, where each byte of the sequence is between 128 # and 255. USER_NAME_BYTES = USER_NAME.encode('utf-8') print(f"\nYour name as sequence of bytes will be: {USER_NAME_BYTES}\n" f"Type: {type(USER_NAME_BYTES)}\n") # --------------------------------------------------------------------- # Unicode code points (UCP) # Literal strings are unicode by default in Python 3 # --------------------------------------------------------------------- USER_NAME_UCP = "" for letter in USER_NAME: USER_NAME_UCP += "{:04x}".format(ord(letter))[1:] print(f"Your name in unicode code points: {USER_NAME_UCP}\n") # --------------------------------------------------------------------- # Binary representation # --------------------------------------------------------------------- USER_NAME_BINARY = ''.join(format(ord(letter), 'b') for letter in USER_NAME) print(f"Your name in binary representation: {USER_NAME_BINARY}")
true
6e03ebaf48358ad05bc5677876d81bc54ed847f1
srajeevteaching/lab2-s923
/lab2.py
2,028
4.53125
5
# Lab Number: 2 # Program Inputs: Births per second (float), deaths per second (float), migration per second (float), # Program Inputs (2): Current population (integer), number of years in future (float) # Program Outputs: Estimated population (integer) # This block asks the user for the three inputs that change population. perSecondBirths = input('How many births per second occur in this country?') perSecondDeaths = input('How many deaths per second occur in this country?') perSecondMigration = input('What is the migration per second of this country? \n(If more people leave then enter, you may enter a negative value.)') # This block asks the user for the current population and the number of years in the future they want to see. currentPopulation = input('What is the current population of this country?') futureYears = input('How many years in the future would you like this estimate?') # This line adds all of the population changing effects into one number. # Then it converts that number from per seconds into per years (which is the unit we're working with). # There are 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day, 365 days in a year. # So the product of those numbers is how many seconds there are in a year. perYearPopulationChange = 60 * 60 * 24 * 365 * ((float(perSecondBirths) - float(perSecondDeaths)) + float(perSecondMigration)) # The estimated population is the current population plus the net change over the next number of years. estimatedPopulation = int(int(currentPopulation) + (perYearPopulationChange * float(futureYears))) # Since countries cannot have a negative population, this line will put a floor cap on the output at 0. if estimatedPopulation <= 0: print('The population of this country will eventually die out.') # If there is more than 0 people in the country (a positive number) after so many years, the program will output it. else: print('The estimated population of this country in', futureYears, 'years will be ' + str(estimatedPopulation) + '.')
true
feb404742b6fafaaa68fd0ceecee57c38c67114c
uknamboodiri/z2m
/section-6/115.py
446
4.1875
4
# Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cat1 = Cat('Dhanya', 16) cat2 = Cat('Dhanya2', 18) cat3 = Cat('Dhanya3', 17) # 2 Create a function that finds the oldest cat def get_oldest_cat(*args): return max(args) print(f'The oldest cat is {get_oldest_cat(cat1.age, cat2.age, cat3.age)} years old.')
true
42d0ac0a8d6344bf06883958b2db071e1c9a44bf
smit-pate-l/HackerRank
/Sets/symmetric_difference.py
375
4.3125
4
# Given 2 sets of integers, M and N, print their symmetric difference in ascending order. # The term symmetric difference indicates those values that exist in either M or N but do not exist in both. m = int(input()) M = set(map(int,input().split())) n = int(input()) N = set(map(int,input().split())) r = sorted(list(M.symmetric_difference(N))) for i in r: print(i)
true
e6c56cf411afde329bc8da11a779e548a717a6b3
fpelaezt/devops
/Python/Workbook/1-2a.py
902
4.4375
4
# Makes a function that will contain the # desired program. def example(): # Calls for an infinite loop that keeps executing # until an exception occurs while True: test4word = input("What's your name? ") try: test4num = int(input("From 1 to 7, how many hours do you play in your mobile?" )) # If something else that is not the string # version of a number is introduced, the # ValueError exception will be called. except ValueError: # The cycle will go on until validation print("Error! This is not a number. Try again.") # When successfully converted to an integer, # the loop will end. else: print("Impressive, ", test4word, "! You spent", test4num*60, "minutes or", test4num*60*60, "seconds in your mobile!") break # The function is called example()
true
4acae9de077b1b1497254d832c393afbff9f7288
fpelaezt/devops
/Python/Course/4_Managing_lists.py
1,692
4.5
4
#For loop magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) for magician in magicians: print(magician.title() + " that was a great trick!!") print("===") print("///") for number in range(2,9): print(number) print("That was it") print("###############") numbers = list(range(1,6)) print(numbers) print(numbers[-1]) print("###############") print("The following are the square numbers") sq_numbers = [] for number in range(1,11): sq_numbers.append(number**2) print(sq_numbers) print("Minimun value: " + str(min(sq_numbers))) print("Maximun value: " + str(max(sq_numbers))) print("Sum value: " + str(sum(sq_numbers))) print("###############") print("###############") #List Comprehension sq_numbers = [value**2 for value in range(1,5)] print(sq_numbers) print("###############") print("###############") #LAB numbers = [value for value in range(1,21)] print(numbers) #numbers = [value for value in range(1,1000000)] #for number in numbers: # print(number) print(min(numbers)) print(sum(numbers)) print("###############") odd_numbers = list(range(1,21,2)) print(odd_numbers) print("###############") #List Comprehension cube_numbers = [value**3 for value in range(1,5)] print(cube_numbers) print("###############") players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:1]) print(players[:2]) print(players[2:]) print("Last two elements") print(players[-2:]) my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods)
true
f70fbdb665c0e479b32b240950618d59569cf037
Kunjal9/Project_Euler
/Problem01.py
598
4.21875
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. def multiple_of_3_and_5(num): list_of_i = [] for i in range(1,num): if (i %5 ==0) or (i%3==0): list_of_i.append(i) return sum(list_of_i) def three_and_five(s = 0): for i in range(1,1000): if (i % 3 == 0 or i%5 == 0): s = s + i return s if __name__ == '__main__': print(multiple_of_3_and_5(1000)) print(three_and_five())
true
d196796bb7db0463ae7f72305630c26d0648b587
askiefer/practice-code-challenges
/missing_element.py
619
4.21875
4
import collections def missing_element(lst1, lst2): lst1.sort() lst2.sort() count = 0 for item in lst1: if item != lst2[count]: return item count += 1 def missing_element_two(lst1, lst2): lst1.sort() lst2.sort() for num1, num2 in zip(lst1, lst2): if num1 != num2: return num1 return False # this is a linear solution using the XOR operator # the XOR operation will be true if only ONE of the elements is present def missing_element_three(lst1, lst2): result = 0 for num in lst1 + lst2: result ^= num return result if __name__ == '__main__': print(missing_element_three([5,5,7,7], [5,7,7]))
true
44c079d95ab1089fbd22e72db89baa863a6ef301
akshirapov/think-python
/15-classes-and-objects/ex_15_9_2.py
1,823
4.28125
4
# -*- coding: utf-8 -*- """ This module contains a code for ex.2 related to ch.15.9 of Think Python, 2nd Edition by Allen Downey http://thinkpython2.com """ import math import turtle from ex_15_9_1 import Point, Circle, Rectangle def polyline(t, n, length, angle): """Draws n line segments. :param t: turtle object :param n: number of line segments :param length: length of each segments :param angle: degrees between segments """ for _ in range(n): t.fd(length) t.lt(angle) def arc(t, r, angle): """Draws an arc with the given radius and angle. :param t: turtle object :param r: radius of the arc :param angle: angle subtended by the arc, in degrees """ arc_length = 2 * math.pi * r * abs(angle) / 360 n = int(arc_length / 4) + 3 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) def draw_rect(t: turtle.Turtle, rect: Rectangle): """Draws the rectangle. :param t: turtle object :param rect: rectangle object """ w = rect.width h = rect.height t.ht() t.fd(w) t.rt(90) t.fd(h) t.rt(90) t.fd(w) t.rt(90) t.fd(h) def draw_circle(t: turtle.Turtle, circle: Circle): """Draws the circle. :param t: turtle object :param circle: circle object """ t.ht() arc(t, circle.radius, 360) def main(): bob = turtle.Turtle() box = Rectangle() box.width = 100 box.height = 50 box.corner = Point() box.corner.x = 0 box.corner.y = 0 circle = Circle() circle.radius = 50 circle.center = Point() circle.center.x = 0 circle.center.y = 0 draw_rect(bob, box) draw_circle(bob, circle) turtle.Screen().mainloop() if __name__ == '__main__': main()
true
af934bf769068533c84ccdff2976c26413f6274d
akshirapov/think-python
/12-tuples/ex_12_10_3.py
1,297
4.15625
4
# -*- coding: utf-8 -*- """ This module contains a code for ex.3 related to ch.12.10 of Think Python, 2nd Edition by Allen Downey http://thinkpython2.com """ def word_list(): """Makes a dictionary where the key is the word. :return: Dictionary """ d = {} with open('words.txt') as fin: for line in fin.readlines(): word = line.strip().lower() d[word] = True return d def anagrams(words: dict): """Searches for anagrams.""" d = {} for word in words: letters = ''.join(sorted(word)) d[letters] = d.get(letters, []) + [word] return d def difference(word1: str, word2: str): """Counts the number of differences between two words.""" count = 0 for c1, c2 in zip(word1, word2): if c1 != c2: count += 1 return count def metathesis_pair(d: dict): """Print all pairs of words that differ by swapping two letters. :param d: map from word to list of anagrams """ for a_list in d.values(): for word1 in a_list: for word2 in a_list: if word1 < word2 and difference(word1, word2) == 2: print(word1, word2) if __name__ == '__main__': wl = word_list() anms = anagrams(wl) metathesis_pair(anms)
true
993f6d68415097284dcd543c5a96e6ac61c640ca
akshirapov/think-python
/14-files/ex_14_12_2.py
1,533
4.125
4
# -*- coding: utf-8 -*- """ This module contains a code for ex.2 related to ch.14.12 of Think Python, 2nd Edition by Allen Downey http://thinkpython2.com """ import shelve def word_list(filename): """Makes a dictionary where the key is the word. :param filename: file with words """ d = {} with open(filename) as fin: for line in fin.readlines(): word = line.strip().lower() d[word] = None return d def anagrams(words): """Searches for anagrams.""" d = {} for word in words: letters = ''.join(sorted(word)) d[letters] = d.get(letters, []) + [word] return d def read_anagrams(filename, word): """Looks up the word in shelf and returns a list of its anagrams. :param filename: file name of shelf :param word: word to look up """ letters = ''.join(sorted(word)) with shelve.open(filename) as db: try: return db[letters] except KeyError: return [] def store_anagrams(filename, a_map): """Stores the anagrams from a dictionary in a shelf. :param filename: file name of shelf :param a_map: dictionary that maps string to list of anagrams """ with shelve.open(filename) as db: for letters, words in a_map.items(): db[letters] = words def main(): wl = word_list('words.txt') ad = anagrams(wl) shelf = 'anagrams' store_anagrams(shelf, ad) print(read_anagrams(shelf, 'hello')) if __name__ == '__main__': main()
true
407190295065104f1c25894e4f1722f5ed0f0f78
linus1211/Learn-Python-The-Hard-Way
/ex9.py
675
4.21875
4
# Here's some new strange stuff, remember type it exactly. # Set a variable called days to a string with shortened day names days = "Mon Tue Wed Thu Fri Sat Sun" yay111 = "Mon" # Set a variable called months to a string with shortened month names, separated by \n (newline) characters months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # print a string, along with days print ("Here's the days:", days) print ("here's the days:%s" %days) # print a string, along with months print ("Here's the months: ", months) # print a long string with line breaks print (""" There's somethings going on here. With the three double-quotes. We'll be able to type as much as we like. """)
true
d63a5ae5a7391fb046373b832d416679fe80c389
BElgy123/Palindrome
/Palindrome.py
1,516
4.5625
5
def is_palindrome(test_string): """ A standalone function to check if a string is a palindrome. :param test_string: the string to test :return: boolean """ t = test_string #Change parameter name cause it's too long for laziness _t = [] #Will be expanded form of t t_ = [] #Will be _t backwards if(not(type(t) is str)): #Check if String return False if(len(t) == 0): #Check if Empty return False t = t.upper() #Make it uppercase for i in t: #Set list _t to an expaded form of the input if(i != " "): _t.append(i) i = len(_t)-1 while(i>=0):# set t_ to _t backwards t_.append(_t[i]) i-=1 if(t_ == _t):#Check if forwards and backwards form are the same return True else: return False if __name__ == '__main__': assert is_palindrome('') == False # an empty string is not a palindrome assert is_palindrome(17) == False # an integer is not a string, not a palindrome assert is_palindrome("1") == True # "1" is the same forwards as it is backwards, in this project, we'll consider 1 character strings palindromes assert is_palindrome("stuff") == False # "stuff" is not a palindrome assert is_palindrome("tacocat") # all lowercase, no spaces assert is_palindrome("MoM") == True # upper and lower, no spaces assert is_palindrome("Borrow or rob") == True # upper and lower, spaces assert is_palindrome("A nut for a jar of tuna") == True # same
true
e3e22a551b6cf3a223f723ca175e7b5ac3056a9c
nkmcheng/Python-Training
/problem2.py
423
4.21875
4
# Question #2: # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 Then, the output should be: 40320 sequence = [8, 5] results = [] for s in sequence: result = 1 for i in range(1, s + 1): result *= i results.append(result) print(results)
true
838652f0cb3ace326b9266fa271b39c031f00d52
User-zwj/Class
/Tim_OOP.py
1,838
4.3125
4
# object oriented programming in python # string = 'hello' # print(string.upper()) # print(string.capitalize()) # class Dog: # # def __init__(self, name): # self.name = name #attribute # print(name) # # def add_one(self, x): # return x+1 # # def bark(self): #method # print('bark') # d = Dog() #instance/object # d.bark() # print(d.add_one(5)) # d = Dog('Tim') # print(d.name) # d2 = Dog('Bill') # print(d2.name) # class Dog: # # def __init__(self, name, age): # self.name = name #attribute # self.age = age # # def get_name(self): # return self.name # # def get_age(self): # return self.age # # def set_age(self, x): # self.age = x # d = Dog('Tim', 24) # d2 = Dog('Bill', 11) # print(d.get_name()) # print(d2.get_name()) # print(d.get_age()) # print(d2.get_age()) # d.set_age(10) # print(d.get_age()) ##======================= class Pet: #upper level class def __init__(self, name, age): self.name = name self.age = age def show(self): print("I am %s and I am %s years old" % (self.name, self.age)) def speak(self): print("I don't know what I say") class Cat(Pet): def __init__(self, name, age, color): # super().__init__(name, age) ##### self.name = name self.age = age self.color = color def speak(self): #overwrite speak in the upper level class print('meow') def show(self): print("I am %s and I am %s years old and I am %s" % (self.name, self.age, self.color)) class Dog(Pet): def speak(self): print('Bark') # class Fish(Pet): # pass # p = Pet('Tim', 19) # p.show() # p.speak() c = Cat('Bill', 34, 'white') c.show() # c.speak() # f = Fish('Bubble', 10) # f.speak()
false
274346c96ad571b3fdc354db141863bdb99a14d5
udaypandey/BubblyCode
/Python/multiplication-table.py
360
4.40625
4
# Write a program that prints a multiplication table for numbers up to 12. def printTable() : num = 1 while num <= 12: end = 12 start = 1 while start <= end: print(f"{num} x {start} = {num * start}") start = start + 1 num = num + 1 printTable()
true
cb01451575debb5050b412cb3cb3cabb4ce6d30f
tbold5/A01072453_1510_assignments
/A1/phone_fun.py
2,574
4.125
4
"""COMP 1510 Assignment 1: PHONE FUN!""" # Trae Bold # A01072453 # Feb 03, 2019 import doctest def number_translator(): """Translates alphabetical numbers. A function that translates alphabetical numbers into numerical equivalent. PRECONDITION: promt user to input 10 character telephone number in the format XXX-XXX-XXXX. POSTCONDITION: translate alphabetical numbers into numerical equivalents. RETURN: returns string in the format XXX-XXX-XXXX. """ user_input = input("Please enter 10-character phone number in the format XXX-XXX-XXXX: ").upper() new_number = str(letter_translator(user_input[0])) + str(letter_translator(user_input[1])) \ + str(letter_translator(user_input[2])) + str(letter_translator(user_input[3])) \ + str(letter_translator(user_input[4])) + str(letter_translator(user_input[5])) \ + str(letter_translator(user_input[6])) + str(letter_translator(user_input[7])) \ + str(letter_translator(user_input[8])) + str(letter_translator(user_input[9])) \ + str(letter_translator(user_input[10])) + str(letter_translator(user_input[11])) return new_number def letter_translator(letter): """Translate number. A function that translates letters to a corresponding numbers. PARAM: str, a single letter. PRECONDITION: must be a str type single letter. RETURN: translated number as a string. >>> letter_translator("B") '2' >>> letter_translator("Z") '9' >>> letter_translator("F") '3' """ my_list = [["0"], ["1"], ["2", "A", "B", "C"], ["3", "D", "E", "F"], ["4", "G", "H", "I"], ["5", "J", "K", "L"], ["6", "M", "N", "O"], ["7", "P", "Q", "R", "S"], ["8", "T", "U", "V"], ["9", "W", "X", "Y", "Z"], ["-"]] if letter in my_list[0]: return "0" elif letter in my_list[1]: return "1" elif letter in my_list[2]: return "2" elif letter in my_list[3]: return "3" elif letter in my_list[4]: return "4" elif letter in my_list[5]: return "5" elif letter in my_list[6]: return "6" elif letter in my_list[7]: return "7" elif letter in my_list[8]: return "8" elif letter in my_list[9]: return "9" elif letter in my_list[10]: return "-" def main(): print((number_translator())) if __name__ == "__main__": main() doctest.testmod()
true
4212b2e337330c2cf72fda3d55a569c0f406a2e3
Jethet/First-Milestone-Project
/OLDChoice.py
2,327
4.21875
4
# This is the function that asks the choice of a player and links to the # board squares. # This function is part of main() import pickle from beautifultable import BeautifulTable board = BeautifulTable() board.append_row(['1', '2', '3']) board.append_row(['4', '5', '6']) board.append_row(['7', '8', '9']) print(board) def board_coordinates(choice): square_taken = [] if choice == '1': square_taken.append('1') #print(square_taken) return (0,0) elif choice == '2': square_taken.append('2') #print(square_taken) return (0,1) elif choice == '3': square_taken.append('3') return (0,2) elif choice == '4': square_taken.append('4') return (1,0) elif choice == '5': square_taken.append('5') return (1,1) elif choice == '6': square_taken.append('6') return (1,2) elif choice == '7': square_taken.append('7') return (2,0) elif choice == '8': square_taken.append('8') return (2,1) elif choice == '9': square_taken.append('9') return (2,2) # The function starts here: def choice(): square = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] square_taken = [] while True: player = input("Are you player X or player O? ") if player != 'X' and player != 'O': print("This is not a valid choice.") break choice = input("Where do you place your mark? ") if choice in square_taken: print("This square is taken.") continue if choice not in square_taken: # HERE the programme should a) determine the coordinates and b) the player # The board_coordinates can be used for X and for O but how?? # And how to use the function board_coordinates inside choice()?? # This needs to be brought together: get the square and place X or O. if player == 'X': board_coordinates(choice) print('X') elif player == 'O': board_coordinates(choice) print('O') else: print("This is not a valid choice.") return # Save board changes with open('board', mode = 'wb') as my_file: pickle.dump(board, my_file) choice()
false
6fc02da1b7a8ae69a06bb8c694061f305e5412e2
richiabhi/Rock_paper_Scissors
/main.py
961
4.1875
4
import random # Rock Paper Scissor def gameWin(comp, you): if comp == you: return None elif comp == 'r': if you == 'p': return True elif you == 's': return False elif comp == 'p': if you == 's': return True elif you == 'r': return False elif comp == 's': if you == 'r': return True elif you == 'p': return False print("Computer's Turn : Rock(r) Paper(p) or Scissor(s) ?") randNo = random.randint(1, 3) if randNo == 1: comp = 'r' elif randNo == 2: comp = 'p' elif randNo == 3: comp = 's' you = input("Your Turn : Choose Rock(r) Paper(p) or Scissor(s) : ") res = gameWin(comp, you) print(f"Computer chose {comp}") print(f"You chose {you}") if res == None: print("The game is a Tie !") elif res: print("You won the game :) ") else: print("You lose :( ")
false
0477c1ba458019c51f17f2e8d8689912f53baa8f
limikmag/python
/algorithms/math/fast_exponential.py
872
4.3125
4
# recursion def power(base: int, to_power: int) -> int: if to_power == 0: return 1 if to_power % 2 != 0: return base*power( base=base, to_power=(to_power - 1)) if to_power % 2 == 0: return power( base=base, to_power=to_power/2)*power(base=base, to_power=to_power/2) #iterative def fast_power(base: int, to_power: int) -> int: """ Returns the result of a^b i.e. a**b We assume that a >= 1 and b >= 0 Remember two things! - Divide power by 2 and multiply base to itself (if the power is even) - Decrement power by 1 to make it even and then follow the first step """ result = 1 while to_power > 0: if to_power % 2 == 1: result = (result * base) to_power = to_power//2 base = (base * base) return result print(fast_power(2,10))
true
50abb7adfbc7d82404e57138b1c3b649b092001e
trinhgliedt/100_days_of_Python
/2021_03_07_Guess_the_number/2021_03_07_Guess_the_number.py
2,024
4.28125
4
# Number Guessing Game Objectives: # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answer correct, show the actual answer to the player. # Track the number of turns remaining. # If they run out of turns, provide feedback to the player. # Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode). from art import logo from replit import clear NO_OF_GUESSES_DICT = {"easy": 10, "hard": 5} def process_difficulty_input(difficulty): while difficulty not in ["easy", "hard"]: difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") if difficulty not in ["easy", "hard"]: print("Invalid choice. Please choose again.") return difficulty play_again = "y" while play_again == "y": clear() print(logo) print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.") import random secret_num = random.randint(1, 100) print(f"Pssst, the correct answer is {secret_num}") difficulty = "" difficulty = process_difficulty_input(difficulty) for no_of_guess in range(NO_OF_GUESSES_DICT[difficulty], 0, -1): print( f"You have {no_of_guess} attempts remaining to guess the number.") guess = int(input("Make a guess: ")) if guess != secret_num: if guess < secret_num: print("Too low.\nGuess again.") elif guess > secret_num: print("Too high.\nGuess again.") if no_of_guess == 1: print("You've run out of guesses, you lose.") play_again = input("Play again? Type 'y' or 'n': ") elif guess == secret_num: print(f"Congratulation! {guess} is the correct number. You won!") break play_again = input("Play again? Type 'y' or 'n': ")
true
e935334b6eb589c4fbf104c5b6da44e29cd21918
trinhgliedt/100_days_of_Python
/2021_03_13_Turtle_Racing/main.py
1,045
4.25
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "indigo"] xCor = -240 yCors = [150, 100, 50, 0, -50, -100] turtles = [] for i in range(6): new_turtle = Turtle(shape="turtle") new_turtle.penup() new_turtle.color(colors[i]) new_turtle.goto(xCor, yCors[i]) turtles.append(new_turtle) is_raced_on = False if user_bet: is_raced_on = True while is_raced_on: for turtle in turtles: if turtle.xcor() > 230: is_raced_on = False winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} is the winner!") else: print(f"You've lost! The {winning_color} is the winner!") rand_distance = random.randint(0,10) turtle.forward(rand_distance) screen.exitonclick()
true
43d7d16a894ed49f2e25e30c15edb67cc22177b7
tangowithfoxtrot/beginner_project_solutions
/multi_table.py
713
4.1875
4
''' Created on Sun 04/20/2020 20:29:08 Multiplication Table @author: MarsCandyBars ''' def table(user_num): ''' Description: This function creates the table in a matrix format with nested for loops, left justifying the numbers, and not causing endlines until the loop is broken. Args: user_num Returns: None. ''' for i in range(1, (user_num + 1)): for j in range(1, (user_num + 1)): print((str(i * j)).ljust(10), end = '') print('') #Title print('MULTIPLICATION TABLE GENERATOR') user_num = int(input('Please enter a number you would like to print a table for: ')) #Calling function and passing value. table(user_num)
true
7dc1f9e2a0e04c95e0b99c9d9f6b89cfec80f24e
puhaoran12/python_note
/11.数据类型转换.py
1,252
4.28125
4
name='张三' age=20 print(type(name),type(age)) #print('我叫'+name+',今年'+age+'岁')#当将str类型与interesting类型连接时,报错。解决方案:类型转换 print('我叫'+name+',今年'+str(age)+'岁')#将int类型通过str()函数转换成str类型 print('-------使用str()函数将其他类型转换成str类型---------') a=10 b=2.2 c=False print(type(a),type(b),type(c)) print(str(a),type(str(a))) print(str(b),type(str(b))) print(str(c),type(str(c))) print('-----使用int()函数将其他的类型转换为int类型--------') s1='123.3' s2=98.4 s3=True s4='77' s5='hello' print(type(s1),type(s2),type(s3),type(s4),type(s5)) #print(int(s1),type(int(s1))) print(int(s2),type(int(s2)))#抹零取整 print(int(s3),type(int(s3))) print(int(s4),type(int(s4))) #print(int(s5),type(int(s5))) #将字符串转换为int类型时,字符串必须是数字串,且不能为小数串 print('---------使用float函数,将其他数据类型转换成float类型-------') s1='123.3' s2=98 s3=True s4='77' s5='hello' print(type(s1),type(s2),type(s3),type(s4),type(s5)) print(float(s1),type(float(s1))) print(float(s2),type(float(s2))) print(float(s3),type(float(s3))) print(float(s4),type(float(s4))) print(float(s5),type(float(s5))) #
false