blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6f2e8a5835e6dc5f395c214d402e01351160e062
oqolarte/python-noob-filez
/prime_checker_2.py
401
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Driver Program print(isPrime(int(input('Type an integer to check if it is prime: '))))
false
443d97ef925c2f0274854f3b32dc8de0785f03d2
oqolarte/python-noob-filez
/reverse_string.py
410
4.8125
5
#Enter a string and the program will reverse it and print it out. def rev_string(string): reversed = '' for i in string: reversed = i + reversed #we call a function to reverse a string, which iterates to every element and intelligently join each character in the beginning so as to obtain the reversed string. print(reversed) rev_string(str(input('Type a string and have its reverse printed out: ')))
true
219d9189fb7821e87bada0eb39b101adefa0780c
oqolarte/python-noob-filez
/multiple_3_5.py
259
4.15625
4
#if we list all 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 multiples of 3 or 5 below 1000 sum = 0 for n in range(1000): if n%3 ==0 or n% 5 == 0: sum += n print(sum)
true
9436331a52b5132752e178df1a7f4bc984528f78
oqolarte/python-noob-filez
/prime_factorization.py
396
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # prime_factorization.py # def primes(n): #returns a list of prime factors primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) # supposing you want multiple factors repeated n //= d d += 1 if n > 1: primfac.append(n) return primfac print(primes(int(input('Type an integer to get its prime factors: '))))
false
4d835817e0f1041997a464e2167b29914ebb7661
johnarathy/PythonStudy
/sortAlgos/BubbleSort.py
890
4.53125
5
#bubble sort for a list without in built functions #16839245 #16839245 #16389245 -swap #16389245 #16382945 - swap #16382495 - swap #16382459 - swap '''In bubble sort the sorting algorithm moves as a bubble between adjacent entries if nth element is greater than n+1th element, then the values are swapped''' #time complexity - O(n2) #function to do bubble sort def bubble_sort(list): #find the length of the list list_len = len(list) #iterate until end of list - 1, to avoid list getting out of bound for i in range(0, list_len-1): for j in range(0,len(list) - 1): #print(j) if(list[j]>list[j+1]): list[j],list[j+1] = list[j+1],list[j] list_len = list_len-1 print(list) return list list = [20,12,-30,5,-1,8,35,-2] bubble_sort(list) print (list) list = ["xr","br","zr","ar"] bubble_sort(list) print(list)
true
1e7b938e4060ca33b429839aface5e92f7f7b722
soham280203/Area-and-file-extension
/area.py
288
4.21875
4
import math #import math for including math library pie=math.pi #math. funtn returns whole value of pi inside pie a=float(input('Input the radius of the circle:')) #asks user to enter radius of circle area=pie*a*a print("The area of the circle with radius %0.1f is %0.16f"%(a,area))
true
959ff16672113bb12d43c7e25d7d9780b20dff2c
neptunecentury/PythonFun
/VendingMachine.py
2,516
4.25
4
# In this example, we will reference an item in the array by its index. An index is the position the # item is in, 0 being the first index. # VendingMachine class provides the functionality to make selections # and insert money and dispense items class VendingMachine: # This variable stores how much money the user has available availableFunds = 0 # Add some money to the vending machine so we can get goodies def AddMoney(self, amount): # Add some money to the vending machine self.availableFunds += amount # Start our vending machine and offer selections def Run(self): # In here we need to present the user selection and # provide them the ability to insert money def Dispense(self): # Show the user that the item was dispensed and deduct the # price from the available funds. Show user how much money # they have left. # Candy class class Candy: name = None candyType = None def __init__(self, name, candyType="Chocolate"): self.name = name self.candyType = candyType candies = [Candy("KitKat"), Candy("M&Ms"), Candy("Snickers"),Candy("Pay Day"), Candy("Twix")] machineOn = True while machineOn: # Show the options to the user, and allow them to make a selection. We will use the enumerate function # to get each item in the array and its corresponding index print("Please enter a selection:") for index, candy in enumerate(candies): # Display the option with it's index, so the user knows what selection to make print("{0} - {1}".format(index, candy.name)) # Print message to show user how to exit print("Press x to quit.") # Now, allow the user to make a selection. But what happens if they enter an invalid number? selection = input("Which item do you want (press a number)? ") if selection == 'x': machineOn = False print("Well, maybe next time then. Bye, bye.") else: # Convert the user's input to an integer (number) because it is a string when they type it. selection = int(selection) # Find the candy the user wants by the index they entered and store it # in a variable called dispense. Note that if you enter a number larger # than the number of items, you will get an error. Try it! dispense = candies[selection] # Tell the user the candy has been dispensed print("Dispensing {0}. Have a nice day :)".format(dispense)) print()
true
f41ed917984f18beb1ee3620953e02f825f212ca
ENRIQUEBELLO/Practica-palindomos
/busquedaBinaria.py
1,384
4.59375
5
""" Busqueda binaria Buscar datos en una coleccion de datos Ventajas: Realiza menos comparaciones que el metodo de busqueda lineal Requisitos antes de realizar dicho algoritmo: Tener la lista ordenada de manera acendente (Menor A Mayor) Algoritmo: 1- calcular el punto medio, (izquierda + derecha)/2 2- comparar el punto medio con el dato a buscar 3- si es igual el dato al punto medio, retornar indice 4- si el dato a buscar es mayor que el punto medio, izquierda es igual al valor del medio + 1 5- si el dato a buscar es menor que el punto medio, derecha es igual al valor del medio - 1 6- se seguira ejecutando siempre y cuando izquierda sea menor o igual a derecha """ def busqueda_binaria(dato): izquierda = 0 derecha = len(lista)-1 while izquierda <= derecha: medio = (izquierda + derecha)//2 if dato ==lista[medio]: return medio elif dato < lista[medio]: derecha = medio - 1 else: izquierda = medio + 1 return None def buscar(dato): if busqueda_binaria(dato) == None: return "El dato %d no se encontro"%(dato) else: return "El dato %d se encontro en el indice: %d"%(dato,busqueda_binaria(dato)) lista = [5,12,15,30,50,65,70,87,88,96,100,125,139,143,155.167,172,189,191,200] for i in range(len(lista)): print("%d => %d"%(i,lista[i])) print(buscar(100))
false
cd4697309056b46fd45bfe6052b9816e785198cc
teethefox/Python-Fundamentals
/MakingDictionaries.py
739
4.1875
4
"""Assignment: Making Dictionaries Create a function that takes in two lists and creates a single dictionary where the first list contains keys and the second values. Assume the lists will be of equal length. Your first function will take in two lists containing some strings. Here are two example lists:""" Part 1 & 2 list1 = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas", "piano"] list2 = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar", "clavicle"] def making(list1,list2): newDic = {} i = 0 if len(list1) >= len(list2): key= list1 value = list2 else: key= list2 value= list2 while i <= key: newDic = {key[i]: value[i]} print newDic i += 1 making(list1,list2)
true
7ad9ffee31ea7a28ae795f08f3906abfd2aad13f
teethefox/Python-Fundamentals
/stars.py
770
4.28125
4
""" Write the following functions. Part I Create a function called draw_stars() that takes a list of numbers and prints out *. For example:""" Part 1 def draw_stars(list): i = 0 while i < len(list): stars= list[i] print "*"* stars i += 1 """Part II Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string according to the example below. You may use the .lower() string method for this part.""" Part 2 def draw_stars(list): i = 0 k=0 while i < len(list): stars= list[i] if isinstance(stars, str): print (list[i][k])* len(list[i]) else: print "*" * stars i += 1
true
dc3b5d746cc8830f309e61710736397c8ed529e4
ASHWINVT/luminarprograms
/LanguageFundamentals/highest among three.py
319
4.15625
4
num1=int(input("enter first no")) num2=int(input("enter second no")) num3=int(input("enter third no")) if ((num1>num2)&(num1>num3)): print("num1 is highest") elif((num2>num3)&(num2>num1)): print("num2 is highest") elif((num3>num1)&(num3>num2)): print("num3 is highest") else: print("numbers are equal")
false
ef0fa766707994dca7f4a890a5f0c3af4665165a
jbbsd/Software-Quality-
/Exercices préliminaires/Exos Python 2.py
618
4.25
4
#!/usr/bin/env python3 def main(): #Récupération des données a = input("1ere valeur: ") operator = input("Opérateur: ") b = input("2eme valeur: ") #Calculatrice avec les opérateurs if (operator == ('+')): x = int(a) + int(b) print("a + b = ", x) elif (operator == ('-')): x = int(a) - int(b) print("a - b = ", x) elif (operator == ('/')): x = int(a) / int(b) print("a / b = ", x) elif (operator == ('*')): x = int(a) * int(b) print("a * b = ", x) else: print("Mauvais opérateur") main()
false
1607c04396815ab25b88fb6b327af4029a68bf8f
mozarik/quicksortPython
/insertionSort.py
1,350
4.40625
4
# Insertion Sort In Python # # Performance Complexity = O(n^2) # Space Complexity = O(n) from random import randint import array def insertionSort(alist): # for every element in our array for index in range(1, len(alist)): current = alist[index] position = index while position > 0 and alist[position-1] > current: print("Swapped {} for {}".format(alist[position], alist[position-1])) alist[position] = alist[position-1] print(alist) print("===================================================================================================") position -= 1 alist[position] = current return alist def randomArray(): array_list = [] len_list = input("Banyak nya list : ") i = int(len_list) for x in range (i): item_list = randint(1 , 100) if item_list in array_list : continue int_item_list = int(item_list) array_list.append(int_item_list) alist = array_list # print("List yang akan di sorted menggunakan metode quick sort adalah {}".format(alist)) return alist alist = randomArray() print("List yang akan di sorted menggunakan metode INSERTION SORT adalah : {}".format(alist)) insertionSort(alist) print("Final Sorted List : {}".format(alist))
false
b10f816241230bc865fbdb8513a6cb8d1d921ddf
Fortune-Labs/Python
/programs/calender.py
704
4.25
4
#Program to calculate and draw a year calender # calendar function year = 2021 def Generating_calendar(year): import calendar month = 1 while month <= 12: cal = calendar.month(year, month) print(cal) month = month +1 # main program starts here Generating_calendar(year = 2018) #Time module time.clock import time def procedure(): time.sleep(2.5) t0 = time.clock() procedure() print (time.clock() - t0, "seconds process time") t0 = time.time() procedure() print (time.time() - t0, "seconds wall time") def change(list): print(list) list[0] = 10 print(list) return list = [20,20,30,40] change(list) #print(list)
true
a61eeb404009d5bc7ab821e6326a6a97acb7b719
klimente/homework
/homework_6/division.py
1,045
4.15625
4
#!/usr/bin/env python3.6 """Division in functional way""" def get_count_pair(): """A function to return number of pair. :returns: int -- count of pair. """ return int(input("Введите количество пар: ")) def get_pair(count_pair): """A function to list of input pair. :param count_pair: number of pair in output list. :param count_pair: int. :returns: list of tuples. """ return [tuple(input("Введите пару через пробел: ").split()) for _ in range(count_pair)] def handler(pair): """A function to handle division of pair. :param pair: tuple of pair that need to divide. :param pair: tuple. :returns: None. """ try: print(int(pair[0])/int(pair[1])) except ZeroDivisionError as ex: print(f"Error code :{ex}") except ValueError as ex: print(f"Error code: {ex}") except IndexError as ex: print(f"Error code:{ex}") if __name__ == '__main__': list(map(handler, get_pair(get_count_pair())))
true
8fefc5fb5cdfea78503fd8f86bbd9481f6a7bf4b
enjey00/Chapter-2
/part2-11b.py
888
4.3125
4
str_ = input("Введите любое слово:").upper() str1 = str_[::-1] print("Операции с индексами символов в строке: ") print("1)", str_[2], "- третий символ строки") print("2)", str_[-2], "- второй символ с конца") print("3)", str_[:5], "- первые пять символов") print("4)", str_[:-2], "- все символы кроме последних двух") print("5)", str_[2::2], "- символы нечётных индексов") print("6)", str_[1::2], "- символы чётных индексов") print("7)", str_[::-1], "- в обратном порядке") print("8)", str1[::2], "- каждый второй символ в обратном порядке, начиная с последнего символа") print("9)", len(str_), "- количество символов")
false
a1f4fc4d3c3c78f82e7dc518b5ba0214bd674b92
mastercsay2511/100daysofcodewithGFG
/Day 30 - 39/30 Day/solution.py
1,312
4.28125
4
#User function Template for python3 class Solution: ##Complete this function #Function to swap odd and even bits. def swapBits(self,n): #Your code here number = n foundodd = "" makebyte = "" stringchange = "" remove0b = "" convertintbinary = bin(number) remove0b = convertintbinary.lstrip('0b') binarylength = len(remove0b) if binarylength % 2 == 1: remove0b = '0' + remove0b binarylength = len(remove0b) for count in range(binarylength, 0,-2): findodd = remove0b[count-2:count] if findodd == "01": foundodd = "10" elif findodd == "10": foundodd = "01" else: foundodd = findodd stringchange = foundodd + stringchange makebyte = '0b' + stringchange number = int(makebyte, base=2) return number #{ # Driver Code Starts #Initial Template for Python 3 import math def main(): T=int(input()) while(T>0): n=int(input()) ob=Solution() print(ob.swapBits(n)) T-=1 if __name__=="__main__": main() # } Driver Code Ends
true
ec83976d68db6ea9763c7ec54a17774e43fd36a5
ambrosy-eric/100-days-python
/intermediate/day-21/game/snake.py
2,419
4.21875
4
from turtle import Turtle class Snake(): """ Class for managing a snake """ def __init__(self): self.snake = [] self.create_snake() self.head = self.snake[0] def create_snake(self): """ Create a snake body from turtles """ for body in range(3): position = ((-20 * body), 0) self._add_segment(position) def move(self, dist=20): """ Given a distance to move Move the snake that distance """ for seg_num in range(len(self.snake) - 1, 0, -1): new_x = self.snake[seg_num - 1].xcor() new_y = self.snake[seg_num - 1].ycor() self.snake[seg_num].goto(new_x, new_y) self.head.forward(dist) def up(self): if self.head.heading() != 270: self.head.setheading(90) def down(self): if self.head.heading() != 90: self.head.setheading(270) def left(self): if self.head.heading() != 0: self.head.setheading(180) def right(self): if self.head.heading() != 180: self.head.setheading(0) def at_wall(self): wall = 295 if self.head.xcor() > wall: return True elif self.head.xcor() < -wall: return True elif self.head.ycor() > wall: return True elif self.head.ycor() < -wall: return True else: return False def _add_segment(self, position): """ Given the position of the snake Add a new segment to it """ segment = Turtle(shape='square') segment.color('white') segment.penup() segment.goto(position) self.snake.append(segment) def extend(self): """ Add a new segment to the snake """ self._add_segment(self.snake[-1].position()) def collision(self): """ Determine if the snake's head is in contact with its body Return True """ for body in self.snake[1:]: if self.head.distance(body) < 10: return True def reset_snake(self): """ Reset snake at end of game """ for segment in self.snake: segment.goto(1000, 1000) self.snake.clear() self.create_snake() self.head = self.snake[0]
false
1e70e3067ab3c57e4b2c2d6bd75b7348ac59ceff
NanLieu/COM404
/Practice Assessment/AE1 Review - TCA 2/3-Loop/bot.py
518
4.1875
4
# Dr Bravestone asks a question print("How many zones must I cross?") # Awaits user response in form of a whole number zones = int(input()) # Prints statement print("Crossing zones...") # Runs while loop function which will loop as long as 'zones' is greater than 0 while (zones > 0): # prints message with the current 'zone' print("...crossed zone",zones) # countdown for 'zones' each time it is looped zones = zones - 1 # Print final message when loop is complete print("Crossed all zones. Jumanji!")
true
f0217de5978805bd5fe62dafd9583a3dc25bb273
NanLieu/COM404
/Practice Assessment/AE1 Review - TCA 2/7-modules/main.py
371
4.1875
4
print("Please enter a word") word = input() from functions import * print("Please type in an option from the following: Under, Over, Both, Grid") option = input() if (option == "Under"): print() under(word) elif (option == "Over"): print() over(word) elif (option == "Both"): print() both(word) elif (option == "Grid"): print() grid(word)
true
0fcbcdec92d3f2a436580e1e97566d43a570a41c
shrutikabirje/Day1-Day-2-Python
/day11.py
2,333
4.9375
5
1. Write a NumPy program to create a 3X4 array using and iterate over it. import numpy as np n=np.arange(1,13).reshape(3,4) print(n) for i in n: for j in i: print(j,end=" ") 2. Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50. n=np.linspace(5,50,10,dtype=int) print(n) 3. Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15. a=np.arange(0,21) print(a) print("Changing signs from 9 to 15") a[(a>=9) & (a<=15)] *= -1 print(a) 4. Write a NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10. a=np.linspace(0,10,5,dtype=int) print(a) 5. Write a NumPy program to multiply the values of two given vectors. m=np.array([1,2,3,4,5,6]) n=np.array([1,2,3,4,5,6]) print("multiplication of arrays",m*n) 6. Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21. x=np.arange(10,22).reshape(3,4) print(x) 7. Write a NumPy program to find the number of rows and columns of a given matrix. x=np.arange(1,13).reshape(3,4) print(x) print("shape of matrix is",x.shape) 8. Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0. n=np.eye(3,dtype=int) print(n) 9. Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0. m=np.ones(100).reshape(10,10) m[1:-1,1:-1]=0 print(m) 10. Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5. v=np.diag([1,2,3,4,5]) print(v) 12. Write a NumPy program to create a 3x3x3 array filled with arbitrary values. n=np.random.normal(1,5,(3,3,3)) print(n) 13. Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array.  n=np.arange(1,10).reshape(3,3) print(n) print("sum of matrix:",np.sum(n)) c=np.sum(n,axis=0) print("sum of columns:",c) r=np.sum(n,axis=1) print("sum of rows:",r) 14. Write a NumPy program to compute the inner product of two given vectors. m=np.array([11,12,13,14]) n=np.array([1,2,3,4]) v=m*n print(sum(v)) 15. Write a NumPy program to add a vector to each row of a given matrix. x=np.arange(1,10) c=np.arange(11,20) print(x) print(c) print(x+c)
true
9e613bc4e66d88410ab4d432225fe2e3c5e39871
shrutikabirje/Day1-Day-2-Python
/day6-p4.py
344
4.34375
4
Given a nested list extend it with adding sub list ["h", "i", "j"] in a such a way that it will look like the following list. Given list: list1 = ["a", "b", ["c", ["d", "e", ["f", "g","h","i","j"], "k"], "l"], "m", "n"] list=["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"] l=["h","i","j"] list[2][1][2].extend(l) print(list)
true
a73d343976314939ed75192f7349183a08e370ae
shrutikabirje/Day1-Day-2-Python
/pg2.py
420
4.25
4
Write a Python program to count the number of even and odd numbers from a series of numbers. n=int(input("enter the no. of elements")) l=[] for i in range (1,n+1): no=int(input("enter the numbers")) l.append(no) print("your no. series is:",l) even=0 odd=0 for i in l: if(i%2==0): even=even+1 else: odd=odd+1 print("number of even numbers:",even) print("number of odd numbers:",odd)
true
93494e64496bd185202d915451b4848ba86cae44
shrutikabirje/Day1-Day-2-Python
/day1-2.py
286
4.21875
4
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. n=int(input("enter the no.")) d={x:x**2 for x in range (1,n+1)} print(d)
true
34d477b1be37294277a9dfe7b51ba4e7812e1f45
shrutikabirje/Day1-Day-2-Python
/day9-p6.py
215
4.28125
4
Write a python program to generate Fibonacci Numbers upto 100 using generator def fibonacci(n): a=0 b=1 for i in range(0,n+1): yield a a,b=b,a+b for i in fibonacci(100): print(i)
false
d3111cab27dd8261ec826e0ac686c4a7d57b6aa7
gkustik/lesson1
/hw_w1.py
987
4.25
4
#Задание №1 (список) numbers = [3, 5, 7, 9, 10.5] print(numbers) numbers.append('Python') print(numbers) print(len(numbers)) #Задание №2 (список) print(numbers[0]) print(numbers[-1]) print(numbers[1:6]) del numbers[5] print(numbers) #Задание №1 (словарь) place = {'city': 'Москва', 'temperature':20} print(place['city']) place['temperature'] -= 3 place['temperature'] = place['temperature'] - 2 print(place) #Задание №2 (словарь) print(place.get('country')) place ['country'] = "Россия" place ["date"] = "27.05.2019" print(place) print(len(place)) #Задание №1 (функции) def get_summ(one, two, delimiter='&'): one = str(one) two = str(two) summ = one + delimiter + two print(summ.upper()) get_summ('Learn', 'python') #Задание №2 (функция) def format_price(price): price = int(price) print('Цена: {} руб.'.format(price)) format_price(56.24)
false
d565798d45b6dc2a1ddcc9972a30cb2209295433
caique-alencar/coursera-python
/crescente_decrescente.py
764
4.125
4
# Função que verifica se os números estão em ordem decrescente def ordem_decrescente: decrescente = True anterior = int(input("Digite o primeiro número da sequência: ")) valor = 1 while valor != 0 and decrescente: valor = int(input("Digite o próximo número da sequência: ")) if valor > anterior: decrescente = False anterior = valor if decrescente: print("A sequência está em ordem decrescente!") else: print("A sequência não está em ordem decrescente!") # Função que verifica se os números estão em ordem crescente def verifica_ordem_crescente(x, y, z): if x < y < z: return "Ordem crescente" else: return "Não está em ordem crescente"
false
41ab951354f1eff82fa052db86c362a98cf3bed1
hanhantw/coding_projects
/date_calculation.py
1,440
4.3125
4
# input (2020, 3, 29, 3) -> (2020, 4, 1) # input (2021, 5, 9, 1129) -> (2024, 6, 11) # input (2003, 12, 15, 100) -> (2004, 3, 24) # # Leap year # can be divided by 4 but not 100 --> leap year # can be divided by 100 but not 400 --> not leap year # can be divided by 400 --> leap year def date_calculator(year: int, month: int, day: int, days_to_add: int) -> set: day += days_to_add month_for_30 = [4, 6, 9, 11] month_for_31 = [1, 3, 5, 7, 8, 10, 12] def is_leap_year(year: int): if year % 4 == 0 and year % 100 != 0: return True elif year % 400 == 0: return True return False if day > 365: if is_leap_year(year) and month <= 2: day -= 366 else: day -= 365 year += 1 while day > 30: if day > 365: if is_leap_year(year): day -= 366 else: day -= 365 year += 1 else: if month in month_for_31: day -= 31 elif month in month_for_30: day -= 30 elif month == 2: if is_leap_year(year): day -= 29 else: day -= 28 month += 1 if month > 12: year += month // 12 month = month % 12 return (year, month, day) date_calculator(2021, 5, 9, 1129)
false
b01601e3e2eba33ab06c3afa591b3062e1510d56
halejon/Exercises
/6.00sc/ps2/ps2_newton.py
2,145
4.375
4
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 poly: tuple of numbers, length > 0 x: number returns: float """ exp = 0 total = 0 for coef in poly: total += coef * (x ** exp) exp += 1 return total def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4.0) poly: tuple of numbers, length > 0 returns: tuple of numbers """ exp = 1 new_poly = [] for x in poly[1:]: new_poly.append(x * exp) exp += 1 return tuple(new_poly) def compute_root(poly, x_0, epsilon): """ Uses Newton's method to find and return a root of a polynomial function. Returns a tuple containing the root and the number of iterations required to get to the root. Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 >>> x_0 = 0.1 >>> epsilon = .0001 >>> print compute_root(poly, x_0, epsilon) (0.80679075379635201, 8.0) poly: tuple of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: tuple (float, int) """ # TO DO ... diff = evaluate_poly(poly, x_0) count = 0 if abs(diff) > epsilon: #Newton's Method Formula x_1 = x_0 - (evaluate_poly(poly, x_0) / evaluate_poly(compute_deriv(poly), x_0)) #Recursion! x_0 , count = compute_root(poly, x_1, epsilon) else: pass return x_0, count + 1
true
6cf8f60b5d19f8057a7fd558079bbb5ded1a55e4
ashacker/LeetCode-Problems
/Python/RotateArray.py
1,615
4.375
4
''' Author: ashacker Date: May 04, 2018 Problem: Rotate Array Difficulty: Easy Question: Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] ''' class Solution: ''' Solution: Use reveral algorithm. First reverse the entire array from 0 to n-1. Then reverse the array from 0 to k-1. Finally reverse the array from k to n-1. The array will be rotated. Time Complexity: O(n) Space Complexity: O(1) ''' def reverseList(self, nums, start, end): while(start < end): temp = nums[start] nums[start] = nums[end] nums[end] = temp start += 1 end -= 1 def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) if(n == 0 or n == 1): return if(k > n): k -=n self.reverseList(nums, 0 , n-1) self.reverseList(nums, 0 , k-1) self.reverseList(nums, k , n-1)
true
03ef5a4aea53212f49c209f5a1e7e972f81a0094
rkkr172/PythonTesting
/1-numbers.py
1,491
4.53125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Pros and Cons of Dynamic Typing Pros of Dynamic Typing - very easy to work with - faster development time Cons of Dynamic Typing - may result in unexpected bugs! - you need to be aware of type() """ """ a=9;b=4 #print("Addition -{}".format(a+b)) #print("Substraction -{}".format(a-b)) #print("Muliplication -{}".format(a*b)) #print("Division -{}".format(a/b)) #print("Floor Division -{}".format(a//b)) #Modulo #print("Modlus -{}".format(10%2)) #print("Remainder of {} & {} is {}".format(10,3,10%3)) #print("Power -{}".format(2**3)) # int, float, str, list [], tuple (), dict {}, set, bool w = ['a','b','c'] # List x = (1,2,3) # Tuple y = {'k1','k2'} # Set z = {'k1':'v1','k2':'v2'} # Dictionary print(type(w)) print(type(x)) print(type(y)) print(type(z)) print(type(5)) print(type(5.5)) print(type('hello')) #print(type(10)) """ def sal_cal(rate,days): per_day_rate=rate total_days=days wages=per_day_rate*total_days return wages while True: try: r=float(input("Rate of wages per day -: ")); #except ValueError: print("Please, retry rate in number only"); except: print("Please input Ruppes of per Day "); else: break; while True: try: d=int(input("Total no. of working days -: ")) except: print("Retry, toatal no. of workings Days"); else: break; sal=float(sal_cal(r,d)) print(f"Total Salary is : {sal}") #"""
true
f287c660f055b9e20ffb2f6071d58730586feec2
gss13/Leetcode
/leetQ116_Populating_Next_Right_Pointers_in_Each_Node.py
1,550
4.34375
4
''' Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). For example, Given the following perfect binary tree, 1 / \ 2 3 / \ / \ 4 5 6 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL ''' class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right self.next = None def level_order(root): cur_level = [root] while cur_level: next_level = [] for node in cur_level: print node.data, '-->', node.next.data if node.next else None if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) cur_level = next_level print def connect(root): while root: left_most = root.left while root and root.left: root.left.next = root.right root.right.next = root.next.left if root.next else None root = root.next root = left_most if __name__ == '__main__': root = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7))) connect(root) level_order(root)
true
f38cd5f93d905a0f3af101b3e1a7c00625a2e7af
gss13/Leetcode
/leetQ110_Balanced_Binary_Tree.py
1,172
4.1875
4
#Practice date: 01-May-2017 class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def level_order(root): cur_level = [root] while cur_level: next_level = [] for node in cur_level: print node.data, if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) cur_level = next_level print class Solution(object): def validate(self, root): if not root: return 0 left = self.validate(root.left) right = self.validate(root.right) if left < 0 or right < 0 or abs(left-right) > 1: return -1 return max(left, right) + 1 if __name__ == '__main__': #r1 = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7))) #r1 = Node(1, Node(2, Node(4)), Node(3)) r1 = Node(1, Node(2, Node(4, Node(5))), Node(3)) v = Solution() result = v.validate(r1) level_order(r1) if result != -1: print 'Tree is height balanced' else: print 'Tree is NOT height balanced'
true
99f6696277db636572366c70886d60560877c815
gss13/Leetcode
/leetQ20_Valid_Parentheses.py
616
4.125
4
''' 20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. ''' def check_paren(string): cache = {'}': '{', ')': ')', ']': '['} stack = [] for s in string: if s in '{([': stack.append(s) elif ((stack == []) or (stack.pop() != cache[s])): return False return stack == [] if __name__ == '__main__': string = '{}' if check_paren(string): print 'Valid Parentheses' else: print 'Invalid Parentheses'
true
18c1ef4bbe8d971ce65f1b27d7fa282a44f2a751
Mujeeb1408/Assignment_2
/ProductIOfdigits.py
380
4.34375
4
# To calculate the product of digits of given number N = int(input('Enter a number: ')) digit = 1 product = 1 while N != 0: digit = N % 10 product = product * digit N = N // 10 if product == 0: print('Product is zero :('+str(product)+') enter a number with no zero in it') else: print('The product of digits of given number is : ' + str(product))
true
64b8d3a2bc1f44ccd346aa7fac16a19e0cc019dd
SachinPitale/Python3
/Python-2020/Chapter_13/1.enumerate_function.py
692
4.21875
4
# we use enumerate function with for loop to track postion of our # item in iterable # How we can do this without enumerate functions names = ['abc','xty', 'pqr'] pos = 0 for i in names: print (f"{pos} -------> {i}") pos += 1 for pos, i in enumerate(names): print (f"{pos} -------> {i}") # Define a function that take two arguments # 1. list containing string # 2. string that want to find in you list # and this function will return the index of string in your list and if string is not present then return -1 def find_pos (l,target): for pos, i in enumerate(l): if i == target: return pos return -1 print (find_pos(names,'pqr'))
true
7e4d47ef70d55930049217afabdaeff20a985caa
SachinPitale/Python3
/Python-2021/6.condition/2.if_else.py
233
4.25
4
user_string = input("Enter your string : ") user_conf = input("Do you want to print this string in title format? valid input is yes or no: " ) if user_conf == "yes": print (user_string.title()) else: print (user_string)
true
43b805f26e5f629d7a967ef64f331100cce5f58a
SachinPitale/Python3
/Python-2021/4.DataType/1.List.py
1,187
4.34375
4
# List is mutable # Tuple is not mutable """ My_list=[] My_list1=[4,5,6,7,'python'] print (My_list1, type(My_list1)) print (My_list1[0]) print (My_list1[-1][1]) print (My_list1[0:3]) My_list1[0]=3 print (My_list1) """ #To get index value of list """ my_list=[4,5,6,7,6,8] my_list1=[11,12,13] my_list2=[21,22,23] print (my_list.index(5)) print (my_list.count(6)) # To count number of list value my_new_list=my_list.copy() #Assign one list to other list print (my_new_list) my_list=my_list1.copy() print (my_list) my_list.append(9) # add value end of the list print (my_list) my_list.insert(5,98) # This will add new value based on index specifi print (my_list) print (dir(my_list)) my_list.reverse() # list the list in reverse order print (my_list) my_list.sort() # sorting list accending order print (my_list) my_list.pop() #remove last element of list print (my_list) my_list1.extend(my_list2) #merge one list to other list print (my_list1) """ my_list=[4,5,6,7,6,8,22] my_list1=[11,12,13,3,5] my_list.remove(5) print(my_list) my_list.pop(3) # delete the index element print(my_list) my_list.extend(my_list1) print (my_list) my_list.sort() print(my_list) print(my_list[-1])
true
17e4b6d4a9902f36c708009142f81b637ba18fda
SachinPitale/Python3
/Python-2020/chapter_8/1.set_intro.py
646
4.40625
4
# set data type : unordered collection of unique order # we can store in set is integer, floating point, string # we can not store any dict and list in set # we define set using {} s = {1,2,3,2} print (s) # To remove the duplicate value for set list1 = [1,2,3,4,5,6,7,6,7,8,9,9] print(list1) list1 = list(set(list1)) print(list1) # To add the value in set using add method s1 = {1,2,3,} s1.add(4) print (s1) # Remove the value from set using remove methond and discard method s1.remove(2) print (s1) s1.discard(5) # If value is not exist in set it will not give any error print (s1) # Copy one set to other set s2 = s1.copy() print (s2)
true
f5056264d080ac35feec221fd10abbf0df6f47d1
SachinPitale/Python3
/Python-2020/Chapter_2/replace_and_find_method.py
616
4.34375
4
# Replace method string = "she is beatiful and she is good dancer" #Task - replace all the spaces via - print(string.replace(" ", "-")) # Task - replace first 2 character print(string.replace("is", "was", 2)) # Find method postion of is word print(string.find("is")) # To find the position of second is word first_is_word = string.find("is") print(string.find("is", first_is_word + 1)) # Center method # It method is used to add the some character or special charater on right and left side Name = "Sachin" # Task : To add two star at right and left side print(Name.center(10, "*")) print(Name[0])
true
6d9a9eebc8cebdd8698ae28f9705bb621b214e42
SachinPitale/Python3
/Python-2021/3.String_Operation/2.String_Case_conversion.py
747
4.125
4
# # Convert the string into lower, upper and title case Script = "Python Scripting is oops " print (Script.upper()) print (Script.lower()) print (Script.title()) print (Script.swapcase()) #print first char small for every word and rest of will b capital print (dir(Script)) #get all the method about string print(Script.capitalize()) # Print first char of line is always capital print(Script.replace(" ","-")) print (Script.casefold()) # all char will get in lowercase print (Script.count("i")) # total number of characther present in string print(Script.istitle()) print(Script.isspace()) print(Script.find("P")) # Find position of char print(Script.index("s")) # Find position of char print (Script.format()) print(Script.endswith("s"))
true
7e764caf0f0279565526236c9753335c269d05c8
SachinPitale/Python3
/Python-2020/Chapter_2/exercise1.py
325
4.28125
4
#a= int(input("Enter your first numbers : ")) #b= int(input("Enter your second numbers : ")) #c= int(input("Enter your third numbers : ")) #sum = a + b + c #print(sum) #avg = sum/3 #print (f"average of three number is : {avg}") # To print the output in reverse latter name= input("Ener your name: ") print(name[-1: :-1])
true
14ff8f3fc8838de6a6efc084a1aed44969f76f23
SachinPitale/Python3
/Python-2021/8.sys-module/3.Action-on-string.py
444
4.25
4
#user_string = input("Enter your string: ") #user_action = input("Select the string operation like upper,title and lower: ") import sys user_string = sys.argv[1] user_action = sys.argv[2] if user_action == "lower": print (user_string.lower()) elif user_action == "upper": print (user_string.upper()) elif user_action == "title": print (user_string.title()) else: print ("Enter valid input paramete only upper,lower,title")
true
5f76c05aeadf5ad02c6b3f079cb929d0c004bed3
pydjamolpomaji/Python_Tutorials
/Kilometers-to-Miles-and-Miles-to-Kilometers-Program.py
660
4.46875
4
# Convert Kilometer to Miles KiloMeters = float(input("Enter the value in kilometers: ")) Conv_Factor = 0.621371 # Conversion Factor Miles = KiloMeters * Conv_Factor # Calculate Miles print(KiloMeters, 'Kilometers is Equal to ', Miles, 'Miles') # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Convert Miles To Kilometer Miles = float(input("Enter the value in Miles: ")) KiloMeters = Miles / 0.621371 print(Miles, 'Miles is Equal to ', KiloMeters, 'Kilometers') # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
false
92b05a1dec988b97a57bd03e64382666a4e36295
pydjamolpomaji/Python_Tutorials
/Positive-Negative-Even-Odd-Big-Number-Program.py
1,545
4.46875
4
# Program 1 :- # Python Program to check if a Number is Positive, Negative or Zero num = float(input('Enter the Number :')) if num > 0: print('{} is Positive Number'.format(num)) elif num == 0: print('{} is Zero'.format(num)) else: print('{} is Negative Number'.format(num)) # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Program 2 :- # Check Number is Even or Odd. num = int(input('Enter the Number :')) if num % 2 == 0: print('{0} is Even Number'.format(num)) else: print('{0} is Odd Number'.format(num)) # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Program 3 :- # Find the Biggest Number using function. def Big(a, b, c): if a > b and a > c: return a elif b > c: return b else: return c return x = int(input('Enter the First Number :')) y = int(input('Enter the Second Number :')) z = int(input('Enter the Third Number :')) print('Biggest Number is :', Big(x, y, z)) # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # Program 4 :- # Find the Biggest Number in List numbers = [10, 50, 40, 20, 30, 60, 143, 80, 70] max = numbers[0] for num in numbers: if num > max: max = num print('Biggest Number in list is :', max) # =-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
true
05ccd5198a0af27baefef1d18ac323ab80f26e0e
alex-muci/small-projects
/MIT course tests/Unit 2 and 3/floats_and_fractions.py
1,176
4.5
4
""" Recall binary and decimal representation in terms of powers of 2 and 10 - then easy to convert between the two (e.g. 10 decimal is 8 + 2 = 2^3+ 0 + 2^1 + 0 = 1010) Fractions as binary: i. multiply by a power of 2 big enough to get an integer ii. convert to binary iii. divide it by the power of 2 example (nice number): 3/8 = 0.375 i. 0.3755 * 2**3 = 3 (decimal) ii 3 (decimal) = 11 (binary) iii. divide by 2**3 (shift right) to get 0.011 (binary) but 0.1 = 0.0001100110011001101 because the binary is an approx """ x = float(input("Enter a decimal number between 0 and 1: ")) # # # # increase decimal to integer p = 0 while ((2**p) * x) % 1 != 0: print("Reminder = " + str((2**p) * x - int((2**p) * x))) p += 1 num = int((2**p) * x) # # # # this part is conversion from decimal integer to binary # # # # result = "" if num == 0: result = '0' while num > 0: result = str(num % 2) + result # NB: position means this is a stack! num = num//2 # # # # put zeroes in front for i in range(p - len(result)): result = '0' + result result = result[0:-p] + '.' + result[-p:] print('The binary representation of the decimal is ' + str(result))
true
8f86be35c679bbdbc45489d82064884534f07e4a
Mahmoud-alzoubi95/data_structures_and_algorithms_python
/python/challenges/queue_with_stacks/queue_with_stacks.py
1,453
4.25
4
from stacks_and_queues import Node,Stack class Pseudo_Queue: def __init__(self): self.stack1 = Stack() self.stack2 = Stack() self.count = 0 self.rear = 0 def enqueue(self,value): """ do enqueue with push methods from Stack """ self.stack1.push(value) self.rear = self.stack1.top.value def dequeue(self): ''' it used to return the first vlaue(node) in your 'PseudoQueue', first pushed: ''' if self.stack1.is_empty(): while self.count > 0: self.stack2.push(self.stack1.pop()) self.count-=1 result = self.stack2.pop() while True: self.stack2.push(self.stack1.pop()) self.count +=1 if self.stack2.is_empty(): return result else: return "stack is empty!" def __str__(self): """ return string of Queue output-{string} """ output='' current=self.stack1.top while current: output+=f"{current.value} --> " current=current.next output+= "None" return output if __name__ == "__main__": new = Pseudo_Queue() new.enqueue("A") new.enqueue("B") # new.enqueue("C") print(new) # new.dequeue() new.dequeue() print(new)
true
fa325d8c260ea2e326b728b313d7dadad6a608d4
ndiazdossantos/DI
/Ejercicio1.py
1,315
4.25
4
#Exercicio 1.8.1 #Opcion manuel """ def calculos (n1,n2): suma = n1 + n2 resta = n1 - n2 multiplicacion = n1 * n2 division = n1 / n2 return suma,resta,multiplicacion,division var = calculos(8,2) sum,rest,mult,div = calculos(10,5) print(var) """ #mi opcion def calculos2(): n3 = int(input("Introduce o primeiro número: ")) n4 = int(input("Introduce o segundo número: ")) suma2 = n3 + n4 resta2 = n3 - n4 multiplicacion2 = n3 * n4 division2 = n3 / n4 return suma2,resta2,multiplicacion2,division2 print(calculos2()) #exercicio 7.1 tupla = ("Pedro","Eduardo","Juan","Pablo","Sofia","Maria") def lista(tupla): for x in (tupla): print("Estimado",x) lista(tupla) """ def listaX(tupla1,ini,fin): for x in (tupla1[ini:fin]): print("Estimado",x) listaX(tup1,2,5) """ #exercicio 7.2 def lista2(tupla): for valor in range(1,5,1): print("Estimado",tupla[valor]) lista2(tupla) #Exercicio 7.3 tuplaGenero=(("Pedro","Hombre"),("Eduardo","Hombre"),("Juan","Hombre"),("Pablo","Hombre"),("Sofia","Mujer"),("Maria", "Mujer")) def lista3(tupla): for valor in tupla: valor[1] if valor [1] == "Mujer": print("Estimada Sra.",valor[0]) else: print("Estimado Sr.",valor[0]) lista3(tuplaGenero)
false
a227c6dbef4dcc3e219a41fe2715c6fc4184097e
TJRobson/MIT6.0001
/problem_set_1/ps0.py
291
4.125
4
import numpy x = int(input('Enter a number x:')) y = int(input('Enter a number y:')) def powerOf(x, y) : return x**y power = powerOf(x, y) log2 = numpy.log2(power) print(str(x) + ' to the power of ' + str(y) + ': ' + str(power)) print('log2 of ' + str(power) + ': ' + str(log2))
true
4d59563a887a5b5b6f4f82e8d368b77d2e24eae0
Zahidsqldba07/coding-exercises
/Python3/other/generators-examples.py
2,719
4.5
4
""" This file are the three examples of generators I made for execises from Linuxtopia tutorial. """ # Example 1 """ The Sieve of Eratosthones. This exercise has three parts: initialization, generating the list (or set) or prime numbers, then reporting. In the list version, we had to filter the sequence of boolean values to determine the primes. In the set version, the set contained the primes. Within the Generate step, there is a point where we know that the value of p is prime. At this point, we can yield p. If yield each value as we discover it, we eliminate the entire "report" step from the function. """ def sieve(num): primes = set(range(2, num+1)) for prime_candidate in range(2, num+1): if prime_candidate not in primes: continue yield prime_candidate multiples = set(range(prime_candidate, num+1, prime_candidate)) primes.difference_update(multiples) # generator_sieve = sieve(5000) # print(list(generator_sieve)) # Example 2 """ The Generator Version of range. The range function creates a sequence. For very large sequences, this consumes a lot of memory. You can write a version of range which does not create the entire sequence, but instead yields the individual values. Using a generator will have the same effect as iterating through a sequence, but won't consume as much memory. Define a generator, genrange, which generates the same sequence of values as range, without creating a list object. """ def genrange(number): index = 0 while index < number: yield index index += 1 # generator_genrange = genrange(101) # print(next(generator_genrange) - 7) # for i in generator_genrange: # print(i**3) # print(", ".join(str(element) for element in genrange(25))) # Exercise 3 """ Prime Factors. There are two kinds of positive numbers: prime numbers and composite numbers. A composite number is the product of a sequence of prime numbers. You can write a simple function to factor numbers and yield each prime factor of the number. Your factor function can accept a number, n, for factoring. The function will test values, f, between 2 and the square root of n to see if the expression n % f == 0 is true. If this is true. then the factor, f, divides n with no remainder; f is a factor. Don't use a simple-looking for -loop; the prime factor of 128 is 2, repeated 7 times. """ def factors(num): f = 2 operator = num while f <= num // 2 + 1: if operator % f == 0: yield f operator = operator / f else: f += 1 if operator == num: yield num # generator_factors = factors(333333) # print(list(generator_factors))
true
dfe38ce6aacd256bed4dcad5fc8b8e962959a323
Zahidsqldba07/coding-exercises
/Python3/exercism/robot-name/robot_name.py
1,338
4.40625
4
"""This program creates a class of robots. Robots are born with no name. On boot they get assigned a random, unique name in format like AA001. 2 uppercase letters, 3 numbers. You can to reset a robot, and assign it a new unique name. """ from random import randint # This is a list of all active robot names. # Used to control uniqueness of names. all_robot_names = [] def random_letter(): """ This generates a random uppercase letter.""" alphabeth = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" num = randint(0, len(alphabeth)-1) return alphabeth[num] class Robot(object): def __init__(self): self.uniquename() def name_gen(self): """ This function generates a random name in the AA001 form.""" random_name = "".join([random_letter(),random_letter(), str(randint(0,9)), str(randint(0,9)),str(randint(0,9))]) return random_name def uniquename(self): """ This function checks the uniqueness of a robot name.""" self.name = self.name_gen() while self.name in all_robot_names: self.name = self.name_gen() else: all_robot_names.append(self.name) def reset(self): """ On a reset, a robot gets a new name. If that name is on the list, it gets another. """ self.uniquename()
true
0800db028fcf1a33ea8eff86d39424244db6e14b
divs-ray/02-algorithmic-thinking
/q1.py
1,561
4.375
4
#!/usr/bin/env python solution = 0 #if not initialized to 0 then if the code fails to compute then this might return garbage value multiple = 0 #0 is assigned to the 'multiple' variable #'multiple' variable holds the value of the 'nth' positive integer #in the list of integers representing the multiples such as 1st, 2nd #3rd, 4th...integers max_multiple = 100000 # 100000 is assigned as the upper limit of the integer 'i' i=1 # integer i is assigned to value 1 while i < max_multiple: # the condition to be evaluated; #the while loop executes the condition when 'i' is less than max_multiple(100000 in this case) #follwing is the if condition for checking divisibility of the integer 'i' #now the 'i' thats is < max_multiple enters into the loop #this execution block will continuein in loop until it satisfies the if condition if (i % 4 == 0) and (i % 13 == 0) and (i % 14 == 0) and (i % 26 == 0) and (i % 50 == 0): # checking divisibility condition # 'and' is used after each condition to compute all conditions at once multiple += 1 #increment 'multiple' variable by 1 if multiple == 9: solution = i #when this 'if' condition is satisfied 'solution' takes the value 'i' break #breaks the while loop once multiple == 9 i += 1 # increment 'i' variable by 1; goes back to the while condition check # checks and prints the correct answer if multiple == 9: print("#1 : 9th Multiple ::", "Correct." if solution == 81900 else ("Wrong: " + str(solution)))
true
7d9baf0fad665e174c726c3e872e9e127c78d485
Shaggy1247/learning-python
/python-lessons/lesson-ten.py
384
4.34375
4
# ----------------------------------------------------------- # Lesson ten # Learning about string methods # # Done 12/28/20, Shaggy1247 # ----------------------------------------------------------- # .strip(), .len(), .lower(), .upper(), .split() text = input("Input something: ") print(text.strip()) print(len(text)) print(text.lower()) print(text.upper()) print(text.split("."))
false
bd40076561c1763cf04dae6b38dd3387add0f63a
Shaggy1247/learning-python
/python-lessons/lesson-thirteen.py
587
4.125
4
# ----------------------------------------------------------- # Lesson thirteen # Learning about reading text file # # Done 12/28/20, Shaggy1247 # ----------------------------------------------------------- file = open('python-lessons/readfile.txt', 'r') f = file.readlines() print(f) newList = [] for line in f: # check by line if line[-1] == "\n": newList.append(line[:-1]) else: newList.append(line) print(newList) for line in f: # easier way to clean up newList.append(line.strip()) print(newList)
true
b28a0fac399add9ac14f5b88e57df770089f5c59
Guitarman9119/Everything-Python-Related
/Tutorials and Snippets/Variables and Simple Data Types/string.py
1,019
4.5
4
""" We will look at simple methods and small programs you can create using strings! The programs is commented out just uncomment to see how it works. """ # .title() method - displays each word in titlecase, where each word begins with a capital letter # A method is an action Python can perform on a piece of data #Example book_title = "harry potter" #print(book_title.title()) #this will give the output Harry Potter # .upper() #print(book_title.upper()) #lower() #print(book_title.lower()) """ Combining or Concatenating Strings """ first_name = "Vernon" last_name = "Peens" full_name = first_name + " " + last_name #print(full_name) #print("Hello, " + full_name.title() + "!") Here we greet the user, using the title() method if name was given in other format to correct the format """ Adding Whitespace to Strings with Tabs or Newlines """ # we use \t to add 4 spaces and \n for a new line """ Stripping Whitespace """ # .lstrip() and .rstrip on a string and strip() # strip the spaces in a string
true
a139d0b83d6e485b310e66e28a42fbeab60bc733
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter10/0009_rev07_match_digits_space_characters.py
500
4.25
4
""" Review Question 7 Write a regular expression which matches strings which starts with a sequence of digits - at least one digit - followed by a blank and after these arbitrary characters """ import re def main(): user_string = input("Enter sequence to match ") pattern = re.compile(r"\d+\s+\w+") match_object = pattern.match(user_string) if match_object: print("Pattern matches") else: print("Pattern does not match") if __name__ == "__main__": main()
true
0bed78657b3120147eb241427f1d117a918a5c8f
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter12/0002_json_load.py
1,197
4.1875
4
""" Program 12.1 Demonstrate Python Deserializing Using JSON load() method """ import json def main(): with open("Chapter12/personal_data.json", "r") as f: json_object_data = json.load(f) print(f"Type of data returned by json load is {type(json_object_data)}") print(f"First Name is {json_object_data['first_name']}") print(f"Middle Name is {json_object_data['middle_name']}") print(f"Last Name is {json_object_data['last_name']}") print(f"Phone Number is {json_object_data['contact']['phone']}") print(f"Email ID is {json_object_data['contact']['email']}") print("----------------********************----------------") for each_json_object in json_object_data["address"]: print(f"Address Type is {each_json_object['address_type']}") print(f"Street Name is {each_json_object['street']}") print(f"City Name is {each_json_object['city']}") print(f"Zip Number is {each_json_object['zip_code']}") print(f"State Name is {each_json_object['state']}") print("----------------********************----------------") if __name__ == "__main__": main()
false
194b821febf732fef98858678988f211a3601abe
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter06/0012_lists_cont(1).py
584
4.65625
5
""" Nested Lists A list inside another list is called a nested list and you can get the behaviour of nested lists in Python by storing lists within the elements of another list Traverse through items of a nested list using a for loop nested_list_name = [[item_1, item_2, item_3], [item_4, item_5, item_6], [item_7, item_8, item_9]] """ asia = [["India", "Japan", "Korea"], ["Srilanka", "Myanmar", "Thailand"], ["Cambodia", "Vietnam", "Isreal"]] asia[0] asia[0][1] asia[1][2] = "Philippines" asia
true
0d62a0e6f029ddbbe257f6a661206f38b34cc5d4
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter06/0002_build_list.py
470
4.1875
4
""" Program 6.1 Dynamically Build User Input as a List """ def main(): list_items = input("Enter list items separated by a space\n").split() print(f"List items are {list_items}") items_of_list = [] total_items = int(input("Enter the number of items\n")) for i in range(total_items): item = input("Enter list item:\n") items_of_list.append(item) print(f"List items are {items_of_list}") if __name__ == "__main__": main()
true
8e0b5d2405057f10c43390b0931e79452fa3b12f
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter07/0007_count_characters.py
621
4.375
4
""" Program 7.6 Count the Number of Characters in a String Using Dictionaries. Display the Keys and Their Values in Alphabetical order """ def construct_character_dict(word): character_count_dict = dict() for each_character in word: character_count_dict[each_character] = character_count_dict.get(each_character, 0) + 1 sorted_list_keys = sorted(character_count_dict.keys()) for each_key in sorted_list_keys: print(each_key, character_count_dict.get(each_key)) def main(): word = input("Enter a string\n") construct_character_dict(word) if __name__ == "__main__": main()
true
f7a398e1bd474d711dd6004b39549a4426d9920a
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter10/0011_rev09_match_z.py
379
4.21875
4
""" Review Question 9 Matches a word containing "z" """ import re def main(): user_string = input("Enter sequence ") pattern = re.compile(r"\b\w*z\w*\b") match_object = pattern.search(user_string) if match_object: print("Match found") print(match_object.group()) else: print("No match found") if __name__ == "__main__": main()
true
f0c09949b2cd1e8d489b1b2b9a63191b590bdf9b
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter08/0002_iterate_over_tuples.py
289
4.34375
4
""" Program 8.1 Iterate Over Items in Tuples Using for Loop """ ocean_animals = ("electric_eel", "jelly_fish", "shrimp", "turtles", "blue_whale") def main(): for each_animal in ocean_animals: print(f"{each_animal} is an ocean animal") if __name__ == "__main__": main()
false
32fdc6db8f1557d2b7e78b732f1a480ee2852ada
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter07/0002_dynamically_build_dictionary.py
947
4.25
4
""" Program 7.1 Dynamically Build User Input as a List """ def main(): print("Method 1: Building Dictionaries") build_dictionary = {} for i in range(0, 2): dic_key = input("Enter key\n") dic_val = input("Enter val\n") build_dictionary.update({dic_key: dic_val}) print(f"Dictionary is {build_dictionary}") print("Method 2: Building Dictionaries") build_dictionary = {} for i in range(0, 2): dic_key = input("Enter key\n") dic_val = input("Enter val\n") build_dictionary[dic_key] = dic_val print(f"Dictionary is {build_dictionary}") print("Method 3: Building Dictionaries") build_dictionary = {} i = 0 while i < 2: dic_key = input("Enter key\n") dic_val = input("Enter val\n") build_dictionary.update({dic_key: dic_val}) i += 1 print(f"Dictionary is {build_dictionary}") if __name__ == "__main__": main()
false
1d82767074abb9b9412fef5d37ad4f6a8df64a6c
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter05/0006_vowel_consonant_blank_count.py
665
4.125
4
""" Program 5.4 Count the Total Number of Vowels, Consonants and Blanks in a String """ def main(): user_string = input("Enter a string:\n") vowels = 0 consonants = 0 blanks = 0 for each_character in user_string: if each_character in "aeiou": vowels += 1 elif each_character == " ": blanks += 1 else: consonants += 1 print(f"Total number of Vowels in user entered string is {vowels}") print(f"Total number of Consonants in user entered string is {consonants}") print(f"Total number of Blanks in user entered string is {blanks}") if __name__ == "__main__": main()
true
1e64029b8ef114ff2c4e68b5abbac3bd8bccbd4d
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter06/0024_rev13_list_divisible_5_or_6.py
371
4.1875
4
""" Review Question 13 Create a list of numbers 1-100 that are either divisible by 5 or 6 """ def create_list(): my_list = list() for i in range(1,101): if i % 5 == 0 or i % 6 == 0: my_list.append(i) return my_list def main(): my_list = create_list() print(f"The list is:\n{my_list}") if __name__ == "__main__": main()
true
1ef79325a3b66bcfd131ca9d5c7d5474c07295c0
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter06/0019_rev08_insertion_sort.py
561
4.34375
4
""" Review Question 8 Sort elements in a list in ascending order using insertion sort """ def insertion_sort(list_name): for j in range(1, len(list_name)): key = list_name[j] i = j - 1 while i >= 0 and list_name[i] > key: list_name[i+1] = list_name[i] i = i - 1 list_name[i+1] = key def main(): integer_list = list([5, 2, 4, 6, 1, 3]) print(f"List is\n{integer_list}") insertion_sort(integer_list) print(f"Sorted list is\n{integer_list}") if __name__ == "__main__": main()
true
ee74b2992a1f2f64d01f373c485285c30947a284
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter07/0015_rev05_daily_temp.py
562
4.1875
4
""" Review Question 5 Prompt user for average temperature for each day of the week and return a dictionary containing the entered information """ def create_dictionary(): temperature = { "Monday": 0, "Tuesday": 0, "Wednesday": 0, "Thursday": 0, "Friday": 0, "Saturday": 0, "Sunday": 0, } for key in temperature.keys(): temperature[key] = int(input(f"Enter Temperature on {key} ")) print(temperature) def main(): create_dictionary() if __name__ == "__main__": main()
true
93a8cb7a17b2dc6ebf8095a601db651482965c2a
SohanJadhav/python_assignments
/Assignment1/Assignment1_10.py
237
4.125
4
def display(name): nameLength = len(name) return nameLength def main(): name = input("Enter Name") lret = display(name) print("Length of Entered Name:{} is {}".format(name,lret)) if __name__=="__main__": main()
false
fc532344f23b9a1105d248e1378a902636f76ee7
pablo2221/TAU-Python
/venv/practica2.py
1,478
4.4375
4
"""Esta es una de las primeras practicas del curso intro a la progra con Python, utilizamos version 3.9.""" #Este es la practica 1 nombre = input("Hola Digite su nombre por favor ") print("su nombre es {}".format(nombre)) #Esta es la practica 2 provincia = input("Digite el nombre de su provincia: ") print("La provincia de residencia es: {}".format(provincia)) #Esta es la practica 3 def datos_persona(nombre, correo, cedula, carrera, telefono): print("Hola {}, su correo electronico es {}, su cedula es {}, actualmente estudias la carrera de {} y su numero " "de telefono es {}".format(nombre, correo, cedula, carrera, telefono)) name = input("Hola digite su nombre ") email = input("Hola digite su correo ") id = input("Hola digite su cedula ") career = input("Hola digite su carrera ") phone = int(input("Hola digite su telefono ")) datos_persona(name, email, id, career, phone) #Esta es la practica 4, calculo de area de triangulo base = int(input("Digite la medida de la base: ")) altura = int(input("Digite la medida de la altura: ")) area = ((base*altura)/2) print("El resultado del area del triangulo es: {}".format(area)) #Esta es la practica 5, convertir monto de colones a dolares y euros monto_colones = float(input("Digite el monto en colones")) conversion_dolares = str(monto_colones/604) conversion_euros = str(monto_colones/717) print("El monto en dolares es: "+conversion_dolares+" Y la conversion en Euros es: "+conversion_euros)
false
5a338cffa3305c2b5d91daf92941dda4d457607b
jianhui-ben/leetcode_python
/114. Flatten Binary Tree to Linked List.py
921
4.125
4
#114. Flatten Binary Tree to Linked List # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ ## tree traversal ## O(n), space O(n) if not root: return self.flatten(root.left) self.flatten(root.right) cur_left= root.left while cur_left and cur_left.right: cur_left=cur_left.right if cur_left: cur_left.right = root.right root.right=root.left root.left = None ## iterative O(1) space traversal is tricky
true
2d606d022c50ddf8e08dfe8fd496f87b764f2c71
jianhui-ben/leetcode_python
/28. Implement strStr().py
373
4.21875
4
#Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. #Example 1: #Input: haystack = "hello", needle = "ll" #Output: 2 #Example 2: #Input: haystack = "aaaaa", needle = "bba" #Output: -1 def strStr(haystack: str, needle: str) -> int: if needle=='': return 0 return haystack.find(needle)
true
a66562d113f86fd1a44bfe6552b88b41f9110326
jianhui-ben/leetcode_python
/249. Group Shifted Strings.py
1,415
4.21875
4
#249. Group Shifted Strings #We can shift a string by shifting each of its letters to its successive letter. #For example, "abc" can be shifted to be "bcd". #We can keep shifting the string to form a sequence. #For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz". #Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order. #Example 1: #Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"] #Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]] #Example 2: #Input: strings = ["a"] #Output: [["a"]] class Solution: def groupStrings(self, strings: List[str]) -> List[List[str]]: def convert(word): if len(word) == 1: return '-' res = '' for i in range(1, len(word)): first, second= word[i - 1], word[i] if ord(second) >= ord(first): d = ord(second) - ord(first) else: d = ord('z') - ord(first) + 1 + ord(second) - 97 res += str(d) + '_' return res stored = defaultdict(list) for word in strings: stored[convert(word)].append(word) return list(stored.values())
true
3f8b1f517ead7581dcbed4cb2e844aa952943ab1
jianhui-ben/leetcode_python
/341. Flatten Nested List Iterator.py
2,078
4.4375
4
#341. Flatten Nested List Iterator #Given a nested list of integers, implement an iterator to flatten it. #Each element is either an integer, or a list -- whose elements may also be integers or other lists. #Example 1: #Input: [[1,1],2,[1,1]] #Output: [1,1,2,1,1] #Explanation: By calling next repeatedly until hasNext returns false, # the order of elements returned by next should be: [1,1,2,1,1]. # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedIterator: ## most efficient way to implement it def __init__(self, nestedList: [NestedInteger]): from collections import deque self.list= deque(nestedList) def next(self) -> int: return self.list.popleft().getInteger() def hasNext(self) -> bool: while self.list and not self.list[0].isInteger(): cur_nest_list=self.list.popleft().getList() for i in range(len(cur_nest_list)-1, -1, -1): self.list.appendleft(cur_nest_list[i]) return len(self.list)>0 class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.l=[] def getall(nestedList): # while nestedList.getInteger() or nestedList.getList(): for ele in nestedList: if ele.isInteger(): self.l.append(ele.getInteger()) else: getall(ele.getList()) getall(nestedList) def next(self): """ :rtype: int """ return self.l.pop(0) def hasNext(self): """ :rtype: bool """ return len(self.l)!=0 # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
ac657a6189390f3b35f6222f17bef41a96e7ea40
jianhui-ben/leetcode_python
/35. Search Insert Position.py
459
4.28125
4
#Given a sorted array and a target value, return the index if #the target is found. If not, return the index where it would be if it were inserted in order. #You may assume no duplicates in the array. #Example 1: #Input: [1,3,5,6], 5 #Output: 2 def searchInsert(nums, target) -> int: i=0 while i<len(nums): if nums[i]>=target: return i i+=1 return len(nums) searchInsert([1,3,5,6], 7) ##4
true
b16ecd06ede171e5d26860c274d2d8ad20b2bd0b
jianhui-ben/leetcode_python
/332. Reconstruct Itinerary.py
2,340
4.1875
4
#332. Reconstruct Itinerary #Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. #Note: #If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. #All airports are represented by three capital letters (IATA code). #You may assume all tickets form at least one valid itinerary. #One must use all the tickets once and only once. #Example 1: #Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] #Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: ##hashmap and backtracking stored= collections.defaultdict(list) available_tickets=dict(collections.Counter([(a, b)for a,b in tickets])) for fr, to in tickets: stored[fr].append(to) for fr, tos in stored.items(): stored[fr]=sorted(tos) ##backtracking(visited, cur_path, stored, cur_location) def dfs(available_tickets, cur_path, cur_location): # print(cur_path) if not available_tickets: return cur_path for next_stop in stored[cur_location]: if (cur_location, next_stop) in available_tickets: available_tickets[(cur_location, next_stop)]-=1 if available_tickets[(cur_location, next_stop)]==0: available_tickets.pop((cur_location, next_stop)) cur_path.append(next_stop) out=dfs(available_tickets, cur_path, next_stop) if out: return out else: if (cur_location, next_stop) in available_tickets: available_tickets[(cur_location, next_stop)]+=1 else: available_tickets[(cur_location, next_stop)]=1 cur_path.pop() return None return dfs(available_tickets, ['JFK'], "JFK")
true
84adf1f3dd08a523a375815a04f2843b9651a29d
adarshbaluni/gfg
/datastructures/array/reverseArrayRecursive.py
533
4.375
4
#http://www.geeksforgeeks.org/write-a-program-to-reverse-an-array/ import sys def reverseArray(array, front,rear): if front >= rear: return temp = array[front] array[front] = array[rear] array[rear] = temp reverseArray(array,front+1, rear-1) if __name__ == "__main__": array = raw_input("Enter Array elements, separated by space >> ") array = map(int,array.split()) front = 0 rear = len(array) - 1 if not len(array) == 1 or len(array) : reverseArray(array,front,rear) print "Reversed array is",array
false
564c51df9df8f23f302af9bf37ca7fb22439e1e5
NatkinMA/DataScience
/vector/vectors.py
804
4.40625
4
''' Домашнее задание N8 Создать класс для представления трехмерных векторов (обычных евклидовых). С помощью специальных методов: "__add__", "__mul__", "__abs__", "__bool__", "__str__" - определить сложение векторов, умножение вектора на число, длинна вектора, булево значение (True - если длинна > 0) и строковое представление объекта. ''' from vector import Vector if __name__ == '__main__': my_vector = Vector(3, 2, 1) print(my_vector) print(my_vector + my_vector) print(my_vector * 5) print(7 * my_vector) print(abs(my_vector)) print(bool(my_vector))
false
b8e7a91ff387107172142d3baa0e724dd2c25220
RahulK847/guess-the-number-start
/main.py
1,257
4.375
4
#Number Guessing Game Objectives: # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answer correct, show the actual answer to the player. # Track the number of turns remaining. # If they run out of turns, provide feedback to the player. # Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode). from art import logo import random print(logo) print("""Welcome to the Number Guessing Game! I'm thinking of a number between 1 and 100.""") number=random.randint(1,100) print(f"pssst, number is {number}") life = 0 difficulty=input("Choose a difficulty. Type 'easy' or 'hard': ").lower() if difficulty=="easy": life = 10 elif difficulty=="hard": life=5 else: print("Invalid Input") while life!=0: print(f"You have {life} attempts remaining to guess the number.") guess = int(input("Make a Guess: ")) if guess==number: print(f"You got it! The answer was {number}") break elif guess>number: print("Too high.") print("Guess again") life-=1 else: print("Too low.") print("Guess again") life-=1
true
658cd9f32da75bbb468af9ae92c502448c42099f
PatSchmitt/PythonHomework
/app.py
1,657
4.34375
4
## FAHRENHEIT TO CELSIUS def fahrenheit_to_celsius(input): print ("Fahrenheit to Celsius conversion.") ## Takes input as int fahrenheit = int(input("What is the temperature in Fahrenheit?: ")) ##Math celsius = (fahrenheit - 32) * 5 / 9 rounded_celsius = round(celsius, 2) #Print string and celsius variable print ("The temperature in Celsius is: ", rounded_celsius) ## CELSIUS TO FAHRENHEIT def celsius_to_fahrenheit(input): print ("Celsius to Fahrenheit conversion.") ## Takes input as int celsius = int(input("What is the temperature in Celsius?: ")) ## Math fahrenheit = (1.8 * celsius) + 32 rounded_fahrenheit = round(fahrenheit, 2) ##Print string and fahrenheit variable print ("The temperature in Fahrenheit is: ", rounded_fahrenheit) #function to select which calculator used def select_conversion(input): #1 = Fahrenheit to Celsius, 2 = Celsius to Fahrenheit. Anything else returns string 'Not a valid input'. user_int_choice = int(input("Which converter are you looking for?: ")) if user_int_choice == 1: return fahrenheit_to_celsius(input) elif user_int_choice == 2: return celsius_to_fahrenheit(input) else: #if input isn't the number 1 or 2, returns string. return "Not a valid input." ## Executing functions if __name__ == "__main__": print ("SELECT CONVERSION TYPE") print ("FAHRENHEIT -> CELSIUS - '(1)'") print ("CELSIUS -> FAHRENHEIT - '(2)'") ##Runs select function print (select_conversion(input)) #Program should continue from input to selected function.
true
2e61a0a95b118cfe169044a2da95106944b58b17
YBrady/pands-problem-set
/second.py
1,778
4.125
4
# Problem No 9 # -------------------------------------------------------------------------------- # Write a program that reads in a text file and outputs every second line. The program # should take the filename from an argument on the command line. # -------------------------------------------------------------------------------- # # Author: Yvonne Brady # Student ID: G00376355 # # -------------------------------------------------------------------------------- # Need the sys module to read in the file name import sys # This part reads what was entered when the program was called # It is saved as a list in sys.argv # If there are more or less than two arguments entered, show an error message if len(sys.argv) != 2: print("Please only supply a single filename.") else: # Make sure what was inputted is actually a file name try: # The file name should be the second element of the sys.argv list # (The first item is calling the program ie "problem-9.py") txtFile = open(sys.argv[1]) # Setting a variable to 0 to count so we can recognise every second line lines = 0 # Loops through each line in the file for line in txtFile: # Checks to see if it is every second line by checking the modulo 2 on the lines counter # As it starts at 0, the modulo will be 0 every second line beginning with the first line if not(lines%2): # This prints the line. The end bit ensures there is no carriage return in the printout. print(line, end ="") # Updates the line counter lines += 1 # If no such file was found except FileNotFoundError: # Error message print("Please enter a valid file!")
true
8c657ae6d5d7855fe810a2c163e62d2e829ff8b5
Asabeneh/python-in-amharic
/conditionals.py
792
4.1875
4
# Conditionals x = 0 if x > 0: print('The number is greater than 0') elif x == 0: print('The number is zero.') else: print('The number is negative') userInput = input('Enter value:') weather = userInput.lower() if weather == 'rainy': print('Please, take your raincoat.') elif weather == 'foggy': print('The day seems very foggy') elif weather == 'cloudy': print('The weather is gloomy and cloudy') elif weather == 'sunny': print('Go out freely, the day seems very shiny') else: print('No one knows about the day') # Conditionals if, if else, if elif else ''' age = int(input('Enter your age: ')) if age >= 18 : print('You are old enough to drive.') else: years_left = 18 - age print(f'You are left with {years_left} years to drive.') '''
true
f3de0fab981fda0d6c4b2c4c45c378cd7082c100
Asabeneh/python-in-amharic
/arthimetics.py
697
4.4375
4
# Operators:Arithmetic, Assignment, Logical operators, comparison operators # Arithmetic: +, - *, /, %, ** // # ==, >, <, >=, <=, != print(1 + 2) # additon print(2 - 1) # subtraction print(2 * 3) # multiplication print(3 / 2) # division print(3 % 2) # modulous print(3 // 2) # floor division print(7 // 4) print(3 ** 4) # exponentation # 3 * 3 * 3 * 3 # Arthimetics a = 3 b = 4 total = a + b sub = b - a product = a * b remainder = b % a floorDivision = b // a exp = b ** a print('The total is ', total) print('The difference is,', sub) print('The product is ', product) print('The remainder is:', remainder) print('The floor division output', floorDivision) print('The power is ', exp)
true
c516351834dd03ca16dbcd5c2a2d577d6f26974f
Asabeneh/python-in-amharic
/lists.py
1,312
4.15625
4
names = ['Asabeneh', 'Abebe', 'Kebede'] fruits = ['Banana', 'Papaya', 'Mango', 'Avocado'] countries = ['Finland', 'Sweden', 'Estonia', 'Norway'] numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10] print(len(numbers)) print(numbers[2]) print(numbers[3]) print(numbers[-2]) lastIndex = len(numbers) - 1 print(numbers[lastIndex]) mixed_values = ['Banana', 10, [1, 2, 3, 4], 9.81, 3.14, True, 2020] shoppingList = ['Banana', 'Milk', 'Honey', 'Meat', 'Coffee', 'Apple'] print(shoppingList) shoppingList[0] = 'Orange' print(shoppingList) shoppingList[2] = 'Sugar' print(shoppingList) lastIndex = len(shoppingList) - 1 shoppingList[lastIndex] = 'Grape' print(shoppingList) list_one = [1, 2, 3, 3] list_two = [4, 5, 6] lists = list_one + list_two print(lists) # List methods: append, extend, slice, sort nums = [1, 2, 3] print(len(nums)) print(nums) nums.append(4) nums.append(5) print(nums) nums.extend([6, 7, 8, 9, 10]) print(nums) nums.insert(5, 0) print(nums) fruits = ['Banana', 'Papaya', 'Mango', 'Avocado'] print(fruits) print(fruits[::-1]) fruits.sort() print(fruits) # sort , sorted countries = ['Finland', 'Sweden', 'Estonia', 'Norway'] sorted_countries = sorted(countries) print(countries) print(sorted_countries) # sort sorted_countries_2 = countries.sort() print(sorted_countries_2) print(countries)
false
ed2af8ada9b3f9723ccb00faadf756eba8bccd69
scoulston/Python-Practice-Algorithms
/4-list_and_tuple_nums.py
671
4.375
4
#!/usr/bin/env python #Question 4 #Level 1 #Question: #Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #Suppose the following input is supplied to the program: #34,67,55,33,12,98 #Then, the output should be: #['34', '67', '55', '33', '12', '98'] #('34', '67', '55', '33', '12', '98') try: lst = input("Enter your list of numbers separated by a comma (no spaces): ").split(',') tup = tuple(lst) for i in range(len(lst)): lst[i] = int(lst[i]) print(lst) print(tup) except ValueError: print("List must be of whole numbers.")
true
e083368b006771f0f73182ad1f865b0887f14144
PauloMorillo/holbertonschool-interview
/0x09-utf8_validation/0-validate_utf8.py~
1,390
4.125
4
#!/usr/bin/python3 def validUTF8(data): """ :type data: List[int] :rtype: bool """ # Number of bytes in the current UTF-8 character n_bytes = 0 # Mask to check if the most significant bit (8th bit from the left) # is set or not mask1 = 1 << 7 # Mask to check if the second most significant bit is set or not mask2 = 1 << 6 for num in data: # Get the number of set most significant bits in the byte if # this is the starting byte of an UTF-8 character. mask = 1 << 7 if n_bytes == 0: while mask & num: n_bytes += 1 mask = mask >> 1 # 1 byte characters if n_bytes == 0: continue # Invalid scenarios according to the rules of the problem. if n_bytes == 1 or n_bytes > 4: return False else: # If this byte is a part of an existing UTF-8 character, then # simply have to look at the two most significant bits # and we make # use of the masks we defined before. if not (num & mask1 and not (num & mask2)): return False n_bytes -= 1 return n_bytes == 0
true
e2682436234e5bac622b34a11d418dc02d2a8383
VinayakSingoriya/Data-Structures-Python
/Binary_Tree/12_Insertion_In_BST (recursive).py
964
4.3125
4
# Recursive implementation of insertion in a BST # Time complexity : O(h), where h is the height of BST class Node: def __init__(self, data): self.data = data self.left = None self.right = None def printInorder(root): if root is not None: printInorder(root.left) print(root.data, end = " ") printInorder(root.right) def insert(root, key): if root is None: return Node(key) else: if root.data == key: return root elif root.data < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root if __name__ == "__main__": r = Node(8) insert(r, 3) # insert(r, 1) # insert(r, 6) # insert(r, 10) # insert(r, 14) # insert(r, 13) # insert(r, 4) # insert(r, 7) # insert(r, 9) printInorder(r)
true
63b2252def57e56fce8a4ef0306062a118914668
VinayakSingoriya/Data-Structures-Python
/Graph/AdjacencyList.py
1,313
4.15625
4
# Representation of Graph Data Structure through Adjacency List # A class to represent the node of the adjancecy List class adjNode: def __init__(self, data): self.vertex = data self.next = None class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None]*self.V def add_edge(self, frm , to): node = adjNode(to) node.next = self.graph[frm] self.graph[frm] = node # Adding the source node to the destination # as it is the undirected Graph node = adjNode(frm) node.next = self.graph[to] self.graph[to] = node def print_graph(self): for i in range(self.V): print(f"Adjacancy list of vertex {i} head", end = '') temp = self.graph[i] while temp: print(f"-> {temp.vertex}", end="") temp = temp.next print() # Driver Mode if __name__ == "__main__": V = 5 g = Graph(V) g.add_edge(0, 1) g.add_edge(0, 4) g.add_edge(1, 3) g.add_edge(1, 4) g.add_edge(2, 3) g.add_edge(3, 4) g.add_edge(1, 2) g.print_graph()
true
d9ad804dcddeff81b38ecbc52a183dee71670a17
Patrick-Gemmell/ICS3U-Unit3-06-Python
/randomnumber.py
775
4.1875
4
#!/usr/bin/env python3 # Created by: Patrick Gemmell # Created on: September 12 2019 # This program does a guessing game import random def main(): # this function guess and compares number while True: # input integer_as_string = input("Try an guess my integer from 0-9: ") try: integer_as_number = int(integer_as_string) # process and output print("") if integer_as_number == random.randint(0, 9+1): print("Correct!") break else: print("Sorry that's wrong, guess again?") except Exception: print("This is not an integer") finally: print("Thanks for playing") if __name__ == "__main__": main()
true
b50101ea4370788d3f7c67fb3b1cad329b2edb58
candytale55/Bitwise_Operations_Py_2
/07_A_BIT_of_This_AND_That.py
1,063
4.21875
4
""" The bitwise AND (&) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if the corresponding bits of both numbers are 1. 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 For example: a: 00101010 42 b: 00001111 15 =================== a & b: 00001010 10 Using the & operator can only result in a number that is less than or equal to the smaller of the two values. """ print 0b111 & 0b1010 # 2 print bin(0b111 & 0b1010) # 0b10 print int(0b10) # 2 # 0b111 (7) & 0b1010 (10) = 0b10 (4) print 0b1110 & 0b101 # 4 print bin(0b1110 & 0b101) # 0b100 # https://discuss.codecademy.com/t/what-if-i-want-to-compare-bit-strings-of-uneven-length/340567 """ If you want to compare bit strings of uneven length, the leftmost unfilled bits will be considered zeros. For example strings 1001 and 1001 1010 would work like this: 0000 1001 & 1001 1010 ------------- 0000 1000 """ print (0b1001 & 0b10011010) # 8 print bin(0b1001 & 0b10011010) # 0b1000
true
052cdfa0a014e700462f3cfb40b21906f72c0d4f
candytale55/Bitwise_Operations_Py_2
/08_A_BIT_of_This_OR_That.py
663
4.5
4
""" The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned ON if either of the corresponding bits of either number are 1. 0 | 0 = 0 0 | 1 = 1 1 | 0 = 1 1 | 1 = 1 For example: a: 00101010 42 b: 00001111 15 ================ a | b: 00101111 47 The bitwise | operator can only create results that are greater than or equal to the larger of the two integer inputs. Meaning: 110 (6) | 1010 (10) = 1110 (14) """ print 0b1110 | 0b101 # 15 print bin(0b1110 | 0b101) # 0b1111 # https://discuss.codecademy.com/t/why-is-my-output-of-bitwise-or-not-correct/340568
true
d8fe5b8fe040a25e69f12327089af80383185c8e
sunshineonmyshoulders/python
/zumbis/lista 2/1.py
1,064
4.28125
4
"""1. Faça um Programa que peça os três lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. """ l1 = int(input("lado 1\n")) l2 = int(input("lado 2\n")) l3 = int(input("lado 3\n")) t = l1 + l2 + l3 if t == 180: if l1 == l2 and l2 == l3: print("É um equilátero") if l1 == l2 and l2 != l3 or l1 != l2 and l2 == l3: print("É um isósceles") if l1 != l2 and l2 != l3: print("É um escaleno") else: print("Não é um triângulo") # Triângulo é o polígono com o menor número de lados (3 lados) e a soma dos seus ângulos internos é igual a 180o. # Triângulo Equilátero: é todo triângulo que apresenta os três lados com a mesma medida. # Triângulo Isósceles: é todo triângulo que apresenta dois lados com a mesma medida, ou seja, dois lados de tamanhos iguais. # Triângulo Escaleno: é todo triângulo que apresenta os três lados com medidas diferentes, ou seja, três lados de tamanhos diferentes.
false
26795547134f4c9ae2f418c353e882034f099bf9
muthianikev/golclinics-assignments
/Kevin-Muthiani/Arrays_and_Strings/reverse_array_in_place.py
384
4.46875
4
# Write a function reverseArray(A) that takes in an array A and reverses it, # without using another array or collection data structure i.e. in-place. def reverseArray(arr): n = len(arr) for i in range(n//2): arr[i], arr[n-1-i] = arr[n-1-i], arr[i] # Test function if __name__ == "__main__": myArray = [10, 5, 7, 6, 9] reverseArray(myArray) print(myArray)
true
b7a62309adb0f13aa661c3a26b158db899a46dc6
muthianikev/golclinics-assignments
/Kevin-Muthiani/Arrays_and_Strings/minimum_swaps.py
759
4.1875
4
# https://www.hackerrank.com/challenges/minimum-swaps-2/problem # You are given an unordered array consisting of consecutive integers # [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any # two elements. Find the minimum number of swaps required to sort the # array in ascending order. def minimumSwaps(arr): swaps = 0 n = len(arr) valueIndexDict = dict(zip(arr, range(1, n+1))) for i in range(1,n+1): if valueIndexDict[i] != i: # Swap valueIndexDict[arr[i-1]] = valueIndexDict[i] arr[valueIndexDict[i]-1] = arr[i-1] swaps += 1 return swaps # Test function if __name__ == "__main__": myArray = [4, 3, 1, 2] print(minimumSwaps(myArray))
true
c038df4cc3dabc8bae521afc7f901b1569ff2c1b
narayanbinu21/c97
/main.py
296
4.21875
4
introstring=input("enter string") charectercount=0 wordcount=1 for i in introstring: charectercount=charectercount+1 if(i == ' '): wordcount=wordcount+1 print("number of word in string") print(wordcount) print("number of charecter in this string") print(charectercount)
true
699e7494c120ce2fe14000ad05181fed49121c28
jnederlo/learning_python
/ex20.py
976
4.1875
4
from sys import argv script, input_file = argv def print_all(f): print(f.read()) # seek will set the pointer to whatever index point in the array of the object file that was opened. def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) # open takes the input file, and then creates a file object called "current_file" current_file = open(input_file) print("First let's print the whole file:\n") print_all(current_file) # the tell() method will give us the current position in the open file. print(current_file.tell()) print("Now let's rewind kind of like a tape.") # this function takes in the current file and rewinds it to some point we specifiy in the function. rewind(current_file) print("Let's print three lines:") current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
true
7b69e6b014691f8d5b4c69a8f6ad1748747fac6b
abishek6380/python-program
/sort array.py
324
4.3125
4
arr = [5, 2, 8, 7, 1] temp =0 print(f"Elements of original array:{arr} ") for i in range(0, len(arr)): for j in range(i+1, len(arr)): if(arr[i] > arr[j]): temp = arr[i] arr[i] = arr[j] arr[j] = temp print("Elements of array sorted in ascending order: ",arr,end=" ")
false
da78f831c654086bda3a5bd16fcb5e95da702dd7
kkirchhoff01/MiscScripts
/binary_tree.py
1,764
4.15625
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class Tree: def __init__(self): self.root = None def insert_node(self, value): if self.root is None: self.root = Node(value) else: self.recursive_insert(self.root, value) def recursive_insert(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self.recursive_insert(node.left, value) else: if node.right is None: node.right = Node(value) else: self.recursive_insert(node.right, value) def search_tree(self, value): if self.root is None: return self.root else: return self.recursive_search(self.root, value) def recursive_search(self, node, value): if node.value == value: return node elif node.left and value < node.value: return self.recursive_search(node.left, value) elif node.right and value > node.value: return self.recursive_search(node.right, value) def print_tree(self): if self.root is not None: self.recursive_print(self.root) def recursive_print(self, node): if node is not None: self.recursive_print(node.left) print str(node.value) + ' ' self.recursive_print(node.right) if __name__ == "__main__": import sys values = None with open(sys.argv[1], 'r') as fh: values = fh.readlines() tree = Tree() for value in values: tree.insert_node(float(value)) tree.print_tree()
false
9da70b9b9f41b0903190feb382c833a086865c13
akathecoder/LearnGit
/Python Projects/IBM Assignment 2/BloodType.py
765
4.125
4
x = input() y = input() if (x=="A") or (y=="A"): if (x=="B") or (y=="B"): print("The combination of ABO alleles "+x+" and "+y+" results in blood type AB.") elif (x=="O") or (y=="O"): print("The combination of ABO alleles " + x + " and " + y + " results in blood type A.") else: print("The combination of ABO alleles " + x + " and " + y + " results in blood type A.") elif (x=="B") or (y=="B"): if (x=="B") or (y=="B"): print("The combination of ABO alleles " + x + " and " + y + " results in blood type B.") else: print("The combination of ABO alleles " + x + " and " + y + " results in blood type B.") else: print("The combination of ABO alleles " + x + " and " + y + " results in blood type O.")
false
c3af2cbd7e60dd48c13d08093a5e6a5bd4783887
akathecoder/LearnGit
/Python Projects/IBM Assignment 1/Heron's Formula.py
350
4.1875
4
# This Program tells the area of a triangle using Heron's Formula. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) x3 = int(input()) y3 = int(input()) a = ((x1-x2)**2 + (y1-y2)**2)**0.5 b = ((x2-x3)**2 + (y2-y3)**2)**0.5 c = ((x3-x1)**2 + (y3-y1)**2)**0.5 s = (a+b+c)/2 area = (s*(s-a)*(s-b)*(s-c))**0.5 print('%.2f'%area)
false
510a429409dc20bb9688633c8e0b950952b409d7
sarah-fitzgerald/PANDS
/Week04/lab4.2.4guess3.py
576
4.1875
4
#This program asks user to guess a number and continue to prompt user until user gets the number right #Will let user know if the number is too high or too low #Number will be generated by program betwen 0 and 100 #Author: Sarah Fitzgerald import random number = random.randint(1, 100) guess = int(input("Please guess the number: ")) while guess != number: if number > guess: print ("Too low") elif number < guess: print ("Too high") guess = int(input("Please guess again: ")) print ("Well done! Yes the number was", number)
true