blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
ad5cb253e28d7e27d12419911a3006b405a6c813
|
JunIce/python_note
|
/note/note_15.py
| 1,326
| 4.3125
| 4
|
#!/usr/bin/python
#coding=utf-8
'''
locals and globals
当一行代码要使用变量 x 的值时,Python会到所有可用的名字空间去查找变量,按照如下顺序:
1.局部名字空间 - 特指当前函数或类的方法。如果函数定义了一个局部变量 x,Python将使用这个变量,然后停止搜索。
2.全局名字空间 - 特指当前的模块。如果模块定义了一个名为 x 的变量,函数或类,Python将使用这个变量然后停止搜索。
3.内置名字空间 - 对每个模块都是全局的。作为最后的尝试,Python将假设 x 是内置函数或变量。
from module import 和 import module之间的不同。
使用 import module,模块自身被导入,但是它保持着自已的名字空间,这就是为什么你需要使用模块名来访问它的函数或属性(module.function)的原因。
但是使用 from module import,实际上是从另一个模块中将指定的函数和属性导入到你自己的名字空间,这就是为什么你可以直接访问它们却不需要引用它们所来源的模块的原因。
locals 是只读的,globals 不是
'''
def foo(arg, a):
x = 1
y = 'xxxxxx'
for i in range(10):
j = 1
k = i
print locals()
foo(1,2) #{'a': 2, 'i': 9, 'k': 9, 'j': 1, 'arg': 1, 'y': 'xxxxxx', 'x': 1}
| false
|
8edcbf1541b7f6ab2121dcefc102414293d58318
|
s724959099/py_pattern_note
|
/BehavioralPattern/visit.py
| 1,489
| 4.28125
| 4
|
class Wheel:
def __init__(self, name):
self.name = name
def accept(self, visitor):
# 每個visitor是同樣的,但是其中的方法是不一樣的,比如這裡是visitWheel,
# 然後傳入瞭self,想想?他其實想做什麼就能做什麼
visitor.visit_wheel(self)
class Engine:
def accept(self, visitor):
visitor.visit_engine(self)
class Body:
def accept(self, visitor):
visitor.visit_body(self)
# 我們要組合成車
class Car:
def __init__(self):
self.engine = Engine()
self.body = Body()
self.wheels = [Wheel("front left"), Wheel("front right"),
Wheel("back left"), Wheel("back right")]
# 這個也不需要在動,他隻是上面部件的組合,隻是做瞭屬性的委托
def accept(self, visitor):
visitor.visit_car(self)
self.engine.accept(visitor)
self.body.accept(visitor)
for wheel in self.wheels:
wheel.accept(visitor)
# 這個才是我們的訪問者,每次的修改都在這裡面
class PrintVisitor:
def visit_wheel(self, wheel):
print("Visiting " + wheel.name + " wheel")
def visit_engine(self, engine):
print("Visiting engine")
def visit_body(self, body):
print("Visiting body")
def visit_car(self, car):
print("Visiting car")
if __name__ == '__main__':
car = Car()
visitor = PrintVisitor()
car.accept(visitor)
| false
|
38134c740f1dac177e5d3263895314053e7a6fcc
|
ism23867017/Python-Estructurado
|
/primo.py
| 227
| 4.125
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
salir = False
numero = input("Introduzca un numero: ")
if numero<2:
print "No es primo"
else:
if numero/numero==0 and numero/numero=1
print "Es primo"
salir = True
| false
|
a3a462573a5d9069a7736bd4036dd1f2012e079f
|
Novandev/chapt2
|
/convert3.py
| 483
| 4.25
| 4
|
# convert3.py
# A program that convert Celsius temps to Fahrenheit and prints a table
# redone by donovan Adams
def main():
print "This is a program that converts Celcius to Fahrenheit."
print "Here are the temperatures every 10 degrees"
print " ____________________"
for i in [10,20,30,40,50,60,70,80,90,100]:
celsius = i
fahrenheit = 9.0 / 5.0 * celsius + 32
print "The temperature is", fahrenheit, "degrees Fahrenheit."
i = i + 10
main()
| true
|
860cdce5fdb20a8ad9ab3ab4e17e3238243ec9a5
|
sageserin/cssi_code
|
/tester-python/datatypes.py
| 279
| 4.3125
| 4
|
"""
exploring data types
lists are mutable
dictionaries
"""
x = [1, 2, 3]
def weird(num, default_ls=None):
default_ls = default_ls or [] #
default_ls.append(num)
print(default_ls)
weird(1)
weird(2)
weird(3)
dict = {1: 'a', 2:'b', 3:['c', 'd', 'e']}
| false
|
9d0a204ea2f2a8311b09b1c3cc7e278e9535364a
|
danieled01/python
|
/myapps/test_scripts/reverse.py
| 355
| 4.5625
| 5
|
#have to write a function that will return the value of a string backwards:
def solution(string):
return string[::-1]
#string[::1] works by specifying which elements you want as [begin:end:step]. So by specifying -1 for the step you are telling Python to use -1 as a step which in turn starts
#from the end. This works both with strings and lists
| true
|
db892f7ee026d9356d5ffce80899ffb20bc3e698
|
DevanKula/CP5632_Workshops
|
/Workshop 7/do from scratch.py
| 364
| 4.15625
| 4
|
word_string = str(input("Enter the a phrase: ")).split()
counter = 0
words_dicts = {}
for word in word_string:
counter = word_string.count(word)
words_dicts = {word:counter}
print(words_dicts)
#print(word_count)
# print(words_lists)
#
# word_count = word_string.count(words)
#for word in words_lists:
# print("{} : {}".format(word[0],word[1]))
| true
|
d73871c1c1b53578c182cb14eb2a66c40f7b2834
|
DevanKula/CP5632_Workshops
|
/Workshop 7/Color.py
| 455
| 4.15625
| 4
|
COLORS = {"coral":"#ff7f50", "coral1":"#ff7256", "coral2":"#ee6a50", "coral3":"#cd5b45", "coral4":"#8b3e2f", "CornflowerBlue":"#6495ed",
"cornsilk1":"#fff8dc", "cornsilk2":"#eee8cd", "cornsilk3":"#cdc8b1", "cornsilk4":"#8b8878"}
color = input("Enter color: ").lower()
while color != "":
if color in COLORS:
print(color, "is", COLORS[color])
else:
print("Invalid color")
color = input("Enter short color: ").lower()
| false
|
8e28859c7fa7cdb32794e51b3c3fc8c45ce6b544
|
shobhit-nigam/strivers
|
/day2/list/11.py
| 539
| 4.1875
| 4
|
# functions
# append vs extend
# part one
lista = ['aa', 'hh', 'aa', 'KK', 'dd', 'rr']
listb = ['ff', '25', 'WW']
print("lista =", lista)
print("len of lista =", len(lista))
lista.append(listb)
print("-----")
print("lista =", lista)
print("len of lista =", len(lista))
print("##################")
# part two
lista = ['aa', 'hh', 'aa', 'KK', 'dd', 'rr']
listb = ['ff', '25', 'WW']
print("lista =", lista)
print("len of lista =", len(lista))
lista.extend(listb)
print("-----")
print("lista =", lista)
print("len of lista =", len(lista))
| false
|
b86a00994c09f0ecf9cd87ef82f50d66b69f9dc7
|
abhisheklomsh/MyTutorials
|
/#100daysOfCode/day1.py
| 2,781
| 4.34375
| 4
|
"""
Two Number Sum:
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum upto the target sum, the function should return them in an array, in any order.
If no two numbers sum up to the target sum, the function should return an empty array.
Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum.
You can assume that there will be at most one pair of numbers summing up to the target sum.
There are 3 possible solutions for the question as follow.
"""
import unittest
"""
# O(n^2,) time | O(1) space
def twoNumberSum(array, targetSum):
for i in range(0, len(array) - 1):
firstNum = array[i]
for j in range(i + 1, len(array)):
secondNum = array[j]
if firstNum + secondNum == targetSum:
return [firstNum, secondNum]
return []
# O(n) time | O(n) space
def twoNumberSum(array, targetSum):
complements = {}
n = len(array)
for i in range(0, n):
temp = targetSum - array[i]
if temp in complements:
return sorted([temp, array[i]])
else:
complements[array[i]] = temp
return []
"""
# O(nlog(n)) time | O(1) space
def twoNumberSum(array, targetSum):
array.sort() #inplace sort
left = 0
right = len(array) - 1
while left < right:
currentSum = array[left] + array[right]
if currentSum == targetSum:
return [array[left], array[right]]
elif currentSum < targetSum:
left += 1
elif currentSum > targetSum:
right -= 1
return []
class TestProgram(unittest.TestCase):
def test_case_1(self):
output = twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
self.assertTrue(len(output) == 2)
self.assertTrue(11 in output)
self.assertTrue(-1 in output)
def test_case_2(self):
output = twoNumberSum([4, 6], 10)
self.assertTrue(len(output) == 2)
self.assertTrue(4 in output)
self.assertTrue(6 in output)
def test_case_3(self):
output = twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 15)
self.assertTrue(len(output) == 0)
def test_case_4(self):
output = twoNumberSum([-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], 163)
self.assertTrue(len(output) == 2)
self.assertTrue(210 in output)
self.assertTrue(-47 in output)
def test_case_5(self):
output = twoNumberSum([-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], 164)
self.assertTrue(len(output) == 0)
if __name__ == '__main__':
unittest.main()
| true
|
cfd5e4b286025af3112ce456e847263fa45dcf1f
|
bopopescu/python-1
|
/m3_operator/format_str.py
| 636
| 4.125
| 4
|
print('{0} is {1} years old !' .format('TOM',30))
print('{1} is {0} years old !' .format(30,'TOM'))
print('{} is {} years old !' .format('TOM',30))
print('{name} is {age} years old !' .format(name='TOM',age=30))
print('{name} is {age} years old !' .format(age=30,name='TOM'))
print('{} is {age} years old !' .format('TOM',age=30))
print('{0} is {1} years old ! He is {2}m!!' .format('TOM',30,1.8872))
print('{0} is {1} years old ! He is {2: .2f}m!!' .format('TOM',30,1.8872))
print('String : {:>10s}'.format('GM'))
print('String : {:^10s}'.format('GM'))
print('String : {:<10s}'.format('GM'))
print('String : {:-^10s}'.format('GM'))
| false
|
ee53bf76298753fd95975aefde030d4ae3baf56a
|
prathimaautomation/python_oop
|
/python_functions.py
| 1,422
| 4.59375
| 5
|
# Let's create a function
# Syntax def is used to declare followed by name of the function():
# First Iteration
# def greeting():
# print("Welcome on Board! enjoy your trip.")
# # pass # pass keyword that allows the interpretor to skip this without errors
#
#
# greeting() # if we didn't call the function it would execute the code with no error but no outcome
#
#
# # DRY Don't Repeat Yourself by declaring functions and reusing code
#
# # Second Iteration using RETURN statement
# def greeting():
# print("Good Morning")
# return "Welcome on board! Enjoy your trip!!"
#
#
# print(greeting())
#
#
# # Third Iteration with username as a String as an argument/args
# def greeting(name):
# return "Welcome on board " + name
#
#
# print(greeting("Prathima"))
#
# # Fourth Iteration to prompt the user to enter their name and display the name back to user with greeting message
#
# def greeting(name):
# return "Welcome on board " + name
#
#
# print(greeting(input("Please give your name: ")))
# Let's create a function with multiple args as an int
def add(num1, num2):
return num1 + num2
print(add(9, 3))
def multiply(num1, num2):
print("This functions multiplies 2 numbers ")
return num1 * num2
print(" this is the required outcome of 2 numbers ") # this line of code will not be executed as return statement is last line of code that function executes
print(multiply(3, 3))
| true
|
b77dc0558251c9f7e86390143e4d708a48249f15
|
2kaiser/raspberry_pi_cnn
|
/mp1/pt2.py
| 2,403
| 4.15625
| 4
|
import numpy as np
#Step 1: Generate a 2-dim all-zero array A, with the size of 9 x 6 (row x column).
A = np.zeros((9,6))
print("A is: ")
print(A)
#Step 2: Create a block-I shape by replacing certain elements from 0 to 1 in array A
A[0][1:5] = 1 #top of I
A[1][1:5] = 1 #top of I
A[2][2:4] = 1 #middle of I
A[3][2:4] = 1 #middle of I
A[4][2:4] = 1 #middle of I
A[5][2:4] = 1 #middle of I
A[6][2:4] = 1 #middle of I
A[7][1:5] = 1 #bottom of I
A[8][1:5] = 1 #bottom of I
print("I shaped A is: ")
print(A)
################################################################################################################################
#todo
#Step 3: Generate a 2-dim array B by filling zero-vector at the top and bottom of the array A.
#make a zero array of desired size and then enclose the previous array around it
B = np.zeros((11,6))
B[:A.shape[0],:A.shape[1]] = A
#add in a row of zeros and remove the last row
Z = np.concatenate(([[0,0,0,0,0,0]],B[0:10][:]))
print("B is: ")
print(Z)
################################################################################################################################
C =(np.arange(66).reshape(11, 6))+1
print("C is: ")
print(C)
################################################################################################################################
D = np.multiply(Z,C)
print("D is: ")
print(D)
################################################################################################################################
E = np.zeros(26)
index = 0
for i in range(D.shape[0]):
for j in range(D.shape[1]):
if(D[i][j] != 0):
#print(D[i][j])
E[index] = D[i][j]
index = index + 1
print("E is: ")
print(E)
################################################################################################################################
max, min = E.max(), E.min()
index = 0
F = np.zeros((11,6))
for i in range(D.shape[0]):
for j in range(D.shape[1]):
if(D[i][j] != 0):
F[i][j] = (D[i][j] - min) / (max - min)
index = index + 1
print("F is: ")
print(F)
#Step 8: Find the element in F with the closest absolute value to 0.25 and print it on screen.
curr_closest = 10000
for i in range(D.shape[0]):
for j in range(D.shape[1]):
if(abs(curr_closest-.25) > abs(F[i][j]-.25)):
curr_closest =F[i][j]
print("Closest value is: ")
print(curr_closest)
| true
|
9b7535587b9e92bcd7cf5bb1577863b01b1f3792
|
lacoperon/CTCI_Implementations
|
/1_ArraysAndStrings/1.3.py
| 1,672
| 4.1875
| 4
|
'''
Elliot Williams
08/02/18
Q: `URLify`: Write a method to replace all spaces in a string with '%20'. You
may assume that the string has sufficient space at the end to hold the
additional characters, and that you are given the "true" length of the string
'''
def URLify(char_array, true_length):
j = len(char_array) - 1 # index of last character
# Iterates through characters in char_array in reverse,
# to prevent overwriting necessary characters
for i in reversed(range(len(char_array))):
current_char = char_array[i]
if current_char is not None:
if current_char is " ":
# Adds in %20 in appropriate places, and goes back 3 characters
char_array[j] = "0"
char_array[j-1] = "2"
char_array[j-2] = "%"
j -= 3
else:
char_array[j] = current_char
j -= 1
return char_array
# Time Complexity: O(N)
# Space Complexity: O(1) ~in place~
# Helper function to generate appropriate input
def char_arrayify(input):
num_spaces = 0
char_array = []
for char in input:
if char is " ":
num_spaces += 1
char_array.append(char)
char_array += [None] * num_spaces * 2
return char_array
fox_str = "The Fox jumped quickly"
empty_str = ""
borg_str = "NoSpacesAreNecessaryForTheBorg"
fox_example = (char_arrayify(fox_str), len(fox_str))
empty_example = (char_arrayify(empty_str), len(empty_str))
borg_example = (char_arrayify(borg_str), len(borg_str))
print("".join(URLify(*fox_example)))
print("".join(URLify(*empty_example)))
print("".join(URLify(*borg_example)))
| true
|
5a481d5050fe713ca17e5b63747f03488e0f6540
|
jknight1725/pizza_compare
|
/pizza.py
| 948
| 4.125
| 4
|
#!/usr/bin/env python3
from math import pi
from sys import argv
p1_size = int(argv[1])
p1_price = int(argv[2])
p2_size = int(argv[3])
p2_price = int(argv[4])
def pizza(size, price):
stats = {}
radius = size / 2
radius_squared = radius*radius
area = radius_squared * pi
stats['size'] = size
stats['price'] = price
stats['area'] = area
stats['price_per_unit'] = price / area
return stats
def compare(p1, p2):
more_expensive, less_expensive = (p1, p2) if p1['price_per_unit'] > p2['price_per_unit'] else (p2, p1)
ratio = more_expensive['price_per_unit'] / less_expensive['price_per_unit']
print("Best deal")
print(f"{less_expensive['size']} inch pizza for {less_expensive['price']}")
print(f"Price per sq. inch {less_expensive['price_per_unit']}")
print(f"{ratio} times more value by choosing this pizza")
p1 = pizza(p1_size, p1_price)
p2 = pizza(p2_size, p2_price)
compare(p1, p2)
| true
|
dafb9574bdc22831f57d013a3d7faf02276b245c
|
lee7py/2021-py-IDE-VE
|
/py code/np 샘플코드3.py
| 497
| 4.15625
| 4
|
# http://riseshia.github.io/2017/01/30/numpy-tutorial-with-code.html
import numpy as np
a = np.arange(12) # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
print(a)
b = a.reshape(4, 3) # 변환된 행렬을 반환
print(b)
a.resize((3, 4)) # 자체를 변환함
print(a)
b = a.flatten()
print(b)
b = a.ravel()
print(b)
b = a.T # 전치 행렬
print(a)
print(b)
a.shape = 2, 6 # 파괴적
print(a)
b = a.reshape(3, -1) # 변환된 행렬을 반환
print(b)
| false
|
3453b1722291df1e10df811649950da89e8abac4
|
SumitAnand1/hello1
|
/Calculator.py
| 2,190
| 4.21875
| 4
|
from math import*
x=float(input('enter:'))
y=float(input('enter:'))
class calculator():
def __init__(self):
'''calculator'''
class math_operation(calculator):
def sum(self):
print('sum of two digits')
print(x+y)
def sub(self):
print('subtraction of two digit')
print(x-y)
def mul(self):
print('multiplicatin of two digit')
print(x*y)
def div(self):
print('division of two digits')
print(x/y)
def pow(self):
print('power of first digit over second')
print(pow(x,y))
def squir_root(self):
import math
print('squir root of the digits')
print('squirroot of first digit',math.sqrt(x))
print('squirroot of second digit',math.sqrt(y))
class trigonometry(calculator):
'''trigonometry solutions'''
def sin(self):
import math
print('sin of first digit',math.sin(x))
print('sin of second digit',math.sin(y))
def cos(self):
import math
print('cos of first digit',math.cos(x))
print('cos of second digit',math.cos(y))
def tan(self):
import math
print('tan of first digit',math.tan(x))
print('tan of second digit',math.tan(y))
class logorithm(calculator):
def log(self):
import math
print('logorithm solutions')
print('log of first digit',math.log(x))
print('log of second digit',math.log(y))
obj1=math_operation()
obj2=trigonometry()
obj3=logorithm()
while True:
op=input('enter the operator:')
if op=='+':
obj1.sum()
elif op=='-':
obj1.sub()
elif op=='*':
obj1.mul()
elif op=='/':
obj1.div()
elif op=='**':
obj1.pow()
elif op=='root':
obj1.squir_root()
elif op=='sin':
obj2.sin()
elif op=='cos':
obj2.cos()
elif op=='tan':
obj2.tan()
elif op=='log':
obj3.log()
else:
print('you have entered wrong operator')
break
input('press any key to exit:')
| false
|
b0c65894f67a4ee168f84e472fd3f8bf1afe0ad7
|
Wormandrade/Trabajo02
|
/eje_p1_06.py
| 448
| 4.28125
| 4
|
#Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente:
print("========================")
print("\tEJERCICIO 06")
print("========================")
print("\nListas dinamicas\n")
def listas(inicio, fin, salto):
num_lista = []
for num in range(inicio, fin+1,salto):
num_lista.append(num)
print(num_lista)
listas(0,10,1)
listas(-10,0,1)
listas(0,20,2)
listas(-19,0,2)
listas(0,50,5)
| false
|
4ea6c3c11397c35e0acadf6e69de7c2489d6ddbf
|
RLewis11769/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/100-append_after.py
| 773
| 4.125
| 4
|
#!/usr/bin/python3
"""
append_after - inserts text to file if line contains string
@filename: file to search and append to
@search_string: if in line, insert text after given line
@new_string: text to insert after found text
"""
def append_after(filename="", search_string="", new_string=""):
""" Appends new_string to filename after search_string line in filename """
string = ""
with open(filename) as f:
for line in f:
""" Adds each line to new line """
string += str(line)
""" If search_string is in line, adds string after """
if search_string in line:
string += new_string
""" Overwrites file with final string """
with open(filename, 'w') as f:
f.write(string)
| true
|
182e81555a1d0d5f4d9312d73ba8dfed7bc50841
|
Andy931/AssignmentsForICS4U
|
/BinarySearchInPython.py
| 2,318
| 4.15625
| 4
|
# Created by: Andy Liu
# Created on: Oct 17 2016
# Created for: ICS4U
# Assignment #3b
# This program searches a number exists in an random array using binary search
from random import randint
array_size = 250 # define the size of the array
def binary_search(search_value, num):
# these variables define a range for searching
start_position = 0
end_position = array_size - 1
mid_position = int((end_position - start_position) / 2 + start_position + 0.5)
# loop the process until the number is found
while search_value != num[mid_position]:
mid_position = int((end_position - start_position) / 2 + start_position + 0.5)
if search_value > num[mid_position]:
start_position = mid_position
else:
end_position = mid_position
if end_position-start_position <= 1:
if search_value == num[start_position]:
return start_position
elif search_value == num[end_position]:
return end_position
else:
print("Not Found!")
return -1
return mid_position
def bubble_sort(number_list):
flag = False # set flag to false to begin first pass
temp = 0 # holding variable
while flag == False:
flag = True # set flag to true awaiting a possible swap
for j in range(len(number_list)-1):
if number_list[j] > number_list[j+1]: # change to > for ascending sort
temp = number_list[j+1] # swap elements
number_list[j+1] = number_list[j]
number_list[j] = temp
flag = False # shows a swap occurred
# Main program starts
numberArray =[randint(1,2000) for i in range(0,array_size)]
bubble_sort(numberArray) # call bubble sort function to sort the array
for counter in range(0, array_size):
print("A[",counter,"] = ", numberArray[counter]) # print out the sorted array
# input
inputNumber = eval(input("Please enter an integer to search: \n")) # input the number to search
# process
position = binary_search(inputNumber, numberArray) # call binary search function to search the number
# output
print("The position of the number is", position) # print out the position
| true
|
697b324ffae85c598109b5ac5986f2c3af5dddc3
|
DenisLo-master/python_basic_11.06.2020
|
/homeworks/less3/task3.py
| 839
| 4.5625
| 5
|
"""
3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
"""
def my_func(num1: int, num2: int, num3: int) -> int:
"""
search for two of the smallest arguments out of three
:param num1: any number
:param num2: any number
:param num3: any number
:return: print (sum of two max value)
"""
m1_num = 0
m2_num = 0
i = 0
numbers = [num1, num2, num3]
while i < len(numbers):
m1_num = numbers[i] if numbers[i] > m1_num else m1_num
i += 1
i = 0
while i < len(numbers):
m2_num = numbers[i] if m1_num > numbers[i] > m2_num else m2_num
i += 1
print(m1_num + m2_num)
my_func(9, 7, 17)
| true
|
d621e1e36862636796eb36c99ecbdc070b4a2328
|
skawad/pythonpractice
|
/datastructures/ex_08_05.py
| 1,003
| 4.1875
| 4
|
# Open the file mbox-short.txt and read it line by line. When you find a line
# that starts with 'From ' like the following line:
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.
# Hint: make sure NOT to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count.
# You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
fname = input("enter file name: ")
count = 0
try:
fhand = open(fname)
for line in fhand:
if line.startswith("From "):
temp_list = line.split()
print(temp_list[1])
count = count + 1
else:
continue
except:
print("File cannot be opened:", fname)
quit()
print("There were", count, "lines in the file with From as the first word")
| true
|
cc6567dbbf51778cc3aa8ca439727d1b6b80ea07
|
janelstewart/myshoppinglistproject.py
|
/shopping_list_project.py
| 2,044
| 4.25
| 4
|
my_shopping_lists_by_list_name = {}
def add_list(list_name):
#check if list name exists in dictionary
#if doesnt exist add list to dictionary
if list_name not in my_shopping_lists_by_list_name:
my_shopping_lists_by_list_name[list_name] = []
def add_item_to_list(list_name,item):
#use list name to retrieve list
#check if item doesnt exists,
list_name = list_name.lower()
if list_name in my_shopping_lists_by_list_name:
shopping_list = my_shopping_lists_by_list_name[list_name]
if item in shopping_list:
print "This %s is already in this list." % (item)
else:
shopping_list.append(item)
shopping_list.sort()
print shopping_list
else:
print "This %s does not exist." % (list_name)
#add item to list
#if item does exists already then tell user its already there
#print out current list after item added using list_sorter function
def remove_item_from_list(list_name,item):
#check if item exists in list
list_name = list_name.lower():
if list_name in my_shopping_lists_by_list_name:
shopping_list = my_shopping_lists_by_list_name[list_name]
if item not in shopping_list:
print "This %s does not exist." % (item)
else:
shopping_list.remove(item)
shopping_list.sort()
print shopping_list
else:
print "This %s does not exist." % (item)
#if yes, remove item
#if it doesnt exist tell user it doesnt exist
#print out current list after removing item use list_sorter function
def remove_list(list_name):
if list_name in my_shopping_lists_by_list_name:
#check if list name is in dictionary
#if yes, remove list
#if not, tell user list does not exist
#def list_sorter(list_name):
#NOT NEEDED IF SORTING LIST THROUGHOUT FUNCTIONS
#get list from dictionary
#sort list using .sort() and return sorted list
def menu_option():
#returns menu option
def all_list():
#need dictionary with key:value pairs
#print
def main():
#ask for input
#use menu function to get choice then based on choice
#you will decide which function to use
if __name__ == '__main__':
main()
| true
|
e4b882493feb4792ecd3b72b781edb0856b5ffb5
|
Suhyun-2012/Suhyun-2012.github.io
|
/Works/CYO.py
| 893
| 4.28125
| 4
|
answer1 = input("Should I go walk on the beach or go inside or go to the city?")
if answer1 == "beach":
if input("Should I go swimming or make a sandcastle?") == "sandcastle":
print("Wow, my sandcastle is very tall!")
#elif input(print("Should I go swimming or make a sandcastle?")) == "jiooswimming":
else:
print("Shark!")
elif answer1 == "inside"
elif input("Should I go walk on the beach or go inside or go to the city?") == "inside":
if input("Should I go sleep or make lunch?") == "sleep":
print("I think I am going to take a nap.")
else:
print("I think I am going to cut carrots.")
print("Aah! I cut myself!")
else:
if answer1 == "court":
print("Lets make a jury")
else:
print ("This is boring")
#elif input(print("Should I go walk on the beach or go inside?")) == "inside":
| true
|
19c38fbcff05936e5b981613229378b6569c890f
|
williamdarkocode/AlgortithmsAndDataStructures
|
/threeway_set_disjoint.py
| 1,243
| 4.125
| 4
|
# given 3 sequences of numbers, A, B, C, determine if their intersection is empty. Namely, there does not exist an element x such that
# x is in A, B, and C
# Assume no individual sequence contains duplicates
import numpy as np
def return_smallest_to_largest(A,B,C):
list_of_lists = [A,B,C]
len_list = [len(A), len(B), len(C)]
fin_list = [0]*3
for i in range(len(len_list)):
idx = np.argmin(len_list)
fin_list[i] = list_of_lists[idx]
len_list = len_list[0:idx] + len_list[idx+1:]
list_of_lists = list_of_lists[0:idx] + list_of_lists[idx+1:]
return fin_list
def set_disjoint1(A,B,C):
smtlrg = return_smallest_to_largest(A,B,C)
for a in smtlrg[0]:
for b in smtlrg[1]:
if a == b:
# we only check an intersection with c if a, and b intersect
for c in smtlrg[2]:
if a == c:
return [False, a]
return [True, '']
def main():
A = input('Enter sequence A: ')
B = input('Enter sequence B: ')
C = input('Enter sequence C: ')
A = A.split(',')
B = B.split(',')
C = C.split(',')
resp = set_disjoint1(A, B, C)
print(resp)
if __name__ == '__main__':
main()
| true
|
11a37184c06031fb300cc01555acc86b5fc7620e
|
milesmackenzie/dataquest
|
/step_1/python_intro_beginner/intro_functions/movie_metadata_exercise3.py
| 785
| 4.375
| 4
|
# Write a function index_equals_str() that takes in three arguments: a list, an index and a string, and checks whether that index of the list is equal to that string.
# Call the function with a different order of the inputs, using named arguments.
# Call the function on wonder_woman to check whether or not it is a movie in color, store it in wonder_woman_in_color, and print the value.
wonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]
def is_usa(input_lst):
if input_lst[6] == "USA":
return True
else:
return False
def index_equals_str(lst, idx, string):
if lst[idx] == string:
return True
else:
return False
wonder_woman_in_color = index_equals_str(wonder_woman,2,"Color")
print (wonder_woman_in_color)
| true
|
144387536b64e9518bb04d72279f8bcd28cd4e77
|
sivabuddi/Python_Assign
|
/python_deep_learning_icp1/stringreplacement.py
| 1,355
| 4.21875
| 4
|
# Replace Class in Python
class Replace:
def replace(self,input_string,original_word, replacement_word):
output_string = ""
temp_string = ""
temp_counter = -1
init = 0
for char in input_string:
# check if its starting with Original word for replacing
if temp_counter < 0 and char == original_word[init]:
temp_counter = init
temp_counter += 1
temp_string += char
# its matching and still going.
elif 0 < temp_counter < len(original_word) and char == original_word[temp_counter]:
temp_counter += 1
temp_string += char
# Matching Complete
if temp_string == original_word:
temp_counter = -1
temp_string = ""
output_string += replacement_word
# Partially matched, but not entirely, so don't replace use the temp string formed so far.
elif 0 < temp_counter < len(original_word) and char != original_word[temp_counter]:
temp_string += char
output_string += temp_string
temp_counter = -1
temp_string = ""
elif temp_counter == -1:
output_string += char
return output_string
| true
|
624fece2eb26804725675757255cafe640ad30a5
|
islamuzkg/tip-calculator-start
|
/main.py
| 1,332
| 4.15625
| 4
|
#If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal
#HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python
print("Welcome to the tip calculator")
bill = input("What was the total bill! ")
bill_as_float = float(bill)
current_bill = (f"Your current bill is {bill_as_float}")
print(current_bill)
tip = input("What percentage tip would you like to leave? 10, 12 or 15? ")
tip_as_int = int(tip)
tip_percent = tip_as_int / 100
how_many_people = int(input("How many people to split the bill?"))
total_tip_amount = bill_as_float * tip_percent
total_bill = total_tip_amount + bill_as_float
total_bill_as_rounded = round(total_bill, 2)
each_person = bill_as_float / how_many_people * (1 + tip_percent)
print(tip_percent)
each_person_as_rounded = "{:.2f}".format(each_person)
message = f" Total bill is {total_bill_as_rounded}, you are giving {tip_as_int} percent tips, between {how_many_people} people each person will pay {each_person_as_rounded}"
print(message)
| true
|
ab4dc1572c3040ffb05287f4779bb16b41b0fa65
|
Magical-Man/Python
|
/Learning Python/allcmd.py
| 990
| 4.34375
| 4
|
assert 2 + 2 == 4, "Huston, we have a probelm"
#If the above was == 5, there would be an error.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
#loop fell through without finding a factor
print(n, 'is a prime number')
#Basically what break does is loop us back to the top of a loop.
#Here is an example of classes
class Dog:
tricks = []
def __init__ (self, name):
self.name = name
def add_tricks(self, trick):
self.tricks.append(trick)
'''This is a class, it says that the variable in the class, or the object, is this list. By using __init__ it is
a bit like argv and lets you add arguments to your functions. Then by using the .\'s we are able to call the functions.
'''
#The thing that the continue statement does is just says to go back to the start of the loop and keep looping.
##Also remember that you have a quizlet to STUDY!!!!
| true
|
5031ef63a8e97b9b55df8c872002e5a03fff41e2
|
Magical-Man/Python
|
/Learning Python/practice/listprc.py
| 1,269
| 4.25
| 4
|
##Here what we are doing is just declaring a variable, and then printing some stuff
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait, there are not 10 things in that list. Let's fix that.")
##Here we declare a variable assigned to the ten_things var, but split
##Then we make a list called more_stuff
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
##Here we make a loop that is adding to more_stuff from stuff
while len(stuff) != 10:
next_one = more_stuff.pop() #Because there is nothing specified in .pop() the default is the last item
print("Adding: ", next_one)
stuff.append(next_one)
print("There are %d items now." % len(stuff))
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1]) #Here we just say to grab the second item, this is becuase of cardinal nums
print(stuff[-1]) #Here we are grabbing the last item cause integers nad negativces
print(' '.join(stuff)) #Here we say to make everything in stuff back into one string
print("#".join(stuff)) #Same but sperate w/ #
print("#".join(stuff[3:5])) #Here we say print eveything between item 4 and 6
| true
|
07e495cda7220ffa3299cb09e7ee082ba57210e2
|
Magical-Man/Python
|
/Learning Python/functions/functions.py
| 994
| 4.75
| 5
|
#Functions let you make our own mini-scripts or tiny commands.
#We create functions by using th word def in python
#This function is like argv scripts
#So here we create a function named print_two, and we call *args on it, just
#Like argv
def print_two(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r" %(arg1, arg2))
#Okay, so the *args is actallty pointless there lets just do
def print_two_again(arg1, arg2):
print("arg1: %r, arg2: %r" %(arg1, arg2))
#Now here is one that just takes one argument
def print_one(arg1):
print("arg1: %r" % arg1)
#This one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Charlie", "Odulio")
print_two_again("Charlie", "Odulio")
print_one("First Place!")
print_none()
'''
Some more notes
Always as a colin after the function parenthesis, ;
Always indent
No duplicate arguments in parenthesis
Print, execpt, len, all that is bassiclaly a function
To run, call, or use a function all use the same thing
'''
| true
|
17d6d883df6ba8104ebfe57d97e5319e4055f058
|
fil0o/git-repo
|
/sort_arr.py
| 1,562
| 4.28125
| 4
|
def find_smallest(arr):
"""Функция поиска индекса наименьшего элемента в массиве"""
smallest = arr[0] # Для хранения наименьшего элемента
smallest_index = 0 # Для хранения индекса наименьшего элемента
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionSort(arr):
"""Функция сортировки массива"""
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr) # Находит наименьший элемент в массиве
new_arr.append(arr.pop(smallest)) # Добавляет найденный элемент в новый массив
return new_arr
print(selectionSort([5, 2, 10, 6, 3, 9, 1, 12, 26]))
def quick_sort(array):
if len(array) < 2: # Базовый случай: массива с 0 и 1 элементом уже отсортированы
return array
else:
pivot = array[0] # Рекурсивный случай
less = [i for i in array[1:] if i <= pivot] # Подмассив всех элементов, меньше опорного
greater = [i for i in array[1:] if i > pivot] # Подмассив всех элементов, больше опорного
return quick_sort(less) + [pivot] + quick_sort(greater)
print(quick_sort([5, 2, 10, 6, 3, 9, 1, 12, 26]))
| false
|
35bf75a0803313c21064ad56b83c47368965b30a
|
Ruiznun/WordMath
|
/wordMath.py
| 2,643
| 4.21875
| 4
|
test = 'ONETWOPLUSONEMINUSNEGATIVETWO'
#two variables that wil be cariong all the data
exp = ''
result = ''
print('The Text : ' + test)
#loops through the expression
for c in test:
exp = exp + c.lower()
#check for numbers and other expressions
if exp == 'negative':
result = result + '-'
exp = ""
elif exp == 'minus':
result = result + ' - '
exp = ""
elif exp == "plus":
result = result + ' + '
exp = ""
elif exp == 'zero':
result = result + '0'
exp = ""
elif exp == 'one':
result = result + '1'
exp = ""
elif exp == 'two':
result = result + '2'
exp = ""
elif exp == 'three':
result = result + '3'
exp = ""
elif exp == 'four':
result = result + '4'
exp = ""
elif exp == 'five':
result = result + '5'
exp = ""
elif exp == 'six':
result = result + '6'
exp = ""
elif exp == 'seven':
result = result + '7'
exp = ""
elif exp == 'eight':
result = result + '8'
exp = ""
elif exp == 'nine':
result = result + '9'
exp = ""
# splits the new string into a list by whitespace
exp = result.split()
print('Parsed text to numbers : ' + result)
#Actual calculation of the expresion begins
#makes result a variable to hold an int
result = int(exp[0])
#flags used to express what calculation is being preformed
add = False
sub = False
for x in exp[1:]:
#actual math
if add == True:
result = result + int(x)
add = False
elif sub == True:
result = result - int(x)
sub = False
#Flags being triggered
if x == '+':
add = True
elif x == '-':
sub = True
# now to read the result and make it into a word expression
exp = str(result)
print('The result of doing math : ' + exp)
result = ''
for x in exp:
#check for numbers
if x == '-':
result = result + 'NEGATIVE'
elif x == '0':
result = result + 'ZERO'
elif x == '1':
result = result + 'ONE'
elif x == '2':
result = result + 'TWO'
elif x == '3':
result = result + 'THREE'
elif x == '4':
result = result + 'FOUR'
elif x == '5':
result = result + 'FIVE'
elif x == '6':
result = result + 'SIX'
elif x == '7':
result = result + 'SEVEN'
elif x == '8':
result = result + 'EIGHT'
elif x == '9':
result = result + 'NINE'
print('Reworded : ' + result)
| false
|
65e0a32d9c63d627800087b4040041ed3b0f04e9
|
rohinikavitake/py_pretice
|
/RE.py
| 700
| 4.15625
| 4
|
import re
text="This is pune , pune is in maharastra"
print(re.search("pune",text))
print(re.findall("pune",text))
phase="What is your email,it is hello@gmail.com"
split_trem="@"
print(re.split('@',phase))
phrase="The rain in pune"
print(re.sub("\s","g",phrase))
#represtation syntax
# text_phrase='sdsd....ssssddd....sdddd....dsds....dsss....sddd'
# sd*,sd+,
phrase1="This is string! But it has punctuation. how can we remove it?"
x=re.findall('[^ ! . ?]+',phrase1)
print(x)
pharse="This is an example sentance. Lets see if we can find letters"
print(re.findall('[a-z]+',pharse))
print(re.findall('[A-Z]+',pharse))
print(re.findall('[a-z,A-Z]+',pharse))
print(re.findall('[A-Z][a-z]+',pharse))
| false
|
fb20e6839f882a85e11b7275a54458dc1c3046a7
|
kalensr/pygrader
|
/prog_test_dir/Debug2.py
| 1,407
| 4.15625
| 4
|
# Debug Exercise 2
# Create a change-counting game that gets the user to enter the number of
# coins required to make exactly one dollar. The program should prompt
# the user to enter the number of pennies, nickels, dimes, and quarters.
# If the total value of the coins entered is equal to one dollar, the
# program should congratulate the user for winning the game. Otherwise,
# the program should display a message indicating whether the amount
# entered was more than or less than one dollar.
numPennies = int(input('Enter the number of pennies: '))
numNickels = int(input('Enter the number of nickels: '))
numDimes = int(input('Enter the number of dimes: '))
numQuarters = int(input('Enter the number of quarters: '))
# need to convert the above to floats
totalCentValue = numPennies + (numNickels * 5) + (numDimes * 10) + (numQuarters * 25)
# convert count of coins to cents - above
totalDollars = totalCentValue / 100
if totalDollars > 1:
# correct spelling with variable above, lower case 'd', changed to uppercase 'D'
print('Sorry, the amount you entered was more than one dollar.')
elif totalDollars < 1:
# corrected syntax above with else/if statement
print('Sorry, the amount you entered was less than one dollar.')
else:
print('Congratulations!')
print('The amount you entered was exactly one dollar!')
print('You win the game!')
| true
|
d4af8a596aed03f073999cf901a4d130875b8807
|
DWaze/CreateDB
|
/checkdb.py
| 230
| 4.15625
| 4
|
import sqlite3
conn = sqlite3.connect("contacts.sqlite")
name = input("Please enter your name : ")
sql_query = "SELECT * FROM contacts WHERE name LIKE ?"
for row in conn.execute(sql_query, (name,)):
print(row)
conn.close()
| true
|
e9312cbdd177670bc054bb0b3e116f17e812dbbc
|
hcerqueira/python
|
/Q2.py
| 1,666
| 4.1875
| 4
|
'''
Lista de exercícios n° 1
Professor: Marcos Simões
Disciplina: Algoritmos
Resolvida em Python e pseudo-código por: @author Carlos Henrique
Questão 2: Dadas duas posições em um plano cartesiano, descritas por dois números reais X e Y,
Informe se os dois pontos estão na mesma posição ou em posições diferentes.
'''
# Observações:
# Sempre que você ver um 'Leia', 'Escreva' ou qualquer outra ação, entenda como uma ordem ao computador...
# Por exemplo: Computador Leia o valor da variável num1 em inteiro (int(input)) e escreva na tela o resultado (print)
# Abaixo ficará mais claro... eu espero.
# Leia valor de *num1* nos números Reais (Ex: -2.5, +2, 0.0001) -- abrindo o teclado p/ o usuário digitar
x = float(input("Digite a posição de X: "))
# Leia valor de *num1* nos números Reais (Ex: -2.5, +2, 0.0001) -- abrindo o teclado p/ o usuário digitar
y = float(input("Digite a posição de Y: "))
# Se x for maior que y:
if (x > y):
# Escreva (Mensagem abaixo...)
print ("X e Y estão em posições diferentes, X está à frente de Y, pois é valor é maior. ")
# Se x for menor que y:
elif (x < y):
# Escreva (Mensagem abaixo...)
print ("X e Y estão em posições diferentes, Y está à frente de X, pois é valor é menor. ")
# Se não:
else:
# Escreva (Mensagem abaixo...)
print ("X e Y estão na mesma posição!!!")
# Lembrando que nem sempre os comentários estarão bonitinhos assim, mas é somente pra entender de maneira rápida
# Mas a identação do código é importante em Python, minha dica é: Seja organizado e dará tudo certo (ou não)!
| false
|
6b65fe8dcc636c019417b307b810b9fc1cf08ae2
|
yousuf1318/hypervage
|
/DSA_step_6/Bubble Sort.py
| 465
| 4.21875
| 4
|
def bubbleSort(arr):
n=len(arr)
for i in range(n):
for j in range(0, n-i-1):
if ar[j] > ar[j+1]:
ar[j], ar[j+1] = ar[j+1], ar[j]
ar = [5,4,1,2,3,5,7,2]
# inp1=int(input("Enter the len of arr"))
# emp_err=[]
# for i in range(inp1):
# ar=int(input("enter the numbers"))
# emp_err.append(ar)
# print(ar)
bubbleSort(ar)
print ("Sorted array is:")
for i in range(len(ar)):
print (ar[i])
| false
|
9faa391b58a4bf2a25cefc344beb926bd7fea41b
|
tharlysdias/estudos-python
|
/aula_6.py
| 704
| 4.28125
| 4
|
# Loop for
# Intera sobre uma lista
# Pode ser qualquer lista (números ou strings)
# Objeto interavel
for i in [1,2,3]:
print(i)
else:
print("Fim do loop")
# Contando Strings
for i in "Tharlys Dias":
print(i)
else:
print("Fim do loop")
# Função biotina do python que conta de 0 até um determinado número
for i in range(4, 10):
print(i)
else:
print("Fim do loop")
list1 = ["Maça", "Banana", "Melao"]
list2 = ["Tomate", "Cebola", "Cenoura"]
# Interando duas listas ao mesmo tempo utilizando zip
for i, j in zip(list1, list2):
print(i, j)
else:
print("Fim do loop")
# Função enumerate que retorna um índice de contagem
for i, j in enumerate(list1):
print(i, j)
else:
print("Fim do loop")
| false
|
faf53bb2c018785736f7b59550d1e86362c2dac8
|
masciarra/encrypted-icmp-tunnel
|
/substitution_encryption.py
| 1,079
| 4.53125
| 5
|
"""Takes input as following:
examples: python substitution_encryption.py encrypt input.txt output.txt"""
def substitutionEncrypt(str):
"""Encrypts string by substituting each character with the ordinal inverse:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ZYXWVUTSRQPONMLKJIHGFEDCBA
"""
str = str.lower()
new = ""
for c in str:
num = 123 - (ord(c) - 96)
new += chr(num)
return new
def substitutionDecrypt(message = ""):
"""Decrypts string by substituting each character with the ordinal inverse:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ZYXWVUTSRQPONMLKJIHGFEDCBA
"""
message = message.lower()
new = ""
for c in message:
num = 123 - ord(c) + 96
new += chr(num)
return new
import sys
foPath = ""
output = ""
foPath = sys.argv[3]
fi = open(sys.argv[2], "r")
fileContents = fi.read()
if sys.argv[1] == "encrypt":
output = output + substitutionEncrypt(fileContents)
else:
output = output + substitutionDecrypt(fileContents)
#output to file
fo = open(foPath, "w+")
fo.write(output)
fo.close
| false
|
1078a1e6e0c3191e26b2f4255cb7b2a3260a1dba
|
ShettyDhanu/17cs060python
|
/pgm9.py
| 250
| 4.25
| 4
|
#is and in operator
x1=5
y1=5
x2='Hello'
y2='Hello'
x3=[1,2,3]
y3=[1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
a="hello python"
b={1:'c',2:'d'}
print('h'in a)
print('Hello'not in a)
print(1 in b)
print('c'in b)
| false
|
e3a318a9cadbfc7d82b3ca5885c80c1bad4e1b36
|
VanessaTan/LPTHW
|
/EX03/ex3.py
| 1,178
| 4.375
| 4
|
#Subject introduction
print "I will now count my chickens:"
#Calculation of how many Hens. 30.0 divided by 6.0 + 25.0.
print "Hens", 25.0 + 30.0 / 6.0
#Calculation of how many Roosters. (25.0x3.0 = 75.0) Take 75.0 ÷ 4.0 = 18 with remainder 3.0. Therefore: 100.0 - 3.0 = 97
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
#New subject introduction
print "Now I will count eggs:"
#Calculation of eggs. 3.0 + 2.0 + 1.0 - 5.0 + (4.0÷2.0= 0 remainders) - (0.25) + 6.0
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
#Questioning statement
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?"
#True/False answer to statement
print 3.0 + 2.0 < 5.0 - 7.0
#Questioning statement and answer to question in orange calculation
print "What is 3.0 + 2.0?", 3.0 + 2.0
#Questioning statement and answer to question in orange calculation
print "What is 5.0 - 7.0?", 5.0 - 7.0
#Comment
print "Oh, that's why it's False."
#Comment
print "How about some more."
#Question and answer in True/False
print "Is it greater?", 5.0 > -2.0
#Question and answer in True/False
print "Is it greater or equal?", 5.0 >= -2.0
#Question and answer in True/False
print "Is it less or equal?", 5.0 <= -2.0
| true
|
4e72c4f48e96103d758a6c766d0b2aa76aed1822
|
anandkrthakur/AlgorithmsEveryProgrammerShouldKnow
|
/01a. BinarySearch_Iterative.py
| 1,206
| 4.15625
| 4
|
# Find out if a key x exists in the sorted list A
# or not using binary search algorithm
def binarySearch(A, x):
# search space is A[left..right]
(left, right) = (0, len(A) - 1)
# till search space consists of at-least one element
while left <= right:
# we find the mid value in the search space and
# compares it with key value
mid = (left + right) // 2
# overflow can happen. Use:
# mid = left + (right - left) / 2
# mid = right - (right - left) // 2
# key value is found
if x == A[mid]:
return mid
# discard all elements in the right search space
# including the mid element
elif x < A[mid]:
right = mid - 1
# discard all elements in the left search space
# including the mid element
else:
left = mid + 1
# x doesn't exist in the list
return -1
if __name__ == '__main__':
A = [2, 5, 6, 8, 9, 10]
key = 5
index = binarySearch(A, key)
if index != -1:
print("Element found at index", index)
else:
print("Element found not in the list")
| true
|
0dccf3b276606b24679a1fc520dc963f8f32600d
|
TsunamiMonsoon/InternetProgramming
|
/Homework3/Homework3.py
| 1,124
| 4.1875
| 4
|
import sqlite3
from os.path import join, split
conn = sqlite3.connect("Courses.sq")
# create a query
cmd = "select * from Courses"
# create a cursor
crs = conn.cursor()
# send a query and receive query result
crs.execute(cmd)
Courses = crs.fetchall()
for row in Courses:
print(row)
cmd2 = """
select Courses.department,
Courses.course_num,
Courses.course_name,
PreReqs.prereq1,
PreReqs.prereq2
from Courses, PreReqs
where PreReqs.course_id = Courses.course_id
"""
crs.execute(cmd2)
Courses2 = crs.fetchall()
#prereqIds = set()
for row in Courses2:
print(row[0] + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4]))
year = input("Enter the year: ")
sem = input("Enter the semester: ")
if year is Courses.years:
print(Courses)
if sem is Courses.semester:
print(Courses)
grade = input("Enter a letter grade: ")
if grade is Courses.grade:
print(Courses)
courseIid = input("Enter the course id: ")
if id is Courses.courseId:
print(Courses)
| true
|
59924003253bf6eaf850df9876ceef651c38f84f
|
KuldeepJagrotiya/python
|
/function/isPalindrome.py
| 254
| 4.21875
| 4
|
## Q3 take the input from user and check if number is palindrome
inp = (input("enter the number : "))
out = str()
for i in range(len(inp)-1,-1,-1):
out+=inp[i]
if out==inp:
print(inp,"is a palindrome")
else:
print(inp,"is not a palindrome")
| true
|
46734740a355dcfab21ca9ed817eda423b106c51
|
mohitKhanna1411/COMP9020_19T3_UNSW
|
/Assignment_3/count_full_nodes.py
| 1,250
| 4.34375
| 4
|
# Python program to count full
# nodes in a Binary Tree
class newNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the count of
# full Nodes in a binary tree
def getfullCount(root):
if (root == None):
return -1
if (root.left == None and root.right == None):
return 0
else:
return 1 + (getfullCount(root.left) + getfullCount(root.right))
# def BST_size(root):
# if root is None:
# return -1
# if root is not None:
# count = 1
# if root.left is not None:
# return count += BST_size(root.left)
# if root.right is not None:
# return count += BST_size(root.right)
# Driver code
if __name__ == '__main__':
""" 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
"""
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
root.right.right.right = newNode(14)
print(getfullCount(root))
# This code is contributed by SHUBHAMSINGH10
| true
|
cf326c3bd46d29e86cfa3574178dc2857a1d1a84
|
natanonsilver/General-Knowledge-City-Quiz-
|
/version 3.py
| 2,036
| 4.125
| 4
|
# In version 3 of my quiz i will doing my 10 question quiz that is a multichoice quiz.
#asking user for name
try:
name=str(input("enter your name:"))
if name == "1234":
raise Exception
except:
input("Please try again, enter your name \n")
#ask the user to enter there age.
try:
age=int(input("Please enter your age?:"))
except:
print("not valid")
else:
print("Please continue")
#asking the user if they are ready to take the quiz
ready=input("are you ready for the quiz?: press y to continue or x to exit:")
if ready=="y" or "yes" :
print("lets continue")
elif ready== "x" or "no":
print("Thank you come again")
#Preparing the dictionary
Captialcitesquiz=(
'1. What is the captial for Nigeria': 'Abuja',
'2. What is the captial for Spain': 'Madrid',
'3. What is the captial for Canada': 'Ottawa',
'4. What is the captial for New Zealand': 'Wellington',
'5. What is the captial for Italy': 'Rome',
'6. What is the captial for Peru': 'Lima',
'7. What is the captial for San Marino': 'San Marino',
'8. What is the captial for Mexico': 'Mexico City',
'9. What is the captial for United States Of America': 'Washington DC',
'10. What is the captial for Syria': 'Damascus',
}
#preparing the multi choice
optlist=['Abuja:11:12:13',
'11:12:18:20',
'Jumping:Swimming:Cycling:Running',
'Speaking:Kicking:Dribbling:Jogging',
'No running with the ball: No speaking with the ball:No passing of the ball:',
'Ants:Coakroaches:Unicorns:Butterfly:',
'3 seconds:50 seconds:10 seconds:100 seconds',
'30 mins:1 hour:1 min:2 mins',
'2 times: 1 time: 3 times: 4 times',
'Running:Passing:Throwing:Breathing techniques',]
| true
|
7878baa20ea886491c4b11fb42d3f1064c6a11ed
|
krisbuote/cryptography
|
/substitution_cipher.py
| 1,945
| 4.1875
| 4
|
import string
''' --- CAESARIAN CIPHERZ --- '''
''' Plaintext is shifted an int. See "substitution cipher" on wikipedia. '''
''' Author: Kristopher Buote '''
def buildCoders(shift):
assert shift >=0 and shift <=26
encoder = dict()
decoder = dict()
alpha_lower = string.ascii_lowercase
alpha_upper = string.ascii_uppercase
alpha_length = len(alpha_lower)
# Use a dictionary to map the input char to the shifted char
# e.g. coder['a'] = 'd' if shift == 3
# The coder dictionary handles lower case and upper case letters
for i in range(-shift, alpha_length-shift):
char_lower = alpha_lower[i]
char_lower_shifted = alpha_lower[i+shift]
char_upper = alpha_upper[i]
char_upper_shifted = alpha_upper[i+shift]
# Build the encoder
encoder[char_lower] = char_lower_shifted
encoder[char_upper] = char_upper_shifted
# Build the decoder
decoder[char_lower_shifted] = char_lower
decoder[char_upper_shifted] = char_upper
return encoder, decoder
def applyCoder(text, coder):
# alphabetic characters are ciphered, punctation remains constant
transformed_text = []
for char in text:
if char in coder:
newChar = coder[char]
transformed_text.append(newChar)
else:
transformed_text.append(char)
# Return the joined list of characters to return a single string of cipher text.
return ''.join(transformed_text)
# Here's an example
myEncoder, myDecoder = buildCoders(shift=17)
sample_text = 'Hello, World!'
ciphertext = applyCoder(text=sample_text, coder=myEncoder)
plaintext = applyCoder(text=ciphertext, coder=myDecoder)
print('Ciphertext: {0} \nPlaintext: {1}\n'.format(ciphertext, plaintext))
# Input your own plain text and receive the ciphertext!
inpText = input('Input your plaintext: ')
print('Your ciphertext: ', applyCoder(inpText,myEncoder))
| false
|
30222559108f77a110df35f437588ddedb1afc21
|
rdoherty2019/Computer_Programming
|
/analyze.py
| 944
| 4.15625
| 4
|
def is_odd(x):
#Module will leave a remainder if it is not divisable
num = x % 2
if num != 0:
return True
else:
return False
def is_prime(x):
for i in range(1, x+1):
if i == x or i == 1:
continue
num = x % i
if num == 0:
return False
return True
def is_abundant(x):
acc = 0
for i in range(1, x+1):
if i == x:
continue
num = x % i
if num == 0:
acc+= i
if acc > x:
return True
else:
return False
user = int(input("Please enter a number: \n>"))
if is_odd(user) == True:
print(str(user) + " is odd")
else:
print(str(user) + " is not odd")
if is_prime(user) == True:
print(str(user) + " is prime")
else:
print(str(user) + " is not prime")
if is_abundant(user) == True:
print(str(user) + ' is abundant')
else:
print(str(user) + ' is not abundant')
| false
|
d2af3f9c481bf5d868e446c186eb9c48efd75157
|
rdoherty2019/Computer_Programming
|
/forwards_backwards.py
| 1,024
| 4.1875
| 4
|
#setting accumulator
num = 0
print("Using while loops")
#Iterations
while num <31:
#If number is divisably by 4 and 3
if num % 4 == 0 and num % 3 == 0:
#accumalte
num += 3
#continue to next iterations
continue
#IF number is divisable by 3 print
if num % 3 == 0 :
print(num)
#accumulate
num += 3
#Setting condition
nu = 30
while nu > 1:
# If number is divisably by 4 and 3
if nu % 4 == 0 and nu % 3 == 0:
#reduce
nu -= 3
#conitune to next itteration
continue
# IF number is divisable by 3 print
if nu % 3 == 0:
print(nu)
#reduce
nu -= 3
print("Using for loops")
#setting range, making sure 30 is included
for n in range(3,31,3):
if n % 4 == 0 and n % 3 == 0:
continue
if n % 3 == 0:
print(n)
#setting range
#making sure 3 is included
#counting backwards
for n in range(30,2,-3):
if n % 4 == 0 and n % 3 == 0:
continue
if n % 3 == 0 :
print(n)
| true
|
780e01cf0530b9f534adb390d52365ea99ca36aa
|
jc23729/day-1-3-exercise-1
|
/main.py
| 220
| 4.3125
| 4
|
#Write your code below this line 👇
#This code prints the number of characters in a user's name.
print( len( input("What is your name? ") ) )
#Notes
#If input was "Jack"
#1st: print(len("Jack"))
#2nd: print(4)
| true
|
adfcda8ef7d793d0f240e811b2676dabd0217023
|
jeanjosephgeorge/python_exercises
|
/Week 1/functionExercises.py
| 1,973
| 4.21875
| 4
|
#1. HELLO FUNCTION
# def name(x):
# print("Hello,",x,"!")
# name(input("What\'s your name?\n"))
#2. Y = X+1 Write a function f(x) that returns x + 1 and plot it for x values of -3 to 3 in increments of 1.
import matplotlib.pyplot as plot
# import matplotlib.pyplot as plot
# def f(x):
# y = x+1
# return y
# xs = list(range(-3,4))
# ys = []
# for x in xs:
# ys.append(f(x))
# plot.plot(xs,ys)
# plot.show()
#3. Square of X:
# import matplotlib.pyplot as plot
# def f(x):
# y = x*x
# return y
# xs = list(range(-100,101))
# ys = []
# for x in xs:
# ys.append(f(x))
# plot.plot(xs,ys)
# plot.show()
#4. ODD or EVEN as BAR GRAPH!
# import matplotlib.pyplot as plot
# def f(x):
# if (x%2==0):
# return (-1)
# else:
# return (1)
# xs = list(range(-5,6))
# ys = []
# for x in xs:
# ys.append(f(x))
# plot.bar (xs,ys)
# plot.show ()
#5. SINE FUNCTION
# import matplotlib.pyplot as plot
# import math
# def f(x):
# y = math.sin(x)
# return y
# xs = list(range(-5,6))
# ys = []
# for x in xs:
# ys.append(f(x))
# plot.plot (xs,ys)
# plot.show ()
#6. SINE II FUNCTION
# import matplotlib.pyplot as plot
# import math
# from numpy import arange
# def f(x):
# y= math.sin(x)
# return y
# xs = arange(-5,6,0.1)
# ys = []
# for x in xs:
# ys.append(f(x))
# plot.plot (xs,ys)
# plot.show()
#7. DEGREE CONVERSION
# import matplotlib.pyplot as plot
# def Cel(x):
# y=(x*1.8)+32
# return y
# xs=list(range(0,50))
# ys=[]
# for x in xs:
# ys.append(Cel(x))
# plot.plot (xs,ys)
# plot.show ()
#8 and 9. PLAY AGAIN
# def play():
# y = input("Do you want to play again?\n")
# if (y=="Y" or y=="y"):
# #return True
# print ("True")
# play()
# elif (y=="N" or y=="n"):
# #return False
# print("False")
# else:
# print("Invalid input")
# play()
# play()
| false
|
841bfb0cf506bdd439d2aa0f5b54814dfda31ebf
|
ani17/data-structures-algorithms
|
/merge-sort.py
| 906
| 4.15625
| 4
|
import math
def mergeSort(A):
# If no more divison possible through mergeSort return to "merge" logic
# for merging subarrays back into same array by repacing values
# accordingly
if len(A) < 2:
return
# Keep Dividing Array in to Left & Right Sub Arrays
mid = int(math.floor(len(A) / 2))
L = A[0 : mid]
R = A[mid : ]
mergeSort(L)
mergeSort(R)
merge(L,R,A)
return A
def merge(L,R,A):
# iterators for L, R and A
i = 0
l = 0
r = 0
# If iterators of both L & R have not reached the end
# compare values in both arrays and put the smaller value
# back into the existing array
while l < len(L) and r < len(R):
if L[l] <= R[r]:
A[i] = L[l]
l += 1
else:
A[i] = R[r]
r += 1
i +=1
# leftovers in L
while l < len(L):
A[i] = L[l]
l += 1
i += 1
# leftovers in R
while r < len(R):
A[i] = R[r]
r += 1
i += 1
A = [5,4,3,2,1]
S = mergeSort(A)
print(S)
| true
|
891262eabe5174b820a8b43673c21e222e8bad85
|
LeonVillanueva/Projects
|
/Daily Exercises/daily_17.py
| 473
| 4.15625
| 4
|
'''
The ancient Egyptians used to express fractions as a sum of several terms where each numerator is one.
For example, 4 / 13 can be represented as 1 / 4 + 1 / 18 + 1 / 468.
Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian fraction.
'''
import numpy as np
def e_frac (n, d):
d_list = []
while n != 0:
x = np.ceil(d/n)
d_list.append (x)
n = x*n - d
d *= x
return d_list
| true
|
efbb95ed9051e1b6127a64f7eb8c967691d26f41
|
Mrfranken/advancepython
|
/chapter02/company.py
| 756
| 4.1875
| 4
|
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
# 魔法函数既不属于object类,也不是Company类特有的方法,作为一个独立的存在的特殊方法可以加强类的功能
# 直接影响类的使用语法,如果不添加__getitem__方法,对这个类的实力的遍历和切片都将不可用
def __getitem__(self, index):
return self.employee[index]
def __len__(self):
"""
添加这个魔法函数可以使用len方法
"""
return len(self.employee)
company = Company(["tom", "bob", "jane"])
company1 = company[:2] # 对实例进行切片
for em in company1: # 对实例进行遍历
print(em)
print(len(company))
| false
|
bfc8e8f9574f6cdbe394ebeabee29b2b3a12f80e
|
aliabbas-s/tathastu_week_of_code
|
/day3/3.py
| 246
| 4.1875
| 4
|
#Day-3
#Program 3
string = input("Enter a Word")
length = len(string)
duplicate_string = ""
for i in range(0,length):
if string[i] in duplicate_string:
continue
else:
duplicate_string += string[i]
print(duplicate_string)
| true
|
d0b6cc898aca8d016713caf44b36612a9f662fa1
|
SteeveJose/luminarpython
|
/languagefundamentals/largestamong2.py
| 243
| 4.125
| 4
|
num1=float(input("enter the first number:"))
num2=float(input("enter the second number:"))
if (num1>num2):
print(num1,"is greater than",num2)
elif (num2>num1):
print(num2,"greater than",num1)
else:
print("the two numbers are equal")
| true
|
0aee0120683e267da353a0af63e518cefebdd7da
|
TheodoreAI/puzzle
|
/algorithm.py
| 2,753
| 4.125
| 4
|
# Mateo Estrada
# CS325
# 03/01/2020
# Description: This algorithm checks to see if the input solution to the 8-puzzle (also known as the sliding puzzle) is solvable.
# Step 1: I choose my favorite puzzle: the 8-puzzle (puzzle number 12 from the list).
# Step 2: The following rules were taken from: file:///Users/mateog.estrada/Downloads/A_Survey_of_NP-Complete_puzzles.pdf
# I. Played on an mxm
# II. m^2 - 1 = n
# III. There is a blank tile that has a possible number of 2, 3, 4 adjacent tiles depending on the location of the blank tile.
# IV. Standard size is a 3x3 and a move of the blank tile will mean the adjacent tile will move to the blank.
# V. 181,440 possible variations that are solvable.
# Step 4: I will use the idea of counting the number of inversions between nodes. Given a board of size N where the size N is an odd integer,
# each legal move changes the number of inversions by an even number.
# If a board has an odd number of inversions, then it cannot lead to the goal board by a sequence of legal moves because the goal board has an even number of inversions.
# I will show my proof by example:
def getInversions(arr):
"""This function was taken from: https://www.geeksforgeeks.org/check-instance-8-puzzle-solvable/#:~:text=What%20is%208%20puzzle%3F,tiles%20into%20the%20empty%20space."""
# we initially the count at 0
countOfInversions = 0
for i in range(0, len(arr)):
for j in range(i + 1, len(arr)):
# value 0 will be used to indicate the "blank"
if arr[i] > arr[j] != 0:
countOfInversions += 1
return countOfInversions
class Solution:
def __init__(self, puzzle):
self.puzzle = puzzle
def hasSolution(self):
# count inversions in 8 puzzle
invertCount = getInversions(self.puzzle)
return invertCount % 2 == 0
def checkSolution(self):
if self.hasSolution():
print("Solvable!")
else:
print("Can't solve that! (Remember, for an 8-puzzle there must be an even number of inversions for the puzzle to have a solution! Please see pdf for more details!")
# The testing:
# this one you should be able to solve because it has an even number of inversions aka 1,3,4,2,5,7,8,6 inversions (3-2, 4-5, 7-6, 8-6) and four inversions is even!
# p1 = [0, 1, 3, 4, 2, 5, 7, 8, 6]
# s1 = Solution(p1)
# s1.checkSolution()
#
# # this one you shouldn't because it has an odd number of inversions aka 8 - 7 is one inversion and one is odd!
# p2 = [1, 2, 3, 4, 5, 6, 8, 7, 0]
# s2 = Solution(p2)
# s2.checkSolution()
# Step 5: The proof is explained using some of the logic from this resource: https://www.cs.princeton.edu/courses/archive/spring13/cos226/assignments/8puzzle.html
| true
|
fd3a67b45acba3593efdd159ba41e1aa57b3c256
|
SushanShakya/pypractice
|
/Functions/14.py
| 298
| 4.21875
| 4
|
# Write a Python program to sort a list of dictionaries using Lambda
nameSort = lambda x: x['name']
sample = [
{
"name" : "Sushan"
},
{
"name" : "Aladin"
},
{
"name" : "Sebastian"
},
]
sorted_list = sorted(sample,key=nameSort)
print(sorted_list)
| true
|
34dd81b6d4c5480951d6be4595848f0f4da63cdc
|
morisasy/data-analysis-with-python
|
/week1/multiplication.py
| 580
| 4.21875
| 4
|
#!/usr/bin/env python3
"""
Make a program that gives the following output.
You should use a for loop in your solution.
4 multiplied by 0 is 0
4 multiplied by 1 is 4
4 multiplied by 2 is 8
4 multiplied by 3 is 12
4 multiplied by 4 is 16
4 multiplied by 5 is 20
4 multiplied by 6 is 24
4 multiplied by 7 is 28
4 multiplied by 8 is 32
4 multiplied by 9 is 36
4 multiplied by 10 is 40
"""
def main():
# Enter your solution here
x = int(input("Input a number: "))
for i in range(11):
print(f"{x} multiplied by {i} is {x*i}")
if __name__ == "__main__":
main()
| true
|
cb6eb22fff86e8a80974c2a21bbe88c2e53af786
|
PetersonZou/astr-119-session-4
|
/operators.py
| 724
| 4.1875
| 4
|
x=9
y=3 #integers
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponentiation
x=9.1918123
print(x//y) #floor division
#Assignment operators
x=9 #sets x to equal 9
x+=3 #x=x+3
print(x)
x=9
x-=3 #x=x-3
print(x)
x*=3 #x=x*3
print(x)
x/=3 #x=x/3
print(x)
x**=3 #x=x**3
print(x)
#Comparison operators
x=9
y=3
print(x==y) #True if x equals to y, False otherwise
print(x!=y) #True if x does not eq y, False otherwise
print(x>y) #True if x is greater than y, False otherwise
print(x<y) #True if x is less than y, False otherwise
print(x>=y) #True if x is greater or eq y, False otherwiseß
print(x<=y)
| true
|
09164664fb940298ad2dfa5fefa78c52121ab04d
|
carlavieira/code-study
|
/algorithms/sorting_searching/sparse_search.py
| 1,250
| 4.125
| 4
|
def sparse_search(arr, string):
if not arr or not string: return -1
return recursive_binary_search(arr, string, 0, len(arr)-1)
def recursive_binary_search(arr, string, first, last):
if first > last: return -1
mid = (first + last) // 2
#that is not midd, find the closest nonempty value
if not arr[mid]:
# set pointers do mid side
left = mid - 1
right = mid + 1
while True:
# if gets to the point that the pointers exceed the perimeters, that is not a valid value
if left < first and right > last:
return -1
elif arr[right] and right <= last:
mid = right
break
elif arr[left] and left >= first:
mid = left
break
left -= 1
right += 1
if arr[mid] == string: return mid
elif arr[mid] > string: return recursive_binary_search(arr, string, first, mid-1)
elif arr[mid] < string: return recursive_binary_search(arr, string, mid + 1, last)
arr=['at', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', '']
print(sparse_search(arr, "ball"))
print(sparse_search(arr, "at"))
print(sparse_search(arr, "dad"))
| true
|
edd7c8fb9a385d76702d906104eb9ccde836fa1e
|
vishnu2981997/Programming_Ques
|
/PROG QUES/1.py
| 2,902
| 4.1875
| 4
|
"""
ID: 437
Given an array of n numbers. sort the array in ascending order based on given conditions:
---convert the elements of array to filesize formats
---convert the file sizes to corresponding binary representations
---sort the actual array based on number of 1's present in the binary representation of their
file sizes.
Note: File sizes should be in integer format
Consider file size till YB (B, KB, MB, GB, TB, PB, EB, ZB, YB)
Input:
---The first line of the input contains a single integer T denoting the number of test cases.
The description of T test cases follows.
---First line of each test case consists of a single integer n denoting the size of the
array.
---The second line of each test case contains n space separated integers.
Output:
---For each test case, print a single line containing the sorted array.
Sample Input:
3
10
1 2 3 4 5 6 7 8 9 10
10
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
3
2048 1024 3072
Sample Output:
1 2 4 8 3 5 6 9 10 7
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
1024 2048 3072
Explanation:
Example case 1: In the array 1 2 3 4 5 6 7 8 9 10
file sizes are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1's count in their binary representation are 1, 1, 2, 1, 2, 2, 3, 1, 2, 2
So sorted array is 1 2 4 8 3 5 6 9 10 7
"""
import math as m
from sys import stdin, stdout
def convert_to_file_size(arr):
"""
:param arr: Array input given by the user
:return: An integer array consisting of file sizes corresponding to arr
"""
arr1 = []
for num in arr:
if num == 0:
arr.append(0)
else:
i = int(m.floor(m.log(num, 1024)))
power = m.pow(1024, i)
size = int(num / power)
arr1.append(size)
return arr1
def count_of_binary_1s(arr):
"""
:param arr: Array returned by convert_to_file_size()
:return: An integer array consisting of count of no.of 1's in array's binary representation
"""
arr1 = []
for num in arr:
if num == 0:
arr1.append(0)
else:
binary = bin(int(num))
arr1.append(binary[2:len(binary)].count("1"))
return arr1
def main():
"""
:return: None
"""
for _ in range(int(stdin.readline())):
#size_name = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
arr_size = int(stdin.readline().strip())
array = [int(i) for i in stdin.readline().strip().split()]
arr = convert_to_file_size(array)
arr1 = count_of_binary_1s(arr)
sorted_arr = [x for i, x in sorted(zip(arr1, array))]
for i in range(arr_size):
stdout.write(str(sorted_arr[i])+" ")
stdout.write("\n")
if __name__ == "__main__":
main()
| true
|
74e106cda0e7a685124ea86603fe61faf9c2fa7f
|
Rich43/rog
|
/albums/3/challenge145_easy/code.py
| 1,818
| 4.34375
| 4
|
'''
Your goal is to draw a tree given the base-width of the tree (the number of characters
on the bottom-most row of the triangle section). This "tree" must be drawn through
ASCII art-style graphics on standard console output. It will consist of a 1x3 trunk on
the bottom, and a triangle shape on the top. The tree must be centered, with the leaves
growing from a base of N-characters, up to a top-layer of 1 character. Each layer
reduces by 2 character, so the bottom might be 7, while shrinks to 5, 3, and 1 on top
layers. See example output.
Originally submitted by u/Onkel_Wackelflugel
Formal Inputs & Outputs
Input Description
You will be given one line of text on standard-console input: an integer and two
characters, all space-delimited. The integer, N, will range inclusively from
3 to 21 and always be odd. The next character will be your trunk character. The next
character will be your leaves character. Draw the trunk and leaves components with
these characters, respectively.
Output Description
Given the three input arguments, draw a centered-tree. It should follow this pattern:
(this is the smallest tree possible, with a base of 3)
*
***
###
Here's a much larger tree, of base 7:
*
***
*****
*******
###
Sample Inputs & Outputs
Sample Input 1
3 # *
Sample Output 1
*
***
###
Sample Input 2
13 = +
Sample Output 2
+
+++
+++++
+++++++
+++++++++
+++++++++++
+++++++++++++
===
'''
def tree(a, b, c, d):
x = 1
while x <= c:
print((a * x).center(c, ' '))
x += 2
print((b * d).center(c, ' '))
if __name__ == '__main__':
N = 3
leaf = '*'
trunk = '#'
trunk_width = 3
ans = tree(leaf, trunk, N, trunk_width)
N = 13
leaf = '+'
trunk = '='
ans = tree(leaf, trunk, N, trunk_width)
| true
|
c8305d2dcb7962c7f460d4e44851d4a24c495e6e
|
Rich43/rog
|
/albums/3/challenge160_easy/code.py
| 2,037
| 4.25
| 4
|
'''
(Easy): Trigonometric Triangle Trouble, pt. 1
A triangle on a flat plane is described by its angles and side lengths,
and you don't need to be given all of the angles and side lengths to work
out the rest. In this challenge, you'll be working with right-angled triangles only.
Here's a representation of how this challenge will describe a triangle.
Each side-length is a lower-case letter, and the angle opposite each side
is an upper-case letter. For the purposes of this challenge, the angle C
will always be the right-angle. Your challenge is, using basic trigonometry
and given an appropriate number of values for the angles or side lengths, to
find the rest of the values.
Formal Inputs and Outputs
Input Description
On the console, you will be given a number N. You will then be given N lines,
expressing some details of a triangle in the format below, where all angles are
in degrees; the input data will always give enough information and will describe
a valid triangle. Note that, depending on your language of choice, a conversion
from degrees to radians may be needed to use trigonometric functions such as
sin, cos and tan.
Output Description
You must print out all of the details of the triangle in the same format as above.
Sample Inputs & Outputs
Sample Input
3
a=3
b=4
C=90
Sample Output
a=3
b=4
c=5
A=36.87
B=53.13
C=90
Tips & Notes
There are 4 useful trigonometric identities you may find very useful.
Pythagoreas' Theorem, where h is the side length opposite the
right-angle and r and s are any 2 other sides.
3 Trigonometric Ratios
'''
import math
def sine(b, c):
''' Compute the sine of the
right-angled triangle'''
return (round(math.degrees(math.acos(b/c)), 2))
def cosine():
''' Cosine can be found to be
180 - (sine + 90)'''
return round(180 - (sine(b, c) + 90), 2)
if __name__ == '__main__':
a = 3
b = 4
c = 5
A = sine(b, c)
B = cosine()
C = 90
print('a={0}\nb={1}\nc={2}\nA={3}\nB={4}\nC={5}'.format(a, b, c, A, B, C))
| true
|
f2a5494dea131dd5bacd09931c98aa04a4fb6e43
|
Rich43/rog
|
/albums/3/challenge87_easy/code.py
| 1,235
| 4.15625
| 4
|
'''
Write a function that calculates the intersection of two rectangles,
returning either a new rectangle or some kind of null value.
You're free to represent these rectangles in any way you want:
tuples of numbers, class objects, new datatypes, anything goes. For
this challenge, you'll probably want to represent your rectangles
as the x and y values of the top-left and bottom-right points.
(Rect(3, 3, 10, 10) would be a rectangle from (3, 3) (top-left) to
(10, 10) (bottom-right).)
As an example, rectIntersection(Rect(3, 3, 10 10), Rect(6, 6, 12, 12))
would return Rect(6, 6, 10, 10), while rectIntersection
(Rect(4, 4, 5, 5), Rect(6, 6, 10 10)) would return null.
'''
'''
Based on:
A.X1 < B.X2: true
A.X2 > B.X1: false
A.Y1 < B.Y2: true
A.Y2 > B.Y1: true
Intersect: false'''
def intersect(rect1, rect2):
if (rect1[0] < rect2[2]) and rect1[2] > rect2[0] and \
rect1[1] < rect2[3] and rect1[3] > rect2[1]:
rectangle = (rect2[0], rect2[1], rect1[2], rect1[3])
return 'rectangle ' + str(rectangle)
else:
return 'no intersect!'
if __name__ == '__main__':
rect_one = (3, 3, 10, 10)
rect_two = (6, 6, 12, 12)
ans = intersect(rect_one, rect_two)
print(ans)
| true
|
401ec919e87f936bd9e31a9d4e413da50bddb44e
|
Rich43/rog
|
/albums/3/challenge23_easy/code.py
| 524
| 4.125
| 4
|
''' Input: a list
Output: Return the two halves as different lists.
If the input list has an odd number, the middle item can go to any of the list.
Your task is to write the function that splits a list in two halves.
'''
lst = [1, 2, 3, 4, 5]
half_lst = len(lst) // 2
first_lst = []
second_lst = []
for x in range(0, half_lst):
candidate = lst[x]
first_lst.append(candidate)
for y in range(0, len(lst)):
if lst[y] not in first_lst:
second_lst.append(lst[y])
print(first_lst)
print(second_lst)
| true
|
d758ed97ea2aea49f6e70a9253952f6ba271e398
|
Rich43/rog
|
/albums/3/challenge168_easy/code.py
| 2,067
| 4.46875
| 4
|
'''
So my originally planned [Hard] has issues. So it is not ready for posting.
I don't have another [Hard] so we are gonna do a nice [Easy] one for Friday
for all of us to enjoy.
Description:
We know arrays. We index into them to get a value. What if we could apply
this to a string? But the index finds a "word". Imagine being able to parse
the words in a string by giving an index. This can be useful for many reasons.
Example:
Say you have the String "The lazy cat slept in the sunlight."
If you asked for the Word at index 3 you would get "cat" back. If you asked
for the Word at index 0 you get back an empty string "". Why an empty
string at 0? Because we will not use a 0 index but our index begins at 1. If
you ask for word at index 8 you will get back an empty string as the string
only has 7 words. Any negative index makes no sense and return an empty string "".
Rules to parse:
Words is defined as [a-zA-Z0-9]+ so at least one of these and many more
in a row defines a word.
Any other character is just a buffer between words."
Index can be any integer (this oddly enough includes negative value).
If the index into the string does not make sense because the word does not
exist then return an empty string.
Challenge Input:
Your string: "...You...!!!@!3124131212 Hello have this is a --- string Solved !
!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
Find the words at these indexes and display them with a " " between them:
12 -1 1 -100 4 1000 9 -1000 16 13 17 15
'''
import re
the_string = "...You...!!!@!3124131212 Hello have this is a --- string Solved ! \
!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
the_string = re.findall('\w+', the_string)
indexes = ' 12 -1 1 -100 4 1000 9 -1000 16 13 17 15'
indexes = indexes.split()
output = ''
for num in indexes:
num = int(num) - 1
if num <= -1:
continue
try:
output += the_string[num] + ' '
except IndexError:
continue
print(the_string)
print(output)
| true
|
12f29461a004ea1e8264153d5cfb473973ee153f
|
Rich43/rog
|
/albums/4/problem18.py/code.py
| 418
| 4.15625
| 4
|
def panagram(strng):
'''(str) -> bool
return whether the string is a panagram
'''
sett = set()
strng = strng.lower()
for letter in strng:
if letter.isalpha():
sett.add(letter)
return len(sett) == 26
strng = 'The quick brown fox jumps over the lazy dog'
ans = panagram(strng)
print(ans)
| true
|
16652e2897466142fd0b285578018c150e0a5a5e
|
Rich43/rog
|
/albums/3/challenge126_easy/code.py
| 2,287
| 4.15625
| 4
|
'''
Imagine you are an engineer working on some legacy code that has some odd constraints:
you're being asked to implement a new function, which basically merges and sorts one
list of integers into another list of integers, where you cannot allocate any other
structures apart from simple temporary variables (such as an index or counter variable).
You will be given two lists, list A and B, where the elements are positive integers
from 1 to 2147483647; the integer '0' is reserved as "buffer space". List A will not
be pre-sorted, though list B will be pre-sorted and will start with a series of '0'
values. These '0' values are simply reserved space in list B which is the same number
of elements that list A has. You cannot modify list A in any way, though list B is
fair game. Your goal is to return a merged and sorted list of elements of list A into
list B, where you cannot allocate any extra space other than simple / trivial local
variables for your function.
Author: nint22
Formal Inputs & Outputs
Input Description
You will be given two lists, list A and B, of integers from 1 to 2147483647. List A
will be unsorted, while list B will be sorted. List B has extra elements in the start
of the list that are all '0' value: this is buffered space for you to work with when
merging and sorting list A into B. These two lists will be space-delimited and on
separate lines.
Output Description
Simply print the contents of list B, after it has had the contents of A merged &
sorted within it.
Sample Inputs & Outputs
Sample Input
692 1 32
0 0 0 14 15 123 2431
Sample Output
1 14 15 32 123 692 2431
Note
Please note that the real challenge here is respecting the premise of the challenge:
you must implement your sort / merge function inline into list B! If you do not
understand the premise, please do ask questions and we will gladly answer. Good luck,
and have fun!
'''
l1 = [692, 1, 32] # unsorted
l2 = [0, 0, 0, 14, 15, 123, 2431] # sorted
def merge(l1, l2):
i = 0
while len(l1) > 0:
i = 0
temp = l1.pop(0)
trim = l2.pop(0)
for item in l2:
while item < temp:
i += 1
break
l2.insert(i, temp)
return l2
if __name__ == '__main__':
ans = merge(l1, l2)
print(ans)
| true
|
5bcf6fd1c5bb4eb598aca0a9c70d0ee65d883a7a
|
Rich43/rog
|
/albums/3/challenge171_easy/code.py
| 1,983
| 4.125
| 4
|
'''
Description:
Today we will be making some simple 8x8 bitmap pictures. You will be given 8 hex values
that can be 0-255 in decimal value (so 1 byte). Each value represents a row. So 8 rows
of 8 bits so a 8x8 bitmap picture.
Input:
8 Hex values.
example:
18 3C 7E 7E 18 18 18 18
Output:
A 8x8 picture that represents the values you read in.
For example say you got the hex value FF. This is 1111 1111 . "1" means the bitmap at that
location is on and print something. "0" means nothing is printed so put a space. 1111 1111
would output this row:
xxxxxxxx
if the next hex value is 81 it would be 1000 0001 in binary and so the 2nd row would output
(with the first row)
xxxxxxxx
x x
Example output based on example input:
xx
xxxx
xxxxxx
xxxxxx
xx
xx
xx
xx
Challenge input:
Here are 4 pictures to process and display:
FF 81 BD A5 A5 BD 81 FF
AA 55 AA 55 AA 55 AA 55
3E 7F FC F8 F8 FC 7F 3E
93 93 93 F3 F3 93 93 93
Output Character:
I used "x" but feel free to use any ASCII value you want. Heck if you want to display
it using graphics, feel free to be creative here.
'''
import re
def hex_to_str(base16):
scale = 16
num_of_bits = 8
my_hexdata = base16
strng = ''
bin_out = bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)
for digit in bin_out:
if digit == '1':
strng += '='
else:
strng += ' '
return strng
if __name__ == '__main__':
base16 = '18 3C 7E 7E 18 18 18 18'
base16 = re.findall('\d[A-Z]|[A-Z]\d|\d+|[A-Z]+', base16)
for num in base16:
ans = hex_to_str(num)
print(ans)
print()
hex_matrix = '''FF 81 BD A5 A5 BD 81 FF
AA 55 AA 55 AA 55 AA 55
3E 7F FC F8 F8 FC 7F 3E
93 93 93 F3 F3 93 93 93'''
hex_matrix = hex_matrix.splitlines()
for line in hex_matrix:
base16 = re.findall('\d[A-Z]|[A-Z]\d|\d+|[A-Z]+', line)
for num in base16:
ans = hex_to_str(num)
print(ans)
| true
|
469bcb352f966ce525cc49271d3c707085ce1e17
|
Rich43/rog
|
/albums/3/challenge10_easy/code.py
| 866
| 4.53125
| 5
|
'' The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers
can be written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code
parenthesized; both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890, (123)
456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
'''
# Note: no '/' or ':' or nine digits.
#call = input('Enter telephone number: ')
call = '345 6 6789'
lst = []
for x in call:
if str.isnumeric(x):
lst.append(x)
if '/' in call or ':' in call or len(lst) < 10:
print('False')
else:
print('Number OK!')
| true
|
458fcbc5b06298bd4fc084465f91f1a86bae2e17
|
Rich43/rog
|
/albums/3/challenge149_easy/code.py
| 1,838
| 4.25
| 4
|
'''
Disemvoweling means removing the vowels from text. (For this challenge, the letters a, e, i, o, and u
are considered vowels, and the letter y is not.) The idea is to make text difficult but not
impossible to read, for when somebody posts something so idiotic you want people who are reading it
to get extra frustrated.
To make things even harder to read, we'll remove spaces too. For example, this string:
two drums and a cymbal fall off a cliff
can be disemvoweled to get:
twdrmsndcymblfllffclff
We also want to keep the vowels we removed around (in their original order), which in this case is:
ouaaaaoai
Formal Inputs & Outputs
Input description
A string consisting of a series of words to disemvowel. It will be all lowercase (letters a-z)
and without punctuation. The only special character you need to handle is spaces.
Output description
Two strings, one of the disemvoweled text (spaces removed), and one of all the removed vowels.
Sample Inputs & Outputs
Sample Input 1
all those who believe in psychokinesis raise my hand
Sample Output 1
llthswhblvnpsychknssrsmyhnd
aoeoeieeioieiaiea
Sample Input 2
did you hear about the excellent farmer who was outstanding in his field
Sample Output 2
ddyhrbtthxcllntfrmrwhwststndngnhsfld
ioueaaoueeeeaeoaouaiiiie
Notes
'''
vowels = 'aeiou'
consononts = ''
vowel_output = ''
samples = '''all those who believe in psychokinesis raise my hand
did you hear about the excellent farmer who was outstanding in his field'''
for line in samples.splitlines():
line = line.strip('\n')
line = line.replace(' ', '')
vowel_string = ''
for x in range(0, len(line)):
if line[x] in vowels:
vowel_output += line[x]
else:
consononts += line[x]
print(consononts)
print(vowel_output)
consononts = ''
vowel_output = ''
| true
|
d702030522318f0d1aa5c9c134e670bf2dd23db5
|
Rich43/rog
|
/albums/3/challenge41_easy/code.py
| 967
| 4.15625
| 4
|
''' Write a program that will accept a sentence as input and then output that sentence surrounded by some type of an ASCII decoratoin banner.
Sample run:
Enter a sentence: So long and thanks for all the fish
Output
*****************************************
* *
* So long and thanks for all the fish *
* *
*****************************************
Bonus: If the sentence is too long, move words to the next line.
'''
def outer():
global leng
return ('x' * (leng +6))
def inner():
global leng
return ('x' + (' ' * (leng + 4)) + 'x')
def string():
global quote
return ('x' + ' ' * 2 + quote + ' ' * 2 + 'x')
if __name__ == '__main__':
#quote = input("Let's have a quote...: ")
quote = 'I am a python'
leng = len(quote)
out = outer()
inn = inner()
txt = string()
print(out + "\n" + inn + "\n" + txt + "\n" + inn + "\n" + out)
| true
|
dc507cd0c38636a157f79882827f66505af93ee2
|
Rich43/rog
|
/albums/3/challenge193_easy/code.py
| 1,657
| 4.4375
| 4
|
''' An international shipping company is trying to figure out
how to manufacture various types of containers. Given a volume
they want to figure out the dimensions of various shapes that
would all hold the same volume.
Input:
A volume in cubic meters.
Output:
Dimensions of containers of various types that would hold the volume.
The following containers are possible.
Cube
Ball (Sphere)
Cylinder
Cone
Example Input:
27
Example Output:
Cube: 3.00m width, 3.00m, high, 3.00m tall
Cylinder: 3.00m tall, Diameter of 3.38m
Sphere: 1.86m Radius
Cone: 9.00m tall, 1.69m Radius
Some Inputs to test.
27, 42, 1000, 2197
'''
import math
def cube(vol):
r = vol / 3
return r
def sphere(vol):
r = ((3 * vol) / (4 * math.pi)) ** (1 / 3)
r = round(r, 2)
return r
def cylinder(vol):
r = (vol / (math.pi * h)) ** 0.5
r = round(r, 2)
return r
def cone(vol):
r = (3 * (vol / (math.pi * h))) ** 0.5
r = round(r, 2)
return r
def display(volume, h):
print('A cube of {0} metres cubed will have sides of {1} metres'.format(volume, h))
print('A sphere of volume {0} cubic metres will have a radius of {1} metres.'.format(volume, sphere(volume)))
print('A cylinder of {0} cubic metres with a height of {1} will have a radius of {2} metres.'.format(volume, h, cylinder(volume)))
print('A cone of {0} cubic metres and height of {1} metres will have a radius of {2} metres'.format(volume, h, cone(volume)))
if __name__ == '__main__':
lst = [27, 42, 1000, 2197]
for num in lst:
h = round((num / 9), 2)
ans = display(num, h)
print(ans)
print()
# 193
| true
|
93ea951e7c2eb9c49eab5ecaefba68570832a79a
|
Rich43/rog
|
/albums/3/challenge191_easy/code.py
| 1,995
| 4.25
| 4
|
'''
You've recently taken an internship at an up and coming lingustic and natural language centre.
Unfortunately, as with real life, the professors have allocated you the mundane task of
counting every single word in a book and finding out how many occurences of each word there
are.
To them, this task would take hours but they are unaware of your programming background (They
really didn't assess the candidates much). Impress them with that word count by the end of the
day and you're surely in for more smooth sailing.
Description
Given a text file, count how many occurences of each word are present in that text file. To
make it more interesting we'll be analyzing the free books offered by Project Gutenberg
The book I'm giving to you in this challenge is an illustrated monthly on birds. You're free
to choose other books if you wish.
Inputs and Outputs
Input
Pass your book through for processing
Output
Output should consist of a key-value pair of the word and its word count.
Example
{'the' : 56,
'example' : 16,
'blue-tit' : 4,
'wings' : 75}
Clarifications
For the sake of ease, you don't have to begin the word count when the book starts, you can just count
all the words in that text file (including the boilerplate legal stuff put in by Gutenberg).
Bonus
As a bonus, only extract the book's contents and nothing else.
'''
import re
word_dict = {}
with open('gutenburg.txt', 'r') as f:
for line in f:
line = re.findall('[a-zA-Z]+', line)
for word in line:
word_dict[word] = word_dict.setdefault(word, 0) + 1
print(word_dict)
#-- Bonus --------------------------------------------
text_string = ''
word_dict = {}
with open('gutenburg.txt') as f:
for line in f:
line = line.rstrip()
text_string += line + ' '
txt = re.findall('Title:.*Patagonia.', text_string)
txt = txt[0]
txt = re.findall('[a-zA-Z]+', txt)
for word in txt:
word_dict[word] = word_dict.setdefault(word, 0) + 1
print(word_dict)
| true
|
83e038b449f0db56788edf9ac5a8d41898141dd9
|
Rich43/rog
|
/albums/3/challenge199_easy/code.py
| 2,042
| 4.15625
| 4
|
'''
You work for a bank, which has recently purchased an ingenious machine
to assist in reading letters and faxes sent in by branch offices.
The machine scans the paper documents, and produces a file with a
number of entries which each look like this:
_ _ _ _ _ _ _
| _| _||_||_ |_ ||_||_|
||_ _| | _||_| ||_| _|
Each entry is 4 lines long, and each line has 27 characters. The first
3 lines of each entry contain an account number written using pipes and
underscores, and the fourth line is blank. Each account number should
have 9 digits, all of which should be in the range 0-9.
Right now you're working in the print shop and you have to take account
numbers and produce those paper documents.
Input
You'll be given a series of numbers and you have to parse them into the
previously mentioned banner format. This input...
000000000
111111111
490067715
Output
...would reveal an output that looks like this
_ _ _ _ _ _ _ _ _
| || || || || || || || || |
|_||_||_||_||_||_||_||_||_|
| | | | | | | | |
| | | | | | | | |
_ _ _ _ _ _ _
|_||_|| || ||_ | | ||_
'''
import itertools
one = '''
|
|
'''
two = ''' _
_|
|_
'''
three = '''_
_!
_!
'''
four = '''
!_!
!
'''
five = ''' _
!_
_!
'''
six = '''_
!_
!_!
'''
seven = '''_
!
!
'''
eight = '''_
!_!
!_!
'''
nine = ''' _
!_!
_!
'''
zero = ''' _
! !
!_!
'''
strings = list(itertools.repeat(zero, 9))
string2 = list(itertools.repeat(one, 9))
string3 = (four, nine, zero, zero, six, seven, seven, one, five)
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in strings])], sep='\n')
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in string2])], sep='\n')
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in string3])], sep='\n')
| true
|
7634f458818e574f22aee33c9c64e0263bc51312
|
Rich43/rog
|
/albums/3/challenge194_easy/code.py
| 2,678
| 4.25
| 4
|
'''
Most programming languages understand the concept of escaping strings. For example,
if you wanted to put a double-quote " into a string that is delimited by double
quotes, you can't just do this:
"this string contains " a quote."
That would end the string after the word contains, causing a syntax error. To remedy
this, you can prefix the quote with a backslash \ to escape the character.
"this string really does \" contain a quote."
However, what if you wanted to type a backslash instead? For example:
"the end of this string contains a backslash. \"
The parser would think the string never ends, as that last quote is escaped! The
obvious fix is to also escape the back-slashes, like so.
"lorem ipsum dolor sit amet \\\\"
The same goes for putting newlines in strings. To make a string that spans two
lines, you cannot put a line break in the string literal:
"this string...
...spans two lines!"
The parser would reach the end of the first line and panic! This is fixed by
replacing the newline with a special escape code, such as \n:
"a new line \n hath begun."
Your task is, given an escaped string, un-escape it to produce what the parser
would understand.
Input Description
You will accept a string literal, surrounded by quotes, like the following:
"A random\nstring\\\""
If the string is valid, un-escape it. If it's not (like if the string doesn't
end), throw an error!
Output Description
Expand it into its true form, for example:
A random
string\"
Sample Inputs and Outputs
1. Sample Input
"hello,\nworld!"
Sample Output
hello,
world!
2. Sample Input
"\"\\\""
Sample Output
"\"
3. Sample Input
"an invalid\nstring\"
Sample Output
Invalid string! (Doesn't end)
4. Sample Input
"another invalid string \q"
Sample Output
Invalid string! (Bad escape code, \q)
'''
import re
import codecs
escape_chars = ['\\newline',
'\\',
"\\'",
'\\"',
'\\a',
'\\b',
'\\f',
'\\n',
'\r',
'\t',
'\\v',
'\\ooo',
'\\uxxxxx',
'\\Uxxxxx']
file = '194.txt'
with open(file, 'r') as f:
for line in f:
line = line.strip('\n')
end_of = re.findall('\\\$', line)
extract = re.findall(r'\\\w|\\', line)
temp = extract
first = temp[0]
if len(end_of) > 0:
print('Invalid string (Doesn\'t end)')
elif first in escape_chars:
print(codecs.escape_decode(bytes(line, "utf-8"))[0].decode("utf-8"))
else:
print('Invalid string' + ' (bad escape code ' + first + ')')
| true
|
b22a560b7c2cdfae02f5a0e47cfc9a9714f5986f
|
Rich43/rog
|
/albums/3/challenge33_easy/code.py
| 885
| 4.125
| 4
|
''' This would be a good study tool too. I made one myself and I thought it would also be a good challenge.
Write a program that prints a string from a list at random, expects input, checks for a right or wrong answer,
and keeps doing it until the user types "exit". If given the right answer for the string printed,
it will print another and continue on. If the answer is wrong, the correct answer is printed and
the program continues.
Bonus: Instead of defining the values in the program, the questions/answers is in a file,
formatted for easy parsing.
Example file:s
Translate: hola,hello
'''
dikt = {'4 times 8 = ': 32, '6 divided by 3 = ': 2, 'Square root of nine? ': 3}
for key in dikt:
question = key
ans = input(question)
ans1 = str(dikt[question])
if ans == ans1:
print('Correct')
else:
print('Wrong! Answer is: ', dikt[question])
| true
|
84e5a596be210ab77c029504c094f3328162aba2
|
Rich43/rog
|
/albums/3/challenge34_easy/code.py
| 373
| 4.25
| 4
|
''' A very basic challenge:
In this challenge, the
input is are : 3 numbers as arguments
output: the sum of the squares of the two larger numbers.
Your task is to write the indicated challenge.
'''
#nums = input('Input three numbers in the form 1/2/3 : ')
nums = '5/8/4'
nums = sorted(nums.split('/'))
ans = (float(nums[1]) ** 2) + (float(nums[2]) ** 2)
print(ans)
| true
|
3fda92e3ae36967245d8366a30d54987ef9f3694
|
kaczifant/Elements-of-Programming-Interviews-in-Python-Exercises
|
/string_integer_interconversion.py
| 1,767
| 4.25
| 4
|
# 6.1 INTERCONVERT STRINGS AND INTEGERS
# Implement an integer to string conversion function, and a string to integer conversison function.
# Your code should handle negative integers. You cannot use library functions like int in Python.
from test_framework import generic_test
from test_framework.test_failure import TestFailure
def int_to_string(x):
minus = False
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
string = ''
if x < 0:
minus = True
x = x * -1
if x == 0:
return '0'
else:
while x != 0:
mod_10 = x % 10
x = (x - mod_10)//10
string += chars[mod_10]
if minus:
return '-' + string[::-1]
return string[::-1]
def string_to_int(s):
num = 0
num_dict = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
if '-' in s:
tens = len(s) - 2
for char in s:
if char in num_dict:
num += num_dict[char] * (10 ** tens)
tens -= 1
return num * -1
else:
tens = len(s) - 1
for char in s:
if char in num_dict:
num += num_dict[char] * (10 ** tens)
tens -= 1
return num
def wrapper(x, s):
if int_to_string(x) != s:
raise TestFailure("Int to string conversion failed")
if string_to_int(s) != x:
raise TestFailure("String to int conversion failed")
if __name__ == '__main__':
exit(
generic_test.generic_test_main("string_integer_interconversion.py",
'string_integer_interconversion.tsv',
wrapper))
| true
|
57f902e278e495aa66de4b3cc1408aaebfbda91e
|
cory-schneider/random-article-generator
|
/writer.py
| 2,873
| 4.21875
| 4
|
#!/usr/bin/python3
#Pulls from a word list, creates "paragraphs" of random length, occasionally entering a blank line.
#User Inputs:
# word list file path
# test file, exit if bad path
# print word count
# file name for output
# number of paragraphs
# min words per paragraph (prompt user not to use zero, random blank functionality is separate)
# max words per paragraphs
import random
#User input for the input file:
def q1():
x = input("Enter word list full file path/name: ")
return x
input_file = q1()
#Check for correct file path. Exit if no such file
try:
wordlist = open(input_file, "r")
except IOError:
print("An error was found. Either path incorrect or file doesn't exist!"
+ '\n' + "Exiting program!")
exit()
source_count = len(open(input_file).readlines())
print("There are {} words in '{}'".format(source_count,input_file))
#Implement output file check. If exists, overwrite?
#User input for the output file:
def q2():
x = input("Enter desired output path/name: ")
return x
output_query = q2()
output = open(output_query, "a+")
#User input for number of paragraphs per article:
def q3():
x = input("How many paragraphs shall we print? ")
return x
try:
art_length = int(q3())
except:
print("Integers only!")
exit()
#User input for min words per paragraph:
def q4():
x = input("Minimum number of words per paragraph? ")
return x
try:
min_w = int(q4())
except:
print("Integers only!")
exit()
#User input for max words per paragraph:
def q5():
x = input("Maximum number of words per paragraph? ")
return x
try:
max_w = int(q5())
except:
print("Integers only!")
exit()
answers = (
'\n' + "Wordlist File: {}" + '\n' + "Words in list: {}" + '\n' + "Output File: {}" + '\n'
+ "Paragraph count: {}" + '\n' + "Min words/paragraph: {}" + '\n'
+ "Max words/paragraph: {}" + '\n' + '------------------------------------------' + '\n'
)
output.write(answers.format(input_file, source_count, output_query, art_length, min_w, max_w))
#Opens the input file, strips out the entries into a list, closes input file.
textBlock = wordlist.readlines()
master_list = []
for line in textBlock:
master_list.append(line.strip())
wordlist.close()
#Creates num_list which will be used to pull from the master_list
def para_list():
w_para = random.randint(min_w, max_w)
x = []
for _ in range(w_para):
x.append(random.randint(1,source_count))
return x
def para_mesh():
num_list = para_list()
paragraph = []
for i in num_list:
paragraph.append(master_list[i])
#alphabetize, otherwise manipulate the list:
# paragraph.sort()
paragraph = ' '.join(paragraph).lower()
print(paragraph + '\n')
output.write(paragraph + '\n')
for _ in range(art_length):
para_mesh()
output.close()
| true
|
dc282841394adaf3cd83d97bf55e1e7bedfbab15
|
saarco777/Centos-REpo
|
/User age - Pub.py
| 672
| 4.21875
| 4
|
# define your age
name = input('Hi there, whats your name?') # user defines their name
age = input('How old are you?') # user gets asked whats their age
if int(age) > 20:
print('Hi', name, 'Welcome in, Please have a Drink!') # if age is bigger than 20, user gets inside and HAS a drink
elif int(age) < 20 and int(age) > 18:
print('Welcome in', name, 'But your age is below 20, Sorry but you CANNOT have a drink') # if age is bigger than 18 but lower than 20, user can get inside but cannot have a drinl
elif int(age) < 18:
print('Sorry', name, 'Your too young. You cannot come inside') # if age is below 20, user is too young and cannot come inside
| true
|
dacafce3f5455a01d105f0f3e017dc17d5f3efde
|
dark-glich/data-types
|
/Tuple.py
| 874
| 4.59375
| 5
|
# tuple : immutable - ordered
tuple_1 = (1, 2, 3, 4, 2, 5, 2, )
print(f"original name : {tuple_1}")
# tuple[index] is used to access a single item from the tuple.
print(f"tuple[2] : {tuple_1[2]}")
# tuple.index[value] is used to get the index of a value.
x = tuple_1.index(3)
print(f"tuple.index : {x}")
# tuple[:index] is used to get the value to the certain index.
print(f"tuple[:2] : {tuple_1[:2]}")
# tuple[index :] is used to get the value from the certain index.
print(f"tuple[2:] : {tuple_1[2 :]}")
# tuple[::num] is used to display the tuple with the jump of num.
print(f"tuple[::2] : {tuple_1[::2]}")
# tuple.count(value) is used to get no. of repetition of a certain value.
print(f"tuple.count(2) : {tuple_1.count(2)}")
# converting tuple to list and set.
print(f"tuple to list : {list(tuple_1)}")
print(f"tuple to set : {set(tuple_1)}")
| true
|
cecd850e5ac271d9cf8f27faf059188ecf53f8c6
|
xiaojias/python
|
/development/script.py
| 1,383
| 4.28125
| 4
|
my_name = "Codecademy"
print("Hello and welcome " + my_name + " !")
# Operators
message = "First Name"
message += ", Sure Name"
print(message)
# Comment on a single line
user = "Jdoe" # Comment after code
# Arithmetic operators
result = 10 + 20
result = 40 - 30
result = 20 * 2
result = 16 / 4
result = 25 % 2
result = 5 ** 3
# Plus-equal operator
counter = 0
counter += 10
# This is equalent to
counter = 0
counter = counter + 10
# This operator will also perform string contactenation
message = "Part 1 of message"
message += "Part 2 of message"
# There are all valid variable and assignment
user_name = "codey"
user_id = 100
verified = False
# A variable can be changed after assignment
points = 100
points = 120
# Modulo operation
zero = 8 % 4
nozero = 12 % 5
# Exact integer number
chairs = 4
tables = 1
broken_chairs = -2
sofas = 0
# Non-integer numbers
lights = 2.5
left_overs = 0.0
# String concatenation
first = "Hello"
second = "World"
result = first + second
long_reslut = first + second + "!"
# Floating point number
pi = 3.1415926
meal_cost = 12.98
tip_percent = 0.20
# Print function
print("Hello World !")
print(100)
pi = 3.1415926
print(pi)
# Idendity
a = "Hello"
b = a
id(a)
# An interger
id(a) == id(b)
# True
b = 'Hell' + 'o'
id(a) == id(b)
# True
# Type
type(a)
# Type conversion
x = '145'
y = int(x)
type(x)
# Str
type(y)
# Int
| true
|
b5694e5bb2c3d591d886a5f21f63f5ef0f1dcadc
|
gururajh/python-standard-programs
|
/Fibonacci.py
| 1,995
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 29 14:27:50 2022
@author: Gururaja Hegde V'
"""
"""Write a program to generate Fibonnaci numbers.
The Fibonnaci seqence is a sequence of numbers where the next number in the sequence
is the sum of the previous two numbers in the sequence.
The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)"""
def gen_fib1():
count=int(input("Gen_fib_1- How many fibonacci numbers would you like to generate?:"))
i=1
if count==0:
fib=[]
elif count==1:
fib=[1]
elif count==2:
fib=[1,1]
elif count>2:
fib=[1,1]
while i<(count-1):
fib.append(fib[i]+fib[i-1])
i+=1
return fib
def gen_fib2():
num=int(input("Gen_fib_2- How many fibonacci numbers would you like to generate:"))
i=1
if num==0:
fib=[]
elif num==1:
fib=[1]
elif num==2:
fib=[1,1]
elif num>2:
fib=[1,1]
while i<(num-1):
fib.append(fib[i]+fib[i-1])
i+=1
return fib
def gen_fib3():
n =int(input("Gen_fib_3- How many fibonacci numbers would you like to generate:"))
f=[]
f.append(1)
f.append(1)
for i in range(2,n):
f.append(f[i-1]+f[i-2])
print(f)
""" Type 4 """
# 1. Take the number of terms from the user and store it in a variable.
# 2. Pass the number as an argument to a recursive function named fibonacci.
# 3. Define the base condition as the number to be lesser than or equal to 1.
# 4. Otherwise call the function recursively with the argument as the number minus
# 1 added to the function called recursively with the argument as the number minus 2.
# 5. Use a for loop and print the returned value which is the fibonacci series.
# 6. Exit.
def gen_fib4(n):
if(n <= 1):
return n
else:
return(gen_fib4(n-1) + gen_fib4(n-2))
n = int(input("Enter number of terms for fibon:"))
print("Fibonacci sequence:")
for i in range(n):
print(gen_fib4(i))
print(gen_fib1())
print(gen_fib2())
print(gen_fib3())
| true
|
1382f8c14d706cf5c5a089821a0e0211b5d5c8f4
|
AmGhGitHub/SAGA_Python
|
/py_lesson8.py
| 1,164
| 4.40625
| 4
|
# Arithmetic operators
x = 10.0
y = 3.1415
exponent = 3
print("sum:", x + y) # addition
print("subtraction:", x - y) # addition
print("multiplication:", x * y) # multiplication
print("float division:", x / y) # float division
print("floor division:", int(x) // int(y)) # floor division
print("modulus:", int(x) % int(y)) # modulus: the remainder when first operand is divided by the second
print("exponent:", x ** exponent) # exponent
# the result of a mathematical expression can be assigned to a new variable
z = x + y
# Use mathematical operation to modify the value of a variable in place
print("before modify: x=", x)
x = x / 2
print("after modify: x=", x)
# each arithmetic operator has an augmented operator equivalent
#y = y + 2
y += 2 # this is equivalent to y = y + 2
y **= 2
print("y=", y)
sw = 0.2
so = 0.45
# un-equality
print(sw != 0.2)
# less than
print(sw < so)
# returns True if both statements are true
print(sw > 0.1 and so < 0.3)
# returns True if one of the statements is true
print(sw > 0.15 or so > 0.60)
# negate the result, returns False if the result is true
print(not sw <= 0.1)
| true
|
9ec395003a967ab68c644c01cd3a792fc27a0d67
|
AmGhGitHub/SAGA_Python
|
/py_lesson17.py
| 1,657
| 4.1875
| 4
|
class Well:
"""
Well class for modelling vertical well
performance
"""
def __init__(self, radius, length):
"""
Initialize well attributes
:param radius (float): radius of the well
in ft
:param length (float): productive length
of the well in ft
"""
self.radius = radius
self.length = length
def get_wellbore_volume(self, correction_factor=1.0):
"""
:param correction_factor (float): a correction-factor
to be applied to volume
:return (float): storage volume of the
well is returned
"""
PI = 3.1415 # by convention, we use all CAPITAL LETTERS name for constant value in Python
well_volume = PI * self.radius ** 2.0 * self.length * correction_factor
return well_volume
# create an instance of the class or create an well object
oil_well = Well(0.30, 551) # please note that init() method requires 3 parameters, but we only provide two parameters
water_well = Well(0.25, 1001.4)
## objects are working independently from each other
print(oil_well.radius > water_well.radius) # you see the application of "dot" notation with objects
print(f"Internal volume:{oil_well.get_wellbore_volume(0.9):.2f} ft3")
## use the object method
oil_well_internal_vol = oil_well.get_wellbore_volume(0.95) # again, we don't need to pass any value for the self parameter
water_well_internal_vol = water_well.get_wellbore_volume(0.81)
print(f"Oil-well internal volume:{oil_well_internal_vol}")
print(f"Water-well internal volume:{water_well_internal_vol:.2f}")
| true
|
118ac7580a7f7c7335e6428eb055a3ed05e3bbf8
|
habahut/CS112-Spring2012
|
/classcode/day12--objects/bobExample.py
| 847
| 4.15625
| 4
|
#! usr/env/bin python
class Student(object): #classes should have a capital letter
def __init__(self, name="Jane Doe"):
self.name = name
def say(self, message):
print self.name + " : " + message
def sayTo(self, other, message):
self.say(message +"," +other.name)
def printMe(self):
print self.name
class Course(object):
def __init__(self,name):
self.name = name
self.enrolled = []
def enroll(self, student):
self.enrolled.append(student)
def printMe(self):
for s in self.enrolled:
s.printMe()
bob = Student("Bob")
fred = Student("Fred")
j = Student()
j.say("pointless")
bob.say("hi fred")
fred.say("go away bob")
cs112 = Course("CS112")
cs112.enroll(bob)
cs112.enroll(fred)
cs112.printMe()
bob2 = bob
print bob2 is bob
| false
|
6e21a23abb976fbfd248c0e107ad86250bed9c12
|
raberin/Sorting
|
/src/recursive_sorting/recursive_sorting.py
| 2,749
| 4.25
| 4
|
# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
merged_arr = []
arrA_index = 0
arrB_index = 0
# Until the merged_arr is as big as both arrays combined
while len(merged_arr) < len(arrA) + len(arrB):
print(
f"arrA_index = {arrA_index}, arrB_index = {arrB_index}\n {merged_arr}")
# If arrB is empty add arrA elements and vice versa
if len(arrB) <= arrB_index:
merged_arr.append(arrA[arrA_index])
arrA_index += 1
elif len(arrA) <= arrA_index:
merged_arr.append(arrB[arrB_index])
arrB_index += 1
# Compare which element is smaller and push to merged
elif arrA[arrA_index] <= arrB[arrB_index]:
merged_arr.append(arrA[arrA_index])
arrA_index += 1
else:
merged_arr.append(arrB[arrB_index])
arrB_index += 1
return merged_arr
# arr1 = [1, 3, 5, 6, 7]
# arr2 = [2, 4, 8, 9]
# print(merge(arr1, arr2))
# # TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
# Base Case
if len(arr) < 2:
return arr
# Make midpt variable
middlePoint = len(arr) // 2
# Recurse the left and right sides of the array
sortLeft = merge_sort(arr[0:middlePoint])
sortRight = merge_sort(arr[middlePoint:len(arr)])
# Merge the arrays
return merge(sortLeft, sortRight)
arr1 = [1, 3, 5, 6, 7, 2, 4, 8, 9]
print(merge_sort(arr1))
def quick_sort(arr):
# Base case
if len(arr) == 0:
return arr
# Set pivot point last number in arr
pivot = arr[len(arr) - 1]
# Create left and right arrays
left_arr = []
right_arr = []
# Loop until right before last element
for i in range(len(arr) - 1):
# if pivot < arr[i] push to rightArr
if pivot < arr[i]:
right_arr.append(arr[i])
# if pivot > arr[i] push to leftArr
else:
left_arr.append(arr[i])
# recurse left + right
left_arr_sorted = quick_sort(left_arr)
right_arr_sorted = quick_sort(right_arr)
print(
f"left_arr_sorted {left_arr_sorted} + right_arr_sorted {right_arr_sorted}")
# return left + pivot + right
return left_arr_sorted + [pivot] + right_arr_sorted
arr1 = [1, 3, 5, 6, 7, 2, 4, 8, 9]
print(quick_sort(arr1))
# STRETCH: implement an in-place merge sort algorithm
# def merge_in_place(arr, start, mid, end):
# # TO-DO
# return arr
# def merge_sort_in_place(arr, l, r):
# # TO-DO
# return arr
# # STRETCH: implement the Timsort function below
# # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
# def timsort(arr):
# return arr
| true
|
26c5201471d8948cfe707093710a05820f85e72b
|
CatLava/oop_practice
|
/car.py
| 697
| 4.28125
| 4
|
class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
# This is a built in function for only car
# Put a repr on any defined class, this helps to understand it
def __repr__(self):
return 'Car({self.mileage})'.format(self=self)
# Python built in method for string
def __str__(self):
return "a {self.color} car".format(self=self)
myc = Car("red", 12000)
myc
# when this is printed, all we get is a memory address, no information
print(myc)
# To help print readable information, we will use the __str__ and __repr__ methods
# __str__ is supposed to be easy to read function and be explicit as possible
| true
|
de853c093fd83515f4a98a5f4c453272a6b5579c
|
sethifur/cs3030-seth_johns_hw5
|
/seth_johns_hw5.py
| 918
| 4.25
| 4
|
#!/usr/bin/env python3
import sys
def GetInput():
"""
Function:
asks for a pin input <9876>
validates the size, type, and number.
returns pin if correct
if incorrect 3 times exits program
"""
for index in range(3):
try:
pin = int(input('Enter your pin: '))
if (pin >= 1000 and pin < 10000):
if pin == 1234:
return pin
else:
print('Your PIN is incorrect')
else:
print('Invalid PIN lenth. Correct format is: <9876>')
except ValueError:
print('Invalid PIN character. Correct format is: <9876>')
print('Your bank card is blocked.')
exit(1)
# Main Function
def main():
validation = GetInput()
print('Your PIN is correct.')
return
if __name__ == '__main__':
#Call Main
main()
exit(0)
| true
|
cdcdb23d6ac63da1b095a1ee68be9b97e4643c20
|
niko-vulic/sampleAPI
|
/leetcodeTester/q35.py
| 1,744
| 4.1875
| 4
|
# 35. Search Insert Position
# Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
from typing import List
class Solution:
def __init__(self):
self.testCases = []
self.funcName = "searchInsert"
def defineTestCases(self):
self.testCases.append([[2, 3, 4], 3])
self.testCases.append([[1, 4, 7, 8], 5])
self.testCases.append([[-1, 0, 4, 7], 4])
self.testCases.append([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 12])
def runTests(self):
for case in self.testCases:
print("Test case:" + str(case) + ", answer is:" + str(getattr(self, self.funcName)(case[0], case[1])))
def searchInsert(self, nums: List[int], target: int) -> int:
# When the last element is reached, return recursively, adding any halfway counters on the return
if len(nums) == 1:
if target <= nums[0]:
return 0
else:
return 1
# fullsize = len(nums)
halfway = int(len(nums)/2)
# print("Size of current array" + str(fullsize))
# print("left half:" + str(nums[:halfway]))
# print("right half:" + str(nums[halfway:]))
# As the requirement is O(log n) time, we perform binary search on the array.
if target < nums[halfway]:
return self.searchInsert(nums[:halfway], target)
else:
return halfway + self.searchInsert(nums[halfway:], target)
if __name__ == '__main__':
soln = Solution()
soln.defineTestCases()
soln.runTests()
| true
|
7fff33692bf4f4aad318681b76b177bb021f6637
|
niko-vulic/sampleAPI
|
/leetcodeTester/q121.py
| 1,311
| 4.125
| 4
|
# 121. Best Time to Buy and Sell Stock
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
# Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
from typing import List
class Solution:
def __init__(self):
self.testCases = []
self.funcName = "maxProfit"
def defineTestCases(self):
self.testCases.append([0, 1, 2])
self.testCases.append([4, 1, 3, 5, 2, 7])
self.testCases.append([3, 2, 1])
def runTests(self):
for case in self.testCases:
print("Test case:" + str(case) + ", answer is:" + str(getattr(self, self.funcName)(case)))
def maxProfit(self, prices: List[int]) -> int:
minBuy = [0] * len(prices)
minBuy[0] = prices[0]
maxDiff = 0
for i in range(1, len(prices)):
minBuy[i] = min(prices[i], minBuy[i-1])
currDiff = prices[i] - minBuy[i]
if currDiff > maxDiff: maxDiff = currDiff
return maxDiff
if __name__ == '__main__':
soln = Solution()
soln.defineTestCases()
soln.runTests()
| true
|
1aca8af29f7519569145abfe34d3cd2efa535327
|
enderceylan/Projects
|
/Solutions/FibonacciSequence.py
| 390
| 4.3125
| 4
|
# Fibonacci Sequence - Enter a number and have the program generate the Fibonacci
# sequence to that number or to the Nth number.
# Solution by Ender Ceylan
x = 1
y = 1
num = int(input("Enter the amount of Fibonacci values to be viewed: "))
while num <= 0:
num = int(input("Input must be above 0: "))
for i in range(num):
print(str(x)+" ")
y = (x-y)
if i != 0:
x = x + y
| true
|
8e328d70a1be51172286f69bb0d9189c6d36a080
|
adityasunny1189/100DaysOfPython
|
/day1.py
| 460
| 4.1875
| 4
|
print("Hello World")
print("Hello" + " " + "Aditya")
print("Hello" + " " + input("Enter your name: "))
print(len(input("Name: ")))
name = input("Enter username: ")
length = len(name)
print(name)
print(length)
#Project Day 1
print("Welcome to band name generator")
city_name = input("Enter the name of city you grew up in? ")
pet_name = input("Enter your pet name? ")
name_of_band = city_name + " " + pet_name
print("Your band name is: " + name_of_band)
| false
|
08eb776f982387f55fe513b09a624472c158dc5f
|
dhrvdwvd/practice
|
/python_programs/34_pr_04.py
| 206
| 4.1875
| 4
|
names = ["dhruv", "ratnesh", "abhinav", "jaskaran"]
name = input("Enter a name to search: ")
if name in names:
print(name+" is present in the list.")
else:
print("Name entered is not in the list.")
| true
|
3ff3ba9cd497c199e24a8683e59595802bedc4f2
|
dhrvdwvd/practice
|
/python_programs/06_operators.py
| 238
| 4.3125
| 4
|
a = 3
b = 4
# Arithmetic Operators
print("a + b = ", a+b)
print("a - b = ", a-b)
print("a * b = ", a*b)
print("a / b = ", a/b)
# Python gives float when two ints are divided.
# Assignment operators.
a = 12
a+=22
a-=12
a*=2
a/=4
print(a)
| true
|
06ead9d50bb8b9eaad3a0c1bf43434331bcda7cb
|
dhrvdwvd/practice
|
/python_programs/66_try.py
| 425
| 4.21875
| 4
|
while(True):
print("Press q to quit")
a = input("Enter a number: ")
if(a == 'q'): break
try:
a = int(a)
if(a>6): print("Entered number is greater than 6.")
except Exception as e:
print(e) # This breaks the loop as well.
print("Thanks for playing the game.")
# The try-except do not let the programs to crash when an error
# occurs, this is useful when making GUI applications.
| true
|
bdec843924ca0e0e4e45ccd6bd315245098bf6ec
|
dhrvdwvd/practice
|
/python_programs/12_strings_slicing.py
| 331
| 4.15625
| 4
|
greeting = "Hello, "
name = "DhruvisGood"
#print(greeting + name)
#print(name[0])
#name[3] = 'd' --> does not work
# String can be accessed but not changed.
print(name[0:3]) # is same as below
print(name[:3])
print(name[1:]) # will print from index 1 to last index
print(name[1:8:2]) # will start printing index 1, 1+2, 5, 7 ...
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.