blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a661836d6a717301fc81f6704de27873d9e9f419
hasanthex/fun-with-python
/python_basic/python_iterators.py
2,515
4.46875
4
# ****************************************************** # ITERATOR IN PYTHON # ****************************************************** # Iterators are everywhere in Python. # They are elegantly implemented within for loops, comprehensions, generators etc. but hidden in plain sight. # Iterator in Python is simply an object that can be iterated upon. # An object which will return data, one element at a time. # Python iterator object must implement two special methods: __iter__() and __next__(), collectively called the iterator protocol. # An object is called iterable if we can get an iterator from it. Most of built-in containers in Python like: list, tuple, string etc. are iterables. # The iter() function (which in turn calls the __iter__() method) returns an iterator from them. print('=============================================') # Python For Loop result_1, result_2 = '','' input = "ABCDEFG" for char in input: result_1 = result_1+' '+char print'Result By For Loop: ',result_1 print('=============================================') # Python Iterator list = iter(input) print'Type is: ',type(list) while True: try: result_2 = result_2+' '+next(list) except StopIteration: break print'Result By Iterator Object:',result_2 print('=============================================') # Create Own Iterator class PowerOfTwo: def __init__(self,limit=0): self.limit = limit def __iter__(self): self.start = 0 return self def __next__(self): if self.start <= self.limit: result = 2 ** self.start self.start += 1 return result else: raise StopIteration obj = PowerOfTwo(3) it = iter(obj) print it.__next__() print it.__next__() print it.__next__() print it.__next__() # We just have to implement the methods __iter__() and __next__(). # The __iter__() method returns the iterator object itself. If required, some initialization can be performed. # The __next__() method must return the next item in the sequence. # On reaching the end, and in subsequent calls, it must raise StopIteration. print('=============================================') # ********************************************** # OUTPUT WILL BE ABOVE CODE # ********************************************** ============================================= Result By For Loop: A B C D E F G ============================================= Type is: <type 'iterator'> Result By Iterator Object: A B C D E F G ============================================= 1 2 4 8 =============================================
true
c2e331eb3c5e3650cd17e4213123bf13f644dbf0
Shockn/FC_2019-02
/lista2_ex014.py
401
4.21875
4
'''Faça um programa que calcule o valor de PI pela soma dos n primeiros termos da série abaixo: raíz ( 12 * (1 - 1/4 +1/9 - 1/16 + 1/25 - 1/16 ... )''' import math def pi(n): pi=0 for i in range(1, n+1): if i%2==0: pi-=1/(i**2) else: pi+=1/(i**2) pi=pi*12 pi=math.sqrt(pi) return(pi) n=int(input('Digite um n: ')) print('Pi: ', pi(n))
false
e1b1bb12f984925d4a015d04637bac7caab33cf4
YS-Avinash/Python-programming
/functionUsingString.py
387
4.59375
5
#Python function to add 'ing' at the end of a given string and return the new string. #If the given string already ends with 'ing' then add 'ly'. #If the length of the given string is less than 3, leave it unchanged. def add_string(str1): return str1 if len(str1)<3 else str1+"ly" if str1.endswith("ing") else str1+"ing" string=input("Enter a string : ") print(add_string(string))
true
973522d56fd1a6083522a66ec6f8873683ef2840
shariqueking/pyscripts
/battleship.py
1,770
4.1875
4
from random import randint board = [] for x in range(5): board.append(["O"] * 5) # creats 5x5 matrics def print_board(board): for row in board: print(" ".join(row)) #use to replace , with " " print("Let's play Battleship!") print_board(board) def random_row(board): return randint(0, len(board) - 1) #give random value of rows def random_col(board): return randint(0, len(board[0]) - 1) #give random value of column ship_row = random_row(board) ship_col = random_col(board) print (ship_row) #printing the ship_col and ship_row print (ship_col) for turn in range(4): # loop which give only 4 turn to player if turn == 3: print("Game Over") else: print("Turn", turn + 1) # display user the count of the turn guess_row = int(input("Guess Row:")) #taking inputs from user guess_col = int(input("Guess Col:")) if guess_row == ship_row and guess_col == ship_col: #checking for win print("Congratulations! You sunk my battleship!") break # if win the break else: if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): #checking for out of range guess print("Oops, that's not even in the ocean.") elif (board[guess_row][guess_col] == "X"): # check already guessed guess print("You guessed that one already.") else: print("You missed my battleship!") board[guess_row][guess_col] = "X" # printing X in place of O ,if guess is wrong print_board(board)
true
813d3c89c6140ae700ba169f3357e048feee465e
Satyam-Bhalla/Python-Scripts
/Python Course/MultiThreading/multiThreading.py
793
4.1875
4
# Python program to illustrate the concept # of threading # importing the threading module import threading def print_cube(num): """ function to print cube of given num """ print("Cube: {}".format(num * num * num)) def print_square(num): """ function to print square of given num """ print("Square: {}".format(num * num)) if __name__ == "__main__": # creating thread t1 = threading.Thread(target=print_square, args=(10,)) t2 = threading.Thread(target=print_cube, args=(10,)) # starting thread 1 t1.start() # starting thread 2 t2.start() # wait until thread 1 is completely executed t1.join() # wait until thread 2 is completely executed t2.join() # both threads completely executed print("Done!")
true
392b8537797cdc5e23af55f4a31169c9c6081c75
Athenian-ComputerScience-Fall2020/greatest-common-factor-ryanabar
/my_code.py
1,102
4.25
4
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # https://www.w3schools.com/python/python_operators.asp # I used the one above to learn what the % operator does (This assingment became a lot easier after I learned that this exists :) # https://www.mathsisfun.com/definitions/modulo-operation.html # I used the one above to actually learn what modulo is because I have never used it before def find_gcf(x,y): # Do not change function name! # User code goes here if x > y: number = y else: number = x for i in range(1, number + 1): if((x % i == 0) and (y % i == 0)): gcf = i return gcf if __name__ == '__main__': # Test your code with this first # Change the argument to try different values x = int(input("Enter a number: ")) y = int(input("Enter another number: ")) print(find_gcf(x,y)) # After you are satisfied with your results, use input() to prompt the user for two values: #x = int(input("Enter a number: ")) #y = int(input("Enter another number: "))
true
bba53f762bd066a9afcb9aaf0ef848a9158b8480
programelu/python-demo
/fundamentals/tuples/simple-tuples.py
1,354
4.5
4
"""tuples may have paranthesys or not""" #tuple with paranthesys, recommanded for redability reasons plane1 = ("Airbus", "319", 200) print(plane1) #tuple without paranthesys - recognized as tuples because comma has been encountered plane2 = "Airbus", "A380", 500 print(plane2) print(plane2[0]) #Tuples with only one element MUST be defined with a comma. Below there is NOT a tuple, it's just a string tup1 = ("Streets of Philadelphia") print(tup1) #Comma MUST be added even if there's only one element! Now we have a tuple as we've added a comma tup1 = ("Streets of Philadelphia",) print(tup1) #access hour minute second and calculate the total seconds in the day from time_tuple = (hour, minute, second) time_tuple = (9, 16, 11) total_sec = time_tuple[0] * 3600 + time_tuple[1] * 16 + time_tuple[2] print(f"Seconds in the day: {total_sec}") #Tuples are immutable! But cotained objects ca be modified student_tuple = ("Amanda", [17, 20 , 22]) print(student_tuple) student_tuple[1][2] = 55 #the list object at position 1 will be modified, it's second element is changed to 55 print(student_tuple) #tuples are immutable, cannot change anything from a tuple but create and assign another value plane2 = "Boeing" ,"777", 380 print(plane2) #THIS CANNOT WORK!!! Cannot assign a value to an item of the tuple - immutability plane2[0] = "Airbus"
true
291453f748f7401fb94920034ee6353af2dbf675
JoseAdrianRodriguezGonzalez/JoseAdrianRodriguezGonzalez
/python/octavo.py
303
4.3125
4
letra = input("Escriba una letra: ") if letra == "a" or letra == "A" or letra == "e" or letra == "E" or letra == "i" or letra == "I" or letra == "o" or letra == "O" or letra == "u" or letra == "U": print(f"La letra {letra} es una vocal") else: print(f"La letra {letra} es una consonante")
false
4ef1f456cf46e7106d53f8ee80f0cac364482a6b
marnovo/lpthw
/exercises/ex07_sd.py
1,470
4.53125
5
# Learn Python the Hard Way # https://learnpythonthehardway.org/python3/ex7.html # Study Drills # 1. Go back through and write a comment on what each line does. # 2. Read each one backward or out loud to find your errors. # 3. From now on, when you make mistakes, write down on a piece of paper what # kind of mistake you made. # 4. When you go to the next exercise, look at the mistakes you have made and # try not to make them in this new one. # 5. Remember that everyone makes mistakes. Programmers are like magicians who # fool everyone into thinking they are perfect and never wrong, but it's all # an act. They make mistakes all the time. # Prints string print("Mary had a little lamb.") # Formats string, replacing the {} with another string, then prints it all print("Its fleece was white as {}.".format('snow')) # Prints string print("And everywhere that Mary went.") # Prints a string (".") a number o times (10) print("." * 10) # what'd that do? # Sets strings to variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens # Prints strings concatenates together with no spaces, besides when end is set print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # Prints strings concatenates together with no spaces, besides when end is set print(end7 + end8 + end9 + end10 + end11 + end12)
true
853d68f2b53695d4e623e66000b7a93f226d5d32
luyihsien/leetcodepy
/Lincode/青銅/846多關鍵排序.py
846
4.40625
4
''' 846. 多关键字排序 中文English 给定 n 个学生的学号(从 1 到 n 编号)以及他们的考试成绩,表示为(学号,考试成绩),请将这些学生按考试成绩降序排序,若考试成绩相同,则按学号升序排序。 样例 样例1 输入: array = [[2,50],[1,50],[3,100]] 输出: [[3,100],[1,50],[2,50]] 样例2 输入: array = [[2,50],[1,50],[3,50]] 输出: [[1,50],[2,50],[3,50]] ''' a=[[3,4,5],[1,2,3],[1,3,2],[3,5,5],[1,10,3]] a.sort(key=lambda x:(x[0],-x[2],-x[1]))#按重要程度排序 print(a) print(type(sorted((123,345,11,0)))) class Solution: """ @param array: the input array @return: the sorted array """ def multiSort(self, array): a=sorted(array,key=lambda x:(-x[1],x[0])) return a # Write your code here print(Solution().multiSort([[3,4],[1,2]]))
false
f9dd60343255a8a25925e5d3633d39c1ad8e24b0
JorgeTranin/Cursos_Coursera
/Curso de Python USP Part1/Exercicios/Func_FizzBuzz.py
740
4.3125
4
''' Escreva a função fizzbuzz que recebe como parâmetro um número inteiro e devolve 'Fizz' se o número for divisível por 3 e não for divisível por 5; 'Buzz' se o número for divisível por 5 e não for divisível por 3; 'FizzBuzz' se o número for divisível por 3 e por 5; Caso o número não seja divisível 3 e também não seja divisível por 5, ela deve devolver o número recebido como parâmetro. ''' def fizzbuzz(n): if n % 3 == 0 and n % 5 == 0: return "FizzBuzz" elif n % 3 == 0 and not n % 5 == 0: return "Fizz" elif n % 5 == 0 and not n % 3 == 0: return "Buzz" else: return n print(fizzbuzz(3)) print(fizzbuzz(5)) print(fizzbuzz(15)) print(fizzbuzz(4))
false
06eb2e35ccbdffa5cdfe571ecb8d2e6eaa10c037
vhngroup/Backend_with_Python_and_Django
/Python_Basico/sring_manage.py
883
4.15625
4
# -*- coding: utf-8 -*- """Como asignar o cambiar el contenido de una variable string""" r='hola' m= 'l' + r[1:] print("El contenido de M es {} y cambio de R que es {}".format(m, r)) """Como recorrer un string y conocer su longitud.""" my_string = 'platzi' my_string [len(my_string)-1] # Se debe restar un valor, para recorrer completo el string. #Manejo de strings en Python name = "platzi" len(name) >>> 6 # devuelve el tamaño del string name.upper() >>> "PLATZI" # convierte a mayusculas name.lower() >>> "platzi" # convierte a minusculas name.find("a") >>> 2 # devuelve la posicion name.join(['hola ',' vamos ', ' a aprender']) >>> "hola platzi vamos platzi a aprender" #ingresa dentro de [] caracteres que seran insertados entre cada string name2 = "nunca pares de aprender" name2.split() >>> ['nunca', 'pares', 'de', 'aprender'] #devuelve en un array el string separada por grupos```
false
5a73e4c50f77dcdda03dc5765f96e9a8173ed643
AlbertMukarsel/Pico-y-Placa
/restrictions.py
1,566
4.1875
4
from datetime import datetime import utilities def restrictionDays(date, licensePlate): """ Each day is represented by a number, Monday=0...Sunday-6 during weekdays, according to each day, if a license plate has one of those digits as its last one, is subject to the Pico y Placa restrictions I.E: on Mondays, a car with its license plate ending on 1 or 2 is subject to restrictions """ plateNumbersPerDay={ 0:[1,2], 1:[3,4], 2:[5,6], 3:[7,8], 4:[9,0], 5:[], 6:[]} day=datetime.strptime(date, '%d/%m/%Y').weekday() if day == 6 or day == 7: return False else: dayRestrictions=plateNumbersPerDay[day] #Gets the plate's last digits that cannot be on the road acording to day lastDigit=licensePlate[-1] #Get the input plate's last digit to check if is allowed or not to be on the road if lastDigit in dayRestrictions: return True else: return False def restrictionHours(time): restrictedHours={ "AM":["7:00","9:30"], "PM":["16:00","19:30"]} hour=datetime.strptime(time, "%H:%M").time() AMRestrictionStartTime, AMRestrictionEndTime = utilities.getRestrictionHours(restrictedHours["AM"]) PMRestrictionStartTime, PMRestrictionEndTime = utilities.getRestrictionHours(restrictedHours["PM"]) if AMRestrictionStartTime <= hour <= AMRestrictionEndTime: return True if PMRestrictionStartTime <= hour <= PMRestrictionEndTime: return True return False
true
d7267185a20504fb7f42e68f71753c8d8b274208
pekasus/randomMusicPlayer
/file_renamer.py
724
4.15625
4
// File Renamer // By: pekasus // CC by 3.0 // This program will rename all files that end in .mp3 within a folder. import os songlist = "songlist.txt" i = 1 with open(songlist, 'w') as fout: fout.write("Legend of Songs\n\n"); fout.close() for filename in os.listdir('/Volumes/musbox'): if filename.lower().endswith(".mp3"): with open(songlist, 'a') as fout: fout.write( str(i) + ". ") fout.write(filename + "\n") fout.close print str(i) + ": " + filename newfilename = str(i) + ".mp3" # print filename + " / " + newfilename os.rename(filename, newfilename) i += 1 print (os.path.dirname(os.path.abspath(__file__)))
true
32cf9ccecb1f2027e2bb47903a27831b1ebbf653
I7RANK/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
1,468
4.21875
4
#!/usr/bin/python3 """contains the island_perimeter function """ def island_perimeter(grid): """returns the perimeter of the island described in grid: ♪ 0 represents a water zone ♪ 1 represents a land zone Args: grid (list of lists): the grid Returns: int: the perimeter of an island """ perimeter = 0 x = len(grid[0]) y = len(grid) for i in range(y): for j in range(x): if grid[i][j] == 1: """ up """ try: if (i - 1) < 0: perimeter += 1 elif grid[i-1][j] == 0: perimeter += 1 except IndexError: perimeter += 1 """ down """ try: if grid[i+1][j] == 0: perimeter += 1 except IndexError: perimeter += 1 """ left """ try: if (j - 1) < 0: perimeter += 1 elif grid[i][j - 1] == 0: perimeter += 1 except IndexError: perimeter += 1 """ right """ try: if grid[i][j+1] == 0: perimeter += 1 except IndexError: perimeter += 1 return perimeter
true
dad3c543d9682d90203cf189bdfad552d1b46a4a
idcrypt3/camp_2019_07_28
/Caelan/Loops.py
736
4.1875
4
number_of_leaves = 14 for x in range(0, number_of_leaves): print("A leaf fell to the ground " + str(x) + " leaves have fallen.") print("All the leaves fell. For loop complete.") on_roller_coaster = True while on_roller_coaster: print("Ahhh!") on_roller_coaster = False times_to_repeat = 5 for x in range(0, times_to_repeat): print(x) for x in range(0, 10): if x == 2: continue print(x) #While loop example on_roller_coaster = True while on_roller_coaster: print("Ahhh!") on_roller_coaster = False #For loop example for x in range(0, 10): print(x) #Break example while True: break #Continue example for x in range(0, 10): if x % 2 == 0: continue print(x)
true
aef1d5641801ee27aadbd8b4bf3dd97a4357eb50
code-in-the-schools/NestedCompoundConditionals_KidirTorain
/main.py
414
4.28125
4
#part1 for i in range(0,5): print(i) print("outer for loop | i :") for j in range(0,5): print("outer for loop | i : inner for loop | j :) #part2 for b in range(0,9): i = ("2,4,6,8") j = ("2,4,6,8") print(i,j) print("these are both even") #part3 for b in range(0,9): i = ("1,3,5,7,9") j = ("1,3,5,7,9") print(i,j) print("these are both odd") print("enter a character...") print("enter a length...")
false
4ff05fbda02740f66a714f0382a47381e237c42e
natterra/python3
/Modulo1/exercicio028_2.py
570
4.28125
4
# Exercício Python 28: Escreva um programa que faça o computador “pensar” em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. from random import randint numpc = randint (0, 5) print("-=-"*20) print("Vou pensar em um número entre 0 e 5. Tente adivinhar...") print("-=-"*20) num = int(input("Em que número pensei? ")) print(f"Eu escolhi {numpc}.") if num == numpc: print("Você venceu!") else: print("Você perdeu!")
false
92f997ab011fe388d96fa2cfc88eb804ec32ea5b
natterra/python3
/Modulo1/exercicio009_2.py
276
4.125
4
#Exercício Python 9: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada. n = int(input("Digite um número: ")) i = 0 print("--------------") while i < 10: i += 1 print("{:2} x {:2} = {:2}".format(n, i, n*i)) print("--------------")
false
c722a50ea46cfcf03b2011373f7371361528d632
skhatri/pylearn
/week1/2_temp_conv.py
830
4.1875
4
""" Convert the given temparature in Celcius to Farenheit """ #your friend came from America. you find temperature for him #37.5 Celcius is 99.5% Farenheit C = 37.5 #F = ? #we know F = 9/5 * C + 32 F = 9 / 5 * C + 32 print F #89.6 F = 9 * 1.0 / 5 * C + 32 print F #types of names/variables print type(5) print type(4.0) print type("My name is Suresh") #convert from one type to next #using str(), int() or float() x = 4 y = float(x) z = str(x) print x, type(x) print y, type(y) print z, type(z) #Now you go to America. #Exercise convert a F into Celcius using the above formula. Hint you need to find C this time. #Find the 6^5 using two different ways. Store the result into 2 different names. Print the result #29F to C #rounds down as it looses the decimal part of the number print int(13.89) print int(1.9999)
true
4dd1d72ede3982aea33d067324950c8345cdee6e
wenqitoh/Recipe-Moderniser
/03_find_scale_factor_v2.py
915
4.34375
4
"""Ask user for number of servings in recipe and number of servings desired and then calculate the scale factor Version 2 - uses number checking function to ensure input is a number Created by Wen-Qi Toh 28/6/21""" # number checking function # gets the sale factor - which must be a number def num_check(question): error = "You must enter a number more than 0" valid = False while not valid: try: response = float(input(question)) if response <= 0: print(error) else: return response except ValueError: print(error) # get serving size serving_size = num_check("How many servings does the recipe make?") # get desired number of servings desired_size = num_check("How many servings needed?") # calculate scale factor scale_factor = desired_size / serving_size print("Scale factor is {}".format(scale_factor))
true
297445e1a3b6886fcb21b73431e723aff27d7efc
unshah/amazon_sales
/sales.py
1,608
4.125
4
# Script to calculate Demand #sold => total products sold (approx.) #rev => total reviews of the product # taking corelation as 1 review per 100 products (ex. rev = 5 || sold = 500) # This is the feature branch !! #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ from datetime import date from tabulate import tabulate #Get the number of reviews per product print("Enter how many reviews the product has: ") rev = int(input()) #Factor which 1 review per f products sold f = 100 #Calculate the approx. sold products sold = f*rev #Get the price for the product print("Please enter the price of the product: ") p = float(input()) #Returns average about 10% ret = (sold/10) swr = sold - ret print("Please enter your per product cost:") cost = float(input()) print("Please enter your per product shipping cost:") sc = float(input()) #Calculate total sales sales = sold*p #With Returns tswr = swr*p tc = (cost*sold)+(sc*sold) profit = tswr - tc print("") today = date.today() print("Date: "+ str(today)) print("") per = (profit/tswr)*100 #Print data print(tabulate([['Approximate qty sold', str(sold)], ['Total sales without returns', str(sales)], ['Average Returns', str(ret)], ['Total sales with returns', str(tswr)], ['Total costs', str(tc)], ['Profit to-date', str(profit), str(per)+' %' ]] , headers=['Statistics', '','Percentage'], tablefmt='orgtbl'))
true
35813bb247e0ee95679723b7cd07a8fe3a1e518b
zhangshv123/superjump
/interview/facebook/mid/LC494_Target Sum.py
1,269
4.1875
4
#!/usr/bin/python """ You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3. Note: The length of the given array is positive and will not exceed 20. The sum of elements in the given array will not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer. http://www.cnblogs.com/grandyang/p/6395843.html """ from collections import defaultdict class Solution(object): def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ dp = [defaultdict(int) for _ in range(len(nums) + 1)] dp[0][0] = 1 for i in range(1, len(nums) + 1): for value, time in dp[i-1].items(): dp[i][value - nums[i-1]] += time dp[i][value + nums[i-1]] += time return dp[len(nums)][S]
true
0e9fb15850ffdefc0b94074e8694a2888a85cc0c
zhangshv123/superjump
/interview/google/mid/LC417. Pacific Atlantic Water Flow.py
2,026
4.15625
4
""" Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower. Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. Note: The order of returned grid coordinates does not matter. Both m and n are less than 150. Example: Given the following 5x5 matrix: Pacific ~ ~ ~ ~ ~ ~ 1 2 2 3 (5) * ~ 3 2 3 (4) (4) * ~ 2 4 (5) 3 1 * ~ (6) (7) 1 4 5 * ~ (5) 1 1 2 4 * * * * * * Atlantic Return: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). """ class Solution: def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if len(matrix) == 0: return [] M, N = len(matrix), len(matrix[0]) pacific = [[False for _ in range(N)] for _ in range(M)] atlantic = [[False for _ in range(N)] for _ in range(M)] def dfs(i, j, height, visited): if i < 0 or i >= M or j < 0 or j >= N or visited[i][j] or matrix[i][j] < height: return else: visited[i][j] = True for di, dj in [(1, 0), (-1, 0), (0, -1), (0, 1)]: dfs(i + di, j + dj, matrix[i][j], visited) for i in range(M): dfs(i, 0, 0, pacific) dfs(i, N - 1, 0, atlantic) for j in range(N): dfs(0, j, 0, pacific) dfs(M - 1, j, 0, atlantic) res = [] for i in range(M): for j in range(N): if pacific[i][j] and atlantic[i][j]: res.append((i, j)) return res
true
ceb685395799009e79f74f6bd2d7f6977d5a3395
zhangshv123/superjump
/interview/others/easy/LintCode Insert Node in a Binary Search Tree.py
1,056
4.15625
4
""" Given binary search tree as follow, after Insert node 6, the tree should be: 2 2 / \ / \ 1 4 --> 1 4 / / \ 3 3 6 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ always insert at the leave """ class Solution: """ @param root: The root of the binary search tree. @param node: insert this node into the binary search tree. @return: The root of the new binary search tree. """ def insertNode(self, root, node): # write your code here if root == None: return node cur = root while cur != node: if cur.val < node.val: if cur.right == None: cur.right = node cur = cur.right elif cur.val >= node.val: if cur.left == None: cur.left = node cur = cur.left return root
true
22784fc51726e32b5c14739dda4195063824e0d5
zhangshv123/superjump
/interview/facebook/easy/LC461_477_Hamming Distance.py
2,199
4.53125
5
#!/usr/bin/python """ The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def toBit(self, x): """ Just to explain the parts of the formatting string: {} places a variable into a string 0 takes the variable at argument position 0 : adds formatting options for this variable (otherwise it would represent decimal 6) 08 formats the number to eight digits zero-padded on the left b converts the number to its binary representation """ return '{0:031b}'.format(x) def hammingDistance(self, x, y): """ Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. """ return sum(el1 != el2 for el1, el2 in zip(self.toBit(x), self.toBit(y))) """ follow up: The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array are in the range of 0 to 10^9 Length of the array will not exceed 10^4. """ def totalHammingDistance(self, nums): return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums)))
true
9f08f217111cb664d37b42416a496c61a09b85b4
itsHuShihang/PythonBeginner
/data_type/tuple.py
307
4.40625
4
t=(1,2,3,4,5,6) ''' the methods of tuple are the same as the methods of list, but the elements in a tuple cannot be changed you cannot delete the elements of a tuple but you can use del to delete the whole tuple ''' # convert list to tuple l = [1, 2, 3, 4, 5] print(type(l)) l2t = tuple(l) print(type(l2t))
true
282cc5a7d9243d2fd1a1a429ec296f0b224d1c89
JamesWJohnson/TruckCapeProjects
/02_Better_Hello_World/better_hello_world.py
731
4.375
4
#!/usr/bin/env python3 # OK, now we're going to do a slightly more complicated Hello World # First, declare two variables. # Here, declare one called print1 with the value "Hello, world!" # Now here, declare another one called print2 with the value "Nice to see you!" # This bit here is called a loop. It executes a block of code multiple times for i in range(10): #Notice how a line that begins a block ends with a colon. if (i % 2) == 0: #print print1 here. Line the function call up with this comment else: #print print2 here # You had to line up the function calls because python uses spaces to group # code into blocks. This is different from how Arduino uses curly braces to # delimit blocks.
true
9f9150ce977b08fed005a19539ab2862699879c2
nickfuentes/Python-Practice
/python/car_dealer.py
605
4.125
4
cars = [] # creating the Car class class Car: # constructor or initializer def __init__(self, make, model, color): self.make = make # set property make to the arguement make self.model = model self.color = color # Passing self makes the the drive function availble to thte Car Objects def drive(self): print("Driving the car") make = input("Enter make: ") model = input("Enter model: ") car = Car("Toyota", "Corrola", "Black") #car.make = make #car.model = model cars.append(car) print(cars) # drive the car, calling the drive car class # car.drive()
true
56835ed8a04a33fb8fc2f08b4937244cbc34b99c
sandroormeno/taller-de-python
/bloque 6/funcion_factorial.py
265
4.125
4
def factorial(n): j = 1 for i in range(1, int(n)+1): # más uno para contar con le número j = j * i print("Factorial: " + str(j)) print("Programa para calcular el factorial de un número.") numero = input("Ingrese un número: ") factorial(numero)
false
06b03068025264b0598e9b5b4dd7ad081fd2b983
akashrajput25/Python
/tkintler_gui/positioning_app.py
262
4.15625
4
#using GRID System , positioning from tkinter import * root =Tk() myLabel1 = Label(root , text="Hello World").grid(row=0 ,column = 0) # positioning on screen and creating a label widget myLabel2 = Label(root , text="Its Akash").grid(row=2 ,column = 1) root.mainloop()
true
13efaaf294755f28b21cb1592e8299127eb7d34d
ishantk/GW2019B
/venv/Session3B.py
367
4.25
4
# Read Data from User and store it in a container data = input("Enter some data: ") print("You Entered:",data) print("Type of data is:",type(data)) num1 = int(input("Enter Number 1: ")) num2 = int(input("Enter Number 2: ")) num3 = num1 + num2 # print("num3 is: ",num3) print("sum of",num1,"and",num2,"is:",num3) print("sum of {} and {} is {}".format(num1,num2,num3))
true
47d67710dd4a6ca5587fae426aaeda209bebbd79
Bakley/effective-journey
/Chapter 7/Exercise7_3.py
556
4.21875
4
""" Write a function named test_square_root that prints a table. The first column is a number, a; the second column is the square root of a computed with the function from Exercise 7.2; the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates. """ def test_square_root(a): for num in range(1, a): x = num print(x) y = (x + a / x) / 2 if y == x: break x = y print(num, x) test_square_root(10) print('done')
true
641e4ba23f7c96415d09e39280320fd20b700544
Konstantine616/1_lesson
/practice_5.py
2,037
4.21875
4
# Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма # (прибыль — выручка больше издержек, или убыток — издержки больше выручки). # Выведите соответствующее сообщение. # Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). # Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. while True: income = input('Введите значение выручки фирмы: ') if income.isdigit(): income = int(income) break else: print('Необходимо ввести число.') while True: costs = input('Введите значние издержек фирмы: ') if costs.isdigit(): costs = int(costs) break else: print('Необходимо ввести число.') if income > costs: profit = income - costs while True: workers = input('Введите количество сотрудников в компании: ') if workers.isdigit(): workers = int(workers) break else: print('Необходимо ввести число.') print(f'Фирма работает с прибылью {profit} rub.\n' f'Соотношение прибыли к выручке {profit/income*100:.2f}%\n' f'Прибыль фирмы в расчете на одного сотрудника {profit/workers:.2f} rub') else: print(f'Фирма работает в убыток {costs - income:.2f} rub')
false
d6051b1eb58bf7a4699a30b1be035b828ea2d5d4
nanakiksc/algorithms
/merge_sort.py
1,204
4.15625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- # Sort and count the number of inversions in an array. def sort_count(array): # Return the inversion count and the sorted subarray. n = len(array) if n <= 1: return array, 0 else: mid = n / 2 l_array, left = sort_count(array[:mid]) r_array, right = sort_count(array[mid:]) merged_array, split = merge_count_split_inv(l_array, r_array) return merged_array, left + right + split def merge_count_split_inv(l_array, r_array): # Return the merged array and count the split inversions. merged_array = [] inv_count = 0 while l_array or r_array: if not l_array: merged_array.append(r_array.pop(0)) elif not r_array: merged_array.append(l_array.pop(0)) elif l_array[0] <= r_array[0]: merged_array.append(l_array.pop(0)) else: merged_array.append(r_array.pop(0)) inv_count += len(l_array) return merged_array, inv_count if __name__ == '__main__': array = [] with open('IntegerArray.txt') as fin: for num in fin: array.append(int(num)) print sort_count(array)[1]
true
069541fdcda77eeeda8c09d251dd63d49fe39948
DeathGodBXX/python-programs-code
/4_flexsible_and_not/字符串.py
286
4.15625
4
str1 = "hello,武汉加油,湖北加油,hello" # 查询字符串的字符个数 # print("len查询到的数量:",len(str1)) # 根据索引值去取数据 # print("index索引得到的对应数据:",str1[3]) print("去查询该数据第一次出现的索引值:", str1.index("武汉"))
false
c7aed50707ef05ea820dba0c56625af458fae4c6
DeathGodBXX/python-programs-code
/16_coroutine/iterable_method.py
2,244
4.34375
4
"""迭代器""" """只要具备iter()方法,就是可迭代对象;只要含有iter()和next()方法,就是迭代器。可以使用next方法取值""" from collections import Iterable from collections import Iterator class Diy: def __init__(self): self.names = [] def add_name(self, name): self.names.append(name) # 变成可迭代对象,魔术方法 def __iter__(self): print('Diy().__iter__方法被调用') return DiyIter(self.names) # 如果只传self,无法使用len(self.names),因为传递的是Diy对象,位置参数。引用。打印的是diy对象地址 # 如果传递self.names,这是一个列表,可以使用len() # 1.range()是否是迭代对象 >>__iter__ ,iter() # 2.iter(对象) >>return 返回值 # 3.返回迭代器 >>__iter__,__next__依赖于next方法取值 class DiyIter: # 迭代器 def __init__(self, names): self.start_num = 0 self.names = names # print(names) # print(id(names)) # print(self.names) # print(id(self.names)) def __iter__(self): print('DiyIter().__iter__方法被调用') return self def __next__(self): # 自带循环功能 # pass if self.start_num < len(self.names): print('DiyIter().__next__方法被调用') a = self.names[self.start_num] self.start_num += 1 return a else: raise StopIteration # python停止循环的固定方式 man1 = Diy() man1.add_name('赵一') man1.add_name('钱二') man1.add_name('孙三') # print(isinstance(man1, Iterable),end='\n') #迭代对象 man2 = iter(man1) # 迭代器对象 print(isinstance(man2, Iterator)) try: while True: print(next(man2)) except StopIteration: print('\n', 'bobo的波很大') # for i in man1: #for循环的实质:自动执行python内置的iter()方法,next(),自动取值下一个,直到stopiteration。 # print(i) # 迭代对象的iter()方法,迭代器的next()方法 # for i in DiyIter(['张三', '李四', '王五', '赵六']): # 迭代对象的iter()方法,迭代器的next()方法 # print(i)
false
e7b03ec619dcf6d805ac05a51eb9825d33afc2a5
DeathGodBXX/python-programs-code
/13_multithreading/multiple threading in class.py
1,131
4.28125
4
""" 利用类实现多线程任务 """ # import threading # import time # # # class Demo(threading.Thread): # # 必须要有实例方法run,run()固定名称,不可更改 代表线程的启动。 # # 大概是通过main()函数中,t1.start,启动这个run函数,线程启动 # # run方法于线程启动相关 # def run(self): # for i in range(3): # time.sleep(0.8) # print(threading.enumerate()) # # # if __name__ == "__main__": # d1 = Demo() # d1.start() # 线程启动 # time.sleep(3) # print(threading.enumerate()) """**************""" # import threading # import time # # # def demo1(): # print("everything is OK") # # # class Demo(threading): # def run(self): # d1 = threading.Thread(target=demo1) # d1.start() # for i in range(3): # time.sleep(0.8) # print(threading.enumerate()) # # if __name__ == "__main__": # d1 = Demo() # time.sleep(3) # print(threading.enumerate()) # 报错 class Demo(threading): # TypeError: module.__init__() takes at most 2 arguments (3 given)
false
8cd1442a3b9767de97724463ca2272a706061da8
arvakagdi/GrokkingTheCodingInterviews
/GTCI_2Pointers_1/DutchFlag.py
1,203
4.3125
4
''' Problem Statement # Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array. The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists of three different numbers that is why it is called Dutch National Flag problem. Example 1: Input: [1, 0, 2, 1, 0] Output: [0 0 1 1 2] Example 2: Input: [2, 2, 0, 1, 2, 0] Output: [0 0 1 2 2 2 ] ''' def dutch_flag_sort(arr): # all elements < left are 0, and all elements > right are 2 # all elements from >= low < i are 1 left = 0 right = len(arr) - 1 index = 0 while index <= right: if arr[index] == 0: arr[left],arr[index] = arr[index], arr[left] index += 1 left += 1 elif arr[index] == 1: index += 1 else: arr[right],arr[index] = arr[index], arr[right] right -= 1 def main(): arr = [1, 0, 2, 1, 0] dutch_flag_sort(arr) print(arr) arr = [2, 2, 0, 1, 2, 0] dutch_flag_sort(arr) print(arr) main()
true
4866640c3c406ca213973d4d38bbc62f9e6255d5
arvakagdi/GrokkingTheCodingInterviews
/GTCI_BitwiseXOR/1/SingleNumber.py
927
4.15625
4
''' Problem Statement # In a non-empty array of integers, every number appears twice except for one, find that single number. Example 1: Input: 1, 4, 2, 1, 3, 2, 3 Output: 4 Example 2: Input: 7, 9, 7 Output: 9 Solution with XOR # following are the two properties of XOR: It returns zero if we take XOR of two same numbers. It returns the same number if we XOR with zero. So we can XOR all the numbers in the input; duplicate numbers will zero out each other and we will be left with the single number. ''' def find_single_number(arr): x2 = arr[0] for i in arr[1:]: x2 = x2 ^ i return x2 def main(): arr = [1, 4, 2, 1, 3, 2, 3] print(find_single_number(arr)) main() ''' Time Complexity: Time complexity of this solution is O(n) as we iterate through all numbers of the input once. Space Complexity: The algorithm runs in constant space O(1).'''
true
e4f28e42bdcc8911c83dce45f55f203553772a00
arvakagdi/GrokkingTheCodingInterviews
/SlidingWindow/NoRepeatSubstring.py
1,490
4.4375
4
''' Given a string, find the length of the longest substring which has no repeating characters. Example 1: Input: String="aabccbb" Output: 3 Explanation: The longest substring without any repeating characters is "abc". Example 2: Input: String="abbbb" Output: 2 Explanation: The longest substring without any repeating characters is "ab". ''' def non_repeat_substring(str1): win_start = 0 max_len = 0 char_index = {} for win_end in range(0, len(str1)): right_char = str1[win_end] # if the map already contains the 'right_char', shrink the window from the beginning so that # we have only one occurrence of 'right_char' if right_char in char_index: # In the current window, we will not have any 'right_char' after its previous index # and if 'window_start' is already ahead of the last index of 'right_char', we'll keep 'window_start' win_start = max(win_start, char_index[right_char] + 1) # insert the 'right_char' into the map char_index[right_char] = win_end # max length count max_len = max(max_len, win_end - win_start + 1) return max_len #Tests def main(): print("Length of the longest substring: " + str(non_repeat_substring("aabccbb"))) print("Length of the longest substring: " + str(non_repeat_substring("abbbb"))) print("Length of the longest substring: " + str(non_repeat_substring("abccde"))) main()
true
8de4537d4df3a92ecd86ab32f1584d0af5b165f2
arvakagdi/GrokkingTheCodingInterviews
/GTCI_2Pointers_1/3SumCloseToTarget.py
1,583
4.21875
4
''' Problem Statement # Given an array of unsorted numbers and a target number, find a triplet in the array whose sum is as close to the target number as possible, return the sum of the triplet. If there are more than one such triplet, return the sum of the triplet with the smallest sum. Example 1: Input: [-2, 0, 1, 2], target=2 Output: 1 Explanation: The triplet [-2, 1, 2] has the closest sum to the target. Example 2: Input: [-3, -1, 1, 2], target=1 Output: 0 Explanation: The triplet [-3, 1, 2] has the closest sum to the target. Example 3: Input: [1, 0, 1, 1], target=100 Output: 3 Explanation: The triplet [1, 1, 1] has the closest sum to the target. ''' import math def triplet_sum_close_to_target(arr, target_sum): arr.sort() min_diff = math.inf for firstnumindex in range(len(arr)): left = firstnumindex + 1 right = len(arr) - 1 while left < right: curr_sum = arr[firstnumindex] + arr[left] + arr[right] curr_diff = abs(target_sum - curr_sum) if curr_sum == target_sum: return target_sum min_diff = min(min_diff, curr_diff) if curr_sum < target_sum: left += 1 else: right -= 1 return target_sum - min_diff def main(): print(triplet_sum_close_to_target([-2, 0, 1, 2], 2)) print(triplet_sum_close_to_target([-3, -1, 1, 2], 1)) print(triplet_sum_close_to_target([1, 0, 1, 1], 100)) print(triplet_sum_close_to_target([-1, 1, -2, 2], 0)) main()
true
724e0b4c178b08a32c7cfe2a1c3fb332062048b2
rsamhollyer/Week-1-Algo-Challenge
/earlierPyAlgos/indicesums.py
1,328
4.125
4
#3. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # You can return the answer in any order. # Examples and clarification here: https://leetcode.com/problems/two-sum/ some_list = [1,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2] target = 3 #soultion should be indices [0,1] def sum_of_indices(arr,n): new_list = list(set(arr)) #this removes duplicate values this_is_list = [] #this will be my returned list of indices for number1 in new_list: for number2 in new_list:#nested loops to loop over all values if number1 != number2: #don't want to check the same number sum_list = [] #initialized each time loop is run sum_list.extend([number1, number2]) # exted the list sum_list = sum(sum_list) #sum list if sum_list == n: #check if list meets target value print(sum_list) this_is_list.extend([some_list.index(number1), some_list.index(number2)]) #when it does, extend the list with the indices of orig list print(this_is_list) return this_is_list sum_of_indices(some_list,target)
true
0ac0b0cc92209e998a6d1ba8210ffbcf4cb2700a
soumikchaki/coursera-py4e
/p2-python-data-structure/week4/a1-string-order.py
632
4.34375
4
# Open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split() method. # The program should build a list of words. For each word on each line check to see if the word is already in the list # and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. fname = input("Enter file name: ") fh = open(fname) lst = list() count = 0 for line in fh: pieces = line.rstrip().split() for piece in pieces: if not piece in lst: lst.append(piece) count = count+1 lst.sort() print(lst)
true
97d1d59e3fb09d918d6d9dc5510fb876d3fc0822
abhishekjee2411/python_repos_novice
/2_odd_even_div.py
1,165
4.25
4
#-------------------------------------------------------------# print ("------------------------------------------------------------") #-------------------------------------------------------------# nbr = int(input("Enter a number: ")) if (nbr%2 == 0): print ("The number is even!") if (nbr%4 == 0): print ("It is also a multiple of 4!") else: print ("It is not a multiple of 4!") else:print ("The number is odd!") #-------------------------------------------------------------# print ("------------------------------------------------------------") #-------------------------------------------------------------# print ("Checking number 1 (check)'s divisibility by number 2 (num)!") check = int(input("Enter a number (check): ")) num = int(input("Enter another number (num): ")) if (check%num == 0): print("The number "+str(check)+" is evenly divided by "+str(num)+"!") else: print("The number "+str(check)+" is not evenly divided by "+str(num)+"!") #-------------------------------------------------------------# print ("------------------------------------------------------------") #-------------------------------------------------------------#
true
a607c7b2ea1f032032c96e8e4e17067a3741bd72
isrdoc/snit-hr-wd1-python-basics
/08_Introduction_to_Python_and_variables.py
309
4.1875
4
message = "Hello" user_name = input("Please enter your name: ") user_age = int(input("Please enter your age: ")) is_user_logged_in = False if message == "Hello": print(message + " " + user_name) print("Your age is: " + str(user_age - 10)) print("User is logged in.") print("After conditional")
true
b688a5a651d9c9e26a5bdeec19b4827759d1b919
Youbornforme/Python9.HW
/hw9.py
1,954
4.15625
4
#Задача 1. Курьер #Вам известен номер квартиры, этажность дома и количество квартир на этаже. #Задача: написать функцию, которая по заданным параметрам напишет вам, #в какой подъезд и на какой этаж подняться, чтобы найти искомую квартиру. room = int(input('Введите номер квартиры ')) # кол-во квартир floor = int(5) # кол-во этажей roomfloor = int(3) # кол-во квартир на этаже c = floor * roomfloor # кол-во квартир в подъезде x = room // c y = (x + 1) # узнаём в каком подъезде квартира z = room % c d = z // roomfloor s = (d + 1) # узнаём на каком этаже print(str(y) + ' Подъезд') print(str(s) + ' Этаж') # Задача 2. Бриллиант # Входным данным является целое число. Необходимо: # • написать проверку, чтобы в работу пускать только положительные нечетные числа # • для правильного числа нужно построить бриллиант из звездочек или любых других символов и вывести его в консоли. #Для числа 1 он выглядит как одна взездочка, для числа три он выглядит как звезда, потом три звезды, потом опять одна, для пятерки - звезда, три, пять, три, одна... total = int(input()) if total %2==1: for i in range(total + 1): up = total - i print (' ' * up + '* ' * i) for i in range(total-1, 0, -1): down = total - i print(' ' * down + '* ' * i)
false
ae8b14f07eff5b367d74c440e58b64bce4fc4899
ManassaVarshni/ProjectEuler
/Problem9.py
747
4.375
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def pythagoreanTriplet(n): # If the triplets are in sorted order. # The value of first element in the triplet will be at-most n/3. for i in range(1, int(n / 3) + 1): # The value of second element will be less than equal to n/2 for j in range(i + 1, int(n / 2) + 1): k = n - i - j if (i * i + j * j == k * k): print(i, ", ", j, ", ", k, sep = "") return i*j*k print("No Triplet") n = 1000 print(pythagoreanTriplet(n))
true
09248cd9bc40e1cfcb6ddad885b28c8ca41c9f9f
lingler412/UDEMY_PYTHON
/factorial_for_loop.py
516
4.53125
5
my_num1 = int(input("Give me a number so I can give you it's factorial! ")) # give me a whole integer def calc_factorial(my_num): # here is a function to caluate the factorial of the provided integer for num in range(my_num - 1, 1, -1): my_num *= num return my_num my_factorial = calc_factorial(my_num1) # calling my function with user input as my argument print("The factorial of " + str(my_num1) + " is " + str(my_factorial)) # printing my original user input along with my calulated factorial
true
66ced30141bf401a6446557ad4f066d0fb69d2ec
James-Ashley/python-challenge
/PyBank/main.py
2,812
4.375
4
# * In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. You will give a set of financial data called [budget_data.csv](PyBank/Resources/budget_data.csv). The dataset is composed of two columns: `Date` and `Profit/Losses`. (Thankfully, your company has rather lax standards for accounting so the records are simple.) # * Your task is to create a Python script that analyzes the records to calculate each of the following: # * The net total amount of "Profit/Losses" over the entire period # * The average of the changes in "Profit/Losses" over the entire period # * The greatest increase in profits (date and amount) over the entire period # * The greatest decrease in losses (date and amount) over the entire period # * As an example, your analysis should look similar to the one below: # * The total number of months included in the dataset # ```text # Financial Analysis # ---------------------------- # Total Months: 86 # Total: $38382578 # Average Change: $-2315.12 # Greatest Increase in Profits: Feb-2012 ($1926159) # Greatest Decrease in Profits: Sep-2013 ($-2196167) # ``` # * In addition, your final script should both print the analysis to the terminal and export a text file with the results. import os import csv budget_data = os.path.join("Resources" , "budget_data.csv") with open (budget_data, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter = ',') header = next(csvreader) delta = [] prevMonth = 0 totalMonths = [] monthsList = [] greatestIncrease = 0 greatestDecrease = 0 increaseIndex = 0 decreaseIndex = 0 for row in csvreader: totalMonths.append(int(row[1])) monthsList.append(row[0]) months = len(totalMonths) profitsTotal = sum(totalMonths) if prevMonth == 0: prevMonth = int(row[1]) else: delta.append(int(row[1])-prevMonth) prevMonth = int(row[1]) avgDelta = sum(delta) / len(delta) greatestIncrease = max(delta) greatestDecrease = min(delta) increaseIndex = delta.index(greatestIncrease) decreaseIndex = delta.index(greatestDecrease) #final script analysisText = (f""" Financial Analysis --------------------------------- Total Months: {months} Total: $ {profitsTotal} Average Change: ${round(avgDelta, 2)} Greatest Increase in Profits: {monthsList[increaseIndex+1]} (${greatestIncrease}) Greatest Decrease in Profits: {monthsList[decreaseIndex+1]} (${greatestDecrease}) """) print(analysisText) #final text output file = os.path.join("analysis", "PyBank_Results.txt") with open (file, 'w') as text: text.write(analysisText)
true
28f51d47018af7c2690031e68529309897cb22ca
pradhanmanva/PracticalList
/pr4.py
298
4.28125
4
# WAP to calculate the area of the triangle side1 = 10 side2 = 6 side3 = 8 semi = (side1 + side2 + side3) / 2 area = (semi * (semi - side1) * (semi - side2) * (semi - side1)) ** (1 / 2) print("Area of the triangle with sides "+str(side1)+", "+str(side2)+" and "+str(side3)+" : "+str(area)+". ")
false
db5211eb8eefe9534af15e817d427204aa2b75e6
Azurick05/Ejercicios_Nate_Academy
/Tabla_de_multiplicar/Tabla_de_multiplicar_for.py
408
4.125
4
numero_multiplicar = int(input("Introduzca el numero a multiplicar: ")) primer_numero = int(input("Introduzca el primer numero del rango: ")) segundo_numero = int(input("Introduzca el segundo numero del rango: ")) for multiplo in range(primer_numero,segundo_numero + 1): print("{} x {} = {}".format(numero_multiplicar, multiplo, numero_multiplicar*multiplo)) print("Se ha acabado la multiplicacion." )
false
03ec30cab8a1c75770778442464c785ea5359562
Ahm36/pythonprograms
/CO1/program17.py
261
4.40625
4
dict={ "ABC":101, "BCS":999, "JKL":888, "IHG":897, "XYZ":345, "MKF":998 } print("Ascending order") for i in sorted(dict.keys()): print(i,dict[i]) print("Descending order") for i in sorted(dict.keys(),reverse=-1): print(i,dict[i])
false
282454d642780f4441398a592aed122eaff363a2
ronmarian7/TAU-HW-Python
/EX7/ex7_316593839.py
2,876
4.4375
4
""" Exercise #7. Python for Engineers.""" ######################################### # Question 1 - do not delete this comment ######################################### class Beverage: def __init__(self, name, price, is_diet): self.name = name self.price = price self.is_diet = is_diet if price < 0: raise ValueError('Price must be greater the 0') def get_final_price(self, size='Large'): if size == 'XL': return self.price * 1.25 elif size == 'Normal': return self.price * 0.75 elif size == 'Large': return self.price else: raise ValueError("We don't have your beverage size") ######################################### # Question 2 - do not delete this comment ######################################### class Pizza: def __init__(self, name, price, calories, toppings): self.name = name self.price = price self.calories = calories self.toppings = toppings if self.price <= 0: raise ValueError('Price must be greater then 0') if self.calories <= 0: raise ValueError('Calories must be greater then 0') def get_final_price(self, size='Family'): if size == 'XL': return self.price * 1.15 elif size == 'Personal': return self.price * 0.60 elif size == 'Family': return self.price else: raise ValueError("We don't have your pizza size") def add_topping(self, topping, calories, price): if topping not in self.toppings: self.toppings.append(topping) self.price = self.price + price self.calories = self.calories + calories else: raise ValueError(f'{self.name} already contains {topping}') def remove_topping(self, topping, calories, price): if topping in self.toppings: self.toppings.remove(topping) self.price = self.price - price self.calories = self.calories - calories if self.price <= 0: raise ValueError("Price can't be negative ") if self.calories <= 0: raise ValueError("remaining calories must be greater the 0") else: raise ValueError(f'{self.name} does not contain {topping}') ######################################### # Question 3 - do not delete this comment ######################################### class Meal: def __init__(self, beverage, pizza): self.beverage, self.pizza = beverage, pizza def get_final_price(self, beverage_size, pizza_size): return self.beverage.get_final_price(beverage_size) + self.pizza.get_final_price(pizza_size) def is_healthy(self): return self.beverage.is_diet == True and self.pizza.calories < 1000
true
15f3739d21506bd03f1edb911a7ebf3ddf921f03
kangli-bionic/coding-challenges-and-review
/random/random_odd.py
2,048
4.5625
5
""" Input: interval a, b Output: a random odd integer in the range of a to b with equal probability Range is inclusive. Given a random function random(a, b) that returns a random integer in the range of a to b, implement a randomOdd(a, b) function that returns a random odd integer in the range of a to b random.randrange(start, stop [, step]) returns a randomly selected integer from range(start, stop, step) Example: random.randrange(2, 20, 2) would return a random integer between 2 and 20 such as 2, 4, 6, 8...18. But we need to use the provided random() function instead. Notes - you can get always get an odd number by calculating 2 * (num // 2) + 1 - cases possible: a is odd, b is odd a is odd, b is even a is even, b is odd a is even, b is even Example (1, 5) gives 1, 2, 3, 4, 5 (1, 4) gives 1, 2, 3, 4 (2, 5) gives 2, 3, 4, 5 (2, 6) gives 2, 3, 4, 5, 6 - just using the rule 2 * (num // 2) + 1 gives you the following distribution, which isn't what you want 1, 3, 3, 5, 5 1, 3, 5 3, 3, 5, 5 3, 3, 5, 5, 7 - In case 1, you'd need to subtract 1 from a and then call the function again - In case 2, subtract 1 from a and b - In case 3, do nothing - In case 4, subtract 1 from b """ from random import randint from collections import Counter def random(a, b): return randint(a, b) def odd_random(a, b): if a % 2 != 0: if b % 2 != 0: return odd_random(a - 1, b) return odd_random(a - 1, b - 1) if b % 2 == 0: return odd_random(a, b - 1) return 2 * (random(a, b) // 2) + 1 # Testing intervals = [(1, 5), (2, 5), (1, 4), (2, 6)] result = [] for interval in intervals: a, b = interval nums = Counter() for _ in range(1000): num = odd_random(a, b) nums[num] += 1 total = sum(nums.values()) for k, v in nums.items(): nums[k] = v / total result.append(nums) print(result)
true
40455235cf6903ce53d012a8236cde45a90d447e
s2097382/Testing
/Assessment2.py
2,661
4.25
4
#Q1 def student_pass(score1, score2, score3): # Insert your code here passed = False avg = (score1 + score2 + score3)/3 if score1 >= 40 and score2>= 40 and score3 >= 40: passed = True elif avg > 50: if score1>=40 and score2>=40: passed = True elif score1>=40 and score3>=40: passed = True elif score2>=40 and score3>=40: passed = True if passed: print("This student has passed.") else: print("This student has not passed.") student_pass(90,39,39) #Q2 # Create a function that determines whether the given year is a leap year. def is_leap(year): # You should have made this function (leap_year) in a previous problem. year = int(year) if year%4 != 0: leap = False elif year%100 != 0: leap = True elif year%400 != 0: leap = False else: leap = True return(leap) # Create a function to calculate the number of days since 1/1/1901 for a given date. def days_since(day, month, year): days_in_months = [0,31,59,90,120,151,181,212,243,273,304,334,365] days_in_months_leap = [0,31,60,91,121,152,182,213,244,274,305,335,366] days_since = 0 if year == 1901: days_since = days_in_months[month-1]+day-1 else: for y in range(1901,year): if is_leap(y): days_since = days_since + 366 else: days_since = days_since + 365 if is_leap(year): days_since = days_since + days_in_months_leap[month-1]+day-1 else: days_since = days_since + days_in_months[month-1]+day-1 return days_since # Create a function to find the day of the week of the given date. def day_of_the_week(day, month, year): how_many_days = days_since(day, month, year) if how_many_days%7 == 0: day = "Tuesday" elif how_many_days%7 == 1: day = "Wednesday" elif how_many_days%7 == 2: day = "Thursday" elif how_many_days%7 == 3: day = "Friday" elif how_many_days%7 == 4: day = "Saturday" elif how_many_days%7 == 5: day = "Sunday" elif how_many_days%7 == 6: day = "Monday" print(day) day_of_the_week(1, 3, 2016) #Q3 def take_integral(A,x1,x2): A.reverse() integral_list = [0]*len(A) for i in range(0,len(A)): eval_x1 = A[i]*(x1)**(i+1)/(i+1) eval_x2 = A[i]*(x2)**(i+1)/(i+1) integral_list[i] = eval_x2 - eval_x1 integral = round(sum(integral_list),2) return integral print(take_integral([1, 2, 1], 0, 3)) print(take_integral([5, 0, 0, -2, 1], 0, 1))
true
8e8a31015a12aa32887939003918bebf7863a9f6
Leandromaro/python
/Basic/dictionary.py
451
4.125
4
def dictionary_comprehension(letter): planets = {'one': 'Mercury', 'two': 'Venus', 'three': 'Earth', 'four': 'Mars', 'five': 'Jupiter', 'six': 'Saturn', 'seven': 'Uranus', 'eighth': 'Neptune'} planetsFiltered = {key: value for (key, value) in planets.items() if letter in value} print(planetsFiltered) dictionary_comprehension("e")
false
596fa4fbbe7968c0423d042994723b1f7ea104c0
gazelleazadi/INF200-2019-Exersices
/src/ghazal_azadi_ex/ex01/letter_counts.py
418
4.125
4
def letter_freq(txt): txt = txt.lower() letter_new = {} for i in txt: letter_new[i] = txt.count(i) return letter_new # Using Dictionary that holds unique "Key Values" pair. if __name__ == '__main__': text = input('Please enter text to analyse: ') frequencies = letter_freq(text) for letter, count in sorted(frequencies.items()): print('{:3}{:10}'.format(letter, count))
true
9fc95f21fc44b7c73361c27af2a63d5d92504b9c
ricardo-vallejo/cursopython
/tiposNumericos.py
1,473
4.15625
4
#Enteros """ Sin decimales Positivos y negativos o 0 No hay tamaño limite """ numeroEntero = 33 type(numeroEntero) #Booleanos """ True o False Subclase del tipo entero (1, 0) """ verdadero = True falso = False print(verdadero) print(falso) verdNum = int(verdadero) #Se puede convertir el valor booleano a entero falNum = int(falso) print(verdNum) print(falNum) verBool = bool(verdNum) #Se puede convertir el valor entero a booleano falBool = bool(falNum) print(verBool) print(falBool) #Reales """ Punto flotante Estan limitados a 64 bits Signo, exponente y mantisa """ precio = 5.34 print(precio) notacionCientifica = 2.5e-6 print(notacionCientifica) #Decimales """ Punto flotante(mayor precision) Importar: from decimal import Decimal Decimal('valor punto flotante') """ from decimal import Decimal numeroDecimal = Decimal('3.6') print(numeroDecimal) print(0.3 - 0.1 * 3) #Los flotantes no tienen precision print(Decimal('0.3') - Decimal('0.1') * Decimal('3.0')) #Los decimales tienen mayor precision #Fracciones """ Numerador/Denominador Minimo termino Importar: from fractions import Fraction Fraction(numerador,denominador) -numerator -denominator """ from fractions import Fraction fraccion = Fraction(15,5) print(fraccion) print(fraccion.numerator) print(fraccion.denominator) #Complejos """ a + bj - real - imag """ numeroComplejo = 5 + 8j print(type(numeroComplejo)) print(numeroComplejo) print(numeroComplejo.real) print(numeroComplejo.imag)
false
4ec2e53de37a6ab733d7695fbb7952623e655972
Madara701/Python_OO
/Python_OO/built-in.py
403
4.15625
4
''' SobreEscrevendo a maneira de somar em python ''' class MeuInt(int): def __add__(self,num): return 0 a = MeuInt(1) r = a + 2 print(r) ''' SobreEscrevendo o metodo append de lista pra que ele funcione da maneira que eu quiser ou achar necessaria! ''' class MinhaLista(list): def append(self, *args): self.extend(args) l = MinhaLista() l.append(1,2,3,4,5,6,7,8,9,10) print(l)
false
659d64a63c101f2fe07e79dd81410bbdc56206a7
lanchunyuan/Python
/PythonCrashCourse/chapter-4/4-10.py
297
4.3125
4
favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie','sausage'] print(r'The first three items in the list are:') print(favorite_pizzas[:3]) print(r'Three items from the middle of the list are:') print(favorite_pizzas[1:4]) print('The last three items in the list are:') print(favorite_pizzas[-3:])
true
1d9c06fd8df38fdba89467496a77666f71fef83a
Sohaib76/Python-Certified-Cisco
/Assignments/Assignment # 1.py
1,914
4.5625
5
'''1. Write a Python program to print the following string in a specific format (see the output). Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are''' print('''Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!''') print("----------------------------------------------------------") '''2. Write a Python program to get the Python version you are using''' import sys print("Python version") print (sys.version) print("----------------------------------------------------------") '''3. Write a Python program to display the current date and time.''' import datetime now = datetime.datetime.now() print ("Current date and time is : ") print (now.strftime("%Y-%m-%d %H:%M:%S")) print("----------------------------------------------------------") '''4. Write a Python program which accepts the radius of a circle from the user and compute the area.''' from math import pi r = float(input ("Input the radius of the circle : ")) print ("The area of the circle is: " + str(pi * r**2)) print("----------------------------------------------------------") '''5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.''' fname = input("Input your First Name : ") lname = input("Input your Last Name : ") print (lname + " " + fname) print("----------------------------------------------------------") '''6. Write a python program which takes two inputs from user and print them addition''' num1 = float(input("Enter first Number: ")) num2 = float(input("Enter second Number: ")) sum = float(num1) + float(num2) print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
true
77263cee411732ef87a4357e9e6e8f6b14e88fa1
TimTheFiend/Python-Tricks
/pyFiles/2.1_assert.py
1,082
4.375
4
def apply_discount(product, discount): price = int(product['price'] * (1.0 - discount)) """Assert: If this isn't true, throw an exception Assertions are meant to be internal self-checks for you program. They work by declaring some conditions as impossible in your code. If one of these conditions doesn't hold, that means there's a bug in the program. If your program is bug-free, these conditions will never occur. But if they do occur, the program will crash with an assertion error telling you exactly which "impossible" condition was triggered. This makes it much easier to track down and fix bugs in your program. Keep in mind that assert statements is a debugging aid, not a mechanism for handling run-time errors. """ try: assert 0 <= price <= product['price'] except AssertionError: return "The discount is so low we're giving people money to buy them" return price shoes = {'name': 'Fancy shoes', 'price': 14900} foobar = apply_discount(shoes, 1.0) print(foobar)
true
59b11140614aee7f6deece88357000b4118ba2e0
TimTheFiend/Python-Tricks
/pyFiles/5.4_sets_and_multisets.py
2,084
4.40625
4
"""A set is an unordered collection of objects that does not allow duplicate elements. """ # set - your go-to set vowels = {'a', 'e', 'i', 'o', 'u',} print('e' in vowels) # True letters = set('alice') print(letters.intersection(vowels)) # {'i', 'e', 'a'} vowels.add('x') print(vowels) # {'i', 'x', 'u', 'e', 'o', 'a'} print(len(vowels)) # 6 # frozenset - immutable sets vowels = frozenset({'a', 'e', 'i', 'o', 'u'}) try: vowels.add('p') except AttributeError: print("AttributeError: 'frozenset' object has no attribute 'add'") # frozensets are hashable and can be used as dictionary keys: d = { frozenset({1, 2, 3}): 'howdy' } print(d[frozenset({1, 2, 3})]) # howdy # collections.Counter - MultiSets """The collections.Counter class in the python standard library implements a multiset(bag) type that allows elements in the set to have more than one occurrence. Which is useful if you need to keep track of not only if an element is part of a set, but also how many times it is included in the set. """ from collections import Counter inventory = Counter() loot = {'sword': 1, 'The Conquest of Bread': 3} inventory.update(loot) print(inventory) # Counter({'The Conquest of Bread': 3, 'sword': 1}) more_loot = {'jc, a bomb': 1, 'A BOMB?': 3, 'sword': 5} inventory.update(more_loot) print(inventory) # Counter({'sword': 6, 'The Conquest of Bread': 3, 'A BOMB?': 3, 'jc, a bomb': 1}) print(len(inventory)) # (unique items) output: 4 print(inventory.values()) # (total no. of elements) output: dict_values([6, 3, 1, 3]) # Stacks (LIFOs) """New plates are added to the top of the stack. And because the plates are precious and heavy, only the topmost plate can be moved (last-in, last-out) To reach the plates that are lower down in the stack, the topmost plates must be removed one by one. """ # LIFO = Last-In, First-Out # FIFO = First-In, First-Out s = [] s.append('eat') s.append('sleep') s.append('code') print(s) # ['eat', 'sleep', 'code'] s.pop() # 'code' s.pop() # 'sleep' s.pop() # 'eat' try: s.pop except IndexError: print("can't pop from empty list")
true
208171031745565970746e7c7c9ae56bb07d826e
mjmandelah07/assignment1
/assignment_2/question_3.py
458
4.25
4
# Given a list slice it into 3 equal chunks and reverse each chunk sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89] chunk_1 = sampleList[:3] chunk_2 = sampleList[3:6] chunk_3 = sampleList[6:9] print("Original list:", sampleList) print("Chunk 1:", chunk_1) print("After reversing chunk 1:", chunk_1[::-1]) print("chunk 2:", chunk_2) print('After reversing chunk 2:', chunk_2[::-1]) print("chunk 3:", chunk_3) print("After reversing chunk 3:", chunk_3[::-1])
true
462be16865837a4a3d365fe1b524f86a6d706c78
mjmandelah07/assignment1
/question2.py
472
4.15625
4
# Given a range of first 10 numbers, Iterate from start number to the end number and # print the sum of the current number and previous number: # HINT : Python range() function def number(num): previous_num = 0 for a in range(num): sum_num = previous_num + a print("Current Number", a, "Previous Number ", previous_num, " Sum: ", sum_num) previous_num = a print("Printing current and previous number sum in a given range(10)") number(10)
true
e351e024fefa1cd4c15d8495eef7beaecdf2be58
zaiyangliu/theo-code-of-python
/sum_of_even_factorial_numbers_less_than_inputed.py
694
4.125
4
#python 3.6 def fib(num): sum = 0 p1 = 1 p2 = 1 i = 1 result = 0 while result < num: if i >= 1: if result % 2 == 0: sum += result result = p1 + p2 p1,p2 = p2, p1 + p2 print(sum) num = int(input("please input an positive integer\n")) print("the sum of the even factorial numbers less than the number you input\n") fib(num) #python 3.6 using recursion def fib(n): if n == 0 or n == 1: return 1 else: return fib(n - 1) + fib(n - 2) sum = 0 i = 0 num = int(input()) while fib(i) < num: if fib(i) % 2 == 0: sum += fib(i) i += 1 print (sum)
true
b4711eeca831fa811438a36dc1f1cd1dbb1c4c6e
Vaishanavi13/Customer-Segregation-ML
/CustomerSegregation.py
2,272
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd import matplotlib.pyplot as plt #Data Visualization import seaborn as sns #Python library for Visualization # In[3]: #importing dataset dataset = pd.read_csv(r'C:\Users\HP\Downloads\customer-segmentation-dataset\customer-segmentation-dataset\Mall_Customers.csv') dataset.head(10) #Printing first 10 rows of the dataset dataset.info() # In[21]: #Missing values computation dataset.isnull().sum() ### Feature sleection for the model #Considering only 2 features (Annual income and Spending Score) X= dataset.iloc[:, [3,4]].values # In[22]: #KMeans Algorithm to decide the optimum cluster number #to figure out K for KMeans, using ELBOW Method on KMEANS Calculation from sklearn.cluster import KMeans wcss=[] #assuming the max number of cluster would be 10 for i in range(1,11): kmeans = KMeans(n_clusters= i, init='k-means++', random_state=0) kmeans.fit(X) wcss.append(kmeans.inertia_) #inertia_ is the formula used to segregate the data points into clusters # In[23]: #Visualizing the ELBOW method to get the optimal value of K plt.plot(range(1,11), wcss) plt.title('The Elbow Method') plt.xlabel('no of clusters') plt.ylabel('wcss') plt.show() #Model Building kmeansmodel = KMeans(n_clusters= 5, init='k-means++', random_state=0) y_kmeans= kmeansmodel.fit_predict(X) # In[26]: #Visualizing all the clusters plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], marker = "*", s = 100, c = '#bd121a', label = 'Cluster 1') plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], marker = "*", s = 100, c = '#f0a618', label = 'Cluster 2') plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], marker = "*", s = 100, c = '#1d881a', label = 'Cluster 3') plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], marker = "*", s = 100, c = '#20536a', label = 'Cluster 4') plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], marker = "*", s = 100, c = '#d51257', label = 'Cluster 5') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 100, c = 'black', label = 'Centroids') plt.title('Clusters of customers') plt.xlabel('Annual Income (k$)') plt.ylabel('Spending Score (1-100)') plt.legend() plt.show() # In[ ]:
true
4ec9dda57eda5aa185f90a34df487fea45812d8c
aliakseisysa/Intro-into-Python
/Practice_3/Task_3_3.py
532
4.21875
4
#3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def max_func(): var_1 = int(input("Enter the first number: ")) var_2 = int(input("Enter the first number: ")) var_3 = int(input("Enter the first number: ")) my_list = [var_1, var_3, var_2] my_list.sort(reverse=True) my_sum = my_list[0]+my_list[1] return my_sum print(max_func())
false
e8d5b7de3cdf9667a2f0daf87acffb1fea0dfb65
sadofnik/basics_python
/Урок 3. Функции/1.py
700
4.25
4
# 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def calc(a,b): try: return a / b except ZeroDivisionError: return f'На ноль делить нельзя' print(f"{'*'*10} Функция деления {'*'*10}") firstNumber = int(input("Введите делимое: ")) secondNumber = int(input("Введите делитель: ")) print(f'{calc(firstNumber,secondNumber):.2f}')
false
21753658f0d6f829974d6b7bd3f7684061e8effb
MaxwellMensah/Data-Structures-and-Algorithms
/Arrays/11. Slice and Delete from a List.py
1,961
4.46875
4
myList = ['a', 'b', 'c', 'd', 'e', 'f'] print(myList[0:2]) # same as: myList = ['a', 'b', 'c', 'd', 'e', 'f'] print(myList[:2]) # omitting the second elements myList = ['a', 'b', 'c', 'd', 'e', 'f'] print(myList[1:]) # omitting both elements myList = ['a', 'b', 'c', 'd', 'e', 'f'] print(myList[:]) # updating first two elements myList = ['a', 'b', 'c', 'd', 'e', 'f'] myList[0:2] = ["x", "y"] print(myList[:]) # Deleting an element in List using pop() method myList = ['a', 'b', 'c', 'd', 'e', 'f'] myList.pop(1) # ---------> O(n) print(myList) # Without index deletes the last element myList = ['a', 'b', 'c', 'd', 'e', 'f'] myList.pop() # ---------> O(1), sinceit del from the last element so no dragging print(myList) # Deleting an element in List using pop() method myList = ['a', 'b', 'c', 'd', 'e', 'f'] myList.pop(2) # ---------> Time complexity: O(n) ; Space complexity: O(1) print(myList) # Delete() Method myList = ['a', 'b', 'c', 'd', 'e', 'f'] # ---------> Time complexity: O(n) ; Space complexity: O(1) del myList[1] print(myList) myList = ['a', 'b', 'c', 'd', 'e', 'f'] del myList[3] print(myList) # Multiple deletion (deleting more than one element using slicing) myList = ['a', 'b', 'c', 'd', 'e', 'f'] del myList[0:2] # del first two print(myList) myList = ['a', 'b', 'c', 'd', 'e', 'f'] del myList[2:4] # del index two and three print(myList) # Remove() Method; deleting the elements itself without knowing any index myList = ['a', 'b', 'c', 'd', 'e', 'f'] myList.remove('e') # ---------> Time complexity: O(n) ; Space complexity: O(1) print(myList) # since we can delete from the first elements causing the remaining elements to move. # NOTE: You can't slice delete with pop() method and remove. Slicing deletion only works with del function/method
true
867a8f1048850aea8c88748e8b783a0a680b4373
MaxwellMensah/Data-Structures-and-Algorithms
/Dictionary/2. Inserting into a dictionary.py
299
4.34375
4
# Update or Add an element to the dictionary myDict = {'name': 'Edy', 'age': 26} myDict['age'] = 27 # overwrite/changed from 26 to 27. Time Complexity : O(1) print(myDict) # Adding new pairs myDict['address'] = 'London' # Time Complexity : O(1) print(myDict)
true
b6928db4afcdcdb5b2fe405d5033122635a51973
loide/hackerrank
/python/staircase.py
1,055
4.6875
5
""" Consider a staircase of size n = 4: # ## ### #### Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n. Input Format A single integer,n, denoting the size of the staircase. Output Format Print a staircase of size n using # symbols and spaces. Note: The last line must have 0 spaces in it. Sample Input 6 Sample Output # ## ### #### ##### ###### Explanation The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n = 6. """ import math import os import random import re import sys def staircase(n): for i in range(0, n): for j in range(0, n): if (j >= n - i - 1): print("#", end ="") else: print(" ", end="") print("") def main(): number = input("give a number ") number = int(number) staircase(number) if __name__ == '__main__': main()
true
d8181599f70a0eb546c9073177bfdbd67c042763
EvanJamesMG/Leetcode
/python/Array/268. Missing Number.py
759
4.125
4
# coding=utf-8 __author__ = 'EvanJames' ''' Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? ''' ''' 解法非常的巧妙 解法:等差数列前n项和 - 数组之和 真心怀疑自己的智商 ''' class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) return n * (n + 1) / 2 - sum(nums) # if __name__ == '__main__': # res = Solution().majorityElement([1, 2, 3, 2, 2, 2, 7]) # print(res)
true
e98bb4522cd61870e4027eb01c8033388c9ecb3d
SUREYAPRAGAASH09/Unsorted-Array-Exercises
/32.shiftrightleft/shiftrightleft.py
750
4.3125
4
Question : ========== Shift Right Left the element of the array Input : ======= Unsorted Integer Array Output : ======== Unsorted Integer Array but, after shifting right left the element of the array Code : ====== def swapRight(array,shiftValue): temp = 0 iterator = 0 while (iterator2!=shiftValue): iterator = -1 while (iterator!=len(array)): array[iterator],temp = temp,array[iterator] iterator += 1 iterator2 += 1 return array def shiftLeft(array,shiftValue): iterator = 0 while(iterator!=shiftValue): iterator2 = 0 temp = (array[iterator2]) array.remove(array[iterator2]) array.append(temp) iterator+=1 return array
true
e00985f648f9c2e443c89141dd5cf4d1e41eee64
SUREYAPRAGAASH09/Unsorted-Array-Exercises
/39.getIndexafterrotationright/getindexRight.py
491
4.40625
4
#37. Given an unsorted integer array A, # find the value that will be in 3rd position or index after 2 rotations to the right. import Rotateright def getIndexAfterrotationRight(array,index,rotation_value): afterRotation = Rotateright.swapRight(array,rotation_value) return afterRotation[index] #array = [5,7,6,9,2,8] #index = int(input("Enter the index value")) #rotation_value = int(input("Enter the rotation value")) #rint(getIndexAfterrotationRight(array,index,rotation_value))
true
91b2938a08664a245836b94af2410b8a84725f21
SUREYAPRAGAASH09/Unsorted-Array-Exercises
/25.2ndLargestNumber/2ndLagestNumbers.py
397
4.21875
4
Question : ========== Get Second largest number form the list Input : ======= Unsorted Integer Array Output : ======== Integer - Get second largest integer Code : ====== import Max def secondLargestNumber(array): Maximum = Max.Max(array) for iterator in array: if Maximum == iterator: array.remove(iterator) maximum = Max.Max(array) return maximum
true
ebf880df76a00a981c9d0430a0da732cae36fc05
mserevko/sorting-algorithms
/algorithms/bubble_sort.py
757
4.3125
4
""" Bubble sort 1. Looping through list 2. Compares elements of list (list[n] > list[n+1]), swaps them if they are in the wrong order. 3. The pass through the list is repeated until the list is sorted. """ import random import copy randomlist = [random.randint(0,100) for i in range(0, 7)] def bubble_sort(some_list: list): list_to_sort = copy.deepcopy(some_list) for i in range(len(list_to_sort)): for k in range(len(list_to_sort)-1): if list_to_sort[k] > list_to_sort[k+1]: list_to_sort[k], list_to_sort[k + 1] = list_to_sort[k + 1], list_to_sort[k] return list_to_sort print(f"\n --- Sorting list {randomlist} by bubble algorithm --- \n") print("\n --- After sorting", bubble_sort(randomlist))
true
6455740e9b80d0ad3327998842788cd6284ea8c3
EOppenrieder/HW070172
/Homework5/Exercise7_5.py
520
4.25
4
# A program to tell you whether your weight is appropriate def main(): weight = float(input("Please enter your weight in pounds: ")) height = float(input("Please enter your height in inches: ")) BMI = (weight * 720) / (height**2) if BMI > 25: print("You're above the healthy range") elif 19 <= BMI <= 25: print("You're in the healthy range") elif BMI < 19: print("You're below the healthy range") else: print("Please enter a valid height and weight") main()
true
08690352d335dee2c78fb17f9e4be53434a1177f
EOppenrieder/HW070172
/Homework4/Exercise3_17.py
359
4.21875
4
# A program to guess the square root of numbers def main(): x = float(input("Enter the number of which you want to know the square root: ")) n = int(input("Enter the number of times to improve the guess: ")) g = x / 2 for i in range (n): g = (g + x / g) / 2 print(g) import math print (g, ":", (math.sqrt(x) - g)) main()
true
6f06c24cc9eecc85ed6ef6c386520cfcab0eed49
EOppenrieder/HW070172
/Homework3/Exercise11.py
272
4.1875
4
def main(): print("This program converts meter per second (ms)") print ("into kilometers per hour (kmh).") ms = eval(input("Enter your velocity in meter per second: ")) kmh = 3.6 * ms print("Your velocity is",kmh,"kilometers per hour.") main ()
false
6fa21435c58ab7dd564676c274660f01c7236b5f
EOppenrieder/HW070172
/Homework4/Exercise3_3.py
489
4.25
4
# A program to calculate the molecular weight # of a carbohydrate (in grams per mole) def main(): H = int(input("Enter the number of hydrogen atoms: ")) C = int(input("Enter the number of carbon atoms: ")) O = int(input("Enter the number of oxygen atoms: ")) Hweight = 1.00794 Cweight = 12.0107 Oweight = 15.9994 molweight = H * Hweight + C * Cweight + O * Oweight print("The molecular weight of your carbohydrate is", molweight, "grams per mole.") main()
true
7db330f7c85ba02facdaa1c36786e7cdcffde435
EOppenrieder/HW070172
/Homework4/Exercise3_13.py
282
4.125
4
# A program to sum a series of numbers def main(): n = int(input("Enter the amount of numbers that are to be summed: ")) x = float(input("Enter a number: ")) for factor in range(2, n+1): y = float(input("Enter a number: ")) x = x + y print(x) main()
true
6ccc66d54d210e84dfa88b25df787a2035eb6d42
Lakssh/PythonLearning
/basic_learning/exception_handling.py
1,128
4.1875
4
""" Exception Handling Exceptions are errors and should be handled in the code link to python built in exceptions https://docs.python.org/3/library/exceptions.html try: <Function to be written here> except: <Exception block, same as catch in java> else: <executed when there is no exception> finally: <always executed despite of checking exception> """ def exception_handling(a,b,c): try: div = a + b / c print("division is : ", div) except ZeroDivisionError: print("division by zero is not possible") raise Exception("Exception Stack Trace") # print exception trace except TypeError: print("Addition of String is not possible") except: print("Entered into Exception block") else: print("Executed when there is no exception") finally: print("Executed always") print("****"*10+" Happy Path "+"****"*10) exception_handling(10,10,2) print("****"*10+" Type Error for String addition "+"****"*10) exception_handling(10,"String",10) print("****"*10+" With Zero division error "+"****"*10) exception_handling(10,10,0)
true
c996e11bbea73af2ee242abe4ee4fb70f5bee606
PnFTech/CodingInterview
/ch10/python/sorted_merge.py
1,212
4.21875
4
#!/usr/bin/env python ''' Author: Ping Guo Email: pingg104@gmail.com Problem Statement: You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. Example: A = [1, 5, 9] B = [2, 4, 7] C = [6, 9, 22, 34, 87, 98,101] D = [3, 6, 9, 10, 23, 68, 90, 403, 3049] Usage: sorted_merge <A> <B> sorted_merge case1 sorted_merge case2 ''' def answer1(a, b): ''' Function for basic solution to problem Complexity: O(AB) ''' for i, __ in enumerate(b): for j, __ in enumerate(a): if b(i) >= a(j) and b(i) < a(j+1): a.insert(j+1, b(i)) break def answer2(a, b): ''' Function with bookmark to record last insert to improve performance Complexity: O(AB) ''' start = 0 for i, __ in enumerate(b): for j, __ in enumerate(a[start:]): if b(i) >= a(j) and b(i) < a(j+1): a.insert(j+1, b(i)) start = j+1 break def answer3(a, b): [1,3,6,9, 22, 34, 87, 98,101] # executable if __name__ == '__main__': # exectuable import only from docopt import docopt # check CLA args = docopt(__doc__) answer(args['<A>'], args['<B>'])
true
fe407ecfd67c5ca3131c83f28114b644b17ddd11
gakkistyle/comp9021
/Practice_1 solution/span.py
1,566
4.125
4
""" prompts the user for a seed for the random number generator, and for a strictly positive number, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 99, prints out the list, computes the difference between the largest and smallest values in the list without using the builtins min() and max(), prints it out, and check that the result is correct using the builtins. """ from random import seed,randint import sys #Prompts the user for a seed for the random number generator, #and for a strictly positive number,nb_of_elements. try: arg_for_seed = int(input('Input a seed for the random number generator: ')) except ValueError: print('Input is not an integer,giving up.') sys.exit() try: nb_of_elements = int(input('How many elements do you want to generate? ')) except ValueError: print('Input is not an integer,giving up') sys.exit() if nb_of_elements <= 0: print('Input should be strictly positive,giving up') sys.exit() #Generates a list of nb_of_elements random integers between 0 and 99. seed(arg_for_seed) L = [randint(0,99) for _ in range(nb_of_elements)] #Prints out the list, computes the maximum and the minimum of the list,and prints the span out. print('\nThe list is:',L) max_element = 0 min_element = L[0] for e in L: if e > max_element: max_element = e for e in L: if e<min_element: min_element = e span = max_element - min_element print('\nThe maximum difference between largest and smallest values in this list is:',span) print('Confirming with builtin operation:',max(L)-min(L))
true
be88c101b67e060cff923ae719e0f178d9733e64
EmmanuelSR10/Curso-Python
/Curso/Condicionales.py
228
4.15625
4
"""CONDICIONALES""" numero = int (input("Numero:")) if numero > 0: print("El numero es positivo") #siempre poner " : " para identacion elif numero== 0: print("El número es cero") else: print("El numero es negativo")
false
db4c1238f2d9177d3ca1abc7cdb3764c3b937028
EmmanuelSR10/Curso-Python
/Ejercicios_Lista/Ejercicio_2.py
552
4.5
4
""" Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista y la muestre por pantalla el mensaje Yo estudio <asignatura>, donde <asignatura> es cada una de las asignaturas de la lista.""" materias = [] num_materias = int(input("Numero de materias >> ")) for num in range(num_materias): name_materia = input("Materia >> ") materias.append(name_materia) print(f"""Yo estudio {materias}, donde {materias} es cada una de las asignaturas de la lista""")
false
daaa3f43ca4efe6d84bf7ff374be168f791d5c7c
EmmanuelSR10/Curso-Python
/POO/MetodosEspeciales.py
1,138
4.15625
4
"""Métodos especiales y objetos embebidos""" class Fabrica: def __init__(self, tiempo, nombre, ruedas): #def __init__ nos ayuda como método constructor self.tiempo = tiempo self.nombre = nombre self.ruedas = ruedas print("Se creó el auto", self.nombre) def __del__(self): # __del__(self) es el método destructor, "delete" print("Se eliminó el auto", self.nombre) def __str__(self): # __str__(self) nos ayuda con los strings (caracteres) return "{} ({})".format(self.nombre, self.tiempo) #las llaves nos sirve para imprimir usando format # en este caso el nombre y tiempo class listado: autos = [] def __init__(self, autos = []): self.autos = autos def fabricar(self, x): self.autos.append(x) def visualizar(self): for x in self.autos: print(x) ob = Fabrica(10, "Yo", 4) # cuando se pone = es para crear el objeto li= listado([ob]) li.visualizar() # cuando se usa el . es para llamar a una funcion li.fabricar(Fabrica(15, "Otro yo", 2)) li.visualizar()
false
3872ae39b4f089816c8110aad6ab6a188bd765a7
yoonju-baek/Learn-Python-Programming
/1.basics/dictionaries.py
1,953
4.5
4
# Dictionaries - a collection of key-value pairs {key:value} fruit_0 = {'color': 'red', 'shape': 'circle'} print(fruit_0) print(fruit_0['color']) print(fruit_0['shape']) # Adding new key-value fruit_0['price'] = 3 print(fruit_0) # Modifying values fruit_0['color'] = 'yellow' fruit_0['shape'] = 'rectangle' print(fruit_0) # Removing key-value del fruit_0['price'] print(fruit_0) # Looping through a dictionary print("Looping through a dictionary") for key, value in fruit_0.items(): print("\nKey: " + key) print("Value: "+ value) # Looping through all the keys # keys() method can be omit family = {'father': 'david', 'mother': 'jessica', 'brother': 'john', 'sister': 'lily'} print('Family members:') for member in family.keys(): print(member) # Looping through all the values print('Family names:') for name in family.values(): print(name.title()) # Only getting unique values favorite_fruits = {'father': 'apple', 'mother': 'banana', 'brother': 'kiwi', 'sister':'apple'} print('Fruits list:') for fruit in set(favorite_fruits.values()): print(fruit.title()) # A list in a dictionary bubble_tea = { 'tea' : 'green', 'sugar' : 'less', 'ice' : 'normal', 'toppings' : ['cheese cream', 'tapioca'] } print("You ordered a " + bubble_tea['tea'] + " bubble tea with "+ bubble_tea['sugar'] + " sugar and " + bubble_tea['ice'] + " ice. The following toppings :") for topping in bubble_tea['toppings']: print("\t" + topping) # A dictionary in a dictionary customers = { 'john' : { 'firstname' : 'john', 'lastname' : 'smith', 'phone' : '6472031234' }, 'jessica' : { 'firstname' : 'jessica', 'lastname' : 'lane', 'phone' : '6478390274' } } for name, info in customers.items(): print("The information of " + name) print("\tFull name: " + info['firstname'].title() + " " + info['lastname'].title()) print('\tphone number: ' + info['phone'])
true
2cb8c1f3f5fee45e1e7dbde9b44e5a3e9795df8a
yoonju-baek/Learn-Python-Programming
/1.basics/ending_while_loops.py
487
4.4375
4
# User enter 'quit' to end the program prompt = "Tell me something. If you want to end the program, enter 'quit': " message = "" while message != 'quit': message = input(prompt) if message != 'quit': print(message) # Using a flag to end the program prompt = "(Using a flag)Tell me something. If you want to end the program, enter 'quit': " active = True while active: msg = input(prompt) if msg == 'quit': active = False else: print(msg)
true
c393006cc9139f859d46d62873d29e3532f51de7
yoonju-baek/Learn-Python-Programming
/1.basics/conditional operations.py
926
4.3125
4
# Checking the condition of case is case sensitive # Equality: == # Inequality: != # Mathematical comparisons: <, > <=, >= # Multiple conditions: and, or # Strings Comparisons coffees = ['moca', 'espresso', 'americano', 'latte'] for coffee in coffees: if coffee == 'americano': print(coffee.title()) else: print(coffee.upper()) # Numberical Comparisons age = 17 if age == 25: print('Your age is 25') else: print("Your age isn't 25") # Checking multiple conditions age = 25 gender = 'F' if (age > 17) and (gender == 'F'): print('Female adult') else: print('Not female adult') # Checking condition in a list teas = ['green', 'black', 'chai','lemon'] if 'chai' in teas: print('chai is in the list') else: print('chai is not in the list') # Or checking condition using 'not in' if 'chai' not in teas: print('chai is not in the list') else: print('chai is in the list')
true
ed7b1ca37da1bfbbbfdf09f56d3fc8bb860a439d
rahulshukla29081999/python-professional-programming-dsa
/bubble sort.py
664
4.15625
4
# Bubble Sort in Python... #time complexity of bubble sort is O(n^2) #it is a simple comparision based algorithm ... #in this compare two adjacent element of list ..if 1st elemnt is bigger than 2nd then swap them ... #largest element of the list will be in last position . #second largest element of the list will come in second last pos. #this will untill,our list is sorted. #in this we use two loops. # if n=len(l) #for i in range (n-1) #for i in range (n-1) def bubblesort(l): n=len(l) for i in range(n-1): for j in range(n-1): if l[j]>l[j+1]: l[j],l[j+1]=l[j+1],l[j] return l print(bubblesort([4,2,6,98,2]))
true
f08cf2d80f0af8a80254ac68c18a7b1977bfdd40
clettieri/Algorithm_Implementations
/breadth_first_search.py
2,685
4.375
4
""" Breadth-First Search This searching algorithm will search through a tree going through each node at one level before continuing to the next level of nodes. BFS will search through the tree assigning each vertex(node) a DISTANCE value, which is the distance from the source vertex, and a PREDECESSOR value which is the node it came from on the path from the source. We start the search from the source node. All distance values are initialized to null. Upon visiting a node if the distance == null, it has not yet been visited. We use a Queue object (a list) to track the nodes we visited but have not searched from yet. Start from source. Visit each node connected to source. Enqueue these nodes, assign distance and predecssor value. Visit first node in queue and repeat the process of visiting each node in the same distnace from source /level and assignign distance & predecssor values. A quick note, for this example we will represent a tree using an adjacency list. There are 3 common forms of representing graphical structures in code: -Edge list -Adjacency Matrix -Adjaceny List This example will use an adjaceny list. In which each element in the list is a list of all of the nodes that particular element is connected to. For example element 0 will have a list of [1] which means it is only connected to node 1. Since this tree will be undirected then the elemnt 1 will also have [0] as well as any other nodes it is connected to. """ adj_list = [ [1, 2], [0, 5], [0, 3, 4], [2, 6], [1, 2], [1, 6], [3, 5] ] def run_bfs(adj_list, start): '''(list, int) -> list of dictionaries Will search through the given graph structure (adjacency list) and build a 'map' for that tree. Returning the map as a dictionary. ''' tree_info = [] #Intialize all nodes for node in adj_list: tree_info.append({'node': None, 'distance' : None, 'source' : None}) #Create Queue queue = [] #Start from Source tree_info[start]['node'] = 'source' tree_info[start]['distance'] = 0 queue.append(start) #Loop through whole tree while queue: current_node = queue.pop(0) #First in, First out for adj_node in adj_list[current_node]: if tree_info[adj_node]['distance'] is None: tree_info[adj_node]['node'] = adj_node tree_info[adj_node]['distance'] = tree_info[current_node]['distance'] + 1 tree_info[adj_node]['source'] = current_node queue.append(adj_node) return tree_info print run_bfs(adj_list, 0)
true
0f24ce9b604ccda5bd7d222b9908dfbf57208982
clettieri/Algorithm_Implementations
/MergeSort.py
2,577
4.3125
4
""" MergeSort Given an array, merge_sort will recursively divide that array until a subarray is length 0 or 1. In this base case (length 0 or 1), the subarray is said to be sorted. Once the array is split up to the base case, the merge function is called on each pairing of subarrays. The merge function looks at the leading element of each subarray and compares the values, putting the smaller value into the resulting array first. The resulting array is then returned as the function returns back up the recurisve chain. Pseudocode: merge_sort(list) -base case if lenght of list <= 1 return list -split list -call merge_sort(list_first_half), merge_sort(list_second_half) -return merge(first, second lists) merge(first, second) -sorted_list = [] -compare each elemnt of both lists, append smaller to sorted list and increment the list taken from, if either list empty, append rest of other list -return sorted_list """ def merge_sort(unsorted_list): '''(list) -> sorted list Will take an unsorted list, run mergesort algorithim and return a sorted list. ''' #Make copy of the list l = unsorted_list[:] #Base Case - List is sorted when length 1 or less if len(l) <= 1: return l #Split list middle_index = len(l) / 2 first_half = l[:middle_index] second_half = l[middle_index:] #Recursively Call merge_sort first_half = merge_sort(first_half) second_half = merge_sort(second_half) return merge(first_half, second_half) def merge(first_half, second_half): '''(list, list) -> sorted list Will loop through each list at same time, comparing ech element, then combining the elements into an output list that is sorted. ''' sorted_list = [] i = 0 j = 0 #Compare each element from both halves of the list while i < len(first_half) and j < len(second_half): #Append the smaller element first if first_half[i] < second_half[j]: sorted_list.append(first_half[i]) i += 1 elif second_half[j] < first_half[i]: sorted_list.append(second_half[j]) j += 1 #Append Remainng part of lists while i < len(first_half): sorted_list.append(first_half[i]) i += 1 while j < len(second_half): sorted_list.append(second_half[j]) j += 1 return sorted_list a = [3,7,1,4,5,8,0,9,2,0] print merge_sort(a)
true
2306352364be797d3e51b2b1380e821e8f68c065
fabiofigueredo/python
/ex/ex009.py
2,910
4.1875
4
frase='Curso em Video Python' print(frase) #Quando se insere uma string no Python, cada letra vira um espaço numerado na memária, iniciando de zero. print(frase[9]) #Mostra a letra que está na posição 9. print(frase[9:13]) #Mostra as letras no intervalo em 9 e 13, excluindo a ultima (13). print(frase[9:21:2]) #Mostra as letras no intervalo de 9 a 13, excluindo a ultima letra e pulando os espaços de 2 em 2. print(frase[:9]) #Mostra todas as letras da string da 0 até a 9 print(frase[9:]) #Mostra todas as letras da string da 9 até o final print(frase[9::3]) #Mostra todas as letras da string de 9 até o final pulando casas de 3 em 3 print(len(frase)) #Mostra o comprimento da frase (quantidade de caracteres) print(frase.count('o')) #Mostra quantas vezes a letra o minuscula aparece na string print(frase.count('o',0,13)) #Mostra quantos vezes a letra o aparece no intervalo entre a posição 0 e a posição 13 da string (excluindo a posição 13) print(frase.find('deo')) #Mostra a posição inicial de onde a primeira letra da string foi encontrada print(frase.find('Android')) #Quandd se solicita a busca de uma palavra não existe o Python retorna o valor -1 print('Curso' in frase) #Retorna o booleano caso a palavra procurada foi encontrada na string. print(frase.replace('Python', 'Android')) #Substitui a palavra encontrada na String por outra. print(frase.upper()) #Coloca tudo em maiusculo print(frase.lower()) #Coloca tudo em minúsculo print(frase.capitalize()) #Coloca a primeira letra em maisculo print(frase.title()) #Coloca a primeira letra de cada palavra em maiúsculo print(frase.strip()) #Remove os espaços antes e depois da string print(frase.rstrip()) #Remove somente os espaços da direita print(frase.lstrip()) #Remove somente os espaços da esquerda print(frase.split()) #É realizada uma divisão entre os espaços da string onde cada palavra vai se transformar em outra lista de caracteres print('-'.join(frase)) #Reagrupa a string em uma unica lista de caracteres colocando o separador desejado - conteúdo entra '' print("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras mollis risus in erat semper, id sollicitudin quam sagittis. Donec tristique orci quis turpis condimentum imperdiet. Morbi ut nisl eu enim lacinia pulvinar. Fusce eu diam placerat, accumsan velit id, viverra nunc. Etiam tincidunt pharetra ante ac ultricies. Mauris in mollis ipsum. Vestibulum tempor commodo nunc, vitae mattis purus iaculis malesuada. Vivamus accumsan pellentesque viverra. Nullam viverra odio a sollicitudin scelerisque. Sed scelerisque rhoncus enim. Curabitur sit amet blandit enim. Proin a magna non ligula porttitor pretium. In nisi enim, volutpat ullamcorper interdum in, gravida et diam. Quisque a convallis risus, in facilisis odio. Cras fringilla augue justo, non gravida ex rutrum feugiat.""") #Com três aspas é possível printar textos longos
false
49c2cbcf5686416914004eb4f071f84d669feb5b
zalthehuman/Python
/eulerPro.py
2,352
4.25
4
import sys import math from collections import OrderedDict #1 Multiples of 3 and 5 """ 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 multThreeOrFive(): sum = 0 for i in range(0, 1000): if((i%5 == 0) or (i%3 == 0)): # check if muliple of 3 or 5 sum += i # if so add value to sum return sum #2 Even Fibonacci Numbers """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ def fib(n): #recursively defining fibonacci sequence if(n == 0): return 0 elif(n <= 2): return 1 else: return fib(n-1) + fib(n-2) def evenFibonacciSum(): sum = 0 i = 0 while True: # go thru sequence if(fib(i) >= 4000000): # break if sequence reach 4mil break elif(fib(i)%2 == 0): #if even add to rolling sum sum += fib(i) i += 1 #i++ return sum #3 Largest Prime Factor """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def largestPrime(n): i = 2 while i * i < n: while n % i == 0: n = n / i i = i + 1 return n #4 Largest Palindrome """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def LargestPalindrome(n): for i in range(900,999): for j in range(900,999): product = str(i*j) #turn product into string if(product[0] == product[-1] and product[1] == product[-2] and product[2] == product[-3]): #check if palindrome max = product #set max palindrome return max #5 Smallest Multiple """ 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def smallestMultiple(): return 0 #//////////////////////Write Under Here////////////////////////////////////// print("Answer:") print(smallestMultiple()) sys.exit()
true
a7387c1ecff82382aa75b75b113e62f318c73d32
MiguelCF06/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
556
4.25
4
#!/usr/bin/python3 """ Prints a square with "#" """ def print_square(size): """ An argument size type integer representing the size of the square """ if isinstance(size, bool): raise TypeError("size must be an integer") elif not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if isinstance(size, int): for rows in range(size): for cols in range(size): print("#", end="") print()
true
e4e2598fbf394b7a2e1c2b660bb21732333a9005
MiguelCF06/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
1,226
4.375
4
#!/usr/bin/python3 """Unit test for the function max_integer """ import unittest max_integer = __import__('6-max_integer').max_integer class TestingMaxInteger(unittest.TestCase): """ Class Test for the max integer cases """ def no_arguments_test(self): """ Test when no arguments is passed """ self.assertIsNone(max_integer()) def empty_list(self): """ Test when the list is empty """ list = [] self.assertIsNone(max_integer(list)) def negative_numbers(self): """ Test for a list with negative numbers """ list = [-2, -3, -567, -4] self.assertEqual(max_integer(list), -2) def passed_None(self): """ Test for when is passed None """ with self.assertRaises(TypeError): max_integer(None) def test_for_no_int(self): """ Test for look is in the list are numbers or not """ list = [34, 23, "What", 45, 67] with self.assertRaises(TypeError): max_integer(list) def one_element(self): """ Test for when the list only has one element """ list = [2908] self.assertEqual(max_integer(list), 2908) if __name__ == "__main__": unittest.main()
true
cc926e711459e9bcb61c56041f6092a967b13cc8
colinbazzano/learning-python
/src/classes/cats.py
489
4.28125
4
class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # Instantiate the Cat object with 3 cats cat1 = Cat("Tiff", 1) cat2 = Cat("Gregory", 3) cat3 = Cat("Harold", 12) # Create a function that finds the oldest cat def oldest_cat(*args): return max(args) # Print out: "The oldest cat is x years old" x will be the oldest cat age print( f"The oldest cat is {oldest_cat(cat1.age, cat2.age, cat3.age)} years old")
true