blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
5cc638d480d73a33a413a565f0375a43e51f1606
|
DeekshaKodieur/python_programs
|
/python/factorial_num.py
| 263
| 4.3125
| 4
|
fact=1
num=int(input("Enter the number to find its factorial : "))
#for i in range(1,(num+1)):
#fact = fact * i
i=1
while(i<=num):
fact = fact * i
i = i+1
print("Factorial of a number",num,"is",fact)
input("press enter to exit")
| true
|
a1a9436268be1b94c6cee6075b1bba00fe4ec9a0
|
romulosccp09/python
|
/pythonteste/aula07a.py
| 833
| 4.28125
| 4
|
# Autor: Rômulo de Cravalho.
# Email: romulo514@hotmail.com
# Exemplo Aula07, operadores aritiméticos!
numero = int(input("Digite um valor: "))
numero1 = int(input('Digite outro valor: '))
# Soma.
print('A soma de {} e {}, vale -> {}! \n'.format(numero, numero1, numero + numero1))
#Subtação.
print('A subtração entre {} e {}, vale -> {}! \n'.format(numero, numero1, numero - numero1))
#Multiplicação.
print('A multiplicação entre {} e {}, vale -> {}! \n'.format(numero, numero1, numero * numero1))
# Divisão.
print('A divisão ente {} e {}. vale -> {:.3f}! \n'.format(numero, numero1, numero / numero1))
#Divisão inteira.
print('A divisão inteira entre {} e {}, vale -> {}! 8\n'.format(numero, numero1, numero // numero1))
# Módulo (Resto da divisão).
print('O Módulo entre {} e {}, vale {}!'.format(numero, numero1, numero % numero1))
| false
|
8f6cf04a3d8692607547aa336b7e4f1d370cdb2f
|
kazinayem2011/python_problem_solving
|
/reverse_number.py
| 209
| 4.21875
| 4
|
number=int(input("Please Enter Your Number : "))
reverse=0
i=0
while i<number:
last_num=number%10
reverse=(reverse*10)+last_num
number=number//10
print("The Reverse of numbers are : ", reverse)
| true
|
48e27e4ccab8f032f30e6f8976e0a31e2cc8408b
|
RenanBomtempo/python-learning
|
/collinear-points.py
| 1,117
| 4.3125
| 4
|
import math
#--get three points--
#get first point
print("First point:")
x1 = float(input("x = "))
y1 = float(input("y = "))
#get second point
print("\nSecond point:")
x2 = float(input("x = "))
y2 = float(input("y = "))
#get third point
print("\nThird point:")
x3 = float(input("x = "))
y3 = float(input("y = "))
#calculate slopes
slope1 = math.fabs((y1 - y2)/(x1 - x2))
slope2 = math.fabs((y1 - y3)/(x1 - x3))
#check if slopes are the same
if slope1 == slope2:
print("\nYES! The points are collinear.")
exit()
else:
print("\nNO! The points are not collinear.")
#check what type of triangle they form
side1 = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
side2 = math.sqrt((x1 - x3)**2 + (y1 - y3)**2)
side3 = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
print(side1)
print(side2)
print(side3)
if side1 == side2:
if side1 == side3:
print("The points form an Equilateral triangle")
else:
print("The points form an Isoceles triangle")
elif side1 == side3 or side2 == side3:
print("The points form an Isoceles triangle")
else:
print("The points form an Scalene triangle")
| false
|
3b55dc4538240ac5435a3001aae919e3d94a71c3
|
nataliacarvalhoreis/aula7_python_pdti
|
/resposta06.py
| 980
| 4.1875
| 4
|
# Classe TV: Faça um programa que simule um televisor criando-o como
# um objeto. O usuário deve ser capaz de informar o número do canal e
# aumentar ou diminuir o volume. Certifique-se de que o número do canal
# e o nível do volume permanecem dentro de faixas válidas
class tv:
def __init__(self, canal=11, volume=11):
self.__canal = canal
self.__volume = volume
def maisvol(self):
self.__volume += 1
if self.__volume > 99:
self.__volume = 99
def menosvol(self):
self.__volume -= 1
if self.__volume < 0:
self.__volume = 0
def mudacanal(self, canal):
if canal > 0 and canal < 500:
self.__canal = canal
def mostra(self):
return self.__canal, self.__volume
def __str__(self):
return f'TV Canal:{self.__canal} Volume:{self.__volume}'
novaTV = tv()
novaTV.maisvol()
novaTV.mudacanal(26)
print(novaTV)
| false
|
768a3e44b3d7e5389f0f30c459ff852808e02642
|
Adriannech/phyton-express-course
|
/Greatest_no#.py
| 693
| 4.46875
| 4
|
print("Description: This program will pick the biggest value from string of numbers")
nums = input("Please input number (coma separated):")
nums = nums.split(",")
if len(nums) == 0:
print("There's no input numbers")
exit(0)
for i in range(len(nums)):
if not nums[i].is_numeric():
nums[i] = float(nums[i])
max_num = nums[0]
for num is nums:
if num > max_num:
max_num = num
print(f"Max value: {max_num}")
number1 = input("Please enter first number:")
number2 = input("Please enter second number:")
number1 = float(number1)
number2 = float(number2)
if number1 > number2:
max_number = number1
info = "first number is greater than second number"
| true
|
3e5b9ff16ca688047db0973d5022bf5f56b3c9bb
|
Guiller1999/CursoPython
|
/BBDD/Prueba.py
| 1,813
| 4.125
| 4
|
import sqlite3
def create_connection():
try:
connection = sqlite3.connect("Test.db")
return connection
except Exception as e:
print(e.__str__())
def create_table(connection, cursor):
cursor = connection.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS USUARIOS" +
"(Nombre VARCHAR(20), Apellido VARCHAR(20), Edad INTEGER)"
)
connection.commit()
#cursor.close()
def insert_data(connection, cursor, name, last_name, years):
data_user = [name, last_name, years]
cursor = connection.cursor()
cursor.execute(
"INSERT INTO USUARIOS VALUES(?, ?, ?)", data_user
)
connection.commit()
#cursor.close()
def get_data(connection, cursor):
cursor = connection.cursor()
rows = cursor.execute("SELECT * FROM USUARIOS")
connection.commit()
#cursor.close()
return rows.fetchall()
connection = create_connection()
cursor = connection.cursor()
create_table(connection, cursor)
answer = "s"
while(answer != "n" and answer != "N"):
name = input(">> Ingrese nombre: ")
last_name = input(">> Ingrese apellido: ")
years = input(">> Ingrese edad: ")
insert_data(connection, cursor, name, last_name, years)
print("------------------------------------------------\n")
answer = input(">> Ingresar otro usuario. Presione S(si) / N(no)....")
print("\n------------------------------------------------\n")
rows = get_data(connection, cursor)
print("\n------------------------------------------------\n")
print("\t\t MOSTRANDO DATOS \n")
for row in rows:
print(f" >> Nombre: {row[0]}")
print(f" >> Apellido: {row[1]}")
print(f" >> Edad: {row[2]}")
print("_______________________________________________________\n")
cursor.close()
connection.close()
| false
|
6dc92fcd7d63fded3c67a6ea9a5ae6d8abd8f5ee
|
Li-congying/algorithm_python
|
/LC/String/string_compression.py
| 2,062
| 4.21875
| 4
|
'''
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3:
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
Note:
All characters have an ASCII value in [35, 126].
1 <= len(chars) <= 1000.
'''
class Solution(object):
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
total = 0
cur_char = ''
cur_count = 0
chars.append('')
for char in chars:
if cur_char != char:
# print cur_char, cur_count
chars[total] = cur_char
if cur_count == 1:
total += 1
if cur_count > 1:
str_c = str(cur_count)
for i in range(len(str_c)):
chars[total+1+i] = str_c[i]
total += (1+len(str(cur_count)))
cur_char = char
cur_count = 0
cur_count += 1
print chars[:total]
return total
obj = Solution()
print obj.compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"])
| true
|
89bb52bd6f25cd45531546efc8b5474f6a57ab56
|
gittygupta/Python-Learning-Course
|
/Tutorials/error_exception.py
| 650
| 4.25
| 4
|
# Exception handling
while True:
try:
x = int(input('Enter your fav number: \n'))
print(8/x) # it can cause a ZeroDivisionError
break
except ValueError: # "ValueError" means an exception
print("ok dude you gotta try again")
except ZeroDivisionError:
print("Dude dont use 0")
except:
# this basically exits your program. Used in a wider angle to handle exceptions. Takes all exceptions
break
finally: # the prog executes this line every time no matter what exception it encounters
print("sorry dude you're dumb")
| true
|
ddcd9d1fb9864438fdb3a1017b7798c2beca0311
|
gittygupta/Python-Learning-Course
|
/Tutorials/download_image.py
| 577
| 4.125
| 4
|
import urllib.request
import random
def download_image_file(url):
name = random.randrange(1, 1000)
full_name = str(name) + ".png"
urllib.request.urlretrieve(url, full_name) # used to retrive url to download the image
# it also stores the name of the file and saves the image in the same directory as the program
# .jpg / .png is written at the end of full_name because python stores images as numbers
download_image_file("https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Sunflower_from_Silesia2.jpg/800px-Sunflower_from_Silesia2.jpg")
| true
|
0cb1ae971bb448f326d9c339c76b3ce55aa2429a
|
alvargas/python_project
|
/tuples.py
| 878
| 4.59375
| 5
|
# Tuples (Datatypes) ()
# Conjunto de datos como las listas, pero que no podemos cambiar.
# La tupla es un valor inmutable. El código se ejecuta más rápido.
# Uso real de la tupla: diccionarios o listas (ver al final)
x = (5, 10, 15, 20) # Método más usado
print(x, type(x))
month = ('Enero', "Febrero", 'Marzo', 'Abril')
print(month)
print(month[2])
print(month.index('Abril'))
#x[2] = 30 # Las tuplas no soportan reasignación.
# Constructor. A partir de la función tuple()
y = tuple((5, 10, 15))
print(y)
z = (3)
print("tupla de un elemento:", z, type(z)) # No es considerado tupla sino lista.
z = (3,)
print("tupla de un elemento:", z, type(z)) # Considerado tupla.
del x
#print(x)
print ("")
print ("Métodos y sus propiedades de una tupla: ", (dir(y)))
""" locations{
(36.24343434, 75.23222): "Tokio",
(24.43333334, 91.03232): "New York"
}
"""
| false
|
7925b186f4b42a1fd9e6fefed9bd9495f2ed2d3a
|
wu95063/HelloWorld
|
/About input.py
| 1,271
| 4.1875
| 4
|
full_name=input('what is your name? ')#获取用户输入信息,并将用户信息返回给full_name变量,full_name这个变量的类型是字符串
print(full_name)#输出变量full_name
print('Hello '+full_name)#字符串和字符串可以进行拼接,公式:字符串+字符串=字符串
print(full_name*10)#公式:字符串*整数=字符串
print(full_name+str('00'))#字符串
birth_year=input('Please input your birth year: ')#获取用户输入信息,并将用户信息返回给bitth_year变量,birth_year这个变量的类型是字符串
age=2020-int(birth_year)#定义一个新的变量,调用int函数将birth_year这个字符串类型转换成整数型(所谓的Tyepe Reversion)。
print(age)#输出age这个变量,age这个变量为整数型
print(f'Your age is {age}')#由于age这个变量是整数型,而your age is 是字符串,如果想要把二者直接进行拼接是无法达到的。所以我们调用format函数,↓↓
#来格式化字符串,format函数即为格式化的意思。
#利用大括号{},age的类型是整数型,{age}={整数型}=字符串型,'your age is {age}'即为'字符串 字符串 字符串 字符串',进而输出这些字符串。
| false
|
1dc3f181e8a7ae4eac3c8797441aab88b359f6ac
|
ryanRATM/code_reff
|
/python/variables/02.py
| 559
| 4.375
| 4
|
# this covers basic operations for variable types
# add: +
# subtract: -
# divide: /
# times: *
# mod: %
# All of the above operations work on numbers
print('3 + 1 = ' + str(3 + 1))
print('3 - 1 = ' + str(3 - 1))
print('3 / 2 = ' + str(3 / 2))
print('3 * 7 = ' + str(3 * 7))
print('17 % 6 = ' + str(17 % 6))
# can use + to concatinate strings together into one
myStr1 = "A"
myStr2 = "C"
myStr3 = myStr1 + myStr2
myStr4 = myStr1 + "B" + myStr2
print('myStr1: ' + myStr1)
print('myStr2: ' + myStr2)
print('myStr3: ' + myStr3)
print('myStr4: ' + myStr4)
| false
|
95c3a925e8eb187fadaeffb4c6daef30b1f0af77
|
jmachcse/2221inPython
|
/newtonApproximation.py
| 905
| 4.40625
| 4
|
# Jeremy Mach
# Function to approximate a square root using Newton's algorithm
def sqrt(x):
estimate = float(x)
approximation = 1.0
while abs(approximation - (estimate / approximation)) > (0.0001 * approximation):
approximation = 0.5 * (approximation + (float(x) / approximation))
# When the approximation is less than 0.0001 * approximation,
# the approximation will be returned as the guess for the square root
return approximation
userAns = input("Would you like to calculate a square root? : ")
while userAns == "Y" or userAns == "y":
userNum = input(
"Please enter the number you would like to calculate the square root of: ")
float(userNum)
sqrt = sqrt(userNum)
print("The square root of your number using Newton Iteration is " + str(sqrt))
userAns = input("Would you like to calculate another square root? (Y/N): ")
print("Goodbye!")
| true
|
18bdaade58490386dcfc47784443ad2c3f871af6
|
K-Maruthi/python-practice
|
/variables.py
| 635
| 4.3125
| 4
|
# variables are used to assign values , variables are containers for storing values
x = 7
y = "Hello World"
print(x)
print(y)
#multiple values to multiple variables (no.of variables should be = no.of values)
a,b,c = "orange",22,34.9
print(a)
print(b)
print(c)
# mutliple variables same value
p=q=r=2
print(p)
print(q)
print(r)
#unpack a collection
colours = ["blue","Red","white","black"]
x,y,z,memine= colours
print(x)
print(y)
print(z)
print(memine)
#global variables created outside of a function and can be used globally
x = "awesome"
def myfunc():
x = "fantastic"
print("python is " +x)
myfunc()
print("python is " +x)
| true
|
f20631d07fb9ce2dfcbb9c79114d497f9920011a
|
anhnguyendepocen/100-pythonExercises
|
/66.py
| 369
| 4.15625
| 4
|
# Exercise No.66
# Create an English to Portuguese translation program.
# The program takes a word from the user and translates it using the following dictionary as a vocabulary source.
d = dict(weather="clima", earth="terra", rain="chuva")
# Solution
def translate(w):
return d[w]
word = input("Enter the word 'earth'/'weather'/'rain': ")
print(translate(word))
| true
|
af7d4d3637bf4ad38004e1fc1eae269ec73698cf
|
jeremy-wickman/combomaximizer
|
/combinationmaximizer.py
| 913
| 4.375
| 4
|
# A Python program to print all combinations of items in a list, and minimize based on target
#Import
from itertools import combinations
import pandas as pd
#Set your list of numbers and the target value you want to achieve
numbers = [49.07, 122.29, 88.53, 73.02, 43.99]
target = 250
combo_list = []
#Create a list of combinatorial tuples
for i in range(len(numbers)):
comb=combinations(numbers,i+1)
combs = list(comb)
combo_list.extend(combs)
#Create a list of the sums of those tuples
combo_sum = [sum(tup) for tup in combo_list]
#Create a dataframe with them both
df = pd.DataFrame({'Combo': combo_list, 'Sum': combo_sum})
#Add a column showing the difference between the target and the sum
df['Difference']=target-df['Sum']
#Remove all rows which go over the target price is right style
df = df[df['Difference']>=0]
df = df.sort_values(by='Difference', ascending=True)
df
| true
|
6c3f8a7b460c383133353a966a5aea62b71db49c
|
sunilmummadi/Hashing-1
|
/groupedAnagram.py
| 1,572
| 4.15625
| 4
|
# Leetcode 149. Group Anagrams
# Time Complexity : O(nk) where n is the size of the array and k is the size of each word in the array
# Space Complexity : O(nk) where n is the size of the array and k is the size of each word in the array
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Assign first 26 prime numbers to a letter. The product of prime numbers is unique.
# All the annagrams will have same product.
# Using a hashmap we can store the product as key and anagrams list as value. Iterate through hashmap and append
# the anagrams to the list if the product is already present. Else add it. Return hashmap values as a list
# Your code here along with comments explaining your approach
class Solution:
# Function to calcuate character prime product
def calculatePrime(self, word):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
count = 1
for letter in word:
# ascii value of the letter - ascii value of a i.e 97 gives index of prime number for that letter
index = ord(letter)-ord('a')
count = primes[index]*count
return count
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashmap = dict()
for word in strs:
temp = self.calculatePrime(word)
if temp not in hashmap:
hashmap[temp] = []
hashmap[temp].append(word)
return list(hashmap.values())
| true
|
c661a44b75f35b7599fe3964f8808e57acbd5ed8
|
AlanOkori/Metodos-Numericos
|
/FuncPar.py
| 219
| 4.125
| 4
|
def even(Num):
if Num % 2 == 0 :
print("Is an even number.")
else :
print("Isn't an even number.")
x = int(input("Please, insert a number: "))
even(x)
input("Press key to continue.")
| true
|
c64a4616c571b8d8226f65939cc4e1287651d7c8
|
ananyasahoo-2001/PathaPadha-DS-P-1
|
/PathaPadha DS P-1 Assignment-2/prime_number.py
| 266
| 4.1875
| 4
|
# To find whether a number is prime number or not
num = int(input("Enter a number"))
for i in range(2,num):
if num%i == 0:
print(num , " is not a prime number")
break
else:
print(num , " is a prime number")
break
| false
|
296c0ee856471edba71b14b43931c1219abf4ea2
|
sacobera/practical-python-project
|
/movie_schedule.py
| 601
| 4.1875
| 4
|
current_movies = {'The Grinch' : "11:00 am",
'Rudolph' : "1:00 pm",
'Frosty the snowman' : "3:00 PM",
'Christmas Vacation': "5:00 PM"}
print ("We're showing the following movies:")
for key in current_movies: #this loops over the list of objects
print(key)
movie = input("what movie would you like the showtime for?\n")
showtime = current_movies.get(movie) #if the movie exists, it will get the movie from the list
if showtime == None:
print("Requested showtime isn't playing")
else:
print(movie, "is playing at", showtime )
| true
|
78cbcdd59219ad25f80c5ee6a7ae9dc9cf4d9d51
|
Gindy/Challenges-PCC
|
/Challenges_PCC/Playing_cards/Playing_cards_3-1.py
| 1,196
| 4.28125
| 4
|
# A standard deck of cards has four suites: hearts, clubs, spades, diamonds.
# Each suite has thirteen cards:
# ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen and king
cards = []
suits = ['Hearts']
royals = ["Jack", "Queen", "King", "Ace"]
deck = []
# We start with adding the numbers 2 through 10.
# Since there are only 4 royals and 9 'regular card'
# Which makes 13 card in total per suit.
def Creating_deck():
for i in range(2, 11):
cards.append(str(i))
# Added the roys to to list
for r in range(4):
cards.append(royals[r])
# Now we attach the suits
for r in range(1):
for c in range(13):
card = (cards[c] + " of " + suits[r])
# Let's add the cards to the deck
deck.append(card)
# Perfect we have a full deck of cards
# print(deck)
# Now we get to the actual assignment, namely printing the list
# and show the heart cards
# Actually, only printing the first 3 cards is already adequate
print("The first 3 items in the list:", deck[:3])
# You can print them as 'strings' as well:
print("The first 3 cards printed as strings: ")
for item, value in enumerate(deck):
if item == 3:
break
print(value)
Creating_deck()
| true
|
5a55a167f68f2c9cdb2431d6b6f17f6edab23fec
|
athwalh/py4e_ch9_solutions
|
/ex_94.py
| 897
| 4.125
| 4
|
#Exercise 4: Add code to the above program to figure out who has the most messages in the
#file. After all the data has been read and the dictionary has been created, look
#through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to
#find who has the most messages and print how many messages the person has.
f1 = input("Enter File: ")
emails = []
counts = dict()
maxima = None
try:
fhand = open(f1)
except:
print("File could not be processed")
exit()
for line in fhand:
line = line.rstrip()
if not line.startswith("From "): continue
word = line.split()
emails.append(word[1])
for mail in emails:
if mail not in counts:
counts[mail] = 1
else:
counts[mail] += 1
for key in counts:
if maxima is None or counts[key] > maxima :
maxima = counts[key]
largestMail = key
print(largestMail,maxima)
| true
|
29dc58276ecd5ffaaa59078cacfccd742b0b6320
|
SouravBarman001/PythonProgram
|
/find the max number.py
| 447
| 4.25
| 4
|
# At first we get three numbers
number1 = int(input("Enter 1st number:"))
number2 = int(input("Enter 2nd number:"))
number3 = int(input("Enter 3rd number:"))
if (number1>number2) & (number1>number3):
print(str(number1)+" is the max number")
elif (number2>number1) & (number2>number3):
print(str(number2)+" is the max number")
elif (number3 > number1) & (number3 > number2):
print(str(number3)+" is the max number")
| false
|
369686ae156bb36d5d52ac927be9554e2e555e44
|
Irachriskhan/0-Python
|
/5 Operators.py
| 1,717
| 4.5625
| 5
|
# Operators 2:56:00
print("Arthimetic operators: -, +, /, * , **, %")
a = 9
b = 2
c = a + b
d = a // b # it print nombres entiers
e = a ** b # exponents
f = a % b # modulo for reminder
print(d)
print(e)
print(f)
print()
# Assignment operator
print('Assignment operator +=, -=, /=, -=, **=')
x = 5
x += 5
print(x)
x = 5
x **= 5
print(x)
x = 5
print()
# comparison operator
print('Comparison operator <, >, >=, <=, !=, ==')
print()
print('Logical operator and, or, not')
x = 4
y = 5
if x == 5:
print('Ego ', x, 'na ', y, 'birangana')
else:
print(x, 'na ', y, 'ntibingana')
print('sample: x<5 and x>10, x<5 or x>10, not(x<5 and x>10)')
print()
print('identity operators')
print('Identity operators are used to compare objects')
x =4
y = 4
print(x is y)
print(x is not y)
print()
print('Membership operators: in, not in')
print('They are used to check if a sequence is present in an object')
list1 = [1, 2, 3, 4, 5]
print(list1)
print(1 in list1)
print()
print('Bitwise operators')
print('They are used to compare binary numbers!')
print('they are: Bitwise AND, Bitwise OR, Bitwise XOR, Bitwise NOT, Left Shift, Right Shift')
print(10 & 12) # 10 = 1010. 12 = 1100 then we get 1000
print(10 | 12) #
print(10 >> 2) #
print(10 << 2) #
print('& , AND: set each bit to 1 if both bits are 1')
print('| , OR: set each bit to 1 if one of the bits is 1')
print('^ , XOR: set each bit to 1 if both bits arte 1')
print('~ , NOT: Invert all bits arte 1')
print('<< , Left Shift: shift left by pushing in zeroes from the right and then let the leftmost bits fell of ')
print('>> , Right Shift: shift right by pushing copies of the leftmost bit in from the left, and let the rightmost '
'bit fall off ')
| false
|
7bbf4efdaa89805899f195843f69704c034f7eb5
|
AadityaDeshpande/TE-Assignments
|
/SDL/pallindrome.py
| 366
| 4.4375
| 4
|
#input a string and check it is pallindrome or not
#enter a word in a input and submit..!!
s=input("Enter the string that is to be checked:")
print(s)
a=s
t=False
lnth=len(a)
z=lnth-1
for i in range(len(a)):
if a[z]!=a[i] or z<0:
print("given string is not pallindrome")
t=True
break
z=z-1
if t==False:
print("Given string is pallindrome..!!")
| true
|
9172ed8eb8747a678eb0809c3024adba350657bc
|
phuclhv/DSA-probs
|
/absolute_value_sort.py
| 828
| 4.28125
| 4
|
'''
Absolute Value Sort
Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.
Examples:
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 10
[output] array.integer
'''
from functools import cmp_to_key
def absSort(arr):
def compare_abs(value1, value2):
if abs(value1) <= abs(value2):
return -1
return 1
compare_abs_key = cmp_to_key(compare_abs)
arr.sort(key=compare_abs_key)
return arr
arr = [2, -7, -2, -2, 0]
print(absSort(arr))
| true
|
c7c65f4e20a88881f77348987187501afd310887
|
jdst103/OOP-basics
|
/animal_class.py
| 1,469
| 4.125
| 4
|
# class Animal():
# # characterstics
# def __init__(self, name, legs, eyes, claws, tasty): # if we dont follow order, use dictionary to define.
# self.name = name
# self.legs = legs
# self.eyes = eyes
# self.claws = claws
# self.tasty = tasty
class Animal():
# characterstics
def __init__(self, name, legs): #if we dont follow order, use dictionary to define.
self.name = name
self.legs = legs
# behaviours - methods
# methods - which are like functions that belong to a class
# what it would be called
def eat(self, food=''): # makes the arguement optional
return 'nom' * 3 + food
def sleep(self):
return 'zzzz'
def potty(self):
return 'O_0 ...... HUMMMM!!!! ---- O_o ---- SPLOSH!'
def hunt(self):
return 'ATTACK'
# Let us create an instance of an Animal object, (also lets assign it to a variable)
animal_1 = Animal('Randy Marsh', 10, )
animal_2 = Animal('Cartman', 8, )
#checking attributes
# print(animal_1) #when run the instance changes every time (look at the number) # cant do much with it
# print(type(animal_1))
#
# print(animal_1.legs) #how tasty it is
# print(animal_2.legs)
# call methods on object of class Animal:
# print(animal_1.eat('chicken and salad'))
# print(animal_1.eat('dunno'))
# print(animal_1.sleep())
# print(animal_1.hunt())
# print(animal_1.potty())
| true
|
103e97a7fe67e1ead44bc00582b08e3013962273
|
sungfooo/pythonprojects
|
/hello.py
| 528
| 4.5
| 4
|
print "hello"
variable = "value of the variable"
data types
#integers
123421
#float (with decimal)
123.23
#boolean
True
False
#array (group of data types)
[1,True,"string"]
#dictionary or object
#{""}
#for loop - can be used to loop through arrays or objects one element at a time
#for x_element in x_array_or_object:
#example v
roommates = ["callie", "gary", "ari", "katie", "tim", "peter"]
for x in roommates:
print x[::-1]
def dogger(arg):
arg = arg+"dog"
print arg
for x in roommates:
dogger(x)
| true
|
0e50dbf6b86984d6782b1940797eb9276c41f476
|
anandjn/data-structure_and_algorithms
|
/algorithms/sorting/bubble_sort.py
| 505
| 4.3125
| 4
|
'''implementing bubble sort
TASK TIME-COMPLEXITY
1) bubbleSort O(n**2) '''
def bubbleSort(array):
#repeat below steps until there seems no change
for _ in range(len(array)):
#keep swapping
for i in range(len(array)-1):
#if first number is greater than second then swap them
if array[i] > array[i+1]:
temp = array[i]
array[i] = array[i+1]
array[i+1] = temp
return(array)
print(bubbleSort([10,12,23,40,55,2,4,5,6]))
| true
|
46b83ee44a8a4645bfd9eff99dfa87be1591d587
|
jihoonyou/problem-solving
|
/Educative/subsets/example1.py
| 676
| 4.125
| 4
|
"""
Problem Statement
Given a set with distinct elements, find all of its distinct subsets.
Example 1:
Input: [1, 3]
Output: [], [1], [3], [1,3]
Example 2:
Input: [1, 5, 3]
Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3]
"""
def find_subsets(nums):
subsets = [[]]
for current_num in nums:
length = len(subsets)
for i in range(length):
new_set = list(subsets[i])
new_set.append(current_num)
subsets.append(new_set)
return subsets
def main():
print("Here is the list of subsets: " + str(find_subsets([1, 3])))
print("Here is the list of subsets: " + str(find_subsets([1, 5, 3])))
main()
| true
|
271fe07e5cd53ad165806d4848de1913ad66354c
|
sashank17/MyCaptain-Python-Tasks
|
/task5 - function most frequent.py
| 362
| 4.125
| 4
|
def most_frequent(string):
string = string.lower()
letters1 = {}
for letter in string:
c = string.count(letter)
letters1[letter] = c
letters = sorted(letters1.items(), key=lambda x: x[1], reverse=True)
for i in letters:
print(i[0], "=", i[1])
str1 = input("Please enter a string: ")
most_frequent(str1)
| true
|
31e3382781897e9cca9bd90c9893c6da158636af
|
gonft/TastePy
|
/PyFill.py
| 2,100
| 4.21875
| 4
|
empty_set = set()
print(empty_set)
even_numbers = {0, 2, 4, 6, 8}
print(even_numbers)
odd_numbers = {1, 3, 5, 7, 9}
print(odd_numbers)
drinks = {
'martini': {'vodka', 'vermouth'},
'black russian': {'vodka', 'kahlua'},
'white russian': {'cream', 'kahlua', 'vodka'},
'manhattan': {'rye', 'vermouth', 'bitters'},
'screwdriver': {'orange juice', 'vodka'}
}
for name, contents in drinks.items():
if 'vodka' in contents:
print(name)
# martini
# black russian
# white russian
# screwdriver
print()
for name, contents in drinks.items():
if 'vodka' in contents and not ('vermouth' in contents or 'cream' in contents):
print(name)
# black russian
# screwdriver
print()
for name, contents in drinks.items():
if contents & {'vermouth', 'orange juice'}:
print(name)
# martini
# manhattan
# screwdriver
print()
for name, contents in drinks.items():
if 'vodka' in contents and not contents & {'vermouth', 'cream'}:
print(name)
# black russian
# screwdriver
print()
bruss = drinks['black russian']
wruss = drinks['white russian']
a = {1, 2}
b = {2, 3}
# 교집합 intersection
print(a & b) #{2}
print(a.intersection(b)) #{2}
print(bruss & wruss) #{'vodka', 'kahlua'}
# 합집합 union
print(a | b) #{1, 2, 3}
print(a.union(b)) #{1, 2, 3}
print(bruss | wruss) #{'kahlua', 'vodka', 'cream'}
# 차집합 difference
print(a - b) #{1}
print(a.difference(b)) #{1}
print(bruss - wruss) #set()
print(wruss - bruss) #{'cream'}
# 대칭 차집합 exclusive
print(a ^ b) #{1, 3}
print(a.symmetric_difference(b)) #{1, 3}
print(bruss ^ wruss) #{'cream'}
# 부분 집합 subset
print(a <= b) #False
print(a.issubset(b)) #False
print(bruss <= wruss) #True
# 진부분 집합 proper subset
print(a < b) #False
print(a < a) #False
print(a <= a) #True
print(bruss < wruss) #True
| false
|
9e4246031adc055ca31af9e82ed617cd3942f9a2
|
BeijiYang/codewars
|
/7kyu/special_number.py
| 1,763
| 4.40625
| 4
|
'''
Definition
A number is a Special Number *if it’s digits only consist 0, 1, 2, 3, 4 or 5 *
Task
Given a number determine if it special number or not .
Warm-up (Highly recommended)
Playing With Numbers Series
Notes
The number passed will be positive (N > 0) .
All single-digit numbers with in the interval [0:5] are considered as special number.
Input >> Output Examples
1- specialNumber(2) ==> return "Special!!"
Explanation:
It's a single-digit number within the interval [0:5] .
2- specialNumber(9) ==> return "NOT!!"
Explanation:
Although ,it's a single-digit number but Outside the interval [0:5] .
3- specialNumber(23) ==> return "Special!!"
Explanation:
All the number's digits formed from the interval [0:5] digits .
4- specialNumber(39) ==> return "NOT!!"
Explanation:
Although , there is a digit (3) Within the interval But the second digit is not (Must be ALL The Number's Digits ) .
5- specialNumber(59) ==> return "NOT!!"
Explanation:
Although , there is a digit (5) Within the interval But the second digit is not (Must be ALL The Number's Digits ) .
6- specialNumber(513) ==> return "Special!!"
7- specialNumber(709) ==> return "NOT!!"
For More Enjoyable Katas
ALL translation are welcomed
Enjoy Learning !!
'''
# solution 1
def is_specialNum(num):
return num in [0, 1, 2, 3, 4, 5]
def special_number(num):
numList = list(map(int, str(num)))
for num in numList:
if not is_specialNum(num):
return 'NOT!!'
return 'Special!!'
# solution 2
sepcial_set = set('012345')
def special_number(num):
return 'Special!!' if set(str(num)) <= sepcial_set else 'NOT!!'
print(
# specialNumber(123)
)
set('012345') # {'2', '3', '0', '4', '1', '5'}
set([0, 1, 2, 3, 4, 5]) # {0, 1, 2, 3, 4, 5}
| true
|
5cf375a9cc32edb6731e3dc78a97ae4ed232b8eb
|
MichoFelipe/python_course
|
/Fundamentos/6_Strings.py
| 1,980
| 4.46875
| 4
|
## CONCEPTOS BÁSICOS DE STRING
saludo = 'Hola'
print("tamaño del texto: ", len(saludo))
# Obtener caracteres de la palabra 'Hola'
# Palabra: Hola
# Posiciones: 0123
print("H: ", saludo[0])
print("o: ", saludo[1])
print("a: ", saludo[3])
#print("ERROR: ", saludo[4]) # Indice fuera de rango.
## Concatenar Strings
nombre = "Juan"
apellido = "Perez"
nombre_completo = nombre + "_" + apellido
print(nombre_completo)
## PARTE DE UN STRING
saludo = 'Hola'
# 0123 # Indices de la palabra Hola
print("ola: ", saludo[1:4]) # Empieza en 1 hasta el 4, pero no incluye el 4
print("Hol: ", saludo[0:3]) # Empieza en 0 hasta el 3, pero no incluye el 3
# OMITIR INDICE EN PARTE DE UN STRING
saludo = 'Hola'
# 0123 # Indides de la palabra Hola
print("Ho: ", saludo[:2]) # Si omite el primer número, se usa el inicio del String
print("la: ", saludo[2:]) # Si omite el segundo número, se usa el fin del String
# UNIR PARTES DE UN STRING
a = 'Hi!'
b = 'Hello'
## Asigna a 'c' los primermos dos caracteres de 'a' seguido por los 2 últimos caracteres de 'b'.
c = a[:2] + b[len(b) - 2:]
#¿Que valor imprime 'c'?
print("Valor de C: ",c)
## PYTHON STRING LOOPS
saludo = 'Hola'
resultado = ''
# len(variable): Retorna el tamaño de la variable.
print("Tamaño variable Saludo: ", len(saludo))
# range(n): retorna la secuencia de valores-> 0,1,2,3, ... n-1
for i in range(len(saludo)):
# Hacer algo con saludo[i]
# Aqui sólo agregaremos cada caracter sobre la variable resultado
resultado = resultado + saludo[i]
if False:
print("Resultado usando range-len: ", resultado)
# Otra forma de iterar/recorrer un String es recorriendo por cada caracter.
saludo = 'Hola'
resultado = ''
for ch in saludo:
# De esta forma, empezamos por cada caracter a través del String -> H, o, l, a
resultado = resultado + ch
print("Resultado usando caracteres: ", resultado)
| false
|
da6c16ba70e42bf9fd1db6578b6a116563011989
|
Hassanabazim/Python-for-Everybody-Specialization
|
/1- Python for Everybody/Week_4/2.3.py
| 389
| 4.28125
| 4
|
'''
2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
You should use input to read a string and float() to convert the string to a number.
'''
hrs = float(input("Enter Hours:"))
rph = float(input("Enter the rate per hour:"))
print ("Pay:",hrs * rph)
| true
|
bf9348541d0a97db5d4c63cf34a01d65b43a5468
|
NathanJiangCS/Algorithms-and-Data-Structures
|
/SPFA.py
| 810
| 4.125
| 4
|
#Python implementation of shortest path faster algorithm
#Implementation for weighted graphs. Graphs can have negative values
infinity = float('inf')
#a is the adjacency list representation of the graph
#start is the initial node, end is the destination node
def spfa(a, start, end):
n = len(a)
distances = [infinity for i in range(n)]
distances[start] = 0
q = [start]
while len(q):
currentNode = q.pop(0)
for i in a[currentNode]:
nextNode, distance = i
if distances[nextNode] > distances[currentNode] + distance:
distances[nextNode] = distances[currentNode] + distance
q.append(nextNode)
return distances, distances[end]
#This code does not check for a negative cycle which would result
#in an infinite loop
| true
|
716028bbd232b3c1b1ab81a8592238fb9dfc733f
|
ArcticSubmarine/Portfolio
|
/Python/hangmans_game.py
| 1,263
| 4.28125
| 4
|
##
# This file contains an implementation of the hangsman's game.
# The rules are the following :
# 1) the computer choses a word (max. 8 letters) in a pre-defined list ;
# 2) the player tries to find the letters of this word : at each try, he/she chose a letter ;
# 3) if the letter is in the word, the computer displays the word making the already found letters appearing. Those that haven't been found are replaced by stars (*).
# 4) the players have only 8 chances to find the letters or he/she lose the game ;
# 5) at the begining of the game, the player enters his/her name in order to save his/her score.
# The score is calculated as following : the number of plays resting at a winning party is added to his/her current scoring. For istance, if there are 3 tries left and that the player wins, 3 is added to his/her score.
# The file "datas.py" contains the datas such as the list of words, the number of authorized tries, etc.
# The file functions.py contains the useful functions for this application.
##
# Importation of the needed files and libraries
from datas import *
from functions import *
scores = HaveScores()
user = PlayerName()
if user not in scores.keys():
scores[user] = 0
Menu(user, scores)
| true
|
afcd89a627b55a754ae64c577ed0e96c724f1873
|
daicorrea/my-project
|
/book_me_up/helpers/date_time.py
| 440
| 4.25
| 4
|
# Function to verify if param day is weekday or weekend
def verify_weekday(date_to_verify):
# Using regular expression to get the day of the week inside the parentheses from the inputted data
day = date_to_verify[date_to_verify.find("(") + 1:date_to_verify.find(")")]
if day in ['mon', 'tues', 'wed', 'thur', 'fri']:
return 'week'
elif day in ['sat', 'sun']:
return 'weekend'
else:
return 'error'
| true
|
4c9f867d489be8e724f5daf0d49f6309b57a96a6
|
jeanchuqui/fp-utpl-18-evaluaciones
|
/eval-parcial-primer-bimestre/Ejercicio8.py
| 589
| 4.125
| 4
|
def main():
titulo_1 = "que letra va primero"
titulo_2 = titulo_1.upper()
print(titulo_2)
x = str(input("Ingrese una letra: "))
y = str(input("Ingrese otra letra: "))
z = str(input("Ingrese una última letra: "))
v1 = x.upper()
v2 = y.upper()
v3 = z.upper()
if v1 < v2 and v1 < v3:
print("La primer letra que aparecce en el abecedario es: ", v1)
elif v2 < v1 and v2 < v3:
print("La primer letra que aparecce en el abecedario es: ", v2)
else:
print("La primer letra que aparecce en el abecedario es: ", v3)
main()
| false
|
84661d9c5549561aaf66cef611e2454a9985492d
|
GemmaLou/selection
|
/selection dev 4.py
| 547
| 4.125
| 4
|
#Gemma Buckle
#03/10/2014
#selection dev 4 grade check
mark = int(input("Please enter your exam mark to receive your grade: "))
if 0<=mark<=40:
print("Your grade is U.")
elif 41<=mark<=50:
print("Your grade is E.")
elif 51<=mark<=60:
print("Your grade is D.")
elif 61<=mark<=70:
print("Your grade is C.")
elif 71<=mark<=80:
print("Your grade is B.")
elif 81<=mark<=100:
print("Your grade is A!")
else:
print("The mark you have entered is unacceptable. Please enter an integer between 0 and 100.")
| true
|
6f096a2cc3c6794534d3dccb0d8a1650857c4592
|
hongdonghyun/My-Note
|
/data_structure/Day3/stack.py
| 562
| 4.15625
| 4
|
"""
1. push(data) -> 삽입
2. pop() -> 맨위 데이터를 출력하고 삭제
3. empty() -> bool
4. peek() -> 데이터 확인
"""
__all__ = (
'Stack',
)
class Stack(list):
push = list.append # push
def empty(self):
if not self:
return True
else:
return False
def peek(self):
return self[-1]
# if __name__ == "__main__":
#
# s = Stack()
# s.push(1)
# s.push(2)
# s.push(3)
# s.push(4)
#
# while not s.empty():
# data = s.pop()
# print(data,end=' ')
| false
|
d833663e075a6d781691dedb79757dce251f45f3
|
lifewwy/myLeetCode
|
/Easy/566. Reshape the Matrix.py
| 1,787
| 4.1875
| 4
|
# Question:
#
# In MATLAB, there is a very useful function called 'reshape', which can reshape a
# matrix into a new one with different size but keep its original data.
#
# You're given a matrix represented by a two-dimensional array, and two positive
# integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
#
# The reshaped matrix need to be filled with all the elements of the original
# matrix in the same row-traversingorder as they were.
#
# If the 'reshape' operation with given parameters is possible and legal,
# output the new reshaped matrix; Otherwise, output the original matrix.
#
# Example 1:
#
# Input:
# nums =
# [[1,2],
# [3,4]]
# r = 1, c = 4
# Output:
# [[1,2,3,4]]
# Explanation:
# The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix,
# fill it row by row by using the previous list.
# Example 2:
#
# Input:
# nums =
# [[1,2],
# [3,4]]
# r = 2, c = 4
# Output:
# [[1,2],
# [3,4]]
# Explanation:
# There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
# Note:
#
# The height and width of the given matrix is in range [1, 100].
# The given r and c are all positive.
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if r*c!=len(nums)*len(nums[0]):
return nums
x = []
ret = []
for row in nums:
for i in row:
x.append(i)
if len(x) == c:
ret.append(x)
x = []
return ret
print(Solution().matrixReshape([[1,2], [3,4]], 1, 4))
| true
|
7ab6dd8fafbb093f0fa20ddd93336785483c5734
|
lifewwy/myLeetCode
|
/基础知识/字符串.py
| 1,898
| 4.21875
| 4
|
# Python 3.5.2
# 字符串(String)
# python中单引号和双引号使用完全相同。
print( '这是一个句子。' )
print( "这是一个句子。" )
# 使用三引号('''或""")可以指定一个多行字符串。
paragraph = """这是一个段落,
可以由多行组成"""
print( paragraph )
paragraph = '''这是一个段落,
可以由多行组成'''
print( paragraph )
# 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
print( '这是' + '一句话。')
print( ('这是' + '一句话。') * 5 )
# Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
str = '中华人民共和国万岁'
print( str[5] )
print( str[-2] ) # 输出字符串倒数第二个字符
print( str[0:-1] ) # 输出第一个到倒数第二个的所有字符
print( str[0] ) # 输出字符串第一个字符
print( str[2:5] ) # 输出从第三个开始到第五个的字符
print( str[2:] ) # 输出从第三个开始的后的所有字符
# Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
# 转义符 '\'
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
# 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。 如 r"this is a line with \n" 则\n会显示,并不是换行。
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
# Python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:
x = '这是'; y = '一句话。'; print( x+y )
# Print 输出
# print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=" "
x="a" ; y="b"
# 换行输出
print( x )
print( y )
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()
| false
|
b11ee4f8692487cba17e93f741642dde1e7439d5
|
lifewwy/myLeetCode
|
/Easy/21. Merge Two Sorted Lists.py
| 2,112
| 4.1875
| 4
|
# Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
#
# Example:
#
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
def println(l, N = 10):
if not l:
return
print(l.val, end='\t')
cursor = l.next
nCount = 1
while cursor != None and nCount < N:
nCount += 1
print(cursor.val, end='\t')
cursor = cursor.next
print()
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
# ①②③④⑤⑥⑦⑧⑨↖↑↗←→↙↓↘
class Solution(object):
def mergeTwoLists(self, l1, l2): # curr l1① → ③ → ④
# ⑧
# :type l1: ListNode # dummy l2② → ⑤
# :type l2: ListNode ---------------------------
# :rtype: ListNode
# curr① → l1③ → ④
curr = dummy = ListNode(8) # ⑧ ↗
while l1 and l2: # dummy l2② → ⑤
if l1.val < l2.val: # --------------------------
curr.next = l1
l1 = l1.next # ① l1③ → ④
else: # ⑧ ↗ ↓
curr.next = l2 # dummy curr② → l2⑤
l2 = l2.next # --------------------------
curr = curr.next
curr.next = l1 or l2 # ① curr③ → l1④
return dummy.next # ⑧ ↗ ↓ ↗
# dummy ② l2⑤
if __name__ == "__main__":
l1 = ListNode(1)
l1.next = ListNode(3)
l1.next.next = ListNode(4)
l2 = ListNode(2)
l2.next = ListNode(5)
l = Solution().mergeTwoLists(l1,l2)
print( l )
# println( l )
| true
|
93f5cd0fbbcf5fdc5d568a6a8d2e5bed8154cbbe
|
trizzle21/advent_of_code_2019
|
/day_1/day_1.py
| 1,101
| 4.3125
| 4
|
"""
Day 1
> Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
> For example:
> For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
> For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
> For a mass of 1969, the fuel required is 654.
> For a mass of 100756, the fuel required is 33583.
> The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
"""
from math import floor
import logging
logging.basicConfig(level=logging.DEBUG)
def calculate(value):
return floor(value/3) - 2
def run():
with open('day_1_input.txt', 'r') as f:
values = f.readlines()
values = [int(value.strip()) for value in values]
return sum([calculate(v) for v in values])
if __name__ == '__main__':
total_fuel = run()
logging.debug(total_fuel)
| true
|
3fe75bfc2d9257f34f8eaeda34c1da3b41cc9c0b
|
sarath-mutnuru/EPI_python_codes
|
/4.7_power.py
| 534
| 4.15625
| 4
|
def power(x, y):
""" return x^y x is double y is int """
res = 1
if y < 0:
x = 1/x
y = -y
while y:
res *= x
y -= 1
return res
def power2(x, y):
if y < 0:
x = 1/x
y = -y
res = 1
while y:
if y & 1:
res = res * x
y = y-1
x = x * x
y = y >> 1
return res
def main():
x=3
y=-3
print(power2(x,y))
print(power(x,y))
if __name__ == '__main__':
main()
| false
|
09526c4fc46617c708a9199e4d9baafec3aaaf0c
|
Chris-Cameron/SNEL
|
/substitution.py
| 470
| 4.21875
| 4
|
#Helper Functions
#"Inverts" the ASCII values of the characters in the text file, so that those at the beginning go towards the end and vice-versa
def substitute(text):
new_message = ""
for t in text:
new_message += chr(158-ord(t)) #158 is 32+126, which is why it is used for the inversion
print(new_message)
#Main Code
with open("text_files/file_2715.txt", 'r') as f:
content = f.read()
substitute(content)
| true
|
82342cf39fd4969586140838a68af53bf7996ee9
|
mfarooq28/Python
|
/Convert_C2F.py
| 452
| 4.5625
| 5
|
# This program will convert the Celsius Temprature into Farenheit
user_response = input (" Please Enter the Celsius Temprature :")
celsius = float (user_response)
farenheit = ((celsius*9)/5)+32
print ("The Equivalent Farenheit Temprature is :", farenheit , "degrees farenheit. ")
if farenheit < 32 :
print ("It is freezing")
elif farenheit < 50:
print("It is chilly")
elif farenheit < 90 :
print("It is OK")
else :
print("It is hot")
| true
|
b41f725cced2727a6b78fc29b0ad1b7feced471a
|
shubham-camper/Python-Course
|
/8. Lists.py
| 476
| 4.4375
| 4
|
friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] #this is the list we have created
print(friends)
print(friends[0]) #this will print out the first element of the list
print(friends[1:]) #this will print out 2nd till the last element of the list
print(friends[1:3]) #this will print out 2nd till the 4 element of the list
friends[1] = "Mike" #you can also creeate the list and change the element of the list later
print(friends[1])
| true
|
0490b178203ec63461baa328d70efd31c40d0218
|
conglinh99/maconglinh-fundamentals-c4e13
|
/Session02/Homework/BMI.py
| 383
| 4.21875
| 4
|
print("That's is program that calculate your BMI")
h = int(input("Enter your height (cm): "))
w = int(input("Enter your weight (kg): "))
bmi = w / ((h/100)**2)
if bmi < 16:
print("You're severely underweight")
elif bmi < 18.5:
print("You're underweight")
elif bmi < 25:
print("You're normal")
elif bmi < 30:
print("You're overweight")
else:
print("You're obese")
| false
|
bcc0bb8f659c22618267ed54d24129820d78022d
|
EvanGottschalk/CustomEncryptor
|
/SortDictionary.py
| 1,322
| 4.46875
| 4
|
# PURPOSE - This program is for sorting dictionaries
class SortDictionary:
# This function sorts a dict alphabetically and/or from least to greatest
def sortDictByKey(self, dictionary):
# Letter characters, numeric characters, and the remaining characters are
# separated into 3 different dicts, each to be sorted individually
letter_chars = {}
number_chars = {}
symbol_chars = {}
for char in dictionary:
if str(char).isnumeric():
number_chars[char] = dictionary[char]
elif str(char).isalnum():
letter_chars[char] = dictionary[char]
else:
symbol_chars[char] = dictionary[char]
sorted_dictionary = dict(sorted(letter_chars.items()))
sorted_dictionary.update(dict(sorted(number_chars.items())))
sorted_dictionary.update(symbol_chars)
del dictionary, letter_chars, number_chars, symbol_chars
return(sorted_dictionary)
# These two function calls serve as alternative ways to call the sortDictByKey function,
# in case a user forgets the original function name
def sortDict(self, dictionary):
self.sortDictByKey(dictionary)
def sortDictionaryByKey(self, dictionary):
self.sortDictByKey(dictionary)
| true
|
bb664e378293f0315af272775652463596776874
|
YashSoni06/AI_Course
|
/functions.py
| 866
| 4.25
| 4
|
# Assigning elements to different lists
langs = []
langs.append("Python")
langs.append("Perl")
langs.extend(("JavaScript", "ActionScript"))
print(langs)
#OUTPUT
['Python', 'Perl', 'JavaScript', 'ActionScript']
#################################################################################
# Accessing elements from Tuple
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
#OUTPUT
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
#################################################################################
# DELETING Different Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
print(dict)
#OUTPUT
{'Age': 7, 'Class': 'First'}
dict.clear() # remove all entries in dict
print(dict)
#OUTPUT
{}
| false
|
f87b9019600d9cd55a79e8abfbd1d5b37560f447
|
Prashidbhusal/Pythonlab1
|
/Lab exercises/question 7.py
| 452
| 4.28125
| 4
|
#Solve each of the following problems using pythone script . Makes sure you use appropriate variable names and comments.
#When there is final answer , have python is to the screen.
# A person's body mass index(BMI) is defined as:
# BMI=(mass in kg) / (height in m)^2
mass=float(input('enter the mass of person in kg'))
height=float(input('entr the height of a person in meter'))
BMI=mass/(height ** 2)
print(f"The BMI index of the person is {BMI}")
| true
|
cc4dc3602877b6245e0841271bb1b83aade95378
|
jana12332/bootcampzajecia20211012
|
/Dzien03/bmi.py
| 1,007
| 4.3125
| 4
|
"""
Skrypt obliczający BMI
BMI = waga (kg) / wzrost (m^2)
Uwaga! - wzrost podajemy w cm
"""
weight = input("Podaj wagę w kg:")
height = input("Podaj wzrost w cm:")
weight = int(weight) # konwertujemy z napisu na int
height = int(height) # konwertujemy z napisu na int
# liczenie formuły
# bmi = weight / pow( height/100 , 2)
# print(bmi)
bmi = weight / (height/100)**2
#print("Twoje BMI = "+str( round(bmi,2) ))
print(f"Twoje BMI = {bmi:.2f}")
# import math
# bmi = weight / math.pow( height/100 , 2 )
# print(bmi)
"""
<18.5 - zjedz coś
>=18.5 i <25 - ok
>= 25 - ogranicz kebaby
"""
# if bmi>=25:
# print("ogranicz kebaby")
# print("ogranicz monsterki")
# elif bmi<18.5:
# print("zjedz coś")
# else:
# print("OK")
if bmi>=18.5 and bmi<25:
print("OK")
elif bmi>=25:
print("ogranicz kebaby")
print("ogranicz monsterki")
if bmi>35:
print("Do lekarza")
elif bmi<18.5:
print("zjedz coś")
else:
pass # celuloza w Pythonie
#print(weight, height)
| false
|
17d573930ff954e98579728f47610e0dff7b1574
|
c0untzer0/StudyProjects
|
/PythonProblems/check_string.py
| 639
| 4.21875
| 4
|
#!/usr/local/bin/python3
#-*- coding: utf-8 -*-
#
# check_string.py
# PythonProblems
#
# Created by Johan Cabrera on 2/15/13.
# Copyright (c) 2013 Johan Cabrera. All rights reserved.
#
#import os
#import sys
#import re
#import random
#!/usr/local/bin/python3
#
#check_string.py
#
strng = input("Please enter an upper-case string, ending with a period: \n")
if strng.isupper() and strng.endswith("."):
print("THAT IS ACCEPTABLE")
elif not(strng.isupper() or strng.endswith(".")):
print("You didn't follow any instructions!")
elif strng.isupper():
print("Input does not end with a period")
else:
print("Input is not all upper-case")
| true
|
0ee88afe44d3292f6f804dea107315db1dad55af
|
Payalkumari25/GUI
|
/grid.py
| 389
| 4.40625
| 4
|
from tkinter import *
root = Tk()
#creating the label widget
label1 = Label(root,text="Hello world!").grid(row=0, column=0)
label2 = Label(root,text="My name is Payal").grid(row=1, column=5)
label3 = Label(root,text=" ").grid(row=1, column=1)
# showing it into screen
# label1.grid(row=0, column=0)
# label2.grid(row=1, column=5)
# label3.grid(row=1, column=1)
root.mainloop()
| true
|
660b09b94d4d5d985bc2d37cf0b3f8813b7f5992
|
bozi6/hello-world
|
/megyek.py
| 1,153
| 4.21875
| 4
|
megyek = ['Bács-Kiskun', 'Baranya', 'Békés', 'Borsod-Abaúj-Zemplén', 'Csongrád-Csanád',
'Fejér', 'Győr-Moson-Sopron', 'Hajdú-Bihar', 'Heves', 'Jász-Nagykun-Szolnok',
'Komérom-Esztergom', 'Nógrád', 'Pest', 'Somogy', 'Szabolcs-Szatmár-Bereg',
'Tolna', 'Vas', 'Veszprém', 'Zala', 'Budapest']
szekhelyek = ['Kecskemét', 'Pécs', 'Békéscsaba', 'Miskolc', 'Szeged', 'Székesfehérvár',
'Győr', 'Debrecen', 'Eger', 'Szolnok', 'Tatabánya', 'Salgótarján',
'Budapest', 'Kaposvár', 'Nyíregyháza', 'Szekszárd', 'Szombathely',
'Veszprém', 'Zalaegerszeg', 'Budapest']
# print(megyek) # prints all elements in a list
# print(megyek[0]) # print first element from a list
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# zip going through multiple lists and extract them
for megye, szeh in zip(megyek, szekhelyek):
print('Megye: {} - Székhely: {}'.format(megye,szeh))
print("Összeg:")
print(sum(lista))
print("Minimum")
print(min(lista))
print("Maximum")
print(max(lista))
print("Lista első eleme:")
print(lista[0])
print("Lista utolsó eleme:")
print(lista[-1])
| false
|
5aac7617351e0466499a1e4f98e0826aec480e22
|
bozi6/hello-world
|
/tankonyv/stars.py
| 312
| 4.34375
| 4
|
for i in range(0, 5):
for j in range(0, i + 1):
print("* ", end="")
print()
# Python Program for printing pyramid pattern using stars
a = 8
for i in range(0, 5):
for j in range(0, a):
print(end=" ")
a = a - 2
for j in range(0, i + 1):
print("* ", end="")
print()
| false
|
da01c417f3e49ba5c0d764d373bc2024c43fcef7
|
victoraagg/python-test
|
/03.py
| 1,348
| 4.125
| 4
|
print('Proyecto de calculadora')
fin = False
print('Calculadora')
print('Opciones:')
print('1 - Suma')
print('2 - Resta')
print('3 - Multiplicación')
print('4 - Division')
print('5 - Salir')
def readNum(text):
valid = False
while not valid:
try:
number = int(input(text))
except ValueError:
print('El valor debe ser un número')
else:
valid = True
return number
while fin == False:
option = int(input('Opción: '))
if option == 1:
number1 = readNum('Numero 1: ')
number2 = readNum('Numero 2: ')
print('Resultado:',number1+number2)
elif option == 2:
number1 = readNum('Numero 1: ')
number2 = readNum('Numero 2: ')
print('Resultado:',number1-number2)
elif option == 3:
number1 = readNum('Numero 1: ')
number2 = readNum('Numero 2: ')
print('Resultado:',number1*number2)
elif option == 4:
number1 = readNum('Numero 1: ')
number2 = readNum('Numero 2: ')
try:
result = number1/number2
except ZeroDivisionError:
print('División entre cero')
except:
print('Error en la división')
else:
print('Resultado:',result)
elif option == 5:
fin = True
print('Fin de operaciones')
| false
|
101843f07a82e4df1b88a3bd1f404e3e2c572b0d
|
milesanp/Python-Essentials
|
/lab 3.1.2.11.py
| 463
| 4.21875
| 4
|
wordWithoutVovels = ""
userWord = input("Please enter your word:")
userWord = userWord.upper()
for wordWithoutVovels in userWord:
if wordWithoutVovels == "A":
continue
elif wordWithoutVovels == "E" :
continue
elif wordWithoutVovels == "I" :
continue
elif wordWithoutVovels == "O" :
continue
elif wordWithoutVovels == "U" :
continue
else :
print(wordWithoutVovels, end ="")
| false
|
6a0b9a98469658afb2ed5d0f6a8ab1cc5d40509f
|
asiahbennettdev/Polygon-Classes
|
/polygon.py
| 2,742
| 4.4375
| 4
|
import turtle # python drawing board module
""" Define polygon by certain amount of sides or name """
class Polygon: # trianlges, squares, pentagons, hexagons, ect.
def __init__(self, sides, name, size=100, color="blue", line_thinckness=3): # initialize with parameters - whats import to a polygon?
self.sides = sides
self.name = name
self.size = size
self.color = color
self.line_thickness = line_thinckness
self.interior_angles = (self.sides - 2)*180 # find sum of all interior angles. number of sides -2 * 180 - (n-2)*180
self.angle = self.interior_angles/self.sides # EX: sum of interior angle for square is 360 each angle is 90 degrees
def draw(self): # can access parameters of Polygon class by passing in self
turtle.pensize(self.line_thickness)
turtle.color(self.color)
for i in range(self.sides):
turtle.forward(self.size)
turtle.right(180-self.angle) # defining exterior andgle insert 180-self.sides, finding supplement of interior angles
#turtle.done()
def draw_function(sides, size, angle, line_thickness, color):
turtle.pensize(line_thickness)
turtle.color(color)
for i in range(sides):
turtle.forward(size)
turtle.right(180-angle)
turtle.done()
class Square(Polygon):
def __init__(self, size=100, color="black", line_thickness=3):
super().__init__(4, "Square", size, color, line_thickness)
def draw(self):
turtle.begin_fill()
super().draw()
turtle.end_fill()
# override draw method
def draw(self):
turtle.begin_fill()
super().draw()
turtle.end_fill()
square = Square(color="#321abc", size=200)
print(square.draw())
turtle.done()
# DEFINING SHAPES
# square = Polygon(4, "Square") # based on what was initalized in __init_ pass in parameters
# pentagon = Polygon(5, "Pentagon", color="red", line_thinckness=25) # size not provided defaults to 100
# hexagon = Polygon(6, "Hexagon", 10) #size gives tiny hexagon
# print(square.sides) # prints 4
# print(square.name) # prints Square
# print(square.interior_angles) # prints 360
# print(square.angle) # prints 90
# print(pentagon.name) # prints 5
# print(pentagon.sides) # prints Pentgon
# pentagon.draw()
# hexagon.draw()
# square.draw()
# draw_function(4, 50, 90, 4, "pink") # not utilizing predefined class methods
# NOTES
# self - allows us to access everything we've intialized in the class Polygon in nice succinct manner
# inheritance - subclassing - define class specifically
# we have created a polygon class we set sides and name through __init__ method by feeding in parameters
# encapsulating information from Polygon class
| true
|
0bacbbc9dee5294be02aa21c6a0560960a3e2f25
|
ararage/flask_python
|
/if_statements.py
| 1,251
| 4.21875
| 4
|
should_continue = True
if should_continue:
print ("Hello")
known_people = ["John","Anna","Mary"]
#person = input("Enter the person you know: ")
# if person in known_people:
# print("You know {}!".format(person))
# else:
# print("You don't {}!".format(person))
#if person not in known_people:
def who_do_you_know():
#Ask the user for a list of people they know
#Split the string into a list
#Return the list
# people = input("Enter the names of people you know, separated by commas: ")
# people_list = people.split(",")
# clean_people = []
# for person in people_list:
# clean_people.append(person.strip())
# return clean_people
people = input("Enter the names of people you know, separated by commas: ")
people_list = people.split(",")
people_without_spaces = [person.strip() for person in people_list]
return people_without_spaces
def ask_user():
#Ask user for their name
#See if their name is in the list of people do you know
#Print out that they know the person
person = input("Enter the person you know: ")
if person in who_do_you_know():
print("You know {}!".format(person))
else:
print("You don't {}!".format(person))
ask_user()
| false
|
387e8d3706a477ba4449fd49e049f9ccf81a55ea
|
shivangi-prog/Basic-Python
|
/Day 5/examples.py
| 650
| 4.1875
| 4
|
# Set Integers
Temperature = int(input("Enter temperature:"))
Humidity = int(input("Enter humidity percentage:"))
# statements
if Temperature >= 100:
print("Cancel School, and recommend a good movie")
elif Temperature >= 92 and Humidity > 75:
print("Cancel schoool")
elif Temperature > 88 and Humidity >= 85:
print("Cancel school")
elif Temperature == 75 and Humidity <= 65:
print("Encourage students to skip school and enjoy the great outdoors")
elif Temperature <= -25:
print("You had better panic, because the world is clearly ending")
elif Temperature < 0:
print("Cancel school")
else:
print("School is in session")
| true
|
e085cfd76c1abc884ce314d832963f08c97a31c6
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/a9e39c62-b442-434d-b053-7f64d9cd9776__square_root.py
| 781
| 4.125
| 4
|
def square_root(number):
if number < 0.0:
return -1
if number == 0.0 or number == 1.0:
return number
precision = 0.00001
start = 0
end = number
if number < 1.0:
end = 1
while end - start > precision:
mid_point = make_mid_point(start, end)
current_square = mid_point * mid_point
if current_square == number:
return print("{0:.5f}".format(mid_point))
if current_square < number:
start = mid_point
else:
end = mid_point
print("{0:.5f}".format(make_mid_point(start, end)))
def make_mid_point(start, end):
return start + (end - start) / 2
def main():
number = int(input())
square_root(number)
if __name__ == '__main__':
main()
| false
|
d0bfd16ddb5208109c3e8d1f826c6f1b269836c7
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/cfff3ebc-345e-47c3-8afb-6fafaa13dae8__square_root.py
| 517
| 4.21875
| 4
|
# Find square root of a number
# Apply the concept of a BST
def square_root(n, precision):
low = 0.0
high = n
mid = (low+high)/2.0
# precision is the +/- error allowed in our answer
while (abs(mid*mid-n) > precision):
if (mid*mid) < n:
low = mid
elif (mid*mid) > n:
high = mid
mid = (low+high)/2.0
return mid
print square_root(1.0, 0.00001)
print square_root(3.0, 0.00001)
print square_root(4.0, 0.00001)
print square_root(49.0, 0.00001)
| true
|
cb89573aca0ed58e385759b6918a1bbd090ca7ac
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/9c1ed404-f5b4-4dc0-928c-59e23d75d315__bubble_sort.py
| 576
| 4.15625
| 4
|
# Sorting a list by comparing it's elements two by two and putting the biggest in the end
def sort_two_by_two(ul):
for index in range(len(ul)):
try:
el1 = ul[index]
el2 = ul[index + 1]
if el1 > el2:
ul[index] = el2
ul[index +1] = el1
except IndexError:
return ul
def bubble(ul):
sorted_list = ul
copyed_list = []
while copyed_list != sorted_list:
copyed_list = sorted_list[:]
sorted_list = sort_two_by_two(sorted_list)
return sorted_list
| true
|
33355877c07b4c62605de51f88829db01a0c07f0
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/8d5d2074-ace0-410b-a057-28b3eed64467__sqrt_x.py
| 503
| 4.21875
| 4
|
"""
Implement int sqrt(int x).
Compute and return the square root of x.
"""
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# the root of x will not bigger than x/2 + 1
if x == 0:
return 0
elif x == 1:
return 1
l = 0
r = x/2 + 1
while r >= l:
mid = (r + l) /2
temp = x / mid
if temp == mid:
return mid
elif temp < mid:
r = mid - 1
else:
l = mid + 1
return r
| true
|
1924d3ebb5f9043df9435f96677ac2036d775e4d
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/0385591b-6a56-4782-9052-1d9ab43f95f4__square_root.py
| 995
| 4.3125
| 4
|
"""
Program that asks the user for a positive number and then outputs the
approximated square root of the number. Use Newton's method to find the
square root, with epsilon = 0.01. (Epsilon is the allowed error, plus or
minus, when you square your calculated square root and compare it to
your original number.)
"""
def ask_for_number():
"""Asks user for a positive number"""
number = 0
while True:
if number > 0:
return number
try:
number = int(input("Please provide a positive nuumber: "))
except:
pass
def newtons_method(num, guess=None):
"""Calculates the square root of a number."""
if guess is None:
# picked 20 out of thin air. Let me know if I should change.
guess = 20
new_guess = .5*(num/guess+guess)
if new_guess == guess:
print("The square root of {} is {}.".format(num, guess))
else:
newtons_method(num, new_guess)
newtons_method(num=ask_for_number())
| true
|
d6d96a671376e09c522197179ec3e1a39e84c16e
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/117291d5-df0d-4d90-a687-2c82344d1d55__RMSE.py
| 1,194
| 4.28125
| 4
|
#!/usr/bin/env python
# -------
# RMSE.py
# -------
def square_of_difference(x, y) :
"""
Squares the differences between actual and predicted ratings
x is one rating from the list of actual ratings
y is one rating from the list of predicted ratings
return the difference of each actual and predicted rating squared
"""
rating_dict = {'1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5}
actual = rating_dict[x]
pred = float(y)
sd = (actual - pred) ** 2
assert type(sd) is float
return sd
def mean(a) :
"""
Calculates the average of a list
a is the list of ints or floats to average
return the average of the numbers in the input list
"""
assert type(a) is list
m = sum(a) / len(a)
assert 0 <= m <= 16
return m
def rmse(a,p) :
"""
Calculates the root mean square error between 2 lists
a is the list of actual ratings
p is the list of predicted ratings
return root mean square error between the two input lists
"""
assert type(a) is list
assert type(p) is list
assert len(a) == len(p)
r = mean(map(square_of_difference, a, p)) ** .5
assert 0 <= r <= 4
return r
| true
|
5d2cfbe84e4aec18dccf9804220b0005a4d91328
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/accf931e-a4c2-45b2-b2df-c999385ff178__ex13-random.py
| 528
| 4.28125
| 4
|
# the following program let the user play a game where he has to guess the square of
# a random number
# modify it as follow:
# print the square of an natural number and let the player guess the square root.
# the square root should be between 1 and 20
import random
def askForNumber():
return int(raw_input("Enter square of x: "))
x = random.randint(1,10)
print "x =",x
inputValue = askForNumber()
while inputValue!=x*x:
print "Answer is wrong!"
inputValue = askForNumber()
print "Right!"
| true
|
738091fc3650a91d3146a6c31aee64629a33fdd7
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/6d22552b-74ae-459d-bb4a-395727bbc2be__069-sqrt.py
| 471
| 4.125
| 4
|
#!/usr/bin/python
# Implement int sqrt(int x).
# Compute and return the square root of x.
import sys
# Binary search in range from 1 to x / 2. O(log(n)).
def sqrt(x):
if x == 0 or x == 1:
return x
i, j = 1, x / 2
while i <= j:
m = (i + j) / 2
if m * m > x:
j = m - 1
elif m * m < x:
i = m + 1
else:
return m
return i - 1
def main():
print sqrt(int(sys.argv[1]))
main()
| true
|
ae33b275f221a81e7d91f603a22e0f44639540f8
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/73ed9c98-ac54-4356-a553-5c6e12e44eb9__forPeopleNotComputers1.py
| 861
| 4.625
| 5
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
############ EJEMPLO 1 ############
#Don't write what code is doing, this should be left for the code to explain and can be easily done by giving class, variable and method meaningful name. For example:
t=10
#calculates square root of given number
#using Newton-Raphson method
def abc( a):
r = a / 2
while ( abs( r - (a/r) ) > t ):
r = 0.5 * ( r + (a/r) )
return r
#Above code is calculating square root using Newton-Raphson method and instead of writing comment you can just rename your method and variable as follows:
def squareRoot( num):
root = num/ 2
while ( abs(root - (num/ root) ) > t ):
r = 0.5 * (root + (num/ root))
return root
if __name__ == "__main__":
print " root abc = " + str(abc(10))
print " root squareRoot = " + str(squareRoot(10))
| true
|
8cb4a22012d691a4ac812cc456464935266ed16e
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/0beb9f98-f5de-47a5-aef2-0f5af5117d90__front_x.py
| 966
| 4.28125
| 4
|
def front_x(words):
x_list =[]
non_x_list = []
sorted_list = []
for str in words:
if str[0].lower().startswith("x"):
x_list.append(str)
else:
non_x_list.append(str)
print x_list,
print non_x_list
print type(x_list)
print sorted(x_list)
print type(sorted(x_list))
sorted_list = sorted(x_list)+sorted(non_x_list)
# +++your code here+++
return sorted_list
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
# +++your code
sort_by = []
for item in tuples:
sort_by.append(item[-1])
sorted_index = sorted(sort_by)
print sorted_index
return sorted_index
| true
|
245a22eb50b7bc37e597a13048012fd994730915
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/1a0efe9c-edb5-4b4a-9d1c-47aca8ecc3bf__main.py
| 441
| 4.4375
| 4
|
"""This function will approximate the square root of a number using Newton's Method"""
x = float(input("Enter a positive number and I will find the square root: "))
def square_root(x):
y = x/2
count = 0
while abs((y**2) - x) > 0.01:
y = (y+x/y)/2
count += 1
print("After iterating {} times, my guess is {}.".format(count, y))
return y
print("The square root of {} is {}.".format(x, square_root(x)))
| true
|
f9f788b0b38bc620286738c74daf9732a43ff3db
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/d411c458-97e1-4a17-b22a-db46445f011a__square_root.py
| 485
| 4.125
| 4
|
# Python Code for Square Root
num = int(input("Enter a positive number: "))
def newtonest(num):
return num ** 0.5
def estimate(num):
guess = num/3
count = 0
epsilon = 0.01
sq_guess = ((num / guess) + guess)/2
while abs(newtonest(num) - sq_guess) > epsilon:
newguess = sq_guess
sq_guess = ((num / newguess) + newguess)/2
count +=1
print("The square root of {} is {} with {} interations.".format(num,sq_guess,count))
estimate(num)
| true
|
012814c4bdfb63d99d967a52027cf6d5b6ebeb8a
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/04d69a32-54b4-4e9c-b998-1c8e7e844774__newtonsMethodOfSquares.py
| 253
| 4.25
| 4
|
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
return approx
x = float(input("what number would you like to square root?"))
print (newtonSqrt(x))
| true
|
faba2172b30a6e3f2a24895770f5210ede6367c7
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/6d7d2e0c-b0a0-4f91-aad3-218cf30cf40c__sqroot.py
| 750
| 4.40625
| 4
|
'''
Find the square root of n.
Input: A number
Output: The square root or the integers closest to the square root
Assume: positive n
Newton's method is a popular solution for square root, but not implemented here.
'''
def sqrt(n):
for number in range(0, n):
if isSqrt(number,n):
return number
else:
if n < number * number:
return number, number - 1
def isSqrt(a,b):
'''
Helper function to use in sqrt function to calculate number squared
'''
if a * a == b:
return True
else:
return False
# Test Section
if __name__ == '__main__':
print "sqrt(25) = 5: %s" % (sqrt(25) == 5)
print "sqrt(30) = (6, 5): %s" % (sqrt(30) == (6,5))
| true
|
e7ecfb257fcc00f8d2732024c7d7eccb8e188d3a
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/54adae2c-fd4c-4b83-a622-a64f867c5643__sqrt.py
| 463
| 4.125
| 4
|
def sqrt(x):
""" Calculate the square root of a perfect square"""
if x >= 0:
ans = 0
while ans * ans < x:
ans += 1
if ans * ans == x:
return ans
else:
print(x, "is not a perfect square")
return None
else:
print(x, "is a negative number")
return None
for i in range (-10, 11):
x = sqrt(i)
if x != None:
print("Square root of", i, "is", x)
| true
|
4e9d81dd456aff5c700a0c4570c1302317bedcd3
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/ef081f79-c5e5-4dd5-9103-050da101fdfc__basic_sorts.py
| 2,674
| 4.46875
| 4
|
from heap import Heap
def insertion_sort(array):
"""
Standard insertion sort alogrithm
Arguments:
array - array of numbers
Returns:
array - array sorted in increasing order
"""
for i in range(1, len(array)):
j = i - 1
while j >= 0 and array[j] > array[i]:
array[i], array[j] = array[j], array[i]
i = j
j-=1
return array
def selection_sort(array):
"""
Standard selection sort algorithm.
Arguments:
array - array of numbers
Returns:
array - array sorted in increasing order
"""
for i in range(0, len(array)-1):
min_index = None
for j in range(i, len(array)):
if not min_index:
min_index = j
else:
if array[j] < array[min_index]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
return array
def merge(array1, array2):
"""
Take two sorted arrays and merge them in sorted order.
Arguments:
array1 - first array to be sorted
array2 - second array to be sorted
Returns:
sorted_array - merged arrays in sorted manner
"""
sorted_array = []
while array1 and array2:
if array1[0] < array2[0]:
sorted_array.append(array1.pop(0))
else:
sorted_array.append(array2.pop(0))
if not array1:
sorted_array.extend(array2)
elif not array2:
sorted_array.extend(array1)
return sorted_array
def merge_sort(array):
"""
Merge sort a given array in ascending order
Arguments:
array - potentially unsorted array
Returns:
sorted_array - sorted array in ascending order
"""
if len(array) == 1 or not array:
return array
else:
sorted_array = merge(merge_sort(array[0:len(array)/2]), merge_sort(array[len(array)/2:]))
return sorted_array
def quick_sort(array, start=0, end=None):
"""
Perform a quick sort in place
Arguments:
array - array to be sorted
start - starting index of array to be sorted
end - end index of array to be sorted
Returns:
array - sorted array
"""
if not array:
return
if not end:
end = len(array)-1
pivot = end
curr_index = start
while curr_index != pivot:
if array[curr_index] > array[pivot]:
array[curr_index], array[pivot-1] = array[pivot-1], array[curr_index]
array[pivot-1], array[pivot] = array[pivot], array[pivot-1]
curr_index = start
pivot-=1
else:
curr_index+=1
if pivot - start > 1:
quick_sort(array, start, pivot-1)
if pivot < end-2:
quick_sort(array, pivot + 1, end)
return array
def heap_sort(array):
"""
Performs a heap sort
Arguments:
array - array of integers to be sorted
Returns:
array - sorted array
"""
sorted_array = []
array_heap = Heap(array)
while array_heap.size > 0:
sorted_array.append(array_heap.remove())
return sorted_array
| true
|
8af2416a3e5d3a075708a385bed2b4e1a5c6f518
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/890cf0d9-d7e4-45a1-9f81-7b7dd4ffcf17__isprime.py
| 362
| 4.15625
| 4
|
def isprime(n):
if n < 2:
return False
if n in (2, 3):
return True
if n % 2 == 0 or n % 3 == 0:
return False
max_divisor = int(n ** 0.5) # square root of n
divisor = 5
while divisor <= max_divisor:
if n % divisor == 0 or n % (divisor + 2) == 0:
return False
divisor += 6
return True
| false
|
db96f8b054620d96ccb6b1d47c0006f94201177f
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/5e8497d9-ed33-401f-a31e-a260f511e0cd__bubbleSort.py
| 505
| 4.125
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def bubble(listToSort, length):
for i in range(length-1):
if listToSort[i] > listToSort[i+1]:
tmp = listToSort[i]
listToSort[i] = listToSort[i+1]
listToSort[i+1] = tmp
def bubbleSort(listToSort):
for i in range(len(listToSort),0,-1):
bubble(listToSort, i)
return listToSort
if __name__=="__main__":
listToSort = [2,7,3,8,5,1,0,5,8,16,39,1,3,23,12,34,82,6,2,8,55,5,20]
sortedList = bubbleSort(listToSort)
print sortedList
| false
|
6d80392cc2a2c228de03adfaa95db8a6db11742f
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/7e22a661-3c4e-4ed5-a12b-0916b621637d__Loops.py
| 1,308
| 4.15625
| 4
|
from sys import float_info as sfi
def square_root (n):
'''Square root calculated using Netwton's method
'''
x = n/2.0
while True:
y = (x + n/x)/2
# As equality in floating numbers can be elusive,
# we check if the numbers are close to each other.
if abs(y-x) < sfi.epsilon:
break
x = y
return x
def factorial_new(n):
'''Factorial using for loop
'''
result = 1
if n < 0: return None
if n == 0: return 1
for i in range(1, n+1):
result = result * i
return result
def skipper01(end, start=0, step=1):
for i in range(start, end, step):
print(i, end=' ')
def skipper02(end, start=0, step=1):
i = start
while(i < end):
print(i, end=' ')
i = i + step
if __name__ == "__main__":
print("The square root of 4 = " + str(square_root(4)))
print("The square root of 9 = " + str(square_root(9)))
print("The square root of 15 = %.4f " % square_root(14))
print("The factorial of 4 = " + str(factorial_new(4)))
print("The factorial of 7 = " + str(factorial_new(7)))
print("The factorial of 10 = %d " % factorial_new(10))
skipper01(10, 5, 2)
print('\n')
skipper02(13, 3, 3)
print('\n')
skipper01(8)
print('\n')
skipper02(7)
| true
|
9599518e6519acb4736f62141cc10e41d9b200e6
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/83701c06-e19a-4c7b-87a6-fa1d10a49446__squareRootBisection.py
| 663
| 4.34375
| 4
|
"""Calculate the square cube of a float number"""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def squareRootBisection(x, precision):
'''
Calculate the square root of a float number through bisection method with given precision
:param x: Float number
:param precision: Square root precision
:return: Square root of the float number
'''
if x < 0 or precision <= 0:
return None
# x>=0
low = 0.0
high = x
value = (low+high)/2
while abs(value**2-x) > precision:
if value**2 < x:
low = value
else: # value**2 > x
high = value
value = (low+high)/2
return value
| true
|
9dc5ed37a27c4c98b989e3bdf2166427e52fcd9a
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/96237146-8b34-46ec-99b8-6c2b8cc9d4af__mergesort.py
| 712
| 4.15625
| 4
|
def merge(a, b):
"""Merging subroutine. Meant to merge two sorted lists into a combined, sorted list."""
n = len(a) + len(b)
d = [0 for i in range(n)]
i = 0
j = 0
for k in range(n):
if a[i] < b[j]:
d[k] = a[i]
if i+1 > len(a)-1:
for l in b[j:]:
d[k+1] = b[j]
k += 1
j += 1
return d
i += 1
elif a[i] > b[j]:
d[k] = b[j]
if j+1 > len(b)-1:
for l in a[i:]:
d[k+1] = a[i]
k+=1
i+=1
return d
j += 1
def merge_sort(c):
"""Recursive merge sort. Takes non-repeating list and returns sorted version of the list."""
if len(c) == 1:
return c
else:
a = merge_sort(c[:int(len(c)/2)])
b = merge_sort(c[int(len(c)/2):])
return merge(a,b)
| true
|
46b516b80a6b5655dfdd6ea7ad6aafe19ac20785
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/c0761eda-0c5d-4fce-b244-a8f29b56b412__newton_raphson_sqrt.py
| 396
| 4.34375
| 4
|
# Newton-Raphson for square root of a number
number = float(raw_input("Enter a positive number: "))
def newton_raphson_sqrt(number):
epsilon = 0.01
y = number
guess = y/2.0
while abs(guess*guess - y) >= epsilon:
guess = guess - (((guess**2) - y)/(2*guess))
#print(guess)
return guess
print('Square root of ' + str(number) + ' is about ' + str(newton_raphson_sqrt(number)))
| false
|
768035c28f0b186ded038a4ac1ba60e49bc35d5c
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/144143a2-f60f-451f-be83-51f5f3fce457__Algorithm-5%20Insertion%20Sort.py
| 308
| 4.1875
| 4
|
def insertion_sort(L):
"""Returns a Sorted List.
Usage:
>>>insertion_sort([6,8,1,8,3])
>>>[1, 3, 6, 8, 8]
"""
n = len(L)
for j in range(1,n):
i = 0
while L[j] > L[i]:
i += 1
m = L[j]
for k in range(0,j-i):
L[j-k] = L[j-k-1]
L[i] = m
return L
print insertion_sort([6,8,1,8,3])
| false
|
b76fb0244a57d12e90d6563ac9c69f17c17e5b0d
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/c614e01c-11a0-4821-8a6d-f748d0098ddb__insertionSort.py
| 472
| 4.15625
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def insertionSort(listToSort):
for i in range(1,len(listToSort)):
curVal = listToSort[i]
pos = i
while pos > 0 and listToSort[pos-1]>curVal:
listToSort[pos] = listToSort[pos-1]
pos = pos-1
listToSort[pos] = curVal
return listToSort
if __name__=="__main__":
listToSort = [2,7,3,8,5,1,0,5,8,16,39,1,3,23,12,34,82,6,2,8,55,5,20]
sortedList = insertionSort(listToSort)
print sortedList
| false
|
975976dac5dcdacbf94c3c7b5d37973ab501e3a1
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/39cf0f2e-d6c1-4606-9e97-3f60bda3a6a1__merge_sort_improved.py
| 1,024
| 4.40625
| 4
|
# Merge Sort
def merge(left, right):
"""Merges two sorted lists.
Args:
left: A sorted list.
right: A sorted list.
Returns:
The sorted list resulting from merging the two sorted sublists.
Requires:
left and right are sorted.
"""
items = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
items.append(left[i])
i = i + 1
else:
items.append(right[j])
j = j + 1
if i < len(left):
items.extend(left[i:])
elif j < len(right):
items.extend(right[j:])
return items
def merge_sort(items):
"""Sorts a list of items.
Uses merge sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
n = len(items)
if n < 2:
return items
m = n // 2
left = merge_sort(items[:m])
right = merge_sort(items[m:])
return merge(left, right)
| true
|
0509c69d4ad62a01518607588f61468cb4aa8ada
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/d302ddc9-b885-4379-b5c8-13288906db2a__HeronsMethod.py
| 1,674
| 4.40625
| 4
|
#!/usr/bin/env python
"""
This script is an implementation of Heron's Method (cs.utep.edu/vladik/2009/olg09-05a.pdf), one of the oldest ways of
calculating square roots by hand.
The script asks for maximum number of iterations to run, the square root to approximate, and the initial guess
for the square root. Each successive guess is closer to the square root until either the maximum number of iterations
is reached or the actual square root is found.
"""
__author__ = 'Carlos A. Gomez'
def ask_and_approx_roots():
num_iterations = int(input("Please enter the number of iterations (an integer): "))
square_root_to_approx = int(input("Please enter the square root to approximate (an integer): "))
sq_root_guess = float(input("Please enter a guess for the square root: "))
return heron_method(num_iterations, square_root_to_approx, sq_root_guess)
def heron_method(num_iterations, square_root_to_approx, sq_root_guess):
sq_root_approximation = 1/2 * (sq_root_guess + square_root_to_approx/sq_root_guess)
result_found = False
run_counter = 0
while not result_found:
run_counter += 1
last_guess = sq_root_approximation
print("Guess number " + str(run_counter) + " is " + str(sq_root_approximation))
sq_root_approximation = 1/2 * (sq_root_approximation + square_root_to_approx/sq_root_approximation)
if abs(sq_root_approximation - last_guess) == 0 or run_counter == num_iterations:
result_found = True
print("The best guess for the square root, using " + str(run_counter) + " iterations, is "
+ str(sq_root_approximation))
if __name__ == '__main__':
ask_and_approx_roots()
| true
|
1a9e104e93631dc74a90e6768991dee980bbadb8
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/f72b109f-64e1-42d5-a0ed-fcaf72e805a5__bubble_sort.py
| 491
| 4.125
| 4
|
from create_list import random_list, is_sorted
def bubble_sort(my_list):
"""
Perform bubble sort on my_list.
"""
while not is_sorted(my_list):
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
return my_list
my_list = random_list(50)
print(my_list)
print(is_sorted(my_list))
sorted_list = bubble_sort(my_list)
print(sorted_list)
print(is_sorted(sorted_list))
| true
|
72c1e0aa39f4022e3483e98d4a586e3b00032d71
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/b104d935-486f-4ca1-b317-bf78949d3ae0__sort.py
| 1,591
| 4.34375
| 4
|
# Executes merge sort on an unsorted list
# Args:
# items: Unsorted list of numbers
#
# Returns:
# Sorted list of items
def merge_sort(unsorted_list):
# If unsorted_list is length = 1, then it's implicitly
# sorted. Just return it. Base case.
if len(unsorted_list) == 1:
return unsorted_list
# Create two new lists
unsorted_list_a = unsorted_list[0:(len(unsorted_list)/2)]
unsorted_list_b = unsorted_list[(len(unsorted_list)/2):len(unsorted_list)]
# Sort them
sorted_list_a = merge_sort(unsorted_list_a)
sorted_list_b = merge_sort(unsorted_list_b)
# Merge the two sorted lists and return
sorted_list = merge(sorted_list_a, sorted_list_b)
return sorted_list
# Merges two sorted lists
# Returns:
# Sorted list
def merge(list_a, list_b):
sorted_list = []
# Iterates over the two lists, removing elements and putting
# them in sorted_list until one of the lists is empty
while (len(list_a) > 0 and len(list_b) > 0):
if list_a[0] < list_b[0]:
sorted_list.append(list_a[0])
list_a.pop(0)
else:
sorted_list.append(list_b[0])
list_b.pop(0)
# One of the lists was empty so just add the rest
# of the non-empty one to sorted_list
if len(list_a) == 0:
sorted_list.extend(list_b)
if len(list_b) == 0:
sorted_list.extend(list_a)
return sorted_list
def merge_unit_test():
list_a = [1,2,8,9]
list_b = [3,4,6,10,11]
sorted_list = merge(list_a, list_b)
print(sorted_list)
# TODO: Add some assertions here
def merge_sort_test():
list_a = [3,6,1,3,7,8,0,10,22,323,1,5,4,2,85,39]
sorted_list = merge_sort(list_a)
print(sorted_list)
| true
|
c5172eca5772e56a8ee0cd1f5dc7df51d72db5d1
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/sort/67a0a05e-aeae-4325-9ac2-e56575c7747b__insertion.py
| 671
| 4.125
| 4
|
def sort(coll):
''' Given a collection, sort it using the insertion
sort method (sorted by reference).
O(n^2) performance
O(n) storage
:param coll: The collection to sort
:returns: The sorted collection
'''
for j in range(1, len(coll)):
k = coll[j]
i = j - 1
while i > 0 and coll[i] > k:
coll[i + 1] = coll[i]
i = i - 1
coll[i + 1] = k
return coll
def sort_clone(coll):
''' Given a collection, sort it using the insertion
sort method (sorted by copy).
:param coll: The collection to sort
:returns: The sorted collection
'''
return sort(list(coll))
| true
|
4bf00048cb0797c83a7b79a1525b4bf504d9be68
|
erickmiller/AutomatousSourceCode
|
/AutonomousSourceCode/data/raw/squareroot/da7d2364-a2f6-4ca1-924c-9801f5195742__findSquareRoot.py
| 1,049
| 4.3125
| 4
|
#!/usr/local/bin/python
import sys
usage = """ Find square root of a give number
Usage: findSquareRoot.py <number>
Example: findSquareRoot.py 16"""
def main(argv):
"""
Executes the main() flow
@param argv: Command-line arguments
@type argv: array of strings
"""
if (len(argv) != 1):
print usage
sys.exit(2)
num = float(argv[0])
print 'Input number: ', num
squareRoot = getSquareRoot(num)
print 'Square root: ', squareRoot
def getSquareRoot(num):
"""
Finds square root of a given number
@param num: Number
@type num: integer
"""
isNegative = False
if (num < 0):
isNegative = True
num = abs(num)
# start with guess num / 2
guess = num / 2
# try to find square root within range
while (abs(guess * guess - num) > 0.001):
print guess
guess = (guess + num / guess) / 2
if (isNegative):
return str(guess) + " i"
return guess
if __name__ == "__main__":
main(sys.argv[1:])
| true
|
0ca64c1c83f6b6ba01a3a8f5082d5aa3b88afcdd
|
kocoedwards/CTBlock4P4
|
/firstParsonsProblems.py
| 837
| 4.5
| 4
|
"""
March 2, 2021
Use this document to record your answers to the Parson's Problems
shared in class.
Remember: the idea behind a Parson's Problem is that you are
shown completely correct code that is presented OUT OF ORDER.
When arranged correctly, the code does what the Parson's Problem
says it should do.
"""
#Write your answer to Parson's Problem #1 below:
#basic for loop
for x in range (0,10):
print ("hello world")
#Write your answer to Parson's Problem #2 below:
#basic list
myList = ["apples", "pineapples"]
myList.append ("apples")
myList.append ("pineapples")
print (myList)
#Write your answer to Parson's Problem #3 below:
#basic conditional
x = input ("10")
x = int (x)
if x > 0:
print ("That're more than nothing!")
else:
print ("That's a small number")
| true
|
20af73f2c6effe194835b9f137cabf854269f249
|
breezey12/collaborative-code
|
/tryingArgv.py
| 977
| 4.34375
| 4
|
from sys import argv
def count(start, end, incrementBy=1):
# enumerates between start and end, only lists even numbers if even = true
while start <= end:
print start
start += incrementBy
def even(start):
start += start % 2
incrementBy = 2
return start, incrementBy
def countBy(countByVal):
incrementBy = countByVal
return incrementBy
if __name__ == "__main__":
""" validates the number of arguments, enumerates positional arguments,
finds and stores optional arguments, then feeds them all to count()
"""
paramct = len(argv)-1
optional_args = []
ordered_args = []
if paramct < 2:
print "At least two arguments are required."
else:
for arg in argv:
if arg[0] == "-":
optional_args.append(arg[1:])
else:
ordered_args.append(arg)
start = int(arg)
end = int(argv[2])
count(start, end)
| true
|
287e21c219a5666f20d2a14b23d70cbc4154cec2
|
ebogucka/automate-the-boring-stuff
|
/chapter_7/strong_password_detection.py
| 948
| 4.28125
| 4
|
#!/usr/bin/env python3
# Strong Password Detection
import re
def check(password):
lengthRegex = re.compile(r".{8,}") # at least eight characters long
if lengthRegex.search(password) is None:
print("Password too short!")
return
lowerRegex = re.compile(r"[a-z]+") # contains lowercase characters
upperRegex = re.compile(r"[A-Z]+") # contains uppercase characters
if lowerRegex.search(password) is None or upperRegex.search(password) is None:
print("Password should contain both lower and upper case characters!")
return
digitRegex = re.compile(r"[0-9]+") # has at least one digit
if digitRegex.search(password) is None:
print("Password should contain at least one digit!")
return
print("That is a strong password!")
passwords = ["abc", "abcdefgh", "dA", "dfJHFcvcjhsdfmn", "dfJHFcvcjhsdfmn69"]
for password in passwords:
print("\n" + password)
check(password)
| true
|
1f6f43f9f60431b78ccec1d4499c2f52f4ee2646
|
soluke22/python-exercise
|
/primenumbers.py
| 496
| 4.15625
| 4
|
#Ask the user for a number and determine whether the number is prime or not.
def get_numb(numb_text):
return int(input(numb_text))
prime_numb = get_numb("Pick any number:")
n = list(range(2,int(prime_numb)+1))
for a in n:
if prime_numb == 2:
print("That number is prime.")
break
elif prime_numb == 1:
print("That number is not prime.")
break
elif prime_numb%a == 0:
print("That number is not prime.")
break
else:
print("That is a prime number!")
break
| true
|
00f478709a36a8623a38ec865bd78d189b369fec
|
hichingwa7/programming_problems
|
/circlearea.py
| 519
| 4.125
| 4
|
# date: 09/21/2019
# developer: Humphrey Shikoli
# programming language: Python
# description: program that accepts radius of a circle from user and computes area
########################################################################
#
def areacircle(x):
pi = 3.14
r = float(x)
area = pi * r * r
return area
print("Enter the radius of the cirle: ")
print(".............................. ")
radius = input()
print(".............................. ", "\n")
print("Area of the circle is: ", areacircle(radius))
| true
|
10c7603e3a8f8d390134f23b5891604f6d0dc74b
|
krushnapgosavi/Division
|
/div.py
| 923
| 4.1875
| 4
|
import pyttsx3
print("\n This is the program which will help you to find the divisible numbers of your number!!")
ch=1
engine= pyttsx3.init()
engine.setProperty("rate", 115)
engine.say(" This is the program which will help you to find the divisible numbers of your number")
while ch==1:
engine.runAndWait()
engine.say("Which number's divisible number you want")
engine.runAndWait()
x=int(input("Which number's divisible no. you want? : "))
engine.say("This is your Divisible Number's of"+str(x))
g=0
for a in range(1,x+1):
g=g+1
b=int(x%g)
if b==0:
print(g)
engine.setProperty("rate",200)
engine.say(g)
engine.setProperty("rate",115)
engine.say("Thanks for using this program , Do you want to use again")
engine.runAndWait()
ch=int(input("Thanks for using this program.Do you want to use again?(Yes(1),No(0)) : "))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.