blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
304bcfdd829e991fa16a7599acec6069ea4ce02b | alicexue/softdev-hw | /hw07/closure.py | 1,063 | 4.65625 | 5 | # CLOSURES
# 1. A function is declared inside another function
# 2. Inner function accesses a variable from the outer function (outside of the local scope of the inner function)
# 3. The external function binds a value to the variable and finishes (or closes) before the inner function can be completed
def repeat(s):
def times(x):
return s * x
return times
# This is an example of a nested function but NOT a closure because
#b=h(1)
#print b
#print b(5)
def f(x):
def g(y):
return x + y
return g
# ^ is not a closure, but f(1) is
#print f(1)
#print f(1)(3)
# closures:
#a=f(1)
#b=h(1)
# ----------------------------------- TASK ----------------------------------- #
def repeat(s):
return lambda n: s*n
#def repeat(word):
# def times(x):
# return word*x
# return times
r1 = repeat("hello")
r2 = repeat("goodbye")
# These create closures because repeat runs, binds s to "hello", and then exits, returning a function (times) with s bound to "hello"
print r1(2)
print r2(2)
print repeat('cool')(3)
| true |
53480cb6f015a3aceab2b74efad30017109bef7b | dexamusx/thPyCh3 | /thPyCh3.py | 2,494 | 4.46875 | 4 | #Exercise 1
#Write a function named right_justify that takes a string named s as a parameter and prints the string
#with enough leading spaces so that the last letter of the string is in column 70 of the display.
#eg: right_justify('monty')
#monty
#Hint: Use string concatenation and repetition. Also, Python provides a built-in function called len that returns the length of a string,
#so the value of len('monty') is 5.
def right_justify(s):
totalString = "";
tempVal = len(s);
length = 70-tempVal;
for i in range(length):
totalString += " ";
totalString += s;
return totalString;
print(right_justify("monty"));
#Exercise 2
#A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice: def do_twice(f):
#f()
#f() Hereโs an example that uses do_twice to call a function named print_spam twice.
#def print_spam():
#print('spam')
#do_twice(print_spam)
#Type this example into a script and test it.
#Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
#Copy the definition of print_twice from earlier in this chapter to your script.
#Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
#Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
def print_spam():
print('spam')
def do_twice(f):
f();
f();
do_twice(print_spam);
def do_more(f,n):
for i in range(n):
f();
do_more(print_spam, 5);
def print_beam():
print('+ - - - -', end=' ');
def print_post():
print('| ', end=' ');
def print_beams():
do_twice(print_beam);
print('+');
def print_posts():
do_twice(print_post);
print('|');
def print_row():
print_beams();
do_more(print_posts,4);
def print_grid():
do_twice(print_row);
print_beams();
print_grid();
#or this works too
def do_top():
print("+ "+"- "*4+"+ "+"- "*4+"+")
def do_middle():
print("|"+" "*9+"|"+" "*9+"|")
def do_square():
for i in range(2):
do_top();
for i in range(4):
do_middle();
do_top();
do_square();
| true |
739da86c8ad51a05972c4e0e9efe317f399226d2 | WritingPanda/python_problems | /anagramAlgorithm.py | 942 | 4.21875 | 4 | __author__ = 'Omar Quimbaya'
word_one = input("Enter the first word: ")
word_two = input("Enter the second word: ")
def is_anagram(string_one, string_two):
stripped_string_one = string_one.strip()
stripped_string_two = string_two.strip()
if not stripped_string_one.isalpha() and not stripped_string_two.isalpha():
print("Strings must be single words only. There also cannot be numbers in it.")
return False
sorted_string_one = sorted(stripped_string_one)
sorted_string_two = sorted(stripped_string_two)
if sorted_string_one != sorted_string_two:
print("The two words, " + stripped_string_one + " and " + stripped_string_two
+ ", are not anagrams of each other.")
return False
else:
print("The two words, " + stripped_string_one + " and " + stripped_string_two
+ ", are anagrams of each other.")
return True
is_anagram(word_one, word_two) | true |
d27f132a7cc830ccc6ef012bac020f9fa97a8315 | amitrajitbose/algo-workshop-lhd19 | /recursion/fibonacci.py | 275 | 4.28125 | 4 | def Fibonacci(n):
"""
Returns the nth term of the Fibonacci Sequence
n is zero based indexed
"""
if n < 0:
raise Exception("Invalid Argument")
elif n < 2:
return n
else:
return Fibonacci(n-1) + Fibonacci(n-2)
print(Fibonacci(0))
print(Fibonacci(3)) | false |
20318d3eb76e871efcaee27efd60bff76ca48823 | nirbhaysinghnarang/CU_Boulder_DSA | /merge_sort.py | 826 | 4.125 | 4 | def merge_sort(array,left,right):
if(left<right):
mid = (left+right)//2
merge_sort(array,left,mid)
merge_sort(array,mid+1,right)
merge(array,left,right,mid)
def merge(array,left,right,mid):
tmp = [0] * (right - left + 1)
left_ctr = left
right_ctr = mid+1
tmp_index=0
while(left_ctr<=mid and right_ctr<=right):
if(array[left_ctr]<array[right_ctr]):
tmp[tmp_index] = array[left_ctr]
left_ctr+=1
tmp_index+=1
else:
tmp[tmp_index] = array[right_ctr]
right_ctr+=1
tmp_index+=1
while(left_ctr<=mid):
tmp[tmp_index] = array[left_ctr]
left_ctr+=1
tmp_index+=1
while(right_ctr<=right):
tmp[tmp_index] = array[right_ctr]
right_ctr+=1
tmp_index+=1
for i in range (left, right+1):
array[i] = tmp[i-left]
arr = [14,66,22,21,91,310,201,202]
merge_sort(arr,0,len(arr)-1)
print(arr)
| true |
8e3126742c0512d221a20be687f742b7f3fdd5a2 | Degelzhao/python | /python_basic/if_prt.py | 343 | 4.1875 | 4 | height = input('please input your height:')
weight = input('please input your weight:')
BMI = float(weight)/pow(float(height),2)
if BMI < 18.5:
print('่ฟ่ฝป')
elif BMI >= 18.5 and BMI < 25:
print('ๆญฃๅธธ')
elif BMI >= 25 and BMI < 28:
print('่ฟ้')
elif BMI >= 28 and BMI < 32:
print('่ฅ่')
else:
print('ไธฅ้่ฅ่') | false |
986f484385ff4e75b25a0e6dbc6cec37c82486d9 | Degelzhao/python | /python_basic/if.py | 457 | 4.375 | 4 | age = 17
if age >= 18:
print('your age is',age)
print('your age is %d'%age)
print('adult')
else:
print('your age is %d'%age)
print('teenager')
#you should pay attention to add the colon(:) to
#the behind of IF and else
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
s = input('please your birthday:')
birth = int(s)
if birth < 2000:
print('Before 00')
else:
print('After 00')
| false |
abed9991559fd5066191f3a64e457761148f4a42 | lisawei/director_to_python | /string.py | 375 | 4.15625 | 4 | name=raw_input("what's your name")
quest=raw_input("what's you quest")
color=raw_input("what is you favorite color")
print "Ah, so your name is %s, your quest is %s, your favorite color is %s." % (name,quest,color)
my_string="wow, you\'re great"
my_age="your age is"
age=18
print len(my_string)
print my_string.upper()
print my_string.lower()
print my_age + " " + str(age)
| true |
d60e3487cec11c3dac203a55fc9e528ec5c3518d | qzhn/linux_OM | /็ๆๅจ.py | 827 | 4.125 | 4 | #!usr/bin/env python
# coding=utf-8
import os
import sys
# !/usr/bin/python3
import sys
# ่ทๆฎ้ๅฝๆฐไธๅ็ๆฏ๏ผ็ๆๅจๆฏไธไธช่ฟๅ่ฟญไปฃๅจ็ๅฝๆฐ๏ผ
# ๅช่ฝ็จไบ่ฟญไปฃๆไฝ๏ผๆด็ฎๅ็น็่งฃ็ๆๅจๅฐฑๆฏไธไธช่ฟญไปฃๅจใ
# ๅจ่ฐ็จ็ๆๅจ่ฟ่ก็่ฟ็จไธญ๏ผ
# ๆฏๆฌก้ๅฐ yield ๆถๅฝๆฐไผๆๅๅนถไฟๅญๅฝๅๆๆ็่ฟ่กไฟกๆฏ๏ผ
# ่ฟๅyield็ๅผใ
# ๅนถๅจไธไธๆฌกๆง่ก next()ๆนๆณๆถไปๅฝๅไฝ็ฝฎ็ปง็ปญ่ฟ่กใ
def fibonacci(n): # ็ๆๅจๅฝๆฐ - ๆๆณข้ฃๅฅ
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f ๆฏไธไธช่ฟญไปฃๅจ๏ผ็ฑ็ๆๅจ่ฟๅ็ๆ
while True:
try:
print(next(f))
except StopIteration:
sys.exit() | false |
96cb4ac82227897b2048fc37e969135c40960b2a | Umakant463/Mini_Projects | /Calculator/cal1.py | 1,110 | 4.21875 | 4 | import math
print ("========== SIMPLE CALCULATOR =========== \n \n ")
print ("--- Enter two numbers ---- \n ")
num1 = int(input('Enter first number : '))
num2 = int(input('Enter second number : '))
# Addition of numbers
def add(a,b):
return (a + b)
#First checks the largest among two numbers and then subtract the smaller from larger.
def sub(a,b):
if a > b:
return (a - b)
elif b > a:
return (b - a)
#Given numbers are same it will return zero.
elif a == b:
return (0)
#Multiplication of numbers
def mul(a,b):
return (a * b)
#Divides the Given numbers.
def div(a,b):
return (a / b)
#Gives the remainder after dividing Numbers.
def rem(a,b):
return (a % b)
print ("Select the Operation you want to perform : ")
print (" 1. Addtion \n 2. Subtraction \n 3. Multiplication \n 4. Divide \n 5. Check Remainder \n")
input = int(input("Enter your input : "))
input -= 1
list = [add(num1,num2) , sub(num1,num2), mul(num1,num2), div(num1,num2), rem(num1,num2)]
u_choice = list[input]
print ("Answer : ",u_choice)
print("========== THANK YOU FOR USING SIMPLE CALCULATOR ===============")
| true |
2f69f87e503e3de98397c50726072bb3198bbe76 | bhabnish/Python-Project | /Project_My_Captain.py | 612 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# In this programme I took a radious from the user and found the area of the given radious
radius = int(input(" Please give the radius of your circle: "))
area = (22/7)*(radius)*(radius)
print ("The area of your circle is: " + str(area))
# In[3]:
# In this programme I asked the user to give a random file and see what extension is it.
file = input("Please a give a file name: ")
print (file)
var = len(file)
inc = 0
while inc < var :
if file [inc] == (".") :
break
inc = inc+1
print("The file extension is : " + file[inc+1:var])
| true |
01347a7deaf574789eaa863881a070e9378cde9f | sylatupa/Pure_Data_Organelle_Patches_and_Mother | /PyPi_Midi_Box/src/Algorithms/fib-spiral2.py | 1,337 | 4.34375 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: sylatupa
#
# Created: 20/09/2015
# Copyright: (c) sylatupa 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
import turtle
def main():
print "here"
fibonacci(1)
draw_spiral()
pass
def fibonacci(n):
fib1 = 0; fib2 = 1
if n == 0:
return fib1
elif n == 1:
return fib2
else:
for i in range(n-1):
fib = fib1 + fib2
fib1, fib2 = fib2, fib
return fib
def square(t, seg, size, fib):
"""
takes a turtle, number of segments, and a side dimension (size)
"""
for i in range(seg):
t.fd(size)
t.left(90)
t.write(fib)# write the current Fibonacci number next to the square
t.fd(size)
def draw_spiral(size=10):
t = turtle.Turtle()
seg = 3 # set to 5 segments after first pass
for i in range(size):
fib = fibonacci(i)
if (fib>0):
size = fib * 10 # a multiplier to give squares a reasonable size
print "seg: ", seg, "size: ", size, "fib: ", fib
square(t, seg, size, fib)
seg = 5
turtle.done()
if __name__ == '__main__':
main()
| false |
90a815d623eea0e183394bba7dc56925d73dd326 | EnginKosure/Jupyter_nb | /ch34.py | 2,634 | 4.25 | 4 | # For the sake of simplicity I'll refer to the array as "arr",
# the beginning index as "left", the end index as "right",
# and the element that we're searching for as "elem".
# The input for left and right initially will be left = 0 and right = sizeOfArray - 1.
# The rest of the algorithm can be broken down in five steps:
# If "left" > "right" then the search should end as being unsuccessful.
# Set the middle index to the floor division of ("left" + "right") / 2.
# If arr(middle) < "elem", set "left" = middle + 1 and start the algorithm over again.
# Else if arr(middle) > "elem", set "right" = middle - 1 and start the algorithm over again.
# Otherwise arr(middle) == "elem" and the item you're looking for has been found.
# Instructions
# The recursive function for this challenge will use a binary search to find an element in a given array.
# If the inputted element is found then the function should return true. If it fails to find the element then it should return false.
def binary_search(arr, left, right, elem):
if right >= left:
middle = (left+right)//2
if arr[middle] == elem:
return True
elif arr[middle] > elem:
return binary_search(arr, left, middle-1, elem)
else:
return binary_search(arr, middle + 1, right, elem)
else:
return False
def binary_search1(lst, left, right, elem):
while lst:
x = len(lst)//2
if lst[x] == elem:
return True
elif lst[x] > elem:
lst = lst[:x]
else:
lst = lst[x+1:]
return False
arr = [0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
elem = 7
print(binary_search(arr, 0, len(arr)-1, 7)) # โ True
arr1 = [1, 11, 14, 15, 32, 64, 67,
88, 92, 94]
elem1 = 12
print(binary_search1([1, 11, 14, 15, 32, 64, 67,
88, 92, 94], 0, len(arr1)-1, elem1)) # โ False
# binary_search([3, 6, 9, 12, 15, 18, 21, 24, 27, 30], left, right, 27) โ True
# Notes
# The operator for floor division in python is //.
# The array will be an int array and all integers will be positive.
# Several of the challenges that will be covered in this collection on algorithms can be solved non-recursively and without implementing the algorithms described in each challenge. I implore anyone solving these challenges to do them as intended. Not understanding the concepts taught will be an obstacle to later challenges and won't aid anyone in advancing their skills as a programmer.
# If you are stuck please check the Resources tab, Comments tab, or if you're really stuck, use the Solutions tab to unlock the answers.
| true |
b08c72697fb4c9e7943f597cf01b07d2039aed34 | pasignature/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,308 | 4.1875 | 4 | #!/usr/bin/python3
'''
2-matrix_divided.py
Contains function that divides all elements of a matrix
'''
def matrix_divided(matrix, div):
'''
Python Function that divide a matrix by variable div
'''
listError = 'matrix must be a matrix (list of lists) of integers/floats'
# Check if matrix is a list
if type(matrix) is not list:
raise TypeError(listError)
# Check if rows in matrix is list
for rows in matrix:
if type(rows) is not list:
raise TypeError(listError)
# Check if length of rows are the same
for row in matrix:
if len(matrix[0]) != len(row):
raise TypeError('Each row of the matrix must have the same size')
# Check to see if div is zero
if div == 0:
raise ZeroDivisionError('division by zero')
# Check if items in matrix are floats or ints
for rows in matrix:
for items in rows:
if not isinstance(items, (int, float)):
raise TypeError(listError)
# Python Function to divide elements of a matrix
new = []
for rows in matrix:
if not isinstance(div, (int, float)):
raise TypeError('div must be a number')
else:
new.append([round((items / div), 2) for items in rows])
return new
| true |
4641f57df69aa565059f5c88006b63fd8ed5f8d4 | malmike/SelfLearningClinic | /Car/app/car.py | 2,046 | 4.28125 | 4 | class Car(object):
"""
Added constructor taking arguments *args and **kwargs where *args
expects a list of items and **kwargs expects a dictionary. This allows
a class to be initialised with dynamic number of variables
"""
def __init__(self, *args, **kwargs):
self.type = ''
#Check whether args has three variables and if so, then the third is assigned to self.type
if len(args)==3:
self.type = args[2]
#Check whether args has two or more variables and if so, then the second is assigned to self.model
if len(args)>=2:
self.model = args[1]
#If args does not hold two or more variables then self.model is assigned GM
else:
self.model = 'GM'
#Check whether args has one or more variables and if so, then the first is assigned to self.name
if len(args)>=1:
self.name = args[0]
#If args does not hold one or more variables then self.name is assigned General
else:
self.name = 'General'
self.speed = 0
self.assign_doors()
self.assign_wheels()
#Function used to assign the number of doors the car has
def assign_doors(self):
if self.name == 'Koenigsegg' or self.name == 'Porshe':
self.num_of_doors = 2
else:
self.num_of_doors = 4
#Function used to assign the number of wheels the car has
def assign_wheels(self):
if self.type == 'trailer':
self.num_of_wheels = 8
else:
self.num_of_wheels = 4
#Function used to check whether the car is a saloon car or not
def is_saloon(self):
if self.type != 'trailer':
return True
else:
return False
#Function used to compute the speed of the car, depending on whether it's a trailer or not
def drive(self, value):
if self.type == 'trailer':
self.speed = 11*value
else:
self.speed = 10**value
return self | true |
8b2cd66bf7b1723237dff6e99cb49d5b7cc29deb | ArutselvanManivannan/Hackerrank-Code-Repository | /Python/Classes/Dealing with Complex Numbers.py | 1,757 | 4.125 | 4 | # https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers/problem
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
r = self.real + no.real
i = self.imaginary + no.imaginary
return Complex(r, i)
def __sub__(self, no):
r = self.real - no.real
i = self.imaginary - no.imaginary
return Complex(r, i)
def __mul__(self, no):
# (a+bi)*(c+di) = a*c + a*di + bi*c + bi*di
a = self.real
b = self.imaginary
c = no.real
d = no.imaginary
return Complex(a*c - b*d, a*d + b*c)
def __truediv__(self, no):
# https://arxiv.org/ftp/arxiv/papers/1608/1608.07596.pdf
# alogirthm for real and imaginary parts in link
a = self.real
b = self.imaginary
c = no.real
d = no.imaginary
real_num = (a * c) + (b * d)
imag_num = (b * c) - (a * d)
denom = pow(c, 2) + pow(d, 2)
return Complex(real_num/denom, imag_num/denom)
def mod(self):
return Complex(math.sqrt(pow(self.real, 2) + pow(self.imaginary, 2)), 0)
def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
elif self.real == 0:
if self.imaginary >= 0:
result = "0.00+%.2fi" % (self.imaginary)
else:
result = "0.00-%.2fi" % (abs(self.imaginary))
elif self.imaginary > 0:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
else:
result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
return result
# github.com/ArutselvanManivannan
| false |
924fb3e750ab299c9dcd51a04d57d0efc1ca2ea4 | skaramicke/editpycast | /tools.py | 682 | 4.25 | 4 | def map_range(s: float, a: (float, float), b: (float, float)):
'''
Map a value from one range to another.
:param s: The source value, it should be a float.
:param a: The range where s exists
:param b: The range onto which we want to map s.
:return: The target value, s transformed from between a1 and a2 to between b1 and b2.
'''
(a1, a2), (b1, b2) = a, b
# if target range is zero in size; value is same as top and bottom.
if b1 == b2:
return b1
# if source range is zero in size; place value in middle of target range.
if a1 == a2:
return b1 + abs(b2 - b1) / 2
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
| true |
4cbad57d3c6b0532d573f606b009abb19fbceb0d | BE-THE-BEST/Python_Study | /conditionalSentence.py | 2,973 | 4.1875 | 4 | # <if>
weather=input("์ค๋ ๋ ์จ๋ ์ด๋์?") # ์ฌ์ฉ์์ ์
๋ ฅ๊ฐ ๋ฐ๊ธฐ
if weather=="๋น" or "๋": # ์กฐ๊ฑด
print("์ฐ์ฐ์ ์ฑ๊ธฐ์ธ์") # ์คํ
elif weather=="๋ง์":
print("์ค๋น๋ฌผ์ด ํ์์์ด์")
else:
print("๋ ์จ๋ฅผ ๋ค์ ํ์ธํ์ธ์")
temp=int(input("์ค๋ ๊ธฐ์จ์ด ๋ช ๋์์?"))
if 30<=temp:
print("๋๋ฌด ๋์์")
elif 10<=temp and temp<30:
print("๋ ์จ๊ฐ ์ข์์")
elif 0<=temp and temp<10:
print("์กฐ๊ธ ์ถ์์")
else:
print("๋๋ฌด ์ถ์์, ๋๊ฐ์ง ๋ง์ธ์")
# <for>
for waiting_no in [0,1,2,3,4]:
print("๋๊ธฐ๋ฒํธ: {0}".format(waiting_no))
for waiting_no in range(5): # 0 1 2 3 4
print("๋๊ธฐ๋ฒํธ: {0}".format(waiting_no))
for waiting_no in range(1,6): # 1 2 3 4 5
print("๋๊ธฐ๋ฒํธ: {0}".format(waiting_no))
starbucks=["์์ด์ธ๋งจ", "ํ ๋ฅด", "์์ด์ ๊ทธ๋ฃจํธ"]
for customer in starbucks:
print("์๋: {0}".format(customer))
# <while>
customer="ํ ๋ฅด"
index=5
while index>=1: #์กฐ๊ฑด
print("{0}์ ์ปคํผ๋ {1}์ ๋จ์์ต๋๋ค".format(customer, index))
index-=1
if index==0:
print("์ฃผ๋ฌธํ์ ์ปคํผ๊ฐ ๋ชจ๋ ๋์์ต๋๋ค")
#customer="์์ด์ธ๋งจ"
#while True: # ๋ฌดํ๋ฃจํ
# print("{0}๋์ ์ปคํผ๊ฐ ๋์์ต๋๋ค".format(customer))
customer="ํ ๋ฅด"
person="Unknown"
while person!=customer:
print("{0}๋์ด์๋ผ๋ฉด ์ปคํผ๋ฅผ ๊ฐ์ ธ๊ฐ์ฃผ์ธ์".format(customer))
person=input("์ด๋ฆ์ ์
๋ ฅํด์ฃผ์ธ์.")
# <continue / break>
absent=[2,5] # ๊ฒฐ์ํ ํ์
no_book=[7] #์ฑ
์ ์๊ฐ์ ธ์จ ํ์
for student in range(1,11): #1~10๋ฒ๊น์ง์ ์ถ์๋ฒํธ์์
if student in absent:
continue
elif student in no_book:
print("์ค๋ ์์
์ฌ๊ธฐ๊น์ง, {0}๋ ๊ต๋ฌด์ค๋ก ์ค์ธ์.".format(student))
break
print("{0}๋ฒ ํ์, ์ฑ
์ฝ์ด์ฃผ์ธ์.".format(student))
# ํ ์ค๋ก ๋๋ด๋ for๋ฌธ
# ์ถ์๋ฒํธ๊ฐ 1 2 3 4๋ก ๊ฐ๋๋ฐ ์์ 100์ ๋ํ๊ธฐ๋กํจ
students=[1,2,3,4,5]
print(students)
student=[i+100 for i in students]
print(student)
# ํ์๋ค ์ด๋ฆ์ ๊ธธ์ด๋ก ๋ณํ
students=["Iron man", "Thor", "I am groot"]
students=[i.upper() for i in students]
print(students)
students=[len(i) for i in students]
print(students)
# ๋ฌธ์ .
# ๋๋ ํ์ ๊ธฐ์ฌ์ด๋ค. 50๋ช
์ ์น๊ฐ๊ณผ ๋งค์นญ ๊ธฐํ๊ฐ ์์ ๋, ์ด ํ์น ์น๊ฐ ์๋ฅผ ๊ตฌํด๋ณด์.
# ์กฐ๊ฑด) ์น๊ฐ๋ณ ์ดํ ์์ ์๊ฐ์ 5~50๋ถ ์ฌ์ด ๋์๋ก ์ ํด์ง, ๋๋ 5~15๋ถ ์ฌ์ด ์น๊ฐ๋ง ๋งค์นญ ๊ฐ๋ฅ
from random import *
cnt=0 #์ด ํ์น ์น๊ฐ ์
for i in range (1,51): # 1~50๋ช
์ ์น๊ฐ
time=randrange(5,51) # 5~50๋ถ ์ฌ์ด์ ์์ ์๊ฐ
if 5<=time <=15: # 5~15๋ถ ์ด๋ด ์๋, ๋งค์นญ ์ฑ๊ณต
print("[O] {0}๋ฒ์งธ ์๋ (์์์๊ฐ {1}๋ถ)".format(i, time))
cnt+=1
else: # ๋งค์นญ ์คํจ
print("[ ] {0}๋ฒ์งธ ์๋ (์์์๊ฐ {1}๋ถ)".format(i, time))
print("์ด ํ์น์น๊ฐ", cnt,"๋ช
")
| false |
67107dc72eb55a203ab779b52df685e5ec7c233b | predator1019/CTI110 | /P4HW1_BudgetAnalysis_alexvanhoof.py | 896 | 4.125 | 4 | # program that calculates the users budget expenses and if they went over it or not
# 9/18/18
# CTI-110 P4HW1 - Budget Analysis
# Alex VanHoof
#
userBudget = float(input("please enter how much you have budgeted "+ \
"for the month:"))
moreExpenses = 'y'
usertotalExpenses = 0
while moreExpenses == 'y':
userExpense = float(input('enter an expense:'))
usertotalExpenses += userExpense
moreExpenses = input('do you have more expenses?: Type y '+ \
'for yes, any key for no:')
if usertotalExpenses > userBudget:
print('you were over your budget of',userBudget,'by',usertotalExpenses - \
userBudget)
elif userBudget > usertotalExpenses:
print('you were under your budget of',userBudget,'by',userBudget - \
usertotalExpenses)
else:
print('you used exactly your buget of',userBudget,'.')
| true |
203b87d5cd8b1e6417bd4b7494b301417c59f387 | ShiekhRazia29/Extra_Questions | /Q8.py | 296 | 4.25 | 4 | #Q12 To check the given caracter is an Alphabet,digit or a special case
ch2 = input("Enter any character:")
if(ch2 >= 'A' or ch2 >='Z' or ch2 >='a' or ch2 >='z'):
print("This character is an ALPHABET")
elif (ch2 <=0 or ch2 >=9):
print("DIGIT")
else:
print("SPECIAL CHARACTER") | true |
2d3dd7d8b26f08e5292d4f29eab4a3dcb782f714 | eoinparkinson/basic-library-manager-compsci | /app.py | 2,452 | 4.375 | 4 | # importing libraries
import sys # using this to "END" the program, in theory it's not actually required.
print("Welcome to the coolboy library\nChoose one of three options:\n\n1. View all available books:\n2. Add a book:\n3. Search for a book:\nEND to end the program.\n\n") # opening spiel
# first choice, list all book names
def choiceOne(data):
cleanData = "" # init variable
for item in data: # each item in list, add it to new variable for nice visual list
cleanData += item
print("\n"+cleanData) # print them books
chooseOption() # back to the start
# second choice, add a book
def choiceTwo():
with open("data/books.txt","a") as f: # opening the file in append mode
bookToAdd = input("Enter a book name: ") # getting the book name to add
f.write(bookToAdd+"\n") # appending to the file with newline "\n"
f.close() # closing the file
chooseOption() # back to the start
# third choice, search for a book
def choiceThree(data):
bookToSearch = input("\nEnter a book name: ") # input book name
if bookToSearch+"\n" in data: # checking if book in list and adding "\n" to the item search as this is how .readlines() formats list items.
print("\n'"+bookToSearch+"' exists.\n") # exists
else:
print("\nBook does not exist.\n") # doesn't exist
chooseOption() # back to the start
# function to request choice input --------------------------------------------------
def chooseOption():
with open("data/books.txt","r") as f: # opening & closing the file in this function allows the first option to hot reload
allLines = f.readlines() # reading all lines
f.close() # closing the file
print("Please type either '1', '2' or '3' to continue, or 'END' to close the program.")
option = input("Option: ") # asking user for option, 1,2,3,END
if option == "1":
choiceOne(allLines) # option 1 function
elif option == "2":
choiceTwo() # option 2 function
elif option == "3":
choiceThree(allLines) # option 3 function
elif option == "END": # end the program
sys.exit() # sys library to exit the app
else:
print("\nOption unavailable. Try again.")
chooseOption() # option didn't exist, goes back to the beginning
# call main function ----------------------------------------------------------------
chooseOption()
| true |
bf6dc93b48cbad78a06b5470bbeb0cbf85532f40 | guangcity/learning-algorithm | /ๅ
ๅ/stack_queue/stack_1.py | 1,433 | 4.25 | 4 | class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.l1=[]
self.l2=[]
self.flag=True
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
if not self.flag:
for i in range(len(self.l2)):
self.l1.append(self.l2.pop())
self.flag=True
self.l1.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.flag:
for i in range(len(self.l1)):
self.l2.append(self.l1.pop())
self.flag=False
return self.l2.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.flag:
return self.l1[0]
else:
return self.l2[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if self.flag:
return False if len(self.l1) else True
else:
return False if len(self.l2) else True
# Your MyQueue object will be instantiated and called as such:
obj = MyQueue()
obj.push(1)
obj.push(2)
param_2 = obj.pop()
print(param_2)
param_3 = obj.peek()
print(param_3)
param_4 = obj.empty()
print(param_4)
| false |
b1d014312d4b452c7057d4db132f3f8acc79ed3b | yamogi/Python_Exercises | /ch02/ch02_exercises/ch02_ex02.py | 491 | 4.28125 | 4 | # ch02_ex02.py
#
# Write a program that allows a user to enter his or her two favorite foods.
# The program should then print out the name of a new food by joining the
# original food names together.
#
print("Hi there!")
food_1=input("Please enter one of your favourite foods: ")
print("Great.")
food_2=input("Please enter another one of your favourite foods: ")
print("...")
print("Your new favourite food is: " + food_1 + food_2) # string concatenation
input("\nPress enter to exit.")
| true |
06bb63a937f6c42d3fc60746f9327c42267c0b04 | sethips/python3tutorials | /lists.py | 1,687 | 4.6875 | 5 |
# ways to initiate a tuple
tupleExample = 5, 6, 2, 6
tupleExample1 = (5, 6, 7, 8)
print("Tuple ", tupleExample)
# accessing a tuple's element
print("Second element of tupleExample ", tupleExample[1])
# ways to create a list, use square brackets
listExample = [5, 2, 4, 1]
print("List:", listExample)
# accessing a List's element
print("Third element of list:", listExample[2])
# slicing of data is to get a subset of the list as another list, by providing a range for the index
print("a slice of the data:", listExample[1:4]) # brings up 1, 2 and 3rd element
# we can access the list from the end, using negative index values.
# The last index value is -1 and the last but one is -2 so on and so forth
print("The last element in this list:", listExample[-1])
print("The last but second element in this list:", listExample[-2])
listExample = [5, 2, 4, 1]
print("List:", listExample)
listExample.append(2)
print("2 added to the end of the List:", listExample)
listExample.insert(2, 77)
print("77 inserted at 3rd location in the List:", listExample)
listExample.remove(2) # will remove the first occuring 2 in the list
print("value 2 is removed from the list:", listExample)
listExample.remove(listExample[1]) # will remove the 2nd element of the list
print("2nd element removed from list:", listExample)
# to find the index value of the element 5, it gives the first matching values's index
print("location of 5 in the list:", listExample.index(5))
# to find out the number of occurences of a particular value
print("no of times 2 occurs in the list:", listExample.count(2))
# To sort the list, use the sort function
listExample.sort()
print("Sorted List:", listExample)
| true |
81b7b3cfb37d991de284a855b3de084b3c74e7b0 | tommy-dk/projecteuler | /p12.py | 1,323 | 4.375 | 4 | #!/usr/bin/env python
from math import sqrt
def factors(n):
# 1 and n are automatically factors of n
fact=[1,n]
# starting at 2 as we have already dealt with 1
check=2
# calculate the square root of n and use this as the
# limit when checking if a number is divisible as
# factors above sqrt(n) will already be calculated as
# the inverse of a lower factor IE. finding factors of
# 100 only need go up to 10 (sqrt(100)=10) as factors
# such as 25 can be found when 5 is found to be a
# factor 100/5=25
rootn=sqrt(n)
while check<rootn:
if n%check==0:
fact.append(check)
fact.append(n/check)
check+=1
# this line checks the sqrt of the number to see if
# it is a factor putting it here prevents it appearing
# twice in the above while loop and putting it outside
# the loop should save some time.
if rootn==check:
fact.append(check)
# return an array of factors sorted into numerial order.
fact.sort()
return fact
def calc_triangle(n):
res = 0
for i in xrange(1,n+1):
res += i
return res
i = 0
divisor = [1]
while len(divisor) <= 501:
i += 1
divisor = factors(calc_triangle(i))
print calc_triangle(i)
| true |
8303693c0075d541f530b714ba2dbc1ce7b57bf9 | CiscoDevNet/netprog_basics | /programming_fundamentals/python_part_1/example3.py | 1,884 | 4.59375 | 5 | #! /usr/bin/env python
"""
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 1
Author: Hank Preston <hapresto@cisco.com>
example3.py
Illustrate the following concepts:
- Creating and using dictionaries
- Creating and using lists
- Working with for loops
- Conditional statements
"""
__author__ = "Hank Preston"
__author_email__ = "hapresto@cisco.com"
__copyright__ = "Copyright (c) 2016 Cisco Systems, Inc."
__license__ = "MIT"
# Example Dictionary
author = {"name": "Hank", "color": "green", "shape": "circle"}
# A list of colors
colors = ["blue", "green", "red"]
# A list of dictionaries
favorite_colors = [
{
"student": "Mary",
"color": "red"
},
{
"student": "John",
"color": "blue"
}
]
# Entry point for program
if __name__ == '__main__':
print("The author's name is {}.".format(author["name"]))
print("His favorite color is {}.".format(author["color"]))
print("")
print("The current colors are:")
for color in colors:
print(color)
print("")
# Ask user for favorite color and compare to author's color
new_color = input("What is your favorite color? ")
if new_color == author["color"]:
print("You have the same favorite as {}.".format(author["name"]))
print("")
# See if this is a new color for the list
if new_color not in colors:
print("That's a new color, adding it to the list!")
colors.append(new_color)
# Print update message about the new colors list
message = ("There are now {} colors in the list. ".format(len(colors)))
message += "The color you added was {}.".format(colors[3])
print(message)
else:
pass
| true |
b47ee9b72263f1a4fd7a5090d73f8dd47771bcb8 | joebary/Challenge-Module-2-Columbia | /Module 2 assignments/Starter_Code/qualifier/qualifier/utils/fileio.py | 1,933 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""Helper functions to load and save CSV data.
This contains a helper function for loading and saving CSV files.
"""
import csv
from pathlib import Path
import sys
def load_csv(csvpath):
"""Reads the CSV file from path provided.
Args:
csvpath (Path): The csv file path.
Returns:
A list of lists that contains the rows of data from the CSV file.
"""
with open(csvpath, "r") as csvfile:
data = []
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the CSV Header
next(csvreader)
# Read the CSV data
for row in csvreader:
data.append(row)
return data
def save_csv(qualifying_loans, output_path):
"""
Desc: This function saves all the filtered results,
in a file with .csv type format in a path
that you specify your local computer.
Args:
qualifying_loans (list[lists]): Has all the data to be saved.
output_path (string): Has the final location for it to be saved.
Output:
None There is no output. The file is simply saved to disk.
"""
## check if it is the correct type.
if type(qualifying_loans) != list:
sys.exit("Type error")
# Checking for qualifying loans.
if len(qualifying_loans) == 0:
sys.exit("Oops! There seems to be no qualifying loans, Exiting the program now.")
# creating a path
csvpath = Path(output_path)
# naming the header.
header = ["bank_data", "credit_score", "debt", "income", "loan_amount", "home_value"]
# writing the list of lists as a csv.
with open(csvpath, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
# Write our header row first!
csvwriter.writerow(header)
# Then we can write the data rows
for row in qualifying_loans:
csvwriter.writerow(row) | true |
62c0eb6baa5ce9f8127352ec4e158d8787c897dc | arjungoel/Real-Python | /str_repr_2_demo.py | 500 | 4.375 | 4 | # __str__ vs __repr__
# __str__ is mainly used for giving an easy-to-read representation of your class.
# __str__ is easy to read for human consumption.
# __repr__ is umambiguous and the goal here to be as explicit as possible about what this object is and more meant
# for internal use and something that would make things easier to debug for developer but you wouldn't necessarily
# want to display that to a user.
import datetime
today = datetime.date.today()
print(str(today))
print(repr(today)) | true |
1c99cd2f5d91cb563decb8c8985a96d1acac5c84 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO29.py | 579 | 4.15625 | 4 | # Ejercicio 29
# Celsius a Fahrenheit y Kelvin
# Escriba un programa que comience leyendo la temperatura del usuario en grados
# Celsius. Entonces su programa debe mostrar la temperatura equivalente en grados
# Fahrenheit y grados Kelvin. Los cรกlculos necesarios para convertir entre diferentes
# unidades de temperatura se pueden encontrar en internet.
Celsius = float(input('Ingrese los grados celcius a convertir: '))
K = Celsius + 273.15
F = (9/5) * Celsius + 32
print('El valor en grados Fahrenheit es: ', F)
print('El valor en grados Kelvin es: ', K) | false |
0781530853346c102d97dc03a958b06f2743a2da | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO81.py | 810 | 4.21875 | 4 | # Ejercicio 81
#
# Escribir una funcion que tome la longitud de los dos lados mas cortos de un triangulo rectangulo como argumentos.
# La funcion debe de regresar la hipotenusa del triangulo calculado utiliando el teorema de pitagoras como el resultado de la funcion.
# Incluya un programa principal que lea las longitudes de los lados mas cortos del triangulo rectangulo insertados por el
# usuario, usando la funcion para calcular la longitud de la hipotenusa y qie tambien se despliegue el resultado.
def calcular_hipotenusa(lado1, lado2):
hipotenusa = (lado1**2 + lado2**2)**(0.5)
return hipotenusa
L1 = float(input('Inserta el valor del lado 1: '))
L2 = float(input('Inserta el valor del lado 2: '))
hip = calcular_hipotenusa(L1,L2)
print('La hipotenusa es: ',hip)
| false |
217ce0434583b1cc99869a06e419f9f12a15e8f0 | knight-furry/Python-programming | /x-shape.py | 288 | 4.125 | 4 | num = input("Enter the odd digit number : ")
length = len(num)
if length % 2 != 0 :
for i in range(length):
for j in range(length):
if i==j or i+j==length-1 :
print (num[i],end=" ")
else:
print (" ",end=" ")
print ()
else:
print ("The number is NOT odd digit......!")
| true |
bdfe9405c236a02b47767da3d7cd5ccde339f1bb | knight-furry/Python-programming | /permit.py | 1,134 | 4.28125 | 4 | # Python 3 program to print all permutations with
# duplicates allowed using prev_permutation()
# Function to compute the previous permutation
def prevPermutation(str):
# Find index of the last element
# of the string
n = len(str) - 1
# Find largest index i such that
# str[i ? 1] > str[i]
i = n
while (i > 0 and str[i - 1] <= str[i]):
i -= 1
# if string is sorted in ascending order
# we're at the last permutation
if (i <= 0):
return False
# Note - str[i..n] is sorted in
# ascending order
# Find rightmost element's index
# that is less than str[i - 1]
j = i - 1
while (j + 1 <= n and
str[j + 1] <= str[i - 1]):
j += 1
# Swap character at i-1 with j
str = list(str)
temp = str[i - 1]
str[i - 1] = str[j]
str[j] = temp
str = ''.join(str)
# Reverse the substring [i..n]
str[::-1]
return True, str
# Driver code
if __name__ == '__main__':
str = "fjadchbegi"
b, str = prevPermutation(str)
if (b == True):
print("Previous permutation is", str)
else:
print("Previous permutation doesn't exist")
# This code is contributed by
# Sanjit_Prasad
| true |
c2fa6cb63efe6e4d6ea38fa45e441fdb4af847cb | cvlg-dev/wy-til | /anything-python/advanced-python/chp03-02.py | 1,002 | 4.59375 | 5 | # ๋งค์ง๋งค์๋๋ฅผ ํตํ ๋ฒกํฐ ์ฐ์ฐ ์์
class Vector:
def __init__(self, *args):
"""
Create a vector, example: v = Vector(5, 10)
"""
if len(args) == 0:
self._x, self._y = 0, 0
else:
self._x, self._y = args
def __repr__(self):
"""
Return vector informations.
"""
return "Vector(%r, %r)" % (self._x, self._y)
def __add__(self, other):
"""
Return vector addition of self and other
"""
return Vector(self._x + other._x, self._y + other._y)
def __mul__(self, y):
return Vector(self._x * y, self._y * y)
def __bool__(self):
return bool(max(self._x, self._y))
v1 = Vector(5, 8)
v2 = Vector(25, 20)
v3 = Vector()
print(Vector.__init__.__doc__)
print(Vector.__repr__.__doc__)
print(Vector.__add__.__doc__)
print(v1, v2, v3)
# ์ฐ์ฐ
print(v1 + v2)
print(v1 * 3)
print(v2 * 10)
print(bool(v1), bool(v2))
print(bool(v3))
| false |
ed07a08f36e349ec938df07c2eb02aeafa32a043 | abvillain22/python | /SubFun.py | 239 | 4.25 | 4 | import re
str1="hello, welcome in the world of python"
pattern1="hi"
pattern2="hello"
print((re.sub(pattern2,pattern1,str1)))
#the sub fun in the re module can be used to search a pattern in the string and replace it with another string
| true |
71d2238b97e5836cc4429dd62c194e2ec34e6566 | 3228689373/excercise_projecteuler | /sum_of_mul_of_3or5.py | 487 | 4.125 | 4 | def sum_of_mul_of_3or5(n=1000):
'''
https://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
arr = list(range(1,n+1))
arr3 = list(filter(lambda ele:ele%3==0,arr))
arr5 = list(filter(lambda ele:ele%3==0,arr))
arr = arr3 + arr5
rslt = sum(arr)
return(sum)
| true |
c5a59b325a2b01ffccab8ccb84affa2246d2c038 | DracoHawke/python-assignments | /Assignment4/Assignment4.py | 2,024 | 4.5625 | 5 | import copy as c
# Q.1 - Reverse the whole list using list methods.
# A.1 ->
num = int(input("Enter the number of elements\n"))
print("Enter the elements")
list1 = []
for i in range(0, num):
ele = int(input())
list1.append(ele)
print(list1)
print("Reversed list is: ")
list1.reverse()
print(list1)
# Q.2 - Print all the uppercase letters from a string.
# A.2 ->
print("enter string")
str1 = input()
final_str = ""
for i in str1:
if i.isupper():
final_str = final_str + i
print("characters in upperCase are: ", final_str)
# Q.3 - Split the user input on comma's and store the values in a list as integers
# A.3 ->
str1 = input("Enter the numbers with commas in between\n")
list1 = []
list1 = str1.split(",")
print("List : ", list1)
# Q.4 - Check whether a string is palindromic or not.
# A.4 ->
print("Enter a string")
str1 = input()
rev = "".join(reversed(str1))
print("str1: ", str1, "rev: ", rev)
if str1 == rev:
print("String is Palindrome")
else:
print("String is not Palindrome")
# Q.5- Make a deepcopy of a list and write the difference between shallow copy and deep copy.
# A.5(a) ->
# DeepCopy
list1 = [1, 2, [3, 4, 5], 6, 7, 8, 9, 10]
list2 = c.deepcopy(list1)
print('List 1: ', list1)
print('List 2(deepcopy of list 1): ', list2)
list2[2][1] = 11
print('After changing List 2')
print('List 1: ', list1)
print('List 2(deepcopy of list 1): ', list2)
print(" ")
# A.5(b) ->
# ShallowCopy
list1 = [1, 2, [3, 4, 5], 6, 7, 8, 9, 10]
list2 = c.copy(list1)
print('List 1: ', list1)
print('List 2(Shallow copy of list 1): ', list2)
list2[2][1] = 11
list2[2][2] = 12
print('After changing List 2')
print('List 1: ', list1)
print('List 2(Shallow copy of list 1): ', list2)
# DIFFERENCE
# Changes made in deep copy of a list are never reflected in the original list
# where as changes made in shallow copy of a list are always reflected in original list.
# In deep copy copy of object is copied to other object where as in shallow copy
# reference of object is copied in other object
| true |
e755e47cc4c5d15ec9c3c0d0b2c9afa97c3baa62 | SebastianG343/LaboratorioFuncionesRemoto | /is_prime3.py | 580 | 4.1875 | 4 | def is_prime():
x=0
n=int(input("Digite un numero"))
try:
while n!=0 and n>0:
n=int(input("Digite un numero"))
if n%n==0 and n%1==0:
if n==4:
print("Is NOT a prime number")
if n>3 and n%2==0 or n%3==0 and n!=4:
print("Is Not a prime number")
print(0)
x+=1
else:
print("Is a prime number")
print(1)
except ValueError:
print(-1)
return(-1)
is_prime() | false |
069dc38c40f3a0223c8dd650c65a60ce172601e2 | HenrryHernandez/Python-Projects | /DataStructuresUdacity/Trees/tree order/binaryTree.py | 1,853 | 4.15625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
self.nodes = ""
def search(self, find_val):
"""Return True if the value
is in the tree, return
False otherwise."""
return self.preorder_search(self.root, find_val)
def print_tree(self):
"""Print out all tree nodes
as they are visited in
a pre-order traversal."""
self.preorder_print(self.root)
print(self.nodes[:-1])
def preorder_search(self, start, find_val):
"""Helper method - use this to create a
recursive search solution."""
# if find_val == start.value:
# return True
#
# if start.left:
# if self.preorder_search(start.left, find_val):
# return True
#
# if start.right:
# if self.preorder_search(start.right, find_val):
# return True
#
# return False
if start:
if find_val == start.value:
return True
else:
return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val)
return False
def preorder_print(self, start):
"""Helper method - use this to create a
recursive print solution."""
self.nodes += "{}-".format(start.value)
if start.left:
self.preorder_print(start.left)
if start.right:
self.preorder_print(start.right)
n1 = Node(1)
n2 = Node(3)
n3 = Node(5)
n4 = Node(7)
n5 = Node(9)
b1 = BinaryTree(n1)
b1.root.left = n2
b1.root.right = n3
b1.root.left.left = n4
b1.root.right.right = n5
print(b1.search(1))
b1.print_tree()
| true |
6c09b38d0502bdedee9dc1c42c890511f9d3a79f | RizkiAsmoro/python | /File-Handling/File_handling.py | 1,136 | 4.4375 | 4 | '''
"w" - Write
"r" - Read
"a" - Append
"x" - Create
"r+"- write and read mode
'''
#write mode 'w' - Opens a file for writing,
#creates the file if it does not exist
file = open("data.txt","w")
file.write("This is data text, created by python")
file.write("\nthis is 2nd row data text")
file.write("\nthis is 3rd row data text")
file.close() #need close tomakesure data.txt saved in write mode
#read mode 'r' - Default value. Opens a file for reading,
#error if the file does not exist
file2 = open("data.txt","r")
#print(file2.read()) # it will read all content data if .read(10) its mean will read 10 character
print(file2.readline()) # read data by line
file2.close()
#append mode 'a' - Opens a file for appending,
#creates the content data if it does not exist
file3 = open("data.txt","a")
file3.write("\nthis text made using append")
file3.close()
#create 'x' - Creates the specified file,
#file4 = open("data.txt","x") #returns an error if the file exists
file4 = open("data2.txt","x") #
file4.write("data create by mode create 'x'")
file4.write("\ndelete the data2.txt before running the program")
file4.close()
| true |
42d5c1f18bbe06f5db0f414ead1e6f2cb789fd56 | RizkiAsmoro/python | /For_loop2.py | 1,434 | 4.125 | 4 | '''
FOR,Else Loop
Continue, pass
'''
# print range number
print(20*"=","RANGE")
for i in range(0,5):
print(i)
print(20*"=","range increment")
for i in range (10,30,5): #range 10 to 30, increment 5
print(i)
# For Else
print(20*"=","FOR ELSE")
number = 3
for i in range (1,6):
print(i) # print range number 1 to 5
if i is number:
print("number",number," was found")
break # 'break' to exit from 'if' condition
else: # 'else' still inside 'for loop' condition
print("number not found")
#BREAK
print(20*"=","BREAK")
for y in range(1,6):
if y is 2:
print("number found :",2)
break # when the number was found, break will ended proccess of loop and out of loop
print("check")
print("number",y)
else:
print("end of loop")
print("out of loop")
#continue
print(20*"=","CONTINUE")
for x in range(1,6):
if x is 3:
print("number found",3)
continue # when the number has been found, continue the looping proccess until end of range then out of loop
print("check")
print("number",x)
else:
print("end of loop")
print("out of loop")
#pass
print(20*"=","PASS")
for z in range(1,6):
if z is 2:
print("number found",2)
pass # when number was found, pass will print check then continue procces until loop proccess ended
print("check")
print("number",z)
else:
print("end of loop")
print("out of loop")
| true |
4ffe624d4ca2a7fc52fbf496a87a5036688cb5e6 | chiayinf/MastermindGame | /count_bulls_and_cows.py | 2,291 | 4.34375 | 4 | '''
CS5001
Spring 2021
Chiayin Fan
Project: A python-turtule built mastermind game
'''
def count_bulls_and_cows(secret_code, guess):
'''
function: count_bulls_and_cows: count how many black and red pegs the player has
parameters: secret_code: 4 colors secret code list
guess: 4 colors player guess list
return: a 2-tuple (a tuple with two elements) \
containing the number of bulls and cows by comparing with the secret code.
'''
# Red pegs meant a correct color but out of position, black pegs meant a correct color in the correct position.
red, black = 0, 0
# Loop through the secret code to check the correctness
for i in range(len(secret_code)):
# If the color and the position are correct, get one black peg
if secret_code[i] == guess[i]:
black += 1
# If the color is correct but the position is not, get one red peg
elif secret_code[i] in guess:
red += 1
return (red, black)
def write_msg(score, name):
'''
function: write_msg, add new record(score and name)
parameter: score: the player's score
name: the player's name
'''
# Open the leaderboard.txt in append mode
with open("leaderboard_test.txt", "a") as outfile:
# Add new record(score and name)
outfile.write(str(score) + ' ' + name + '\n')
def read_msg():
'''
function: read_msg, read the text on leaderboard_test.txt,
the same as read_msg in mastermind_game without turtle part
parameter: None
return: ranking: a sorted ranking list
'''
try:
# Open the leaderboard.txt in read mode
with open("leaderboard_test.txt", "r") as inFile:
ranking = []
# Append name and score to the ranking list
for each in inFile:
score, name = each.split(' ')
ranking.append([score, name[:-1]])
# Sort the ranking list so lower score comes first
ranking.sort()
# If there are more than 10 records, remove worse records. Only save the top ten record
if len(ranking) > 10:
ranking = ranking[:10]
return ranking
except OSError:
print('An error happens')
| true |
0630bc008d61731144e41d2da5a473b929530d3d | guyrux/udacity_statistics | /Aula 25.29 - Extract First Names.py | 322 | 4.46875 | 4 | '''
Quiz: Extract First Names
Use a list comprehension to create a new list first_names containing just the first names in names in lowercase.
'''
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names = [name.lower().split()[0] for name in names] # write your list comprehension here
print(first_names) | true |
996dbf33c8f16d6f99d714c49c9039af0d8f4514 | Potokar1/Python_Review | /sorting_algorithms/quick_sort.py | 2,546 | 4.3125 | 4 | # Select a pivot, which we will use to split the list in half by comparing every other number to the pivot
# We will end up with a left partition and a right partition. Best splits list in half
# This can be better if there is less than a certain amount of values, then we can use selection sort
# Helps the user by just letting them pass in the list to be sorted.
# Parameter a is a list
def quick_sort_helper(a):
quick_sort(a, 0, len(a)-1)
return a
# The recursive method
# Parameter a is a list
# low is the low index
# high is the high index
def quick_sort(a, low, high):
# If there is more than one item to be sorted
if low < high:
# Most of the work, returns the pivot
pivot = partition(a, low, high)
# All items left of the pivot
quick_sort(a, low, pivot-1)
# All items right of the pivot
quick_sort(a, pivot+1, high)
# Parameter a is a list
# low is the low index
# high is the high index
def partition(a, low, high):
# We get out pivot, which returns the pivot index
pivot_index = get_pivot(a, low, high)
# Get the pivot value which we are going to use to make out comparisons
pivot_value = a[pivot_index]
# Swap the pivot value into the left most position of our list
a[pivot_index], a[low] = a[low], a[pivot_index]
# Set a border which is where we replace any items in the list that is less than the pivot_value
border = low
# Iterate through our list from low to high
for i in range(low, high+1):
# If the item is less than the pivot-value, we swap it with out border value,
# so border is the control point where left of border is < pivot_value
if a[i] < pivot_value:
border += 1
a[i], a[border] = a[border], a[i]
# When we are done, we swap out low value, which is the pivot_value, into the border position.
a[low], a[border] = a[border], a[low]
# Return border which is the index for the pivot
return border
# Parameter a is a list
# low is the low index
# high is the high index
def get_pivot(a, low, high):
# Get the middle index
mid = (high + low) // 2
pivot = high
# These if elif does comparisons to choose the middle (median not mean) of the three indecies
if a[low] < a[mid]:
if a[mid] < a[high]:
pivot = mid
elif a[low] < a[high]:
pivot = low
return pivot
list = [9, 6, 2, 4, 8, 3, 5, 10, 7, 1]
print(quick_sort_helper(list))
| true |
8fc9d5a8e60bcac345468ed59382ee1848061d2b | Potokar1/Python_Review | /data_structures/stack_divide_by_two.py | 896 | 4.40625 | 4 | '''
Use a stack data structure to convert integer values to binary
Example: 242 (I learned this in class!) (bottom up of remainder is bin of 242)
remainder
242 / 2 -> 0
141 / 2 -> 1
60 / 2 -> 0
30 / 2 -> 0
15 / 2 -> 1
7 / 2 -> 1
3 / 2 -> 1
1 / 2 -> 1
'''
from stack import Stack
# Divides a number by two in order to get the remainder
def div_by_2(dec_num):
s = Stack()
# While the interger value of the number is greater than zero
while dec_num > 0:
remainder = dec_num % 2
# Put the lsb - msb in the stack so we can pop() off in correct order
s.push(remainder)
dec_num = dec_num // 2
bin_num = ''
# Get the bits from msb to lsb from the stack to get the bin rep of the integer
while not s.is_empty():
bin_num += str(s.pop())
return bin_num
print(div_by_2(242))
| true |
9b2f97a9a34750879cde3e23fb3219211e31638f | Jcarlos0828/py4eCourses-excercisesCode-solved | /Using Databases with Python/Week 2/countEmailWithDB.py | 1,382 | 4.3125 | 4 | #Code Author: Josรฉ Carlos del Castillo Estrada
#Excercise solved from the book "Python for Everybody" by Dr. Charles R. Severance
#Following the Coursera program "Using Databases with Python" by the University of Michigan
'''
Count the number of emails sent by each domain and order them in a DESC way.
The data extracted is obtained from mbox.txt
'''
import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = input('Enter file name: ')
if (len(fname) < 1): fname = 'mbox.txt'
count = 0
fh = open(fname)#r'C:\users\Path\file\Using Python Databases with Python\Week 2\mbox.txt')
for line in fh:
if not line.startswith('From: '): continue
count = count + 1
pieces = line.split()
email = pieces[1].split('@')
org = email[1]
cur.execute('SELECT count FROM Counts WHERE org = ? ', (org,))
row = cur.fetchone()
if row is None:
cur.execute('''INSERT INTO Counts (org, count)
VALUES (?, 1)''', (org,))
else:
cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',
(org,))
# https://www.sqlite.org/lang_select.html
conn.commit()
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
for row in cur.execute(sqlstr):
print(str(row[0]), row[1])
print(count)
cur.close() | true |
7ab6ac45fce569df75e799346005eb9b15f51277 | lucassilva-dev/codigo_Python | /ex041.py | 600 | 4.21875 | 4 | from datetime import date
ano = int(input('Qual o ano em que vocรช nasceu? '))
dataatual = date.today()
idade = dataatual.year-ano
if idade <= 9:
print('Vocรช tem {} anos, estรก na categoria MIRIM'.format(idade))
elif idade <= 14:
print('Vocรช tem {} anos, estรก na categoria INFANTIL'.format(idade))
elif idade <= 19:
print('Vocรช tem {} anos, estรก na categoria JUNIOR'.format(idade))
elif idade <= 20:
print('Vocรช tem {} anos, estรก na categoria SรNIOR'.format(idade))
else:
print('Vocรช tem {} anos, estรก na categoria MASTER a maior categoria'.format(idade))
| false |
6542bb2afe9b53282b8276a06ef142874aaa8fb2 | marquesarthur/programming_problems | /leetcode/regex/mini_parser.py | 2,397 | 4.21875 | 4 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
class NestedInteger(object):
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
self._int = None
self._elements = None
if value:
self.setInteger(value)
else:
self._elements = []
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
def add(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""
def setInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""
def getInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
class Solution(object):
def deserialize(self, s):
"""
:type s: str
:rtype: NestedInteger
"""
if "," in s:
head = NestedInteger(value=int(s[1:s.index(",")]))
tail = Solution().deserialize(s[s.index(",") + 1:len(s) - 1])
result = NestedInteger()
result.add(head)
result.add(tail)
return result
else:
return NestedInteger(value=int(s.replace("[", "").replace("]", "")))
# Given
s = "324"
Solution().deserialize(s)
# You should return a NestedInteger object which contains a single integer 324.
# Given
s = "[123,[456,[789]]]"
Solution().deserialize(s)
# Return a NestedInteger object containing a nested list with 2 elements:
#
# 1. An integer containing value 123.
# 2. A nested list containing two elements:
# i. An integer containing value 456.
# ii. A nested list with one element:
# a. An integer containing value 789. | true |
c4d0acf509af5620273ae604f23777776fc1baf9 | gcharade00/programs-hacktoberfest | /lenlist.py | 431 | 4.4375 | 4 | # Python code to demonstrate
# length of list
# using naive method
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
# Printing test_list
print ("The list is : " + str(test_list))
# Finding length of list
# using loop
# Initializing counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
print ("Length of list using naive method is : " + str(counter))
| true |
a8575326c07c78421ad1340f45c36b51958dc2a8 | drussell1974/a-level | /recursion/recursion_factorial.py | 437 | 4.28125 | 4 | def iterative_factorial(num):
factorial = 1
for x in range(1, num+1):
factorial = factorial * x
return factorial
def recursive_factorial(num):
if num < 2:
""" stop the recursion when num = 1 or less """
return 1
else:
""" recursive call """
return num * recursive_factorial(num-1) # num - 1 will stop the recursion
#print(iterative_factorial(5))
print(recursive_factorial(1)) | true |
9c37992199846681936822ba20f99e7178ace550 | SobrancelhaDoDragao/Exercicio-De-Programacao | /Exercicios-Python/Basico/Exercicios/exercicio25.py | 233 | 4.21875 | 4 | # Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
nome = input("Digite um nome: ").upper()
if nome.find("SILVA") != -1:
print("O nome possui silva")
else:
print("O nome nรฃo possui silva")
| false |
caffd24184b954254165bfc744aa6eb0f48f50bc | SobrancelhaDoDragao/Exercicio-De-Programacao | /Exercicios-Python/Basico/Exercicios/exercicio41.py | 918 | 4.21875 | 4 | # A confederaรงรฃo Nacional de Nataรงรฃo precisa de um programa que leia o ano de nascimento
# de um atleta e mostre sua categoria, de acordo com a idade:
# Atรฉ 9 anos: MIRIM
# Atรฉ 14 anos: INFANTIL
# Atรฉ 19 anos: JUNIOR
# Atรฉ 20 anos: SรNIOR
# Acima: MASTER
from datetime import date
print('-'*20)
nascimento = int(input('Digite o ano do nascimento: '))
ano_atual = date.today().year
idade = ano_atual - nascimento
if idade <= 9:
print('O atleta tem {} anos, e sua classificaรงรฃo รฉ JUNIOR!'.format(idade))
elif idade <= 14:
print('O atleta tem {} anos, e sua classificaรงรฃo รฉ INFANTIL!'.format(idade))
elif idade <= 19:
print('O atleta tem {} anos, e sua classificaรงรฃo รฉ JUNIOR!'.format(idade))
elif idade <= 25:
print('O atleta tem {} anos, e sua classificaรงรฃo รฉ SรNIOR!'.format(idade))
else:
print('O atleta tem {} anos, e sua classificaรงรฃo รฉ MASTER!'.format(idade))
| false |
e94ad71067de273a105041d9c8e516661fabc62c | SobrancelhaDoDragao/Exercicio-De-Programacao | /Exercicios-Python/Basico/Exercicios/mostrando_tipo.py | 663 | 4.25 | 4 | # -*- coding: utf-8 -*-
# Mostrando o tipo do valor recebido -----
#------------------------------------------------------------------
#------------------------------------------------------------------
# Indepedente do que for digitado o valor serรก um string
# Por isso รฉ necessรกrio formatar o valor com o int
valor = input("Digite um valor: ")
print (type(valor))
#Convertendo para float
valor1 = float(input("Digite um valor: "))
print("Esse รฉ o valor: {} convertido para float".format(valor1))
#Convertendo para boleano
valor2 = bool(input("Digite um valor :"))
print("Esse รฉ: {} o valor convertido para boleano".format(valor2))
| false |
8f208e7c3c0aec9b5264244d75e0969e9ac30cd5 | SobrancelhaDoDragao/Exercicio-De-Programacao | /Exercicios-Python/Basico/Exercicios/exercicio53.py | 510 | 4.15625 | 4 | # Crie um programa que leia uma frase qualquer e diga se ela รฉ um
# palรญdromo, desconsiderando os espaรงos
# EX:
# Apรณs a sopa
# A sacada da casa
# A torre da derrota
# O lobo ama o bolo
# Anotaram a data da maratona
frase = str(input("Digite uma frase: "))
inverso = frase[::-1]
if frase == inverso:
print("A frase '{}' รฉ exatamente igual ao seu inverso: '{}'".format(frase,inverso))
print("Portando รฉ um polรญdromo")
else:
print("A frase '{}' nรฃo รฉ um polรญdromo".format(frase))
| false |
c171054c698c293d887a043f832cca3323fe3518 | abaah17/Programming1-examples | /w12s1_rps.py | 1,617 | 4.53125 | 5 | # This example will show case various ways to create a rock paper scissors program
# using functions from the random library
# More information here:
from random import *
# In this approach, we pick a random number between 1 and 3, then connect each number with a
# move in an if statement:
def taiwo_bot():
x = randint(1, 3)
if x == 1:
return 'rock'
elif x == 2:
return 'paper'
else:
return 'scissors'
# In this approach, we put all the moves in a list, then we randomly generate an index
def nehemie_bot():
moves = ['rock', 'paper', 'scissors']
random_index = randint(0, len(moves) - 1)
return moves[random_index]
# Note the choice method from the random library does the same as the above, just in 1 line.
def nadia_bot():
moves = ['rock', 'paper', 'scissors']
return choice(moves)
# Finally, we can use random to give each outcome a specific probability
# Below is an example of
def joyce_bot():
x = random()
if x < 0.5:
return 'rock'
elif x < 0.75:
return 'paper'
else:
return 'scissors'
def rps_rules(move1, move2):
if move1 == move2:
print("It's a tie!")
elif (move1 == 'rock' and move2 == 'paper') or \
(move1 == 'paper' and move2 == 'scissors') or \
(move1 == 'scissors' and move2 == 'rock'):
print('Player 2 wins!')
else:
print('Player 1 wins!')
# rps_rules('paper', rps_bot())
rps_rules('rock',taiwo_bot())
# rps_rules('rock', 'rock')
# rps_rules('paper', 'paper')
# rps_rules('scissors', 'scissors')
# rps_rules('rock', 'scissors')
| true |
73cb2e4ada1d9727b65198ef1f7152adeda5067a | abaah17/Programming1-examples | /w7s1_string_demo.py | 1,173 | 4.21875 | 4 | alu_quote = "take ownership"
# Indexing into Strings
print(alu_quote[10])
# Length of String: len returns how many characters are in a string
# Think of a character as the act of typing a key. Spaces and punctuation are characters too!
print(len(alu_quote))
# Strings are immutable
# The following line will trigger an error
#alu_quote[0] = 'T'
# print each character in the String:
counter = 0
while (counter <= len(alu_quote) - 1):
print(alu_quote[counter])
counter = counter + 1
# Demonstrate startswith
print(alu_quote.startswith("take ownership"))
print(alu_quote.startswith("ta"))
# Demonstrate the "in" syntax
# "some string" in "the main string" will return true or false
# depending on whether the sequence "some string" can be found, in the exact order, in the main string
test = "t" in alu_quote and "k" in alu_quote
print(test)
# Lots of functions return booleans based on what kind of string we have
text = "fourteen"
print(text.isnumeric())
print(text.isalnum())
print(text.isalpha())
# Demonstrate 'split'
student_info = "Salmane, Tamo, Niger, ALC Mauritius"
print(student_info)
result = student_info.split(' ')
print(result)
print(alu_quote.split(" "))
| true |
6064cd6b129e1896ffc803734bd2ec79bae75b65 | cauequeiroz/MITx-6.00.1x | /week2/is_in_recursive.py | 824 | 4.125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if aStr == '':
return False
if len(aStr) == 1:
return aStr == char
middle_pos = int(len(aStr)/2)
if aStr[middle_pos] == char:
return True
elif aStr[middle_pos] > char:
return isIn(char, aStr[:middle_pos])
elif aStr[middle_pos] < char:
return isIn(char, aStr[middle_pos:])
print(isIn('a', 'abcdef')) # => True
print(isIn('b', 'abcdef')) # => True
print(isIn('c', 'abcdef')) # => True
print(isIn('d', 'abcdef')) # => True
print(isIn('e', 'abcdef')) # => True
print(isIn('f', 'abcdef')) # => True
print(isIn('g', 'abcdef')) # => False
print(isIn('g', 'g')) # => True
print(isIn('g', '')) # => False | false |
5a3b728b655f7f82c4aecf90ef8066e311119e69 | a55779147/Notes | /Python3/Fluent Python ็ซ ่ๆป็ป/chapter1/2.py | 957 | 4.3125 | 4 | # ๅฎ็ฐไธไธชๅ้็ฑปVector
# ไฝฟๅ
ถๅฎ็ฐ + - *
from math import hypot
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __sub__(self, other):
x = self.x - other.x
y = self.y - other.x
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __abs__(self):
# ่ฟๅๆฌงๆฐๆน็จ๏ผsqrt๏ผx * x + y * y๏ผ
return hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __repr__(self):
return "Vector(%r, %r)" % (self.x, self.y)
# return "Vector({}, {})".format(self.x, self.y)
# __init__
v1 = Vector(1, 2)
print(v1)
# __add__
v2 = v1 + v1
print(v2)
# __sub__
v3 = v2 - v1
print(v3)
# __mul__
v4 = v1 * 2
print(v4)
# __bool__
print(bool(v4))
| false |
aba6b636759d7bbd52f488da76d3307a72df5757 | perryriggs/Python | /mindstorms.py | 1,534 | 4.46875 | 4 | #mindstorms - from the book by the same name
import turtle
#define a function to draw a square
def draw_square(t):
x = 1
while x <= 4:
t.right(90)
t.forward(100)
x = x+1
# define a function to draw a circle
def draw_circle():
circ = turtle.Turtle()
circ.shape("arrow")
circ.color("blue")
circ.speed(4)
circ.circle(100)
#define a function to draw a triangle
def draw_triangle(tri):
tri.forward(100)
tri.left(160)
tri.forward(100)
tri.left(100)
tri.forward(34.73)
tri.left(100)
#define a function that drawsa circle from squares
def draw_circ_with_squares(t, angle_increment):
curr_angle = 0
while curr_angle < 360:
draw_square(t)
t.right(angle_increment)
curr_angle = curr_angle+angle_increment
#define a function to draw a flower from triangle
def draw_flower_with_triangle(t,angle_increment):
curr_angle = 0
while curr_angle <= 360:
draw_triangle(t)
t.left(angle_increment)
curr_angle = curr_angle+angle_increment
t.right(100)
t.forward(200)
#start exeuction of the program
window = turtle.Screen()
window.bgcolor("red")
#sqr = turtle.Turtle()
#sqr.shape("turtle")
#sqr.color("green")
#sqr.speed(10)
#draw_circ_with_squares(sqr,6)
#draw_square(sqr)
#draw_circle()
tri = turtle.Turtle()
tri.shape("arrow")
tri.color("white")
tri.speed(15)
#draw_triangle(tri)
draw_flower_with_triangle(tri,10)
window.exitonclick()
print("Program mindstorms.py has completed")
| true |
d6674bf9af185d6ac97df47396f46ace4af3adef | dgranillo/Projects | /Classic Algorithms/sorting.py | 1,698 | 4.3125 | 4 | #!/usr/bin/env python2.7
"""
Sorting - Implement two types of sorting algorithms: Merge sort and bubble
sort.
Author: Dan Granillo <dan.granillo@gmail.com>
ToDo: Merge sort does not append remaining values from one half if the other's
counter has reached the limit. Generally 2nd half's last number is ommitted.
Bubble sort would be more efficient if instead of running max iterations,
results were compared to originalList.sort()
"""
import random
def genNums(x, y):
nums = [random.randrange(x, y) for i in range(20)]
print 'Random: ', nums
return nums
def mergeSplit(nums):
half1 = [nums[i] for i in range(len(nums)/2)]
half2 = [nums[i] for i in range(len(nums)/2, len(nums))]
return (half1,half2)
def mergeConquer(halves):
half1 = sorted(halves[0])
half2 = sorted(halves[1])
return (half1, half2)
def mergeCombine(halves):
mergedNums = []
half1 = halves[0]
half2 = halves[1]
i,j = 0,0
while i < len(half1) and j < len(half2):
if half1[i] <= half2[j]:
mergedNums.append(half1[i])
i += 1
else:
mergedNums.append(half2[j])
j += 1
print 'Merged: ',mergedNums
def bubbleSort(nums):
pivot = 0
for x in range(len(nums)):
i = 0
j = 1
while j < len(nums):
if nums[i] <= nums[j]:
i += 1
j += 1
else:
pivot = nums[i]
nums[i] = nums[j]
nums[j] = pivot
i += 1
j += 1
print 'Bubble: ',nums
if __name__ == '__main__':
mergeCombine(mergeConquer(mergeSplit(genNums(0,100))))
bubbleSort(genNums(0,100)) | true |
f1369ab1fe6a5f6648c5100bf7c92a0a2b0bc432 | obrunet/Apprendre-a-programmer-Python3 | /07.05.max_of_3num.py | 655 | 4.15625 | 4 | # Dรฉfinissez une fonction maximum(n1,n2,n3) qui renvoie le plus grand de 3 nombres n1, n2, n3 fournis en arguments.
# Par exemple, lโexรฉcution de lโinstruction : print(maximum(2,5,4)) doit donner le rรฉsultat : 5
def maximum (a, b, c):
max = a
if a < b:
max = b
if b < c:
max = c
return (max)
def main():
print("Enter a first nb:", end=" ")
a = float (input())
print("Enter a second nb:", end=" ")
b = float (input())
print("Enter a third nb:", end=" ")
c = float (input())
print("The maximum is equal to:", maximum(a, b, c))
if __name__ == "__main__":
main() | false |
5b0473d6043a2e689d0d29719112b1754d37aa7d | obrunet/Apprendre-a-programmer-Python3 | /12.05.circle.py | 1,659 | 4.3125 | 4 | # Dรฉfinissez une classe Cercle(). Les objets construits ร partir de cette classe seront des cercles de tailles variรฉes.
# En plus de la mรฉthode constructeur (qui utilisera donc un paramรจtre rayon), vous dรฉfinirez une mรฉthode surface(), qui devra renvoyer la surface du cercle.
# Dรฉfinissez ensuite une classe Cylindre() dรฉrivรฉe de la prรฉcรฉdente.
# Le constructeur de cette nouvelle classe comportera les deux paramรจtres rayon et hauteur.
# Vous y ajouterez une mรฉthode volume() qui devra renvoyer le volume du cylindre (rappel : volume dโun cylindre = surface de section ร hauteur).
# Exemple dโutilisation de cette classe :
# >>> cyl = Cylindre(5, 7)
# >>> print(cyl.surface()) 78.54
# >>> print(cyl.volume()) 549.78
class Circle(object):
"Circle class definition"
def __init__(self, name, radius):
"Initializes a Circle object"
self.name = name
self.radius = radius
def area(self):
"Returns the circle area"
return(3.14 * self.radius **2)
class Cylinder(Circle):
"Cylinder class definition"
def __init__(self, name, base_radius, height):
"Initializes a Cylinder object"
Circle.__init__(self, name, base_radius)
self.height = height
def volume(self):
"Retunrs the cylinder volume"
return(self.height * self.area())
if __name__ == "__main__":
cyl = Cylinder('cyl_dude', 5, 7)
print("The area of the cylinder named '{}' is equal to: {:.1f}".format(cyl.name, cyl.area()))
print("The volume of the cylinder named '{}' is equal to: {:.1f}".format(cyl.name, cyl.volume())) | false |
4d8f3af5a231a15714a41d95a036839ebb420c5e | obrunet/Apprendre-a-programmer-Python3 | /06.12.sqrt__not_corrected__.py | 453 | 4.15625 | 4 | # Demander ร lโutilisateur quโil entre un nombre.
# Afficher ensuite : soit la racine carrรฉe de ce nombre,
# soit un message indiquant que la racine carrรฉe de ce nombre ne peut รชtre calculรฉe.
from math import sqrt
print("Enter a floating number", end=" ")
nb=float(input())
if nb<0:
print("The square root of a negative number cannot be calculated!")
else:
print("The square root of this number is equal to ", sqrt(nb)) | false |
a5336d2b84c265d219e64313929cb2a8370f7a9b | obrunet/Apprendre-a-programmer-Python3 | /10.32.longest_word_in_sentence___not_corrected___.py | 525 | 4.125 | 4 | # รcrivez un script qui recherche le mot le plus long dans une phrase donnรฉe
# (lโutilisateur du programme doit pouvoir entrer une phrase de son choix).
inputStr = input("Enter a long sentence with serveral words: ")
inputList = inputStr.split(" ")
# print(inputList)
longest_word, length = "", 0
for word in inputList:
if len(word) > length:
length = len(word)
longest_word = word
result = "The longest word is {} with {} char"
print(result.format(longest_word, len(longest_word))) | false |
f551c16169e31061b1f8c8b26f7dd56bd3b8b716 | obrunet/Apprendre-a-programmer-Python3 | /07.11.name_of_the_month.py | 579 | 4.125 | 4 | # Dรฉfinissez une fonction nomMois(n) qui renvoie le nom du n-iรจme mois de lโannรฉe.
# Par exemple, lโexรฉcution de lโinstruction :
# print(nomMois(4)) doit donner le rรฉsultat : Avril.
monthList = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
def nameMonth (index):
return (monthList[index-1])
def main():
print("Choose the number of a month in year:", end=" ")
print("The corresponding month is", nameMonth(int(input())))
if __name__ == "__main__":
main() | false |
175c0fad6f626e3c813cf55450b581f73b660267 | dimaalmasri/pythonCodes | /Functions/built-in-functions.py | 1,918 | 4.40625 | 4 | """
This file contains some examples for built-in functions in python
they are functions that do certain things
I will explain
"""
#example 1 = .upper()
#added by @basmalakamal
str1 = "hello world"
print str1.upper()
#this how we use it and it is used to return the string with capital letters
#example 2 = isupper()
#added by @basmalakamal
str2 = "I love coding"
print str2.isupper()
#this function returns a boolean it is used to see if all letters in the string are capital I have only one capital letter here
#so it returned False
#lets try again here
str3 = "PYTHON IS AWESOME"
print str3.isupper() #prints True
#example 3 = lower()
#added by @basmalakamal
str4 = "BASMALAH"
print str4.lower()
#it returns the string with small letters
#example 4 = islower()
#added by @basmalakamal
str5 = "Python"
print str5.islower()
#this function returns a boolean it is used to see if all letters in the string are small I have one capital letter here
#so it returned False
#lets try again here
str6 = "python"
print str6.islower() #prints True
#example 5 = float()
#added by @basmalakamal
print float('12\n')
#we can use this one to input an integer and it will return a float depends on what you have written
#for example I wrote 12\n (\n means a space) so it returned 12.0
#example 6 = id()
#added by @basmalakamal
print id(str6)
#it returns the identity of any object cause every object has an identity in python memory
#example 7 = len()
#added by @basmalakamal
#example 8 = int()
#added by @basmalakamal
#example 9 = str()
#added by @basmalakamal
#example 10 = max()
#added by @basmalakamal
#example 11 = sort()
#added by @basmalakamal
#example 12 = replace()
#added by @basmalakamal
#example 13 = append()
#added by @basmalakamal
#example 14 = index()
#added by @basmalakamal
#example 15 = split()
#added by @basmalakamal
#example 16 = join()
#added by @basmalakamal
| true |
c8081213be5dae1651f642dc605dbb868daa9570 | Flimars/Python3-for-beginner | /_listas_execicios/list1_ex1.py | 335 | 4.3125 | 4 | # 1. Desenvolva o algoritmo de um programa onde o usuรกrio irรก informar um nรบmero
# inteiro e o programa deve calcular e exibir o nรบmero imediatamente antecessor ao
# nรบmero digitado pelo usuรกrio.
num = int(input('Digite um nรบmero inteiro: '))
antecessor = num - 1
print('O antecessor do seu nรบmero รฉ {}:'.format(antecessor))
| false |
7f8c90512749b9861743a98aba866debc7cb9f03 | Flimars/Python3-for-beginner | /_listas_execicios/list1_ex6.py | 265 | 4.1875 | 4 | # 6. Desenvolva o algoritmo de um programa para calcular a mรฉdia de duas notas das
# avaliaรงรตes de um aluno.
nota_1 = float(input('Digite a 1ยบ nota: '))
nota_2 = float(input('Digite a 2ยบ nota: '))
media = (nota_1 + nota_2)/2
print('A nota mรฉdia รฉ = ',media) | false |
c9777249c747b0ce1a86cae1147dbc479b802ae3 | ialtikat/gaih-students-repo-example | /Final Project/FinalProje.py | 2,308 | 4.15625 | 4 | class Food:
def __init__(self,name):
self.name=name
def pisir(self, name):
if self.name == "Kavurma":
print("Piลmesi iรงin 75 DK bekleyelim")
elif self.name=="Pilav":
print("Piลmesi iรงin 40 DK bekleyelim")
def karistir(self):
print("Karฤฑลtฤฑrmayฤฑ unutmayalฤฑm :)")
def urun(self,name):
print("<Malzemeler>")
for i in range(len(name)):
print("> {}".format(name[i]))
def yemek(self):
print("Afiyet olsun.")
class Kavurma(Food):
def __init__(self,name, malzeme):
self.name = name
self.malzeme=malzeme
print("<------------------------Bu Gรผnรผn Menรผsรผ------------------------------>")
print("Yemeฤimiz: {}".format(self.name))
self.urun(self.malzeme)
self.pisir(self.name)
self.karistir()
self.yemek()
class Pilav(Food):
def __init__(self,name, malzeme):
self.name = name
self.malzeme=malzeme
print("<------------------------Bu Gรผnรผn Menรผsรผ------------------------------>")
print("Yemeฤimiz: {}".format(self.name))
self.urun(malzeme)
self.pisir(self.name)
self.karistir()
self.yemek()
class Cacik(Food):
def __init__(self,name, malzeme):
self.name = name
self.malzeme=malzeme
print("<------------------------Bu Gรผnรผn Menรผsรผ------------------------------>")
print("Yemeฤimiz: {}".format(self.name))
self.urun(malzeme)
self.pisir(self.name)
self.karistir()
self.yemek()
if __name__ == "__main__":
kavurma = Kavurma("Kavurma", ["Et","1 Adet Soฤan", "2 Yemek Kaลฤฑฤฤฑ Yaฤ ", "1 Tatlฤฑ Kaลฤฑฤฤฑ Tuz", "1 รay Kaลฤฑฤฤฑ Kekik", "1 รay Kaลฤฑฤฤฑ Karabiber", "1 Bardak Sฤฑcak Su"] )
pilav = Pilav("Pilav",["2 su bardaฤฤฑ pirinรง", "2 yemek kaลฤฑฤฤฑ tereyaฤฤฑ","2 yemek kaลฤฑฤฤฑ sฤฑvฤฑyaฤ","1 รงay kaลฤฑฤฤฑ tuz","4 yemek kaลฤฑฤฤฑ tel ลehriye ","3 su bardaฤฤฑ sฤฑcak su","1 adet tavuk suyu"])
cacik= Cacik("Cacฤฑk",["3 su bardaฤฤฑ yoฤurt","1,5 su bardaฤฤฑ soฤuk su","4 adet orta boy salatalฤฑk", "2 diล sarฤฑmsak","1 รงay kaลฤฑฤฤฑ tuz"])
| false |
b45fcda91797777b337cf5e426cf5d225413662d | pythonshiva/Pandas-Ex | /Lesson5/lesson5.py | 485 | 4.53125 | 5 | #Stacking and unstacking functions
import pandas as pd
#Our small dataset
d = {'one':[1,1], 'two': [2,2]}
i = ['a', 'b']
#Form DataFrame
df = pd.DataFrame(data= d, index=i)
# print(df)
#Bring the column and place them in the index
stack = df.stack()
print(stack)
#now it became the multi level index
# print(stack.index)
unstack = df.unstack()
print(unstack)
print(unstack.index)
#We can also flip the column names with the index using Transpose
transpose = df.T
print(transpose)
| true |
1cec851dea3b5601b95b3fd71cdd669f974b94c4 | khanshoab/BASIC-OF-HTML | /python project/exp201.py | 457 | 4.15625 | 4 | ''' 2.1 wrote a python program to implement the loop
@ author khan shoab akhtar vbakil ahmad khan
'''
# factorial using loop
num=int(input('enter the number :'))
fact=1
for i in range(1,num+1):
fact=fact*i
print('factorial of ',num,'is',factpy)
# fibonacci using while loop
num=int(input('entre the number:'))
a=0
b=1
c =a+b
print('fibonaci series till ',num ,':',a,'\t',b,end='')
while(c<=num):
print("t\",c,end='')
a=b
b=c
c=a+b
''''something is happen '''
| false |
21bec91a2b0ba523b2d99b1ed30d43a934709f91 | bc-maia/udacity_python_language | /A - Basics/10 - LambdaFilter.py | 808 | 4.40625 | 4 | # Quiz: Lambda with Filter
# filter() is a higher-order built-in function that takes a function
# and iterable as inputs and returns an iterator with the elements
# from the iterable for which the function returns True. The code
# below uses filter() to get the names in cities that are fewer than
# 10 characters long to create the list short_cities. Give it a test
# run to see what happens.
# Rewrite this code to be more concise by replacing the is_short
# function with a lambda expression defined within the call to filter().
cities = [
"New York City",
"Los Angeles",
"Chicago",
"Mountain View",
"Denver",
"Boston",
]
# def is_short(name):
# return len(name) < 10
is_short = lambda name: len(name) < 10
short_cities = list(filter(is_short, cities))
print(short_cities)
| true |
2526043e6fdc0407bb5746c00b1ca6b9c134e118 | prowrestler215/python-2020-09-28 | /week1/day2/afternoon/for_loop_basic_II.py | 1,097 | 4.15625 | 4 | # Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list.
# Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 }
def ultimate_analysis(list_parameter):
# create our dictionary to add our values
analysis = {
'sumTotal': 0,
'average': 0,
'minimum': list_parameter[0],
'maximum': list_parameter[0],
'length': 0
}
# look through the list
for number in list_parameter:
# do some math
analysis['sumTotal'] += number
if number < analysis['minimum']:
analysis['minimum'] = number
if number > analysis['maximum']:
analysis['maximum'] = number
# calculate the average
analysis['average'] = analysis['sumTotal'] / len(list_parameter)
analysis['length'] = len(list_parameter)
# return the dictionary
return analysis
returned_value = ultimate_analysis([37, 2, 1, -9])
print(returned_value)
| true |
6973aa76eff67755325892efe399c0454b22145b | danny237/Python-Assignment2 | /palindrome.py | 883 | 4.21875 | 4 | """ Program to check the given word is palindrome or not """
# check using reverse method
# def is_palindrome(str1):
# reverse_string = list(reversed(str1))
# if list(str1) == reverse_string:
# return True
# else:
# return False
def is_palindrome(str1):
"""
Function to check palindrome
Parameter:
str1(string): given string
Return:
Boolean: True or False
"""
length = len(str1)
middle = length // 2
for i in range(middle):
if str1[i] != str1[length-i-1]:
return False
return True
def main():
""" Main Function """
# user input
user_input = input('Enter the string: ')
if is_palindrome(user_input):
print(user_input, ' is palindrome.')
else:
print(user_input, ' is not palindrome.')
if __name__ == '__main__':
main()
| true |
ea7b1c878e51f549714901af7cda5cea24a4b5a3 | danny237/Python-Assignment2 | /valid_string_paren.py | 803 | 4.46875 | 4 | """Program to valid a string of parenthese."""
class Parenthese:
"""
Class for validating parenthese
Attribute:
str1(string): given parentheses
"""
def __init__(self, str1):
self.str1 = str1
def is_valid(self):
"""function that return True if valid parenthese"""
stack = []
para_char = {"(": ")", "{": "}", "[": "]"}
for parenthese in self.str1:
if parenthese in para_char:
stack.append(parenthese)
elif len(stack) == 0 or para_char[stack.pop()] != parenthese:
return False
return len(stack) == 0
# user input
user_input = input('Enter the string of parenthesse: ')
obj = Parenthese(user_input)
if obj.is_valid():
print('Valid.')
else:
print('Not Valid.')
| true |
7583c18f0bae28b4e05b3e677d30f1a295da24d6 | HenrikSamuelsson/exercism-python-track | /python/pangram/pangram.py | 859 | 4.15625 | 4 | import string
def is_pangram(sentence):
"""Check if all the characters in the alphabet (a - z) is used in a given sentence."""
# Convert the input to all lower case letters.
lower_case_sentence = sentence.lower()
# Get a list of all the ASCII lower case letters i.e. a-z.
all_lower_case_ascii_letters = string.ascii_lowercase
set_of_letters_in_sentence = set() # Start with an empty set.
for c in lower_case_sentence:
if c in all_lower_case_ascii_letters:
set_of_letters_in_sentence.add(c) # Attempt to add each symbol that is a letter into the set.
# In a pangram so will the number of letters equal the number of letters in the alphabet.
if len(set_of_letters_in_sentence) == len(all_lower_case_ascii_letters):
return True
else:
return False
| true |
c220c282db5e1453430dbcfd7843b1f8cebfc04e | morrisunix/python | /projects/list_overlap.py | 1,245 | 4.125 | 4 | from random import randint
def get_intersection(list_1, list_2):
""" Returns a new list with the intersecion of both lists
Parameters
----------
list_1: list
First given list
listd_2: list
Second given list
Returns
-------
list
The intersection list
"""
intersection_list = set(list_1) & set(list_2)
return list(intersection_list)
def random_list_generator(number_of_elements):
""" Returns a list of random numbers
Parameters
----------
number_of_elements: int
Size of the list
Returns
-------
list
New list with size number_of_elements and random elements
"""
new_list = []
for count in range(number_of_elements):
new_list.append(randint(0, 100))
return new_list
def main():
""" Main function
Parameters
----------
None
Returns
-------
None
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = random_list_generator(10)
d = random_list_generator(20)
intersection_list = get_intersection(c, d)
print("{} \n{}".format(c, d))
print(intersection_list)
if __name__ == "__main__":
main()
| true |
48089f24a5b66de04df58c61d050b74171f986cc | Favi0/python-scripts | /MIT/ps1/ps1b.py | 834 | 4.3125 | 4 | portion_down_payment = 0.25
current_savings = 0
investment_return = 0.04
months = 0
annual_salary = float(input("Enter your annual salary:โ "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal:โ "))
total_cost = float(input("Enter the cost of your dream home:โโ "))
semi_annual_raise = float(input("Enter the semiยญannual raise, as a decimal: "))+1
monthly_salary = annual_salary/12
flag = 0
while(current_savings <= total_cost * portion_down_payment):
monthly_interest_of_savings = current_savings * (investment_return/12) # initially zero
current_savings += monthly_interest_of_savings + (monthly_salary*portion_saved)
months +=1
if(flag == 6):
flag = 0
monthly_salary = monthly_salary*semi_annual_raise
flag +=1
print("Months: "+str(months))
| true |
58651ca614673607d7f6af83fd7c547f119a6d3a | srmcnutt/100DaysOfCode | /d8-caesar_cipher/main.py | 1,183 | 4.125 | 4 | # 100 days of code day 8 - Steven McNutt 2021
from resources import logo, alphabet
print(logo)
#super awesome ceasar cipher function w00t!
def caesar(text="foo", shift=0, direction = "e"):
transformed_text = ""
cipher_direction = "encode"
if direction[:1] == 'd':
cipher_direction = "decode"
shift *= -1
for letter in text:
if letter == " ":
transformed_text += letter
else:
index = ((alphabet.index(letter)) + shift) % 26
transformed_text += alphabet[index]
print(f"The {cipher_direction}d text is: {transformed_text}")
# *** Game loop ***
play = ""
while play[:1] != "n":
direction = input("Type '(e)ncode' to encrypt, type '(d)ecode' to decrypt:\n")
text = input("Type your message:\n").lower()
# prevent game from crashing on non-integer input
try:
shift = int(input("Type the shift number:\n"))
except ValueError:
print ("come on, dog, enter an integer\n")
# basic input validation and then call our function
if text and (direction[0] in ['e', 'd']) :
caesar(text, shift, direction)
else:
print("seems to be a problem")
play = input("Run again? \n")
print("\n")
print("end of line.") | true |
bf526aa21e5c7eada8c6bdd5cda629989211104e | aparnabreddy/python-assignment-1 | /list_1.py | 328 | 4.25 | 4 | cities=["Bangalore","Hyderabad","Delhi","Mangalore"]
towns=["pavagada","chitradurga"]
print(cities) #printing list elements
print(cities+towns) #merging two lists
print(len(cities)) #finding length of list
print(len(cities+towns))
cities.remove('Mangalore') #removinh element from list
print(cities)
cities.pop(2)
print(cities)
| false |
3760de65a11afb88923d8a409d9973994d94dccb | VishalGohelishere/Python-tutorials-1 | /programs/Conditionals.py | 243 | 4.25 | 4 | x=5
if x==5 :
print("Equals 5")
if x>4 :
print("Greater then 4")
if x>=5:
print("Greater then or equal to 5")
if x<6:
print("Less then 6")
if x<=5:
print("Less then or equal to 5")
if x!=6 :
print("Not equal to 6")
| true |
6527fd5b804fbaba356c9244a5def3a96038143d | faizerhussain/TestingEclipseGitUpload | /Hello1/conditional.py | 270 | 4.125 | 4 | x=3
if x<4:
print(True)
if x<5:
print('yes')
else:
print('no')
color='red'
if color=='red':
print('color red')
elif color=='blue':
print('color blue')
if color=='red' and x<5:
print('color red number 5')
| false |
34bd49ebdd08097ee10ab002bdb93ce558efc45c | MariusArhaug/RPNCalculator | /container.py | 812 | 4.21875 | 4 | """Container superclass"""
from abc import ABC, abstractmethod
class Container(ABC):
"""
Super class for Queue and Stack
"""
def __init__(self):
self._items = []
def size(self):
"""
Get number of items
:return: int number of items
"""
return len(self._items)
def is_empty(self):
"""
check if size > 0
:return: boolean
"""
return self.size() == 0
def push(self, item):
"""
Push items into list
:param item:
:return: None
"""
self._items.append(item)
def __str__(self):
return str(self._items)
@abstractmethod
def pop(self):
"""Get item from list"""
@abstractmethod
def peek(self):
"""See item"""
| true |
0ecc7fff80aba73ccf12bee5907d190ffcc200bc | Praveenstein/Intern_Assignment | /autocorrelation_for_all_lags.py | 1,482 | 4.59375 | 5 | # -*- coding: utf-8 -*-
""" Computing autocorrelation for a given signal
This script allows the user to compute the autocorrelation value
of a given signal for lags = 1, 2, 3.....N-2, where N is the length
of the signal
This file contains the following function:
* main - the main function of the script
"""
def main():
"""
Main function to find the autocorrelation for lags = 1,2,3.....N-2
"""
signal = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = len(signal)
mean = sum(signal)/n
# Finding variance - ignoring to divide by n
# as it will be cancelled with the n in numerator while calculating the autocorrelation
variance = sum(map((lambda x: (x - mean)**2), signal))
# The corrs calculates the autocorrelation for all lags and stores as a list
#
# The inner most function lambda-function computes the sum of individual terms
# that make up the autocorrelation formula and divides it by the variance
#
# The map function is used to compute the autocorrelation for all lags using
# a range function denoting all the lags and the lambda function
corrs = list(map((lambda k: sum(((signal[i] - mean) * (signal[i+k] - mean)
for i in range(n-k)))/variance),
range(1, n-1)))
# Printing the lag value and corresponding correlation
print(list(enumerate(corrs, 1)))
if __name__ == '__main__':
main()
| true |
c2c3eb6e0230082565cd461d481464aaede738af | mt-digital/flask-example | /files_example.py | 957 | 4.3125 | 4 | '''
Run this like so:
python example.py
It will create a directory 'files_dir' if it
doesn't exist then put a new random text file in there.
The file name before ".txt" will be one greater
for each new file added to the files directory.
'''
import os
dirname = 'files_dir'
# Check if directory exists.
if not os.path.isdir(dirname):
# If it does not, create it.
os.mkdir(dirname)
# See how many files are in files_dir.
idx = len(os.listdir(dirname))
# Convert that number to a string.
idx_str = str(idx)
# Some fake text to go in our new file..
file_text = 'This is an example file.\n'
# Create a filename; note this depends on no other person/program.
# Putting a file with a name like <integer>.txt.
filename = os.path.join(dirname, idx_str + '.txt')
# This is the most common way to handle writing to files in Python.
# This is also the most idiomatic Python-"Pythonic" for short.
with open(filename, 'w+') as f:
f.write(file_text)
| true |
b7ca9d69fe171766db59c39d846109d2b37659af | Faybeee/Session-2-homework | /session 2 task 3 homework.py | 1,599 | 4.375 | 4 | #Write a program which will ask for two numbers from a user.
#Then offer a menu to the user giving them a choice of maths operators.
#Once the user has selected which operator they wish to use,
# perform the calculation by using a procedure and passing parameters.
def procedure_a(first,second):
print(first + second)
def procedure_b(first,second):
print(first-second)
def procedure_c(first,second):
print(second / first)
def procedure_d(first, second):
print(second*first)
def procedure_e(first, second):
print(first ** second)
def procedure_f(first, second):
print(pow(first, 2), pow(second, 2))
print("Hi! I'm here to help you calculate! I want you to give me two numbers!")
first = int(input("What is your first number choice?"))
second = int(input("What is your second number choice?"))
print("Great job!")
print ("""
A = Add Numbers together.
B = Subtract the second number from the first.
C = Divide second number by first number.
D = Multiply numbers together.
E = First number to the power of second.
F = Square the numbers.
""")
method = str(input("Choose a letter A-F"))
if method == "A" or method =="a":
procedure_a(first,second)
elif method == "B" or method =="b":
procedure_b(first,second)
elif method == "C" or method =="c":
procedure_c(first, second)
elif method == "D" or method =="d":
procedure_d(first, second)
elif method == "E" or method =="e":
procedure_e(first, second)
elif method == "F" or method =="f":
procedure_f(first, second) | true |
6c5d690754798e80ef8d8a261700cca7eeb472ee | HamplusTech/PythonCodes2021Update | /AnswersToTask - Week 1 Task 1.py | 1,629 | 4.46875 | 4 | print("Answers to online task by Hampo, JohnPaul A.C.")
print()
print("Week 1 Answers")
print("Answer to last week's task No.1\
Hello Dear! Here is a little task for us in python.\
\
1] Write a program to find the sum of the data structure below\
[[1,2,3],[4,5,6,7],[8,9]]\
\
2] Write a program to convert the tuple to a dictionary where\
name is the key and age is the value. Example: x = ('John', 23, 'm'), ('Peter', 43, 'm')\
then the output will be y = {'John': 23, 'Peter': 43}.")
print()
print("Solution")
print("Task Number 1")
a = [[1,2,3],[4,5,6,7],[8,9]]
print("Using a for loop")
b = []
for i in range(len(a)):
for j in range(len(a[i])):
b.append(a[i][j])
print("The sum of the list of lists = ", sum(b))
print()
print("Alternatively: using list comprehension")
c =[sum(a[i]) for i in range(len(a))]
print("The sum of the list of lists = ", sum(c))
print()
print("Or")
print()
d = sum([sum(a[i]) for i in range(len(a))])
print("The sum of the list of lists = ", d)
'''
from itertools import accumulate
datalist = [[1,2,3], [4,5,6,7], [8,9]]
print(list(accumulate([x for x in datalist for x in x]))[8])
print(list(accumulate([x for x in datalist for x in x]))) 'returns a list of progressive sums
'''
print()
print("Solution")
print("Task Number 2")
x = ('John', 23, 'm'), ('Peter', 43, 'm')
print("Using a for loop")
y = dict()
for name, age, sex in x:
y[name] = age
print("The new dictioary is:\n", y)
print()
print("Alternatively: using dictionary comprehension")
print()
y2 = {name:age for name, age, sex in x}
print("The new dictioary is:\n", y2)
| true |
1aee7f38b51816f3cb4361cac64668722f39fbd9 | HamplusTech/PythonCodes2021Update | /AnswersToTask - Week 1 Task 2.py | 1,794 | 4.625 | 5 | print("Answers to online task by Hampo, JohnPaul A.C.")
print()
print("Week 1 Answers - Task 2")
print("Answer to last week's task No.1\
Hello Dear! Here is a little weekend task for us in python.\
Consider the data structure below:\
menu = {'meal_1': 'Spaghetti',\
'meal_2': 'Fries',\
'meal_3': 'Cheeseburger',\
'meal_4': 'Lasagna',\
'meal_5': 'Soup',\
'meal_6': ['Pancakes', 'Ice-cream', 'Tiramisu']}\
1] Create a new dictionary that contains the first five meals as keys and assign the following\
five values as prices (in dollars): 10, 5, 8, 12, 5. Start by Price_list = {}.\
2] Create a JSON in which the values of the keys of menu dictionary have a dictionary\
showing the recipe for the values.)")
print()
print("Solution")
print("Task Number 1")
menu = {'meal_1': 'Spaghetti',
'meal_2': 'Fries',
'meal_3': 'Cheeseburger',
'meal_4': 'Lasagna',
'meal_5': 'Soup',
'meal_6': ['Pancakes', 'Ice-cream', 'Tiramisu']}
print("Using Dictionary comprehension")
prices = [10, 5, 8, 12, 5]
Price_list = {list(menu.values())[i] : prices[i] for i in range(len(prices))}
print("The menu by price dictionary is \n", Price_list)
print()
print("Solution")
print("Task Number 2")
print("A JSON is a list of dictionary. JSON stands for Java Script Object Notation ")
print("Observing the dictionary called menu, the value of meal_6 is a list, hence for \
simplicity I change the list to a value as shown below: \n")
menu_new = menu
menu_new["meal_6"] = "Fruits"
print("The new menu without a list value is :", menu_new)
ingredient_sample = ["ingredient1", "ingredient2", "ingredient2", "..."]
ingredients_menu = [{value: ingredient_sample for key, value in list(menu_new.items())}]
print("The JSON showing ingredients is:\n", ingredients_menu)
| true |
49a439f7914640a0ed185871ec8d2d6b2ddc90db | HamplusTech/PythonCodes2021Update | /tryExcept.py | 336 | 4.5 | 4 | numCar = input("Please enter how many cars do you have\n")
try:
numCar = int(numCar)
if numCar.__neg__():
print("You have entered a negative number")
elif numCar >= 3:
print("You have many cars")
else:
print ("You have not many cars")
except:
print("You haven't entered a number")
| true |
0d4eb88906b569b5553d84f3f024665d6e0af0e3 | HamplusTech/PythonCodes2021Update | /breakContinuePass.py | 1,062 | 4.3125 | 4 | # using BREAK, CONTINUE and PASS statements
print ("To end this script type 'end' not 'END'. Enjoy!")
count = 0
while True:
name = input("Please enter your name\n")
print("You type ", name)
if name == "end":
break
elif name == "END":
pass
elif name:
count += 1
continue
import datetime
print ("Thanks for your time. \nYou typed a name for ", str(count) + "\n Today is:\n", datetime.date(2020,3,25))
# using pass statement for comment
while True:
text = input("Enter any text\n")
if text[0] == "#":
pass
print("You typed a comment in python language")
continue
pass
else:
print("This is the text you typed:\n",text)
answer = input("Do you want to play again? Y or N\n")
if (answer =="Y"):
#print("Please enter Y or N not y or n\n")
continue
elif (answer=="y") or (answer== "n"):
print("Please enter Y or N not y or n")
break
else:
break
print("Made by:\n Hamplus Technologies")
| true |
6d8977dcce04e80570fb94408e5dc50dc9dd1410 | joshuajz/grade12 | /1.functions/Assignment 1.py | 1,921 | 4.4375 | 4 | # Author: Josh Cowan
# Date: October 8, 2020
# Filename: Assignment #1.py
# Descirption: Assignment 1: Function Based Calculator
def calc():
# Asks for the first number (error checking)
try:
num1 = int(input("Number 1: "))
except ValueError:
print("Invalid Input -> Provide a number.")
return
# Asks for the second number (error checking)
try:
num2 = int(input("Number 2: "))
except ValueError:
print("Invalid Input -> Provide a number.")
return
# Asks for the operator
try:
operator = int(
input("Operators: 1. Add | 2. Subtract |3. Multiply, 4. Divide: ")
)
except ValueError:
print("Invalid Operator -> Provide a number.")
return
# Ensures the operator is between 1-4
if not (1 <= operator and operator <= 4):
print("Invalid Operator Number (ie. not between 1-4)")
return
# Calls the specific function and prints out the output
if operator == 1:
print(add(num1, num2))
elif operator == 2:
print(sub(num1, num2))
elif operator == 3:
print(mult(num1, num2))
elif operator == 4:
print(divide(num1, num2))
# Asks if the user wants to play again
again = input("Play Again? (yes/no): ")
# If they don't, quit
if again.lower() != "yes":
print("Quitting")
return
# If they want to play again, call the function again
else:
calc()
# Functions for adding, subtracting, multiplying, and dividing
def add(a: int, b: int) -> str:
return f"{a} + {b} = {a + b}"
def sub(a: int, b: int) -> str:
return f"{a} - {b} = {a - b}"
def mult(a: int, b: int) -> str:
return f"{a} * {b} = {a * b}"
def divide(a: int, b: int) -> str:
return f"{a} / {b} = {a / b}"
# Call the function
calc() | true |
8c3e3680b1bfb94e79a23d72d45494f9134b5f33 | joshuajz/grade12 | /0.review/5. multiply.py | 1,065 | 4.28125 | 4 | # Author: Josh Cowan
# Date: October 5, 2020
# Filename: multiply.py
# Descirption: Assignment 5: Multipcation Table
# Stores the actual table
table = []
# The row value (top value)
row = 1
# Iterates from 1 to 12
for i in range(1, 13, 1):
# a row value stored in a list
l = []
# The column value
col = 1
# Iterates to 12 for that specific row
for i in range(1, 13, 1):
# Adds the value (row * col)
l.append(row * col)
# Increases col for the next value
col += 1
# Increases row and adds the list
row += 1
table.append(l)
# Prints out the table
# Iterates over the rows
for row in table:
# Iterates over each value
for value in row:
# Adds an amount of spaces depending on the length of the digit(s)
if len(str(value)) == 1:
print(value, end=" ")
elif len(str(value)) == 2:
print(value, end=" ")
else:
print(value, end=" ")
# adds a new line after each row
print("\n") | true |
61f7c080d17f91319a6c2c2b15ab9b49ff497cdd | joshuajz/grade12 | /0.review/058.py | 291 | 4.25 | 4 | for z in range(3):
for i in range(9):
print("#", end="")
print("")
for i in range(4):
for g in range(5):
print("|", end=" ")
print("")
# You could do this in 2 but it would be more manual ie. print("#########") and print("| | | | |") | false |
941047f4b1bb82e4588fab7d6a80794cf56d7bc2 | joshuajz/grade12 | /1.functions/Assignment 3b.py | 1,160 | 4.1875 | 4 | # Author: Josh Cowan
# Date: October 8, 2020
# Filename: Assignment #3b.py
# Descirption: Assignment 3: Hypotenuse
import math
# Hypoten^2use function a^2 + b^2 = c
def pyth(a, b):
ab = (a * a) + (b * b)
return math.sqrt(ab)
# Function to ask the user for an integer
def get_int(dialog):
while True:
try:
response = int(input(dialog))
except ValueError:
print("Invalid Input")
continue
return response
# Asks the user for the two side lengths
def ask():
a = get_int("Length of first side: ")
b = get_int("Length of second side: ")
# Prints out the hypotenuse
print(f"Hypotenuse: {pyth(a, b)} cm\N{SUPERSCRIPT TWO}")
# Asks the user if they want to play again
while True:
again = input("Play again? y (yes) | n (no) ")
if again.lower() not in ["y", "n"]:
print("Invalid Input")
continue
break
# IF they do, call the function again
if again.lower() == "y":
ask()
else:
print("Quitting")
return
# Call the function
ask()
| true |
1f267aa4fd9ba74fe06b23c83cb5e69b0c0810fd | coxd6953/cti110 | /P2HW2_MealTip_DamienCox.py | 558 | 4.15625 | 4 | # Meal Tip Calculator
# 3/3/19
# CTI-110 P2HW2 - Meal Tip Calculator
# Damien Cox
#
#Enter the cost of the meal.
cost = int(input('Enter the total cost of the meal: '))
#Calculate the amount of the following tip percentages: 15%, 18% and %20.
fifteen = .15 * cost
eighteen = .18 * cost
twenty = .20 * cost
#Display results.
print('A 15% tip on a bill of $', cost, 'is $', format(fifteen, ',.2f'))
print('A 18% tip on a bill of $', cost, 'is $', format(eighteen, ',.2f'))
print('A 20% tip on a bill of $', cost, 'is $', format(twenty, ',.2f'))
| true |
e68db92bb6ef2bb9c140beec9394dd26d53df5a9 | SardulDhyani/MCA3_lab_practicals | /MCA3HLD/20712004_Garima Bisht/Answers_Codes/Ques11_Dictionaries.py | 322 | 4.15625 | 4 |
test_str = 'She is Good Girl'
print("The original string is : " + str(test_str))
lookp_dict = {"Good" : "very good", "Girl" : "She is also Beautiful"}
temp = test_str.split()
res = []
for wrd in temp:
res.append(lookp_dict.get(wrd, wrd))
res = ' '.join(res)
print("Replaced Strings : " + str(res)) | true |
67cca33a6f7d91f8d5e596a2740c8a1e2887878b | SardulDhyani/MCA3_lab_practicals | /MCA3C/Saurabh_Suman_Section_C/ques_7.py | 360 | 4.28125 | 4 | #Write a program to demonstrate the use of the else clause.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if num1 > num2:
print("largest number is : ", num1)
else:
print("largest number is : ", num2)
#output:
#Enter the first number: 8
#Enter the second number: 45
#largest number is : 45 | true |
107f47f702084bd146b462fd8ffc2a5d0abe7e8e | b20bharath/Python-specialization | /Python-fundamentals/indefinite loop.py | 817 | 4.1875 | 4 | # Program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number
largest = 0
smallest = None
while True :
num = input("Enter a number: ")
if num == "done":
break
else:
try:
flNum = float(num)
except:
print("Invalid input")
continue
if largest<flNum:
largest = flNum
if smallest is None:
smallest = flNum
elif smallest>flNum:
smallest = flNum
print("Maximum is", int(largest))
print("Minimum is", int(smallest)) | true |
2305c87b9c7128b1c75bee43208a10e793fef79f | hansamalhotra/learn-python-the-hard-way | /ex33 study drills 5.py | 343 | 4.125 | 4 | #Now changing while loop to for loop
#Do not need the i += increment part anymore
numbers = []
def make_a_list(last, increment):
for i in range(0,last, increment):
numbers.append(i)
last = int(input("Enter the last number ")) + 1
inc = int(input("Enter the increment "))
make_a_list(last, inc)
print("Number is ", numbers)
| true |
2f8f05e85e4d9ebf73673bd5622bdf2befc146da | JoseAcevo/Python_Course_2020 | /trabajo_tuplas.py | 1,728 | 4.4375 | 4 | #ยฟQue son las tuplas en python?
#Son "listas", inmutables..
#misdatos=("jose",3,8,1979) # Creaciรณn de una tupla
#misdatoslista=list(misdatos) # Conversiรณn de una tupla a lista
#misdatoslista=tuple(misdatos)
#print(misdatoslista) # Impresiรณn de la tupla convertida a lista
#print(misdatos) # Impresiรณn tupla
#print("jose"in misdatos) # localizar elemento en una tupla
#print(misdatos.count("jose")) # Localizar el nรบmero de veces que se repite un elemento dentro de una tupla
#print(len(misdatos)) # Consultar el nรบmero de elementos totales dentro de una tupla
#Desempaquetado de tuplas.
#nombre,dia,mes,agno=misdatos # Asignaciรณn de datos a elementos de una tupla.
#print(nombre)
#print(agno)
#print(dia)
#------------------------------------------------------------------------------------------------
| false |
433c2beeb9a7ec415713a2204b881d1f482d8490 | jerrywu65/Leetcode_python | /problemset/007 Reverse Integer.py | 2,156 | 4.21875 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [โ231, 231 โ 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
####72ms
# temp=0
# ans=0
# if (x<(0-pow(2,31))) or (x>(pow(2,31)-1)):
# ans=0
# if x==0:
# ans=0
# elif x>0:
# while(x>0):
# temp=x%10
# ans=10*ans+temp
# x=x//10
# else:
# x=abs(x)
# while(x>0):
# temp=x%10
# ans=10*ans+temp
# x=x//10
# ans=0-ans
# #ๅๆตๅ่ฝฌๅๆฏๅฆ่ถ
ๅบ่ๅด
# if (ans<0-pow(2,31)) or (ans>(pow(2,31)-1)):
# return 0
# return ans
###64ms
if (x<(0-pow(2,31))) or (x>(pow(2,31)-1)):
ans=0
if x>=0:
x=str(x)
x=list(x)
x.reverse()
ans=''.join(x)
else:
x=abs(x)
x=str(x)
x=list(x)
x.reverse()
ans=''.join(x)
ans='-'+ans
#ๆฃๆตๅ่ฝฌๅๆฏๅฆๅจ่ๅดๅ
if ans[0]=='-':
if len(ans)<11:
return int(ans)
elif len(ans)>11:
return 0
else:
a=ans[1:len(ans)]
temp=str(pow(2,31))
if a>temp:
return 0
else:
return int(ans)
else:
if len(ans)<10:return int(ans)
elif len(ans)>10:return 0
else:
temp=str(pow(2,31)-1)
if ans>temp:
return 0
else:
return int(ans) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.