blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c8b643d16c3e97b66dc304ba2ab4323134de3430 | leoniepnzr/MyExercises | /ex18.py | 1,246 | 4.8125 | 5 | #functions: name pieces of code, take arguments, lets you do mini-scripts
#created with def
#* tells Python to take all arguments and collect them in list, like argv for functions
def print_two(*args):#make a function with "def", giving function a name, *args in parantheses to work, just like argv, start with :
arg1, arg2 = args #unpacks arguments
print "arg1: %r, arg2: %r" % (arg1, arg2) #print arguments out
def print_two_again(arg1, arg2):#shorter way of doing it, setting names in brackets
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):#one argument
print "arg1: %r" % arg1
def print_none():#function with no argument
print "I got nothin'."
print_two("Leonie","Panzer")
print_two_again("Leonie","Panzer")
print_one("First!")
print_none()
#function checklist:
#function starts with def?
#function name only characters and underscores?
#open paranthesis after function name?
#arguments in paranthesis separated with commas?
#arguments unique?
#closing paranthesis and colon?
#indent 4 spaces after function?
#closing function with dedenting?
#run function checklist:
#run function by typing its name?
#put ( after name to run?
#values in paranthesis separated by commas?
#end function call with )?
| true |
d566fd621c31a770484e719e9096930421f30c49 | leoniepnzr/MyExercises | /ex33.py | 399 | 4.25 | 4 | #while loops for running until Boolean expression is False
#to follow loop jumping, write print everywhere in code (top, middle, bottom) -> trying to understand
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
| true |
976be5017743a3f36e2587676b76b4ae6bc7be8c | JuliusBoateng/data_structs_and_algs | /fundamentals/selection_sort.py | 780 | 4.125 | 4 | #!/usr/bin/env python3
import random
def find_index_of_min(arr, start):
min_element = arr[start]
min_index = start
for index in range(start + 1, len(arr)):
if arr[index] < min_element:
min_element = arr[index]
min_index = index
return min_index
def swap(arr, first, second):
temp = arr[first]
arr[first] = arr[second]
arr[second] = temp
def selection_sort(arr):
for index in range(len(arr)):
min_index = find_index_of_min(arr, index)
if min_index != index:
swap(arr, index, min_index)
return arr
def main():
arr = [random.randrange(101) for _ in range(101)]
print(arr)
result = selection_sort(arr)
print(result)
if __name__ == "__main__":
main() | true |
8d8fc57bb1d3617fb301628ffdecbd633446ce33 | luoyi94/Python | /02-循环判断/案例:九九乘法表.py | 367 | 4.21875 | 4 | # 第 1 步:用嵌套打印小星星
# i = 1
# while i <= 5:
# print("*" * i)
# i += 1
# print("end")
# 用列row来控制总数 有多少列就有多少行col 只有 列 +1,对应 行 才 +1
row = 1
while row <= 9:
col = 1
while row >= col:
print("%d X %d = %d" % (row, col, row * col),end="\t")
col += 1
print()
row += 1
| false |
c1cc167c298d81f5eea15a63cbf1e0b5a0251769 | dathanwong/Dojo_Assignments | /Python/python/ForLoopBasicII.py | 2,346 | 4.15625 | 4 | #1. Biggie Size
#Given a list write a function that hanges all positive numbers to big
def biggie(list):
for x in range(len(list)):
if list[x] > 0:
list[x]="big"
return list
print(biggie([-2,3,5,-5]))
#2. Count Positives
# given a list of numbers replace the last value wiht the number of positive values
def countPos(list):
count = 0
for x in range(len(list)):
if list[x] > 0:
count += 1
list[len(list)-1] = count
return list
print(countPos([-1,1,1,1]))
print(countPos([1,6,-4,-2,-7,-2]))
#3. Sum Total
#Take a list and return the sum of all values in list
def sumTot(list):
sum = 0
for x in range(len(list)):
sum += list[x]
return sum
print(sumTot([1,2,3,4]))
print(sumTot([1,2,3,4]))
#4. Average
# return average of input list
def avg(list):
sum = 0.0
for x in range(len(list)):
sum += list[x]
return sum/len(list)
print(avg([1,2,3,4]))
#5. Length
#returns length of list
def getLength(list):
return len(list)
print(getLength([]))
#6. Minimum
#Return minimum value in list return false if empty
def min(list):
if(len(list)<1):
return False
min = list[0]
for x in range(len(list)):
if list[x] < min:
min = list[x]
return min
print(min([37,2,1,-9]))
print(min([]))
#7 Maximum
#Return max of list, return false if empy
def max(list):
if(len(list)<1):
return False
max = list[0]
for x in range(len(list)):
if list[x] > max:
max = list[x]
return max
print(max([37,2,1,-9]))
print(max([]))
#8 Ultimate Analysis
#Create function that takes a list and returns dictionary with the sumTotal, average, minimum, maximum, length
def ult(list):
max = list[0]
min = list[0]
sum = 0.0
for x in range(len(list)):
if(list[x] > max):
max = list[x]
if(list[x]< min):
min = list[x]
sum += list[x]
return {'sumTotal':sum, "average":sum/len(list), "minimum":min, "maximum":max}
print(ult([37,2,1,-9]))
#9 Reverse List
#Take a list and return list with values reveresed without creating a second list
def reverse(list):
for x in range(len(list)/2):
temp = list[x]
list[x] = list[len(list)-1-x]
list[len(list)-1-x] = temp
return list
print(reverse([37,2,1,-9,10])) | true |
82818bf299d970c9bd47036bb268cc2c88330c41 | abhishekk40/Test1 | /test1.py | 423 | 4.15625 | 4 | a=6
y=0
for i in range(1,6): # Always keep the first loop for the Count of Number of lines
for j in range(1,y+1): # This loop is for Printing Space
print(" ",end=" ")
y=y+1 #This is for increasing the number of spaces everytime
for k in range(1,a): #This loop is for Printing "1"
print("1",end=" ")
a=a-1 #This is for decreasing the value of "a" everytime
print("\n")
| true |
18231c614f5ae04068e1b33132e31f3e16317f00 | jonvaljean/flask-course | /decorators.py | 1,102 | 4.59375 | 5 | #a decorator is a function that gets called before another function
#SAVE THESE TEMPLATES for decorators with and without parameters
import functools
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func():
print("in the decorator!")
func() #always call the function inside the decorator or it will not work
print("after the decorator!")
return function_that_runs_func
@my_decorator
def my_function():
print("I'm the function !")
my_function()
##
def decorator_with_arguments(number):
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*args, **kwargs):
print("In the decorator !")
if number == 56:
print("Not running the function !")
else:
func(*args, **kwargs)
print("After the decorator !")
return function_that_runs_func
return my_decorator
@decorator_with_arguments(57)
def my_function_too(x,y):
print("Hello", x + y)
my_function_too(57,67)
| true |
58ec57242e5f775f110328bf2a8af557c9329c18 | HYPERTONE/EPI-Python | /Primitive Types/4.3 - Reverse Bits.py | 789 | 4.375 | 4 |
# Write a program that takes a 64-bit unsigned integer and returns the 64-bit unsigned integer consisting
# of the bits of the input in reverse order.
def reverseBit(num):
result = 0
while num:
result = (result << 1) + (num & 1)
num >>= 1
return result
# The goal here is to AND our num by 1 and then have it shifted to the LEFT one place while
# num is being shifted to the RIGHT. Every time we AND something, we will get a 1 when num had a 1,
# and a 0 when num had a zero. The loop terminates because num gets shifted until it becomes 0.
# Note that this is reversing the base 2 value of the integer. So if we input an integer of 123, its binary value is 1111011.
# The reverse of 1111011 is 1101111 which when converted to an integer is actually 111.
| true |
cbfc948f149cb6c96efa71a300146b902bf60b6f | HYPERTONE/EPI-Python | /Binary Trees/9.1 - Test If A Binary Tree Is Height-Balanced.py | 1,597 | 4.375 | 4 |
# A binary tree is said to be height balanced if for each node in the tree, the difference in height of its left and right subtrees
# is at most one. A perfect binary tree is height-balanced, as is a complete binary tree. A height-balanced binary tree does not have to
# be perfect or complete.
# Write a program that takes as input the root of a binary tree and checks whether the tree is height-balanced.
import collections
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
lefty = BinaryTreeNode(10)
righty = BinaryTreeNode(20)
root = BinaryTreeNode(0, lefty, righty)
def is_balanced_binary_tree(tree):
BalancedStatusWithHeight = collections.namedtuple(
'BalancedStatusWithHeight', ('balanced', 'height')
)
# first value of return indicates if balanced and if so
# the second value is the height of the tree
def check_balanced(tree):
if not tree:
return BalancedStatusWithHeight(True, -1) # base case
left_result = check_balanced(tree.left)
if not left_result.balanced:
return BalancedStatusWithHeight(False, 0)
right_result = check_balanced(tree.right)
if not right_result.balanced:
return BalancedStatusWithHeight(False, 0)
is_balanced = abs(left_result.height - right_result.height) <= 1
height = max(left_result.height, right_result.height) + 1
return BalancedStatusWithHeight(is_balanced, height)
return check_balanced(tree).balanced
| true |
5f5693cd376ba31a0f25d7882a7d34c71b255646 | HYPERTONE/EPI-Python | /Binary Trees/9.2 - Test If A Binary Tree Is Symmetric.py | 1,135 | 4.4375 | 4 |
# A binary tree is symmetric if you can draw a vertical line through the root and then the left subtree is a mirror image of the
# right subtree.
# Write a prgoram that checks whether a binary tree is symmetric.
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
lefty = BinaryTreeNode(15, left=lefty1, right=None)
lefty1 = BinaryTreeNode(10)
righty = BinaryTreeNode(15, left=None, right=righty1)
righty1 = BinaryTreeNode(10)
root = BinaryTreeNode(0, lefty, righty)
def symmetric(tree):
def checkSymmetric(subtree_0, subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_0 and subtree_1:
return (subtree_0.data == subtree_1.data
and checkSymmetric(subtree_0.left, subtree_1.right)
and checkSymmetric(subtree_0.right, subtree_1.left))
# One subtree is empty, and the other is not
return False
return not tree or checkSymmetric(tree.left, tree.right)
symmetric(root) # -> True
| true |
d63590eb2be1bc0891198db6fc5c4f19666a95d4 | chengjun0917/DailyQuestion | /shuaidi/question02.py | 1,650 | 4.15625 | 4 | from random import randint
from sys import exit
min_of_target = 0
max_of_target = 100
target = randint(min_of_target,max_of_target)
chances = 7
print("Welcome to guess number game!")
print(f"You have {chances} chances to guess the number, which is range from {min_of_target} to {max_of_target}.")
print("Each time you guessed, you will get a hint about that your number is greater or smaller, until you guesss it or you use up all {chances} chances.")
print("Are you ready? (y or n)")
is_ready = input("> ")
while(True):
if is_ready == "y":
print("Let's begin.")
break
elif is_ready == "n":
print("Bye")
exit(0)
else:
print("Are you ready? (y or n)")
is_ready = input("> ")
for i in range(0, chances):
print(f"Now, you have {chances-i} chance(s), please input your number.")
input_number = None
while(True):
try:
input_str = input("> ")
input_number = int(input_str)
break
except ValueError:
print(f"Please input a NUMBER, {input_str} is not a number.")
if i == chances-1 and input_number != target:
print(f"You don't guess it, but you already use up all chances, the target number is {target}.")
exit(0)
elif input_number == target:
print(f"Congratulations! The target number is {input_number}")
exit(0)
else:
if input_number > target:
print(f"Your number {input_number} is greater than the target, pleas try again.")
elif input_number < target:
print(f"Your number {input_number} is less than the target, pleas try again.")
| true |
554532a2f891decc28fcbb9b448c4156825b1b41 | k1211/30daysHackerRank | /Day12/day12.py | 2,088 | 4.21875 | 4 | # You are given two classes, Person and Student, where Person is the base class and Student is the derived class.
# Completed code for Person and a declaration for Student are provided for you in the editor.
# Observe that Student inherits all the properties of Person.
#
# Complete the Student class by writing the following:
# A Student class constructor, which has parameters:
# -A string, first_name.
# -A string, last_name.
# -An integer, id.
# -An integer array (or vector) of test scores, scores.
# -A char calculate() method that calculates a Student objects average
# and returns the grade character representative of their calculated average:
# O 90 <= a <= 100
# E 80 <= a <= 90
# A 70 <= a <= 80
# P 55 <= a <= 70
# D 40 <= a <= 55
# T a < 40
# INPUT
# The first line contains first_name, last_name and id respectively.
# The second line contains the number of test scores.
# The third line of space-separated integers describes scores .
class Person(object):
def __init__(self, firstName, lastName, idNumber):
self.first_name = firstName
self.last_name = lastName
self.id = idNumber
def printPerson(self):
print "Name:", self.last_name + ",", self.first_name
print "ID:", self.id
class Student(Person):
def __init__(self, firstName, lastName, idNumber, scores):
Person.__init__(self, firstName, lastName, idNumber)
self.scores = scores
def calculate(self):
num_scores = len(self.scores)
grade = sum(self.scores)/num_scores
if grade >=90:
return "O"
elif grade >= 80 and grade < 90:
return "E"
elif grade >= 70 and grade < 80:
return "A"
elif grade >= 55 and grade < 70:
return "P"
elif grade >= 40 and grade < 55:
return "D"
else:
return "T"
line = raw_input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
scores = map(int, raw_input().split())
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print "Grade:", s.calculate() | true |
1e07fbc119e4d4714a20308b7d6c6a66d5f6250a | k1211/30daysHackerRank | /Day13/day13.py | 1,099 | 4.28125 | 4 | # Given a Book class and a Solution class, write a MyBook class that does the following:
#
# - Inherits from Book
# - Has a parameterized constructor taking these 3 parameters:
# - string title
# - string author
# - int price
# Implements the Book class' abstract display() method so it prints these 3 lines:
# Title: , a space, and then the current instance's title.
# Author: , a space, and then the current instance's author.
# Price: , a space, and then the current instance's price.
from abc import ABCMeta, abstractmethod
class Book:
__metaclass__ = ABCMeta
def __init__(self, title, author):
self.title = title
self.author = author
@abstractmethod
def display(): pass
class My_Book(Book):
def __init__(self, title, author, price):
Book.__init__(self,title,author)
self.price = price
def display(self):
print "Title: {}\nAuthor: {}\nPrice: {}".format(self.title, self.author, self.price)
title = raw_input()
author = raw_input()
price = int(raw_input())
new_novel = My_Book(title,author,price)
new_novel.display() | true |
66a7797612d2d64534d42cb1a99951d8ca3ddd58 | k1211/30daysHackerRank | /Day3/day3.py | 569 | 4.5625 | 5 | # Given an integer, n , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5 , print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Complete the stub code provided in your editor to print whether or not is weird.
N = int(raw_input().strip())
if N % 2 != 0:
print "Weird"
else:
if N >= 2 and N<= 5:
print "Not Weird"
elif N>=6 and N<= 20:
print "Weird"
else:
print "Not Weird" | true |
99d5cd5b49cf6dc7eefc30daae1d06d755c8364e | kiranraju03/PractiseCode | /HackerEarth/e-maze-in.py | 698 | 4.3125 | 4 | """
Maze display
A person is stuck in a maze at a starting position of (0,0), a route map is given as an input, find the end position
after he has traversed the route map
Route Map directions, L,R,U,D : left, right, up and down
Hint : Numberical Scale concept
Complexity:
Time : O(N) : N is the length of the route map
Space : O(1)
"""
# Eg : LLRRDDUUDDLR
route_direction = input("Enter the route directions : ")
# initial position
x = y = 0
for each_direction in route_direction:
if each_direction == "L":
x -= 1
elif each_direction == "R":
x += 1
elif each_direction == "U":
y += 1
elif each_direction == "D":
y -= 1
print("%d %d" % (x, y))
| true |
f009eded0a83e3a3555f3512b41a5130cbf5965c | kiranraju03/PractiseCode | /HackerRank/CountingValley.py | 640 | 4.375 | 4 | """
Counting Valley
Check for number of valleys crossed in a hike with uphills(U) and downhills(D)
When the hiker comes to a valley after U/D count the valley
Sample Input : UDDDUDUU
Visual : _ is the valley
_/\ _
\ /
\/\/
"""
def valleyCounter(path):
sea_level = 0 # represents surface/valley
valley = 0
for each_part in path:
# print(each_part)
if each_part == "U":
sea_level += 1
if sea_level == 0:
valley += 1
else:
sea_level -= 1
return valley
print(valleyCounter("UDDDUDUU"))
print(valleyCounter("DDDUUDUDUUUUDDDU"))
| false |
e26ac036f6b8a05e4fde1e2d6e42e8dbe212272e | kiranraju03/PractiseCode | /Strings/CaesarCipher.py | 1,595 | 4.15625 | 4 | """
Caesar Cipher
Create an encrypted string using the key as the number of shifts to be made
"""
# Solution 1 : 26 characters Approach
# Time : O(1) : as we are dealing with only 26 characters, O(26), i.e., O(1) constant operation
# Space : O(n) : n is the length of the string that needs to be encrypted
def caesar_cipher(string, key):
all_characters = "abcdefghijklmnopqrstuvwxyz"
encrypted_format = ""
for each_char in string:
encrypted_format += all_characters[(all_characters.find(each_char) + key) % 26]
return encrypted_format
print("Approach1")
print(caesar_cipher("kiranraju", 50))
# Solution 2 : 26 characters approach, with more focus on the key value, in scenarios where key>100, we need to keep in the 26 char range
def caesar_cipher2(string, key):
all_char_str = "abcdefghijklmnopqrstuvwxyz"
new_reduced_key = key % 26
encry_str = ""
for each_letter in string:
encry_str_pos = all_char_str.index(each_letter) + key
encry_str += (all_char_str[encry_str_pos] if encry_str_pos <= 25 else all_char_str[encry_str_pos % 26])
return encry_str
print("Approach2")
print(caesar_cipher2("kiranraju", 50))
# Solution 3 : using ord function
def caesar_cipher_ord(string, key):
all_char_str = "abcdefghijklmnopqrstuvwxyz"
new_reduced_key = key % 26
encry_str = ""
for each_char in string:
encry_pos = ord(each_char) + new_reduced_key
encry_str += (chr(encry_pos) if encry_pos <=122 else chr(96 + encry_pos % 122))
return encry_str
print("Approach3")
print(caesar_cipher2("kiranraju", 50))
| true |
78cda78517737e238cdb18e820cee96de227f072 | kiranraju03/PractiseCode | /HackerRank/SockMerchant.py | 1,343 | 4.125 | 4 | """Find the number of pairs of socks from the set of socks
Input : number of socks (n) and array of socks ([])
Output : number of socks pairs available in the array
"""
from collections import Counter
def sockPairChecker(socks):
socks_count = Counter(socks)
for eachcount in socks_count:
sock_color = eachcount
sock_quantity = socks_count[eachcount]
#print(sock_color,sock_quantity)
if sock_quantity == 1:
print("Socks of color " + str(sock_color) +" is only "+ str(sock_quantity)+ " in number, FIND THE OTHER ONE!")
elif sock_quantity == 2:
print("Found a pair of "+str(sock_color))
elif sock_quantity > 2:
temp_quantity = sock_quantity
pair_counter = 0
while temp_quantity >= 2:
temp_quantity -= 2
pair_counter += 1
if temp_quantity > 0:
print("Found "+str(pair_counter)+" pairs of socks of color "+str(sock_color)+" and one more extra sock")
else:
print("Found " + str(pair_counter) + " pairs of socks of color " + str(sock_color))
sock_array = ['red', 'green', 'red', 'grey', 'blue','red','red','red','red','green']
#sock_array_numbers = [1,1,1,1,3,3,3,2,2,4,4,5,5,6]
sockPairChecker(sock_array)
#sockPairChecker(sock_array_numbers) | true |
e6ab2e9ed88ef22e88e56ca8ca68640bd3d1ac88 | kiranraju03/PractiseCode | /Searching/ThreeLargeNumbers.py | 1,159 | 4.53125 | 5 | """
Find the 3 largest numbers in a array
Complexity :
Time : O(N) : N is the length of the array
Space : O(1) : Only shifting of values is involved
"""
# Helper method : Used to assign values to the three number array
# if the index is 2, then the values have to be left shifted once and so for others
def shift_update(array, numb, index):
for i in range(index + 1):
if i == index:
array[i] = numb
else:
array[i] = array[i + 1]
# Helper method : Used to call a particular shift function based on the index value
def update_large_num(large_array, num):
if large_array[2] is None or num > large_array[2]:
shift_update(large_array, num, 2)
elif large_array[1] is None or num > large_array[1]:
shift_update(large_array, num, 1)
elif large_array[0] is None or num > large_array[0]:
shift_update(large_array, num, 0)
# Main caller
def three_large_numbers(array):
large_number_array = [None, None, None]
for each_num in array:
update_large_num(large_number_array, each_num)
return large_number_array
print(three_large_numbers([123, 78, 90, -45, 89, 3, 7]))
| true |
f9bd700a14a2def73cf25ffd208443c9f958fcd6 | a-soliman/py-hello_you | /hello.py | 605 | 4.15625 | 4 | '''
1. Ask user for name.
2. Ask user for age.
3. Ask user for city.
4. Ask user what they enjoy
5. Create output text.
6. Print output to screen
'''
from person_class import *
from sanitize import *
name = input('What is your name?: ')
name = trim(name)
name = make_lower(name)
name = make_title(name)
age = int(input('How old are you?: '))
city = input('In which city do you live?: ')
city = trim(city)
city = make_title(city)
hobbies = input('What do you enjoy doing?: ')
hobbies = make_capital(hobbies)
new_person = Person(name, age, city, hobbies)
print(new_person.get_user_info()) | true |
0a1fe2c9621a03a5529fef3b866b2fcb10e251e4 | PassionateLooker/competetive-programming-python | /27convertCm_to_inchMeterAndKm.py | 826 | 4.15625 | 4 | # print(46.52/2.54) #cm to inch
# print(3491/100) #cm to meter
# print(3491/1000) #cm to km
cent=float(input("Enter centemeter"))
cent_to_inch=cent/2.54
cent_to_meter=cent/100
cent_to_km=cent/1000
print(cent,"centemeter in inches is",cent_to_inch)
print(cent,"centemeter in meter is",cent_to_meter)
print(cent,"centemeter in kilometer is",cent_to_km)
# 48641.664000000004
# 123456.0 centemeter in meter is 1234.56
# 123456.0 centemeter in kilometer is 1.23456
# cent=float(input("Enter centemeter"))
#
# inch=0.394
# meter=0.01
# km=0.00001
#
# cent_to_inch=cent*inch
# cent_to_meter=cent*meter
# cent_to_km=cent*km
#
# print(cent,"centemeter in inches is",cent_to_inch)
# print(cent,"centemeter in meter is",cent_to_meter)
# print(cent,"centemeter in kilometer is",cent_to_km)
| false |
ce8d3d9bc08854ea430b7b9b50d248d81772cf13 | hmangukia/Hack2020 | /Python/SumOfSquares.py | 581 | 4.25 | 4 | '''
This program finds the sum of square
of first n natural numbers.
Input is obtained from the user.
'''
def SumOfSquares(n):
sum = 0
for i in range(1, n+1):
sum = sum + i * i
return sum
def SquaresOfSum(n):
sum = 0
for i in range(1, n+1):
sum = sum + i
return (sum * sum)
n = int(input("Enter a number: "))
if n < 1:
print("Please enter a number greater than 0")
else:
ans = SquaresOfSum(n) - SumOfSquares(n)
print("The difference between square of sums and sum of squares of first {} natural numbers is {}".format(n, ans))
| true |
8709f9c81dbf0cff43a7b72b1bafc58dacc22669 | MoRahmanWork/Py4Fin | /LearningHowToCode/Programmiz/Functions.py | 1,374 | 4.40625 | 4 | def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not provided,
it defaults to "Good
morning!"
"""
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
| true |
3e362c72c37808bb83f742e336e7a354db4d1ee3 | carwyyn/Jumblejumble | /get_words.py | 742 | 4.375 | 4 | import pickle
#a function to retrieve the words from the text file, save them to a list of lists, and store it in pickle
def get_word(file_name, l_name):
#open the text file at the address of file_name
with open(file_name, "r+") as l_name:
#read the text file
whole = l_name.read()
#create a list of each word that is seperated by a comma on text file
l_name = [x.strip() for x in whole.split(',')]
word_list = pickle.load(open("save.p", "rb"))
#add the list of words from text file to a list of all the lists
word_list.append(l_name)
#save the list of lists of words to a pickle, to store words outside program
pickle.dump(word_list, open("save.p", "wb"))
| true |
d95a59cedaa3724c86391d90ef72bfe66d6586f8 | merinjo90/PHYTHON_MINI_PROJECT | /Bank_Application/bank_application.py | 2,197 | 4.34375 | 4 |
"""
#create a bank application.
# : "Account"-parent class, with a "BankName: ABC bank,IFSCcode : 45154,Balance" as
# class variables. inital balace "10000"common to all customer.
# :"AccountHolder"-child class, with instance variables "name,AccNo" and functions
# "Deposit,widrow,Balacecheck" .
# : if the user use any of these method by passing an amount, we want to get full
# bank details and current balance .
# : for balance checking dont want to pass any amount.
# : provided min balance required is limited to 1000.
"""
class Account: #parent class
Balance=10000 #class variables
BankName="ABC"
IFSCcode=45154
min_balance=1000
class AccountHolder: # child class
def __init__(self, name, accNo):
self.Name = name # instance variable
self.AccNo = accNo
def personal_details(self): #instance functions
print("BANK DETAILS\n")
print("Bank Name: ", Account.BankName)
print("IFSCcode : ", Account.IFSCcode)
print("")
print("CUSTOMER DETAILS")
print("")
print("Name: ", self.Name)
print("Account Number",self.AccNo)
print("")
def Deposit(self):
self.personal_details()
# Account.bank_details()
amount = float(input("Enter the amount to be deposite:"))
Account.Balance = Account.Balance + amount
print("Deposite is succesful and the balance in the account is %f" % Account.Balance)
print("------------------")
def widrow(self):
widr_amount=float(input("Enter the amount to be Widrow:"))
if Account.Balance-widr_amount >=Account.min_balance:
Account.Balance=Account.Balance-widr_amount
print("Widrow is succesful and updated balance in the account is %f" % Account.Balance)
else:
print("Sorry Insufficient balance")
print("------------------")
def Balacecheck(self):
print("Balance in the account is %f" %Account.Balance)
account=Account()
account_holder=AccountHolder("amala",123)
account_holder.Deposit()
account_holder.widrow()
account_holder.Balacecheck()
| true |
61b9117744cbaca25ef9ec0144b0bb5fc276cc78 | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020F/Code/notes/20 - formal_documentation/formalDocumentation_ex3.py | 1,175 | 4.46875 | 4 | #-----------------------------------------------------------------------------
# Name: Formal Documentation i.e. docstrings (formalDocumentation_ex3.py)
# Purpose: Provides an example of how to create docstrings in Python using
# formal documentation standards.
#
# Author: Mr. Seidel
# Created: 22-Aug-2018
# Updated: 04-Nov-2018 (fixed spacing)
#-----------------------------------------------------------------------------
def printPerson(name, age=0):
'''
Prints out the information given about a person.
Takes in information from the user and then prints out
a summary of the name and age of the information. If
the age isn't given, then it is defaulted to zero.
Parameters
----------
name : str
The name of the person to be printed
age : int, optional
The age of the person to be printed. If nothing given, value will be zero.
Returns
-------
None
'''
print('Name: ' + str(name))
print('Age: ' + str(age))
return
# Program runs starting here. Above this line, the functions are just defined.
printPerson('Einstein', 40)
printPerson('Newborn') # used the default value of the "age" parameter
| true |
bf39ffd74d9b82192bffa74b189dd30b71788dc3 | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020F/Code/notes/30 - dictionaries/dictionaries_ex1.py | 827 | 4.5 | 4 | #-----------------------------------------------------------------------------
# Name: Dictionaries (dictionaries_ex1.py)
# Purpose: To provide examples of how to use dictionaries
# Accessing keys, values, and adding in information
#
# Author: Mr. Seidel
# Created: 18-Nov-2018
# Updated: 18-Nov-2018
#-----------------------------------------------------------------------------
fruit = {'apple' : 10, 'pear' : 4, 'peach' : 9, 'banana' : 24, 'pineapple' : 3}
print(fruit)
print(fruit.keys()) # function to get all the keys from the dictionary
print(fruit.values()) # function to get all the values from the dictionary
fruit['kiwi'] = 2 # add the key 'kiwi' with a value of 2 to the dictionary
print(fruit)
print(fruit['peach']) # access the value of the key 'peach' from the dictionary
| true |
1f20f0afd76db21f0a9b952d072892e981a47d1d | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020S/Code/notes/21 - logging/logging_ex1.py | 2,170 | 4.15625 | 4 | #-----------------------------------------------------------------------------
# Name: Logging (logging_ex1.py)
# Purpose: To provide examples of how to debug and log information in
# Python programs.
#
# Author: Mr. Seidel
# Created: 11-Nov-2018
# Updated: 02-May-2020 (updated NoneType)
#-----------------------------------------------------------------------------
# These two lines are necessary to import the logging module
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.info('Start of program')
def hypotenuse(sideA, sideB):
'''
Calculates the hypotenuse and returns it to the sender based on
sideA and sideB given
Parameters
----------
sideA : float
One of the arms of the right angle of the triangle
sideB : float
The other arm of the right angle of the triangle
Returns
-------
float
The hypotenuse value
NoneType
Returns None if the values entered were not numbers.
'''
if not isinstance(sideA, (int, float)) or not isinstance(sideB, (int, float)):
logging.error('The values entered into the hypotenuse function were not valid.')
return None
logging.debug('Starting hypotenuse with values ' + str(sideA) + ' and ' + str(sideB))
cSquare = sideA**2 + sideB**2 # local variable used to hold information
logging.debug('cSquared == ' + str(cSquare))
hypotenuseValue = cSquare**0.5 # takes the square root
logging.debug('hypotenuseValue == ' + str(hypotenuseValue))
logging.info('End of function')
return float(hypotenuseValue)
hyp = hypotenuse(3,4)
logging.info('End of program')
'''
This is what the output of the program was after running.
2018-11-11 12:40:28,031 - INFO - Start of program
2018-11-11 12:40:28,044 - DEBUG - Starting hypotenuse with values 3 and 4
2018-11-11 12:40:28,049 - DEBUG - cSquared == 25
2018-11-11 12:40:28,054 - DEBUG - hypotenuseValue == 5.0
2018-11-11 12:40:28,054 - INFO - End of function
2018-11-11 12:40:28,059 - INFO - End of program
'''
| true |
57b208265cf027b9cfd74921fbb1b16cb2ebf371 | mrseidel-classes/archives | /ICS4U/ICS4U-2021-2022S/Code/examples/recursion/Python/recursive_drawing.py | 976 | 4.28125 | 4 | '''
Recursive example using Turtle graphics to draw
Modified from this work
https://p5js.org/examples/simulate-recursive-tree.html
'''
def branch(height, theta): # recursive function
'''
Draws a single branch of a tree.
Parameters
----------
height : int
The length of the branch in the tree
theta : int
The angle between the branches
'''
height *= 0.66;
if (height > 10): # if this is true, continue recursion
right(theta)
forward(height)
branch(height, theta) # recursive call with new height, same theta
backward(height)
left(theta)
left(theta)
forward(height)
branch(height, theta) # recursive call with new height, same theta
backward(height)
right(theta)
return
from turtle import *
speed(10)
color('black')
left(90)
forward(120) # draws initial trunk
branch(120, 45) # change second parameter for angle
backward(120)
done() | true |
6c4ca067f7d85cb9b3c999fca62a3b332fe18604 | mrseidel-classes/archives | /ICS3U/ICS3U-2018-2019-Code/notes/08b - logging/logging_ex5.py | 2,992 | 4.40625 | 4 | #-----------------------------------------------------------------------------
# Name: Logging (logging_ex5.py)
# Purpose: To provide examples of how to debug and log information in
# Python programs.
# Important:
# This version implicitly creates a CRITICAL error
# Commented out some of the debugging info to lower output.
#
# Author: Mr. Seidel
# Created: 11-Nov-2018
# Updated: 26-Nov-2018
#-----------------------------------------------------------------------------
# These two lines are necessary to import the logging module
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.info('Start of program')
def multiply(numbers):
'''
Multiplies all the numbers given in the input list
Parameters
----------
numbers : list of (int, float)
All the numbers to multiply together
Returns
-------
float
The final value of the multiplication
'''
logging.info ('Starting multiply function')
logging.debug('Ensuring input is a list')
assert isinstance(numbers, list), 'Expecting a float'
logging.debug('Ensuring each item in the list is an int or float')
for item in numbers:
# logging.debug('Checking ' + str(item) + ' is an int or a float')
assert isinstance(item, (int, float)), 'Expecting an int or float'
logging.debug('All values are numbers, starting to multiply them all')
total = 1.0
for item in numbers:
# logging.debug('Total is ' + str(total) + ', now multiplying ' + str(item) + ' to the total.')
total *= item
# logging.debug("Total's new value is " + str(total))
logging.debug('Ensuring the final value is a float value')
assert isinstance(total, float), 'Expecting a float'
if isinstance(total, float):
logging.critical('Critical error!')
logging.debug('Final value of total is ' + str(total))
logging.info('End function')
return total
nums = [1, 2, 3, 4, 5, 6, 20, 8]
product = multiply(nums)
assert isinstance(product, float), 'Expecting a float'
logging.info('End of program')
'''
Note the usage of the logging.critical() function shows something slightly different
in the output below.
2018-11-11 13:00:42,103 - INFO - Start of program
2018-11-11 13:00:42,115 - INFO - Starting multiply function
2018-11-11 13:00:42,120 - DEBUG - Ensuring input is a list
2018-11-11 13:00:42,125 - DEBUG - Ensuring each item in the list is an int or float
2018-11-11 13:00:42,131 - DEBUG - All values are numbers, starting to multiply them all
2018-11-11 13:00:42,136 - DEBUG - Ensuring the final value is a float value
2018-11-11 13:00:42,142 - CRITICAL - Critical error!
2018-11-11 13:00:42,147 - DEBUG - Final value of total is 115200.0
2018-11-11 13:00:42,152 - INFO - End of function
2018-11-11 13:00:42,152 - INFO - End of program
'''
| true |
4c577daf3b94303327af0cfbf8ca06b63cdf98f2 | mrseidel-classes/archives | /ICS3U/ICS3U-2018-2019S/Code/notes/02 - conditionalStatements (if)/conditionalStatements.py | 883 | 4.21875 | 4 | #-----------------------------------------------------------------------------
# Name: Conditional Statements (conditionalStatements.py)
# Purpose: To provide information about how conditional statements (if)
# work in Python
#
# Author: Mr. Seidel
# Created: 15-Aug-2018
# Updated: 15-Aug-2018
#-----------------------------------------------------------------------------
# Using 3D coordinates for variable nomenclature
x = 1
y = 2
z = 300
# Basic if statement
if x > 0:
print('Hello!')
# Using 'elif' in a conditional
if x > 1:
print("It's not supposed to be!")
elif y == 2:
print('Yup!')
else:
print('Nope!')
# Using 'and' in a conditional chain
if x > 0 and z > 10:
print("It's supposed to be here!")
else:
print("Shouldn't reach here")
# Using 'or' in a conditional chain
if x > 10 or y > 10 or z > 10:
print('Yup!')
else:
print('Nope!') | true |
1825a895b2ece800dfb949c115529043607cd498 | theIncredibleMarek/algorithms_in_python | /insertion_sort.py | 2,537 | 4.1875 | 4 | #!/usr/bin/env python3
# TODO - start from the 2nd element - index is 1
# if ascending - check if smaller than the one immediately preceding
# if descending - check if bigger than the one immediately preceding
# finish when you reach the end of the list
def sort(input, ascending=True):
print("Original: {}".format(input))
print("Ascending sort: {}".format(ascending))
# empty and one item lists are considered sorted
if((len(input)) <= 1):
return input
passes = 0
for index in range(1, len(input)):
# no point in checking the first[0] item, that one is in order already
target_index = 0
if(ascending):
first = input[index - 1]
second = input[index]
else:
first = input[index]
second = input[index - 1]
if(first > second):
# value is not at the correct place
target = input[index]
if index == 1:
# if index is 1 then we just automatically swap the values - no
# need for a for loop
shift(input, 0, index)
else:
# start a loop to find out the target_index
for i in range(index - 1, 0 - 1, -1):
# 0-1 is there because 0 index must be reached
if ascending:
if target >= input[i]:
target_index = i + 1
break
else:
if target <= input[i]:
target_index = i + 1
break
shift(input, target_index, index)
passes += 1
print("{} passes".format(passes))
return input
def shift(input, start_index, finish_index):
# it's safe to assume that the number we want to move to the beginning of
# the list(start_index) is at the end of it(finish_index)
target = input[finish_index]
for i in range(finish_index - 1, start_index - 1, -1):
# since the target is already saved, I will just move all the items
# below it one place forward
input[i + 1] = input[i]
input[start_index] = target
print(sort([1, 2, 1], False))
print(sort([2, 1, 7, 3, 4, 5, 6, 2, 3, 1], False))
print(sort([1, 2, 3, 4, 5, 6], False))
print(sort([2], False))
print(sort([], False))
print(sort([2, 1]))
print(sort([1, 2, 1]))
print(sort([2, 1, 7, 3, 4, 5, 6, 2, 3, 1]))
print(sort([1, 2, 3, 4, 5, 6]))
print(sort([2]))
print(sort([]))
| true |
59a3a226dfc7ce191d25ff070d356adb970d984a | hugofolloni/50-days-of-code-challenge | /019/fibonacci-sequence.py | 432 | 4.125 | 4 | print("-----------\n FIBONACCI\n-----------")
parameters = int(input("Tell me the length of your wanted Fibonacci sequence?\n "))
fibArray = [0, 1]
def fibonacciCalculator():
penultimo = fibArray[-2]
ultimo = fibArray[-1]
newNumber = penultimo + ultimo
fibArray.append(newNumber)
for i in range(0, parameters):
fibonacciCalculator()
beautifulArray = (", ".join(map(str, fibArray)))
print(beautifulArray)
| false |
963fdbbf6fe77bcbd86e55c03d7ec1938de8d6f7 | Prot0type1/IS-51-FINAL | /FINAL.py | 1,378 | 4.125 | 4 | """
start
this program will output the grades of students on the final by:
-number of grades
-average of grades
-percentage of grades above the average percentage
the average grade is 83.25.
the total number of grades is 24.
the percentage of grades above average is 54.17
the list will be introduced from the dictionary by using the open method
the grades will then be listed as integers.
after, the calculations can begin.
the end result will display the 3 solutions.
finalize
"""
"""
main()
initiates the program
infile = open
output total number of grades
print("")
display average
print("")
calculate_percentage_above_average()
caluate the percentage
print("")
"""
def main():
file = "Final.txt"
calculate_percentage_above_average(file)
"File is being called"
def calculate_percentage_above_average(file):
infile = open(file, 'r')
listGrades = [int(line.rstrip()) for line in infile]
infile.close()
lenght = len(listGrades)
sum1 = sum(listGrades)
avg = sum1 / lenght
print("number of grades:", lenght)
print("average grade:", avg)
counter = 0
for item in listGrades:
if item > avg:
counter += 1
percentHigher = counter / lenght
print("Total Percentage of Grades above Average:", end =" ")
print("{0:.2%}".format(percentHigher))
main() | true |
79bf452c4f9f4e5d78565fd0efdfa77f5302e891 | shearocke/IT_SQL1 | /MyDatabase.py | 1,074 | 4.4375 | 4 | import sqlite3
# create a name for the database
database = 'Company.db'
# create a connection to the database
conn = sqlite3.connect(database)
# conn.execute('DROP TABLE IF EXISTS Customers')
#
# create table with fields and data types
# conn.execute('''CREATE TABLE Customers
# (id INT NOT NULL,
# name TEXT NOT NULL,
# age INT NOT NULL,
# gender TEXT NOT NULL);''')
i = int(input("Press 1 to continue: "))
while i == 1:
ids = input('Enter id: ')
name = input('Enter name: ')
age = input('Enter age: ')
gender = input('Enter gender: ')
myTuple = (ids, name, age, gender)
# enter data values into the database
conn.execute('''INSERT INTO Customers (id, name, age, gender)VALUES
(?,?,?,?);''', myTuple)
# save changes into db
conn.commit()
i = int(input("Press 1 to continue: "))
# print results from query
records = conn.execute('''SELECT * FROM Customers;''')
for rows in records:
print(rows)
# closes db so other programs can access it
conn.close()
| true |
2c340beb71b8bce58cc3c5b1b2e1683a1b82c820 | Luciano0000/Pyhon- | /object/魔术方法/QianFeng023object3.py | 1,064 | 4.3125 | 4 | # 魔术方法续:
# __str__
'''
触发时机:使用print(对象名)或者str(对象名)的时候触发去调用__str__里面的内容
参数:一个self接收对象
返回值:必须要在__str__中有返回值且是字符串类型
作用:print(对象时)进行操作,得到字符串,通常用于快捷操作
注意:无
'''
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name是:'+self.name+',age是:'+str(self.age)
p = Person('tom', 20)
print(p)
# 单纯的打印对象名称则出来的时一个地址,这个地址对于开发者来说无意义
# 如果想在打印对象名的时候能够给开发者更多的一些信息量
p1 = Person('jack', 27)
print(p1)
# str(p1)
'''
总结魔术方法:s
重点:
__init__ (构造方法,创建完空间之后调用的第一个方法) __str__
非重要:
__new__ 作用 开辟空间
__del__ 作用 没有指针引用的时候会调用,99%都不需要重写
__cal__ 作用 想不想将对象当成函数用
''' | false |
97c2b618a64f9ee80aa0317ea2e204f52495dd39 | Luciano0000/Pyhon- | /List/QianFeng008list02.py | 1,047 | 4.15625 | 4 | # 列表的切片
#['abc','kkokok','dasd','geeww',99,80.8]
list1 = ['abc','kkokok','杨幂','胡一菲',666,68.8]
#列表里允许任意类型
print(list1)
print(list1[2:4]) #杨幂 胡一菲 脚标:2 3 同样包前不包后 [2:4]
#截取的结果再次保存在一个列表中 ['','']
print(list1[::2]) #支持步长
print(list1[-1::-2]) #支持逆序
# list 列表的添加:
# 临时的小数据库: list
# list的添加函数 :1.append()追加 2.extend()列表的合并 3.insert()指定位置插入元素
# list的删除函数 : 1.remove() 2.pop() 3.clear() 4.del()
names = ['黑嘉嘉','孙俪','功利','王丽坤']
girls = ['杨幂']
while True:
name = input('请输入你心目中的美女')
if name == 'quit':
break
girls.append(name)
print(girls)
#extend():合并 或 一次添加多个元素
girls.extend(names) #合并两个列表
print(girls)
# 符号 +
girls = girls+names # + 也用于列表的合并 等价于extend()函数
print(girls)
#insert(位置,'')
girls.insert(1,'刘涛') #
print(girls) | false |
68647861144f8807638df84e08185d03264c8d02 | Carla08/cracking-the-interview | /data_structures/linked_lists/node_lists_problems.py | 2,890 | 4.125 | 4 | from typing import List
from data_structures.linked_lists.linked_list import LinkedList
def reverse_linked_list(lst):
n = lst.head
_next = None
_prev = lst.head
while n:
_next = n.nxt
n.nxt = _prev
_prev = n
n = _next
lst.head.nxt = None
lst.head = _prev
return lst
####################################################################################################
def find_intersection_of_linked_lists(lst_of_lsts: List['LinkedList']):
# get the shortest list
shortest_len = min(len(lst) for lst in lst_of_lsts)
# for each list set the pointer on the nth before last node
for linked_list in lst_of_lsts:
nth = (len(linked_list) - shortest_len) + 1
linked_list.set_pointer('common', nth)
# iter through all lst at the same time.
nodes = get_all_lst_nodes(lst_of_lsts)
while nodes:
all_equal = check_all_nodes_equal(nodes)
if all_equal:
return nodes[0] # any node will do, since they're all equal.
else:
nodes = get_all_lst_nodes(lst_of_lsts)
def get_all_lst_nodes(lst_of_lsts):
nodes = []
for lst in lst_of_lsts:
common_pointer = lst.get_pointer('common')
nodes.append(common_pointer)
lst.update_pointer('common') # move pointer one ahead
return nodes
def check_all_nodes_equal(lst):
return len(set(lst)) == 1
####################################################################################################
def find_list_circular_node(lst):
# set quick n slow pointers
lst.set_pointer('quick')
lst.set_pointer('slow')
#advance quick pointer.
lst.update_pointer('quick', 2)
try:
while not lst.get_pointer('slow') == lst.get_pointer('quick'):
lst.update_pointer('slow')
lst.update_pointer('quick', 2)
return lst.get_pointer('slow') # or quick, since they're equal.
except IndexError:
return False # not a circular list.
####################################################################################################
def remove_nth_from_end(head, n: int):
"""
Given a linked list, remove the n-th node from the end of list and return its head.
"""
nth_map = {}
# go through the list and count the nodes
node = head
i = 1
while node:
nth_map[i] = node
node = node.nxt
i += 1
# the nth from the end
nth_from_end = i - n
node_to_remove = nth_map[nth_from_end]
node_before = nth_map[nth_from_end - 1]
# remove - case 1: node is head.
if node_to_remove == head:
head = node
# remove - case 2: node is end.
elif node_to_remove.nxt == None:
node_before.nxt = None
# remove - case 3: node in the middle of list
else:
node_before.nxt = node_to_remove.nxt
return head
| true |
c25ab8635033d6aa75ba95f82cdd6b7d2f8d3301 | MichaelKirkaldyV/Algos_ | /findmiddle.py | 1,330 | 4.125 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
self.size = 0
self.head = head
def insertNode(self, value):
node = Node(value)
print(node)
if self.head == None:
node = self.head
return
else:
currentNode = self.head
while currentNode:
if currentNode.next is None:
currentNode.next = node
break
else:
currentNode = currentNode.next
def printList(self):
currentNode = self.head
while currentNode:
print (currentNode.value)
currentNode = currentNode.next
def findMiddleElement(self):
slow_pntr = self.head
fast_pntr = self.head
if self.head is not None:
while fast_pntr is not None and fast_pntr.next is not None:
fast_pntr = fast_pntr.next.next
slow_pntr = slow_pntr.next
print ("Here is the middle element", slow_pntr.value)
LL = LinkedList()
LL.insertNode(5)
LL.insertNode(20)
LL.insertNode(96)
LL.insertNode(67)
LL.insertNode(34)
LL.printList()
LL.findMiddleElement()
| true |
b128d95e3c348686674f2162d958e4705d72bf45 | 123akhil/datascience | /6.00.1x_Introduction_to_Computer_Science_and_Programming_Using_Python/edx_old/Resources/6.00.1x/PROBLEMS/Finger Excercises/test.py | 210 | 4.3125 | 4 | # -*- coding: cp1252 -*-
a = int(raw_input('Mete tu nmero: '))
if a>3:
print(' ')
print ('Tu nmero es mayor que 3')
else:
print('Tu numero es menor o igual que 3')
print ('Hemos terminado')
| false |
ec6bae2cb2305d4d9f86090204a7025481a130ea | ganesspandian2/programming-in-python | /vowcha.py | 269 | 4.125 | 4 | def isvowel(s):
for i in s:
if i=="a" or i=="e" or i=="i" or i=="o" or i=="u":
return True
return False
s=input()
if isvowel(s):
print("The given character is Vowel")
else:
print("The given character is Consonant")
| false |
f71dc34a7f9a7010f8c6cf830149d3a649a996b1 | daviidluna/PythonLists | /lists.py | 1,195 | 4.1875 | 4 | mine = ['a promised', 'land', 'hehe']
print(mine)
yes = ['cabbage', 'eggplant', 'watermelon']
if 'watermelon' in yes:
print('yes, watermelon is present in the list \'yes\'')
wait_list = ['amanda', 'fiber', 'oliver']
if 'oliver' in wait_list:
print('yes he is on the wait list')
# Accessing list items
one = ['first series', 'second series', 'third']
print(one[2])
one_ = one[1:2]
print(one_)
two = ['fifty', 'shades', 'of grey', 'is', 'cool', 'yes']
print(two[:4]) # By leaving out the start value, the range will start at the first item
print(two[3:]) # By leaving out the end value, the range will go on to the end of the list
water = ['cool water', 'lukewarm', 'cold', 'hot']
print(water[:3])
print(water[2:])
comp = ['red one', 'blue one', 'grey oone', 'pink', 'food', 'yes']
print(comp[-5:-2])
list_of_food = ['chips', 'soda', 'candy', 'potatoes', 'eggplant', 'banana']
print(list_of_food[3:-1])
print(list_of_food[-6:-3])
list_of_students = ['mia', 'lial', 'ria', 'code', 'yep', 'yurpa']
if 'yurpa' in list_of_students:
print('yes yurpa is there')
# Changing list items
this_list = ['iphone', 'android', 'nokia', 'sprint']
this_list[3] = 'galactic'
print(this_list)
| true |
859566908e2be6b188a8c660df0e7d766d1624b5 | ahdeshpande/PythonPrograms | /html_unordered_list.py | 1,454 | 4.21875 | 4 | def string_list_to_html_ul(string_list):
"""
Function that converts a string list to an HTML unordered list
"""
# Create a html unordered list from the user input list.
# Add the start tag of ul
html_string = "<ul>\n"
# Iterate through input list
for user_input in string_list:
html_string += "\t<li>" + user_input + "</li>\n"
# Append the closing tag of ul
html_string += "</ul>\n"
return html_string
print("Welcome to string to HTML unordered list conversion!")
# This is a list to store the user inputs.
user_input_list = []
# Set an initial condition depending on if you want to accept input from user.
accept_input = True
print("Enter the string: [enter blank string when done]")
# Set up the while loop to accept.
while accept_input:
str_input = input("> ")
if str_input == "":
accept_input = False
else:
# Check for special characters '<' '>'
# If '<', change to <
str_input = str_input.replace('<', '<')
# If '>', change to >
str_input = str_input.replace('>', '>')
# If not converted like above, they can mess up the interpreter.
# Once converted, append the string to the list.
# Strip the whitespace at the beginning or at the end of the string.
user_input_list.append(str_input.strip())
# Print the output
print("\nOutput:")
print(string_list_to_html_ul(user_input_list))
| true |
708f717b8ed7b06eb15998d711fa97cf70e1da14 | renatamoon/python_classes_poo | /python_98_classes_pessoa.py | 2,603 | 4.25 | 4 | from datetime import datetime
class Pessoa: #quando uma funcao esta dentro de uma classe
#ela é um metodo
ano_atual = int(datetime.strftime(datetime.now(), '%Y')) #var da classe
#todos os objetos terão essa variavel
def __init__(self, nome, idade, comendo=False, falando=False):
self.nome = nome #mesmo que o valor da self seja igual ao
#parametro da funcao, eles nao sao iguais, pois um recebe o valor do outro
self.idade = idade
self.comendo = comendo
self.falando = falando
#variavel = 'Valor'
#print(variavel) #somente podemos usar o valor dessa variavel dentro
#dessa classe, nao podemos usa-la fora
def falar(self, assunto):
if self.comendo:
print(f'{self.nome} nao pode falar comendo')
return
if self.falando:
print(f'{self.nome} ja esta falando')
return
print(f'{self.nome} esta falando sobre {assunto}')
self.falando = True
def parar_falar(self):
if not self.falando:
print(f'{self.nome} não está falando')
return
print(f'{self.nome} parou de falar')
self.falando = False
def comer(self, alimento):
if self.comendo:
print(f'{self.nome} já está comendo')
return
if self.falando:
print(f'{self.nome} não pode comer falando')
return
print(f'{self.nome} está comendo {alimento}.')
self.comendo = True
def parar_comer(self):
if not self.comendo:
print(f'{self.nome} nao está comendo ...')
return
print(f'{self.nome} parou de comer.')
self.comendo = False
def get_ano_nascimento(self):
return self.ano_atual - self.idade #para usar a variavel ano_atual que está
#fora da classe, tem que usar o self pra chamar como usamos acima
# ---------------- não precisa estar em files diferentes
p1 = Pessoa('Luiz', 29) #usando o modulo para criar uma pessoa
#p2 = Pessoa('Joao', 32) #usando o modulo para criar outra pessoa
#todas as instancias devem ter esses parametros padrao
p2 = Pessoa('Joao', 32)
# print(p1.ano_atual)
# print(p2.ano_atual)
#print(Pessoa.ano_atual) #usando a classe em si, usando a var da classe
print(p1.get_ano_nascimento()) #usando o valor da idade de p1 e pegando o ano de nascimento
print(p2.get_ano_nascimento())
p1.comer('maça')
p1.comer('maça')
p1.falar('assunto')
p1.parar_falar()
p1.comer('massa') | false |
276ea714e674774dd1ab9f1256be7068c7629d27 | renatamoon/python_classes_poo | /python_110_heranca.py | 1,333 | 4.59375 | 5 | #APRENDEREMOS HERANÇA - ONDE UM OBJETO É OUTRO OBJETO
#a herança funciona de cima para baixo. A pessoa é quem decidiu os metodos principais para as
#outras classes. O CLIENTE E ALUNO é uma melhoria da classe Pessoa, é mais especializado.
#enquanto a Pessoa pode ser usada por qualquer classe, as outras subclasses (Cliente, Aluno)
#não podem pegar metodos da Classe Cliente e vice versa.
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.nomeclasse = self.__class__.__name__ #chamando o nome da classe que está usando
# a classe
def falar(self):
print(f'{self.nomeclasse} está falando ...')
class Cliente(Pessoa): #herdando os atributos de pessoa / cliente é uma Pessoa
def comprar(self):
print(f'{self.nomeclasse} está comprando ...')
class Aluno(Pessoa): #herdando os atributos de pessoa / Aluno é uma Pessoa
def estudar(self):
print(f'{self.nomeclasse} está estudando ...')
cliente1 = Cliente("Renata", 25)
print(cliente1.nome)
#cliente1.falar()
cliente1.comprar()
aluno1 = Aluno("Maria", 40)
print(aluno1.nome)
#aluno1.falar()
aluno1.estudar()
p1 = Pessoa('João', 43)
p1.falar() #a Pessoa somente herdou o metodo falar, não herdou o estudar nem o comprar.
| false |
65025e1d13901d95f63f6d2783100aa1608c46c0 | KKAiser97/trantrungkien-fundamentals-c4e26 | /exses2/BMI.py | 295 | 4.15625 | 4 | cm=float(input("Enter your height(cm): "))
h=cm/100
w=float(input("Enter your weight(kg): "))
bmi=w/(h*h)
print(bmi)
if bmi<16:
print("Severely underweight")
elif bmi<18.5:
print("Underweight")
elif bmi<25:
print("Normal")
elif bmi<30:
print("Overweigh")
else:
print("Obese") | false |
19e233a3acb218beb3108334b725d5bce97020e2 | 7134g/m_troops | /py/common/design_patterns/Duty.py | 967 | 4.15625 | 4 | """
责任链模式
这条链条是一个对象包含对另一个对象的引用而形成链条,每个节点有对请求的条件,当不满足条件将传递给下一个节点处理。
"""
class Bases:
def __init__(self, obj=None):
self.obj = obj
def screen(self, number):
pass
class Top(Bases):
def screen(self, number):
if 200 > number > 100:
print("{} 划入A集合".format(number))
else:
self.obj.screen(number)
class Second(Bases):
def screen(self, number):
if number >= 200:
print("{} 划入B集合".format(number))
else:
self.obj.screen(number)
class Third(Bases):
def screen(self, number):
if 100 >= number:
print("{} 划入C集合".format(number))
if __name__ == '__main__':
test = [10, 100, 150, 200, 300]
c = Third()
b = Second(c)
a = Top(b)
for i in test:
a.screen(i)
| false |
a05cc0a95deaa4eeb51a108105ec6d11dfa77df6 | unclexo/data-structures-and-algorithms | /3.Maps/python/Map.py | 2,894 | 4.125 | 4 | """
The implementation of Map ADT
But using Python list ADT
"""
class Map:
""" Creates empty map instance """
def __init__(self):
self._items = list()
""" Returns the number of entries in the map """
def __len__(self):
return len(self._items)
""" Determines if the map contains the given key """
def __contains__(self, key):
index = self._findPosition(key)
return index is not None
"""
Adds a new entry to the map if the key does exist. Otherwise,
the new value replaces the current value associated with the key.
"""
def add(self, key, value):
index = self._findPosition(key)
if index is not None:
self._items[index].value = value
return False
else:
new_entry = _MapEntry(key, value)
self._items.append(new_entry)
return True
""" Returns the value associated with the given key """
def valueOf(self, key):
index = self._findPosition(key)
if index is None:
raise ValueError("Invalid map key.")
return self._items[index].value
""" Removes the entry associated with the key """
def remove(self, key):
index = self._findPosition(key)
if index is None:
raise ValueError("Invalid map key")
self._items.pop(index)
""" Returns an iterator for traversing the keys in the map """
def __iter__(self):
return _MapIterator(self._items)
""" Finds index position for the given key in the list """
def _findPosition(self, key):
# Iterates through each entry in the list
for i in range(len(self)):
# Is the key stored in the position (i)th?
if self._items[i].key == key:
return i
# When not found, return None
return None
""" Storage class for holding key=>value pairs """
class _MapEntry:
def __init__(self, key, value):
self.key = key
self.value = value
""" Helper class for map iterator """
class _MapIterator:
def __init__(self, items):
self._current = 0
self._items = items
def __iter__(self):
return self
def __next__(self):
if self._current < len(self._items):
item = self._items[self._current]
self._current += 1
return item
else:
raise StopIteration
def main():
# Should create an empty map
m = Map()
# Should add some key/value pairs
m.add("key1", "MNO")
m.add("key2", "XYZ")
len(m)
# Should remove "key2"
m.remove("key2")
# Should contain "key1"
print("key1" in m)
# Should raise ValueError
# print(m.valueOf("key2"))
# Should be iterable
for item in m:
print(item.key, item.value)
if __name__ == '__main__':
main()
| true |
a702ddc653080253f5b99f72af3a6bfc7577c212 | jaychovatiya4995/B6-python-Es-LU | /day4Assignment1.py | 573 | 4.5625 | 5 | # Find all occurrence of substring in given string
import re
test_str = "what we think we become; we are python programmer"
# get substring
test_sub = input("Enter a substring : ")
# printing original string
print("The original string is : " + test_str)
# printing substring
print("The substring to find : " + test_sub)
# using re.finditer()
# All occurrences of substring in string
res = [i.start() for i in re.finditer(test_sub, test_str)]
# printing result
print("The start indices of the substrings are : " + str(res))
| true |
120e946f16c877c7fc5f2e3ebf3f32dabd8c7290 | MrYangShenZhen/pythonstudy | /类的学习/迭代器.py | 1,228 | 4.21875 | 4 | ########通过iter()内置函数取得可迭代对象的迭代器。
# list = [1,2,3,4,5] # list是可迭代对象
# lterator = iter(list) # 通过iter()方法取得list的迭代器
# print(lterator)
# ####next()函数是通过迭代器获取下一个位置的值。
# print(next(lterator)) # 1
# print(next(lterator)) # 2
# print(next(lterator)) # 3
# print(next(lterator)) # 4
# print(next(lterator)) # 5
# print(next(lterator))
#####判断一个对象是否可迭代isinstance(object,classinfo)内置函数可以判断一个对象是否是一个已知的类型,类似 type()
#####object -- 实例对象。
#####classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组
########需要知道collections模块里的Iterable。通俗点讲,凡是可迭代对象都是这个类的实例对象。
# import collections
# print(isinstance([1, 2, 3], collections.Iterable))
# print(isinstance((1,2,3), collections.Iterable))
# print(isinstance({"name":"chichung","age":23}, collections.Iterable))
# print(isinstance("sex", collections.Iterable))
# print(isinstance(123,collections.Iterable))
# print(isinstance(True,collections.Iterable))
# print(isinstance(1.23,collections.Iterable))
| false |
fe4612af0b77bc0b63393dd4866dd40b57a15b67 | MrYangShenZhen/pythonstudy | /类的学习/私有类(封装).py | 872 | 4.15625 | 4 | #####双下划线代表该属性是类的私有属性。只能内部调用
######## 私有属性/方法可以在类本身中使用,但不能在类/对象外、子类/子类对象中使用python中的封装操作,
######## 不是通过权限限制而是通过改名实现的可以通过“类名.__dict__”查看属性(包括私有属性)和值,在类的内部使用
######## 私有属性,python内部会自动改名成“_类名__属性名”形式
class People(object):
def __init__(self,name,age,gender, money):
self.name = name
self.age = age
self.gender = gender
self.__money = money
def __play(self):
print("王者荣耀正在进行时")
def test(self):
self.__play()
p1 = People('user1', 10, 'male', 1000000)
print(p1.gender)
# print(p1.__money)
# p1.__play()
# p1.test()
p1.__play()
| false |
c7c07302b753e1441634b08603f7eae31f878865 | michaelpotgieter/em-ai-cee | /02_guess_number_game/program.py | 1,472 | 4.125 | 4 | import random
print('----------------------------------')
print('| GUESS THE NUMBER |')
print('----------------------------------')
print()
# initialise numbers and ask for name
unumber_a = 0
unumber_b = 0
user_name = input('What is your name ')
print("I'll guess a number between two which you choose")
print()
# enforce two different numbers
while unumber_a == unumber_b:
# Accept number from user and convert to integer
unumber_a_text = input('Enter the first number ')
unumber_a = int(unumber_a_text)
unumber_b_text = input('Enter the second number ')
unumber_b = int(unumber_b_text)
if unumber_a < unumber_b:
number = random.randint(unumber_a, unumber_b)
guess = unumber_a - 1
elif unumber_a > unumber_b:
number = random.randint(unumber_b, unumber_a)
guess = unumber_b - 1
else:
print('You have entered the same number. Please select two different numbers.')
print()
while guess != number:
guess_string = input('What is your guess ')
guess = int(guess_string)
if guess < number:
print('Sorry {}, your guess of {} is too LOW'.format(user_name, guess))
print()
elif guess > number:
print('Sorry {}, your guess of {} is too HIGH'.format(user_name, guess))
print()
else:
print('Well done {}, your guess of {} is CORRECT'.format(user_name, guess))
print()
| false |
27a74709b50496ca2af27051d2862558db520143 | Lopez-John/lambdata-Lopez-John | /module4/anothersqlite3_example.py | 1,080 | 4.375 | 4 | """creating and inserting data with sqlite"""
import sqlite3
def create_table(conn):
curs = conn.cursor()
create_table = '''
CREATE TABLE students(
id INTEGER PRIMARY KEY AUTOINCREMENT
name CHAR(20)
favorite_number INTEGER
leaste_favorite_number INTEGER
);
'''
curs.execute(create_table)
curs.close()
conn.commit()
def insert_date(conn, data):
curs = conn.cursor()
for date_point in data:
insert_data = '''
INSERT INTO students
VALUES (
{}
)
'''.format(data_point)
curs.execute(insert_data)
curs.close()
conn.commit()
def show_all(conn):
curs = conn.cursor()
curs.execute('SELECT * FROM students')
info = curs.fetchall()
curs.close()
return curs
if __name__ == '__main__':
data = [
('Nick', 77, 13),
('John', 101, 1010)
]
conn = sqlite3.connect('example_db.sqlite3')
create_table(conn)
insert_data(conn, data)
show_all(conn)
| false |
ffd8f674640427e61c5bc5ac96ab3f7f04548177 | joseEnrique/Algoritmos | /Recursividad-con-python/potencyRecursionNotFinalWithoutMemory.py | 718 | 4.21875 | 4 | # Jose Enrique Ruiz Navarro
# email- joseenriqueruiznavarro@gmail.com
#http://www.systerminal.com
# -*- encoding: utf-8 -*-
def potenciaNoFinal(base,exponente):
# base case
if(exponente==0):
result=1
elif(exponente<0):
result=1/potenciaNoFinal(base,-exponente)
else:
result = base*potenciaNoFinal(base,exponente-1)
# For example : 2^3 =2*2*2*1
# multiply the base until the exponent is 0 which multiply by 1 in the final case
return result
def main():
# enter base
base = int(input("Introduce la base: "))
# enter exponent
exponente=int(input("Introduce el exponente: "))
res = potenciaNoFinal(base,exponente)
# print result
print(res)
if __name__ == "__main__":
main()
| false |
0cf9b382e746712ad7fcf946a17f029b137c3ace | hari197/Tasks | /Task3.py | 603 | 4.40625 | 4 | # Program to find the sum of the series 1 + 3^2/3^3 + 5^2/5^3... upto n terms
#Taking input from user for the number of terms
n=int(input("Please enter the number of terms: "))
sum=0 #initialize sum
i=1 #initialize increment variable for loop
counter=0 #initialize counter
#If the input from the user is 0, print the sum is 0
if(n==0):
print("The sum of the series is 0")
#To find the sum of series upto n terms
while(i!=0):
if(i%2!=0):
sum=sum+((i*i)/(i*i*i))
counter+=1
i+=1
if counter==n:
break
#Displays the sum of series
print("The sum of the series is: ", sum)
###########
| true |
a634936bcf212b5bc9d5c44e52c89098241992e8 | ninaderi/Data-Sceince-ML-projects | /copy_loops.py | 1,939 | 4.125 | 4 | # import copy
#
# # initializing list 1
# li1 = [1, 2, [3,5], 4]
#
# # using deepcopy to deep copy
# li2 = copy.deepcopy(li1)
#
# # original elements of list
# print ("The original elements before deep copying")
# for i in range(0,len(li1)):
# print (li1[i],end=" ")
#
# print("\r")
#
# # adding and element to new list
# li2[2][0] = 7
#
# # Change is reflected in l2
# print ("The new list of elements after deep copying ")
# for i in range(0,len( li1)):
# print (li2[i],end=" ")
#
# print("\r")
#
# # Change is NOT reflected in original list
# # as it is a deep copy
# print ("The original elements after deep copying")
# for i in range(0,len( li1)):
# print (li1[i],end=" ")
# colors = ["red", "green", "blue", "purple"]
# for i in range(len(colors)):
# print(colors[i])
# presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
# for i in range(len(presidents)):
# print("President {}: {}".format(i + 1, presidents[i]))
presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
for num, name in enumerate(presidents, start=1):
print("President {}: {}".format(num, name))
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors):
ratio = ratios[i]
print("{}% {}".format(ratio * 100, color))
#Our real goal is to loop over two lists at once. This need is common enough that there’s a special built-in function just for this.
# Python’s zip function allows us to loop over multiple lists at the same time:
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for color, ratio in zip(colors, ratios):
print("{}% {}".format(ratio * 100, color))
#If you need to loop over multiple lists at the same time, use zip
#If you only need to loop over a single list just use a for-in loop
#If you need to loop over a list and you need item indexes, use enumerate | false |
4597c560c59325945747cf07858f5acc54e57435 | jswindlehurst/SumofPrimes2 | /main.py | 1,066 | 4.1875 | 4 | import math
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(math.sqrt(number) + 1), 2):
if number % current == 0:
return False
return True
return False
def get_primes(number):
while True:
if is_prime(number):
yield number
number += 1
def solve_number_10(num):
total = 2
for next_prime in get_primes(3):
if next_prime < num:
total += next_prime
else:
return (total)
# def prime_num(n):
# for i in range(2, int(n//2) + 1):
# if n % i == 0:
# yield False
# yield True
def main():
# returns the sum of the prime numbers between 0 and num.
# See jeffknupp blog on generators - really good explanation.
num = int(input("Please enter the top range number: "))
print("The sum of prime numbers to ", num, "is: ", solve_number_10(num))
if __name__ == '__main__':
main() | true |
48fd6448e063ada5e4cfa3d0ff9583de375f413c | intouchkey/GIT_TASK1 | /question3.py | 2,134 | 4.375 | 4 | import abc
class Transportation(metaclass = abc.ABCMeta):
"""Abstract base class"""
def __init__( self, start, end, distance ):
if self.__class__ == Transportation:
raise NotImplementedError
self.start = start
self.end = end
self.distance = distance
def get_start(self):
return self.start
def get_end(self):
return self.end
def get_distance(self):
return self.distance
@abc.abstractmethod
def find_cost( self ):
"""Abstract method; derived classes must override"""
raise NotImplementedError
class Walk(Transportation):
def __init__(self, start_place = "", end_place = "", distance = 0):
super().__init__(start_place, end_place, distance)
def find_cost(self):
cost = super().get_distance() * 0
## print ("From " + super().get_start_place() + " to " + super().get_end_place() + ", it will cost " + str(cost) + " Baht by walking")
return cost
# main program
class Taxi(Transportation):
def __init__(self, start_place = "", end_place = "", distance = 0):
super().__init__(start_place, end_place, distance)
def find_cost(self):
cost = super().get_distance() * 40
## return ("From " + super().get_start_place() + " to " + super().get_end_place() + ", it will cost " + str(cost) + " Baht by taking a taxi")
return cost
class Train(Transportation):
def __init__(self, start_place = "", end_place = "", distance = 0, stations = 0):
super().__init__(start_place, end_place, distance)
self.stations = stations
def find_cost(self):
cost = self.stations * 5
## return ("From " + super().get_start_place() + " to " + super().get_end_place() + ", it will cost " + str(cost) + " Baht by taking a train")
return cost
travel_cost = 0
trip = [ Walk("KMITL","KMITL SCB Bank",0.6),
Taxi("KMITL SCB Bank","Ladkrabang Station",5),
Train("Ladkrabang Station","Payathai Station",40,6),
Taxi("Payathai Station","The British Council",3) ]
for travel in trip:
travel_cost += travel.find_cost()
print(travel_cost)
| false |
157b9433760356c688e53921e2669343b3855881 | levashovn/test_task_sos | /task_5.py | 971 | 4.1875 | 4 | import random
def create_txt_file():
ask = True
f = open('random_numbers.txt', 'w')
while ask:
try:
rows_count = int(input('Please enter a number of rows to write: '))
ask = False
for row in range(rows_count):
for i in range(25):
num = random.randint(1, 100)
f.write(str(num))
f.write('\n')
except:
print('Please enter an integer number of rows')
def read_file():
ask = True
f = open('random_numbers.txt', 'r')
while ask:
try:
rows_count = int(input('Please enter a number of rows to read: '))
ask = False
lines = f.readlines()
if rows_count > len(lines):
print('Provided number of rows is greater than the rows in a file, you will get the whole file as an ouput')
for line in lines[-rows_count:]:
##using split here to bypass endlines in console
print(line.split('\n')[0])
except:
print('Please enter an integer number of rows')
if __name__ == "__main__":
create_txt_file()
read_file() | true |
659a31b1550d3e59f969b1d33d1dbf0be88b6baf | DanielBMeeker/module4 | /main/basic_if.py | 1,919 | 4.21875 | 4 | """
Program: basic_if.py
Author: Daniel Meeker
Date: 06/09/2020
This program accepts user input for desired membership
level then calculates and returns the cost of the level.
"""
# function definitions:
def get_membership(): # Get user input
membership = input("Welcome to the Programmer's Toolkit Monthly Subscription Box! "
"\n Our membership level's are:"
"\n 1: Platinum"
"\n 2: Gold"
"\n 3: Silver"
"\n 4: Bronze"
"\n 5: Free Trial"
"\n Please enter the number corresponding to your desired level: ")
# I chose to request integers from the user to avoid possible errors with spelling and to
# make a simple input validation possible
return membership
def calculate_cost(membership): # Use the user input to calculate cost
if int(float(membership)) == 1:
price = 60
level = "Platinum"
elif int(float(membership)) == 2:
price = 50
level = "Gold"
elif int(float(membership)) == 3:
price = 40
level = "Silver"
elif int(float(membership)) == 4:
price = 30
level = "Bronze"
elif int(float(membership)) == 5:
price = 0
level = "Free Trial"
else:
price = 0
level = "Error"
membership_cost = [level, price] # Saved as a list to make output function easier.
return membership_cost
def output_result(membership_cost):
if membership_cost[0] == "Error":
return "Error, must choose a level between 1-5"
else:
return "You chose {} membership, your price is ${:.2f} per month".format(membership_cost[0], membership_cost[1])
if __name__ == '__main__':
print(output_result(calculate_cost(get_membership()))) # call the functions to run the program
| true |
3b376c2319a691ae7e89e5408050c6ae552da1fb | jongfranco/python-workshop-2 | /day-1/if-else.py | 662 | 4.1875 | 4 | """
Structure of if else
if predicate:
code
code
code
elif predicate2: (not cumpolsory)
code
code
elif predicate3: (not cumpolsory)
code
code
elif predicate4: (not cumpolsory)
code
code
else: (not compulsory)
code
code
elif --> else if
"""
# if 1 > 2:
# print('i am in if block')
# else:
# print('i am in else block')
#
# print('i am outside if else')
number = int(input())
if number < 5:
print('less than 5')
elif 5 <= number < 10:
print('greater than equal to 5 and less than 10')
elif 10 <= number < 20:
print('very large number')
else:
print('OMG!!!!')
print('outside if else block')
| false |
ce0923065367583a597ca521b774fa28ff50b04f | jekhokie/scriptbox | /python--learnings/list_comprehension.py | 1,098 | 4.25 | 4 | #!/usr/bin/env python
#
# Topics: List Comprehension
#
# Background: List comprehension examples and functionality.
#
# Sources:
# - https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/
import unittest
# test functionality
class TestMethods(unittest.TestCase):
def test_loop(self):
my_items = ['a', 'b', 'a', 'c']
adjusted_items = [x for x in my_items if x == 'a']
self.assertEqual(adjusted_items, ['a', 'a'])
def test_nested_loop(self):
'''
How to transpose nested loops:
names = []
for person in people: # (1)
for (key, val) in person.items(): # (2)
names.append(val) # (3)
Into:
names = [(3)val (1)for person in people (2)for (key,val) in person.items()]
'''
people = [{'name': 'joe'}, {'name': 'sally'}]
names = [val for person in people for (key,val) in person.items()]
self.assertEqual(names, ['joe', 'sally'])
# main execution
if __name__ == '__main__':
unittest.main()
| true |
c57fbb2147a8edefafd100334fba3a43167ba878 | jekhokie/scriptbox | /python--learnings/coding-practice/weird_or_not.py | 382 | 4.34375 | 4 | #!/usr/bin/env python
#
# If n is:
# odd, print Weird
# even and 2 <= n <= 5, print Not Weird
# even and 6 <= n <= 20, print Weird
# even and > 20, print Not Weird
#
N = int(input())
if N % 2 != 0:
print("Weird")
else:
if N >= 2 and N <= 5:
print("Not Weird")
elif N >= 6 and N <= 20:
print("Weird")
elif N > 20:
print("Not Weird")
| false |
ae9f23d7211586056bcc0419a76fd8cb2cf756fd | Saurabh-001/Small-Python-Projects | /Guess the Number/Input Range.py | 1,450 | 4.25 | 4 | import random
import math
name = input("Enter your name: ")
lower_bound = int(input("Enter the lower bound: "))
upper_bound = int(input("Enter the upper bound: "))
maximum_chance = int(math.log2(upper_bound-lower_bound+1)) + 1
wins = 0
row_wins = 0
option = 'Y'
option_list = ['Y','N','y','n']
while option=='Y' or option=='y':
number = random.randint(lower_bound,upper_bound)
chance = 1
won = 0
print(f'Hello {name}, you have {maximum_chance} chances to guess the number')
while chance<=maximum_chance:
choice = int(input(f'Enter your number {chance}: '))
if choice == number:
wins += 1
row_wins += 1
won += 1
print(f'Hurray, You got that right in {chance} chance.')
print(f'You beat me {wins} times and {row_wins} times in a row.\n')
break
elif choice<number:
print(f"Oops, Your number is too low.")
chance += 1
else:
print(f"Oops, Your number is too high.")
chance += 1
if won==0:
print(f"Oh no! You ran out of chances. The number was {number}.\n")
row_wins = 0
option = input(f'Hey {name}, Would you like to play again?(Y/N) ')
while option not in option_list:
option = input(f"Sorry, I didn't understand that.\n Would you like to play again?(Y/N) ")
print(f"Thank You {name} for playing. Hope you enjoyed.")
exit("Now exiting...")
| true |
86c7acab30712b8770f6b413e8d34854c5715622 | deadbok/eal_programming | /Assignment 2A/prog1.py | 1,037 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 1
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (13/11-2016)
Convert kilometres to miles.
'''
def km2miles(kilometres = 0):
'''
Convert kilometres to miles.
:param kilometres: Distance in kilometres.
:return: Distance in miles.
'''
#Code that converts km to miles
return(kilometres * 0.6214)
def main():
'''
Main entry point.
'''
# Get the amount of kilometres from the user.
try:
kilometres = float(input('Input kilometres: '))
except ValueError:
# Complain when something unexpected was entered.
print('\nPlease use only numbers.')
exit(1)
print('{:0.2f} kilometres is {:0.2f} miles'.format(kilometres, km2miles(kilometres)))
# Run this when invoked directly
if __name__ == '__main__':
main()
| true |
bf5f81da98a32189b8c4d147b522e9ddaf30db0b | deadbok/eal_programming | /Assignment 2A/prog2.py | 1,948 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 2
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (13/11-2016)
Calculate the county and state sales tax, and the final total of a purchase.
'''
def county_tax(total_purchase = 0):
'''
Calculate the county tax of 2% of the total purchase.
:param total_purchase: Amount spend on the purchase in total.
:return: Amount of county tax.
'''
# Calculate the county tax.
return(total_purchase * 0.02)
def state_tax(total_purchase=0):
'''
Calculate the state tax of 4% of the total purchase.
:param total_purchase: Amount spend on the purchase in total.
:return: Amount of state tax.
'''
# Calculate the state tax
return(total_purchase * 0.04)
def main():
'''
Program main entry point.
'''
# Get the amount of purchase from the user.
try:
total_purchase = float(input('Enter the amount of a purchase: '))
except ValueError:
# Complain when something unexpected was entered.
print('\nPlease use only numbers.')
exit(1)
# Print the totals
# Use new style Python 3 format strings.
# {:12.2f} means align for a total of 12 digits with 2 digits
# after the decimal point.
print('\nTotal purchase:\t\t\t{:12.2f}'.format(total_purchase))
print('State sales tax (4%):\t{:12.2f}'.format(state_tax(total_purchase)))
print('County sales tax (2%):\t{:12.2f}'.format(county_tax(total_purchase)))
print('Final total:\t\t\t{:12.2f}'.format(total_purchase +
state_tax(total_purchase) +
county_tax(total_purchase)))
# Run this when invoked directly
if __name__ == '__main__':
main()
| true |
7d9f56f41b590c03af0be8e72ba22b92a933cbf0 | deadbok/eal_programming | /Assignment B1/prog7.py | 1,140 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 7
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (6/11-2016)
Calculate miles-per-gallon for a given set of miles and gallons.
'''
def main():
'''
Program main entry point.
'''
# Get the data from the user.
try:
miles = float(input('Enter the distance in miles: '))
gallons = float(input('Enter the gas used in gallons: '))
except ValueError:
# Complain when something unexpected was entered.
print('\nPlease use only numbers.')
exit(1)
# Miles per gallon.
mpg = miles / gallons
# Print mpg
# Use new style Python 3 format strings.
# {:0.2f} means 2 digits after the decimal point.
print('\n{:0.2f} miles using'.format(miles),
'{:0.2f} gallons of gas is'.format(gallons),
'{:0.2f} miles per gallon.'.format(mpg))
# Run this when invoked directly
if __name__ == '__main__':
main()
| true |
ca11d5f806eb1105b7d11d2ed52890f049b33407 | deadbok/eal_programming | /Assignment 5/prog6.py | 2,424 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
"""
Name: Program 6 "Test Average and Grade"
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (2017-01-10)
Convert 5 grades from numbers into letter.
"""
def calc_average(grade1, grade2, grade3, grade4, grade5):
"""
Return the avarage of 5 scores.
:param grade1: Grade 1
:param grade2: Grade 2
:param grade3: Grade 3
:param grade4: Grade 4
:param grade5: Grade 5
:return: The average grade as a number.
"""
# Return the average.
return (grade1 + grade2 + grade3 + grade4 + grade5) / 5
def determine_grade(score):
"""
Return the letter score using the following conversion
table:
Score | Letter Grade
----------|---------------
90–100 | A
80–89 | B
70–79 | C
60–69 | D
Below 60 | F
:param score: The numerical score.
:return: The letter score.
"""
# Be !positive and return 'F' by default.
ret = 'F'
# Use if to convert to letter score.
if score >= 90:
ret = 'A'
elif score >= 80:
ret = 'B'
elif score >= 70:
ret = 'C'
elif score >= 60:
ret = 'D'
return ret
def get_grade():
"""
Get the one grade from the user.
:return: The grade.
"""
try:
return (float(input('Input a numerical score (0-100): ')))
except ValueError:
# Complain when something unexpected was entered.
print('\nPlease use only numbers.')
exit(1)
def main():
"""
Program main entry point.
"""
# Handle the input in a list.
scores = list()
for i in range(5):
scores.append(get_grade())
# I would much rather have passed the list, but the assignment says
# otherwise.
average = calc_average(scores[0], scores[1], scores[2], scores[3],
scores[4])
# Print the input scores and their letter scores.
print('\nScores: ')
for score in scores:
print(' {:6.2f}: {}'.format(score, determine_grade(score)))
# Print the average.
print(
'\nAverage score {:0.2f}: {}'.format(average, determine_grade(average)))
# Run this when invoked directly
if __name__ == '__main__':
main()
| true |
5b5ace9639d6044ebca12fd640dbf83fc0aa053b | guto-alves/datastructures-and-algorithms | /daily-coding-problem/88-ContextLogic-Division/division.py | 750 | 4.21875 | 4 | """
Implement division of two positive integers without using the division,
multiplication, or modulus operators. Return the quotient as an integer,
ignoring the remainder.
"""
def divide(dividend, divisor):
if divisor == 0:
return None
sign = -1 if dividend < 0 or divisor < 0 else 1
dividend = abs(dividend)
divisor = abs(divisor)
quotient = 0
while dividend > 0:
dividend -= divisor
quotient += 1
if dividend < 0:
quotient -= 1
return quotient * sign
assert divide(10, 2) == 5
assert divide(6, 2) == 3
assert divide(0, 5) == 0
assert divide(10, 0) == None
assert divide(10, -2) == -5
assert divide(10, 3) == 3
assert divide(45, -8) == -5
| true |
6564708f15277b9bd4f0ef5adcdbaf97d52dfae8 | lawun330/Python_Basics | /Regular Expression/regular expressions.py | 2,013 | 4.625 | 5 | #regular expressions work with strings
import re
string=r"@" #a raw string called "@" desired to be matched
#raw strings don't escape anything which makes regular expression easier
if re.match(string,"wun333@gmail.com"):
#re.match() matches one string with another starting from the beginning of both strings until one is exhausted
#return false if two strings are no longer matched
print("Match!")
else :
print ("No match!")
print("\n")
confirmation=re.search(string,"wun332@gmail.com")
#re.search() check if the desired string matches as string (search for a match)
#return True / False
if confirmation:
print("vaild email")
print(confirmation.group()) #return the matched substrings
print(confirmation.start()) #return the first matching position
print(confirmation.end()) #return the last matching position
print(confirmation.span()) #return the above positions in tuple
else :
print("It's not an email")
print('\n')
print (re.findall(string,"wun330@gmail.comwun332@gmail.com")) #findall() returns a list containing substrings(of one complete string) that match the desired string
print (re.finditer(string,"@gmail.com")) #return iterator instead of list
#replacing function sub()
incomplete_email='wun3301email.com'
mistake=r'1email'
complete_email=re.sub(mistake,"@gmail",incomplete_email) #re.sub() is substitution function for replacing raw strings from main strings with new words(strings)
print(incomplete_email,'to', complete_email)
#we can then extract the email by using r"[\w.%+-]+@[\w.-]+"
#split function to split the strings or sentences into list
sentence = "A sentence. Second sentence? No It is not!"
example = re.split(r"[.?!]", sentence) #here in split(), special characters act like a normal character that pass to match
print(example)
#by using capturing ie, '()' , we can include such '.' '!' characters that are in a [] bracket when returning a list. eg - try use re.split(r"([.?!])",sentence)
#learn more in metacharacters.py and Special sequences.py
| true |
4b6e5276714dd23c45a39e1fe9bd7adccee3cf36 | quizque/ICS4U | /Labs/Lab 1/Calculators.py | 924 | 4.3125 | 4 | import math
# Calculate area of a cone
# INPUTS
# - Radius (float)
# - Height (float)
# OUTPUT
# - Area (print)
print("~~~~~ CALCULATE AREA OF CONE ~~~~~")
print("Area of the cone: ", (1/3)*(3.14159*math.pow(float(input("Enter radius of cone: ")),2)*float(input("Enter height of cone: "))))
# Calculate fahrenheit to celsius
# INPUTS
# - Fahrenheit (float)
# OUTPUT
# - Celsius (print)
print("\n~~~~~ CALCULATE FAHRENHEIT TO CELSIUS ~~~~~")
print("The temperature in Celsius: ", (float(input("Enter temperature in Fahrenheit: ")) -32.0 ) * (5/9))
# Calculate area of a trapezoid
# INPUTS
# - Top base (float)
# - Bottom base (float)
# - Height (float)
# OUTPUT
# - Area (print)
print("\n~~~~~ CALCULATE AREA OF TRAPEZOID ~~~~~")
print("The area is: ", (1/2)*(float(input("Enter trapezoid length of bottom: ")) + float(input("Enter trapezoid length of top: ")))*float(input("Enter trapezoid height: ")))
| true |
efb714d84deea785f55a6057e7889eac10d7c26d | quizque/ICS4U | /Labs/Lab 9/Part2.py | 730 | 4.28125 | 4 | #********************************************************************************
#** Nick Coombe 2020/03/14 ***
#** Lab 9 Part 2 ***
#** ***
#** Part 2 of Lab 9 ***
#** Create a function that prints a box ***
#** ***
#********************************************************************************
# Prints a box of given width and height
# INPUTS
# - height (int)
# - width (int)
# OUTPUT
# - a box (print)
# - NO RETURN
def box(height, width):
for x in range(height):
for y in range(width):
print("*", end="")
print("")
box(7,5) # Print a box 7 high, 5 across
print() # Blank line
box(3,2) # Print a box 3 high, 2 across
print() # Blank line
box(3,10) # Print a box 3 high, 10 across | true |
db8923680b9e9f72b78ece2c179dccb9bf1e8a83 | carlabeltran/data_analytics_visualization | /3.1_introduction_to_python_I/in_class/07-Ins_Conditionals/conditionals.py | 376 | 4.1875 | 4 | x = 1
y = 10
if x > y:
print("x is greater than y!")
if x == 1:
print("x equals one")
if y != 1:
print("y is not one")
if (x == 1 and y == 10):
print("both conditionals are true")
if (x > 10):
print("x is greater than 10")
elif (x < 5):
print("x is less than 5")
else:
print("x is between 5 and 10")
if (x < 10):
if ( y > 5):
print("x < 10 an y > 5") | true |
34f5adc2c7c2150186b7f45496db28f1258b03d4 | adrianlebaron/python_notes | /work/week_three.py | 1,265 | 4.125 | 4 | # make variable word
# def word_reverser(string):
# print(f"I'm sorry, you need to be at least 25 years old")
# usernames = [
# 'jon',
# 'tyrion',
# 'theon',
# 'cersei',
# 'sansa',
# ]
# for username in usernames:
# if username == 'cersei':
# print(f'Sorry, {username}, you are not allowed')
# continue
# else:
# print(f'{username} is allowed')
# for username in usernames:
# if username == 'cersei':
# print(f'{username} was found at index {usernames.index(username)}')
# break
# print(username)
# def word_reverse():
# # while True:
# print('What is the word you would like to see backwords?')
# word = input()
# # if word == 'Adrian':
# print(f"here is your word backwords {word[::-1]} ")
# return False
# word_reverse()
# for num in range(1, 21): #does not include the last num you will be off by one
# print(num)
# for x in range(1, 20,):
# if (x == 3 or == 9 or == 14):
# continue
# print(x)
# range_print()
#
# def full_name(first, middle, last, maiden): ##full_name is function not variable
# print(f'{first} {middle} {last} {maiden}')
# full_name('Adrian', 'Dan', 'Lebaron', 'munoz')
def hundred():
for inte in range(1, 101):
print(inte)
hundred() | true |
a2bc458851e87a37aab20734fb93c3754024d0c8 | adrianlebaron/python_notes | /dictionaries/complicated/comprehension.py | 659 | 4.40625 | 4 | # Exercise 21: Solution in small_course.py
Section 1, Lecture 47
Exercise for reference:
Filter the dictionary by removing all items with a value of greater than 1.
d = {"a": 1, "b": 2, "c": 3}
# Answer:
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)
Explanation:
Here we're using a dictionary comprehension. The comprehension is the expression inside dict() . The comprehension iterates through the existing dictionary items and if an item is less or equal to 1,the item is added to a new dict. This new dict is assigned to the existing variable d so we end up with a filtered dictionary in d. | true |
04b064ff66f0758e9c3d79da65b372ddaca16e32 | wesenu/python-algorithms | /insertion_sort.py | 970 | 4.46875 | 4 | # From Lecture 3, Insertion Sort & Merge Sort
class InsertionSortArray:
''' Maintains a sorted one-dimensional array of comparable elements using insertion sort.
The one-dimensional array is represented as a list.
Interface with the array using insert, remove, and display. '''
def __init__(self, array):
self.array = array
self.length = len(array)
self.__sort()
def insert(self, element):
self.array.append(element)
self.__sort()
def remove(self, element):
self.array.remove(element)
def display(self):
return self.array
def __swap(self, loc1, loc2):
self.array[loc1], self.array[loc2] = self.array[loc2], self.array[loc1]
def __sort(self):
num_swaps = 0
for i, element in enumerate(self.array):
while i > 0 and element < self.array[i-1]:
self.__swap(i, i-1)
num_swaps = num_swaps + 1
i = i - 1
print 'Sorted array in %s swaps' % num_swaps
print self.array
| true |
9cd7fe204067cdff5641d3603a032e3604d44f93 | Anirban2404/MachineLearning_Coursera | /Assignments_Python/Week2/computeCost.py | 771 | 4.15625 | 4 | # COMPUTECOST Compute cost for linear regression J = COMPUTECOST(X, y, theta)
# computes the cost of using theta as the parameter for linear regression to fit
# the data points in X and y
import numpy as np
def computeCost(X, y, theta):
# Initialize some useful values
m = y.size # number of training examples
# You need to return the following variables correctly
J = 0
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta
# You shoulD set J to the cost.
h_theta = X.dot(theta)
summation = sum(np.power((h_theta - np.transpose([y])), 2))
J = (1.0 / (2 * m)) * summation
# =============================================================
return J | true |
ddcb7e96cc70e2df680acd96fc321d9561d8761e | sraj-s/Data-case-handling | /grid.py | 266 | 4.28125 | 4 | from tkinter import *
root = Tk()
#creating a label widget
myLabel1 = Label(root, text="Hello world")
myLabel2 = Label(root, text="My name is sambeg")
#shoving it into the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=5)
root.mainloop()
| true |
242f6e74796f62432d702fe1b422965a55a0292f | rajputrajat/teaching_basic_programming | /day_22/functions_exercise.py | 788 | 4.15625 | 4 | # take - how many numbers in a list
# take individual number, and create a list
# print that list
# find out maximum and minimum number in that list
def make_list():
count = int(input('how many numbers: '))
numbers = []
for n in range(count):
num = int(input('enter number: '))
numbers.append(num)
return numbers
def print_min_max(a_list):
max = a_list[0]
min = a_list[0]
for num in a_list:
if num > max:
max = num
if num < min:
min = num
print('max:', max)
print('min:', min)
# actual python excution starts from below
# list_of_numbers = make_list()
# print(list_of_numbers)
# print_min_max(list_of_numbers)
print_min_max([10, 23, -1, 20])
b_list = [10.2, 43.0, -0.2]
print_min_max(b_list) | true |
2f0e624f57747767f9eb20638ef85e95b52eda2d | rajputrajat/teaching_basic_programming | /day_11/fruits_shopping.py | 415 | 4.15625 | 4 | num_fruits = int(input('how many fruits did you buy today: '))
print()
cost = 0.0
while num_fruits >= 1:
num_fruits = num_fruits - 1
name = input('name of fruit: ')
weight_input = 'how much ' + name + ' did you buy: '
weight = float(input(weight_input))
rate = float(input('cost of ' + name + ' rs/kg: '))
cost = cost + (rate * weight)
print()
print('you spent: ' + str(cost) + ' Rs') | false |
61664092edac9d06f2e97ee28e2e36368a0f294f | nataly247/Python-Core | /Loops/task7-list-add-element.py | 523 | 4.125 | 4 | #7. Змінити попередню програму так, щоб в кінці кожної букви елементів
# при виводі додавався певний символ, наприклад “#”.
# (Підказка: цикл for може бути вкладений в інший цикл,
# а також треба використати функцію print(“ ”, end=”%”)).
list = ["cat", "dog", "boy", "girl"];
for i in list:
for j in i:
print(j, end = '#')
print() | false |
fd24661a2c11233d39c60fbb3780b8265d79764e | yedkk/python-datastructure-algorithm | /python basic/basic 5.py | 568 | 4.1875 | 4 | # This is the programs that convert Celsius to Fahrenheit
# I get the number of Celsius and print the list of convert
# Author Kangong Yuan
# Get the input from users
celsius = int(input("Enter the number of celsius temperatures to display: "))
# Print the title of list
print('Celsius\tFahrenheit')
# Set the variable
display_celsius = 0
# Convert the temperature and display it
while display_celsius <= celsius:
fa_temperature = float(9/5*display_celsius+32)
print(str(display_celsius) + '\t' + str(fa_temperature))
display_celsius = display_celsius + 1
| true |
c4d1cb84dbd8b6b343baa94fed074c62ebc7c18b | yedkk/python-datastructure-algorithm | /python basic/basic 2.py | 875 | 4.375 | 4 | #This progroms want to get user's weight and height and calculate their then tell then the situation of their bmi
#First get the wieght and height of the user
#Second calculate the bemi throgh formula
#Third decide the situation of their bmi
# Author Kangdong Yuan
#Get the input of the height and the weight
height=float(input("Enter your height in inches: "))
weight=float(input("Enter your weight in pounds: "))
#Use the formula to get the bmi
bmi = weight*703//height**2
#Print the bmi for the user
print("Your BMI is "+str(bmi))
#Decide the bmi situation of bmi by range tha given by website
#And print the result of situation for users
if bmi >=18.5 and bmi <=25.0:
print("Your BMI indicates that you are optimal wieght")
elif bmi <18.5:
print("Your BMI indicates that you are underwieght")
elif bmi >25.0:
print("Your BMI indicates that you are overwieght")
| true |
63024e12ceabc427d785a055513a66c73b586ed9 | yedkk/python-datastructure-algorithm | /python basic/basic_GUI.py | 1,161 | 4.5625 | 5 | # This program ask user to give sides and return graph to users
# Author Kangdong Yuan
# import random and turtle
import random
import turtle
t = turtle.Turtle()
# set the function
def makePolygon (sides,length,width,fillColor,angle,borderColor):
# fill the color
t.color(borderColor,fillColor)
t.begin_fill()
# draw the graph
for i in range(sides):
t.color(borderColor,fillColor)
t.pensize(width)
t.forward(length)
t.right(angle)
t.end_fill()
# get the color and sides from user
colors = ['coral','gold','brown','red','green','blue','yellow','purple','orange','cyan','pink','magenta','goldenrod']
sides = int(input("Enter the number of sides, less 3 to exit."))
# set a while loop to ensure enter less 3 to exit
while sides >= 3:
turtle.home()
# calculate the length width angle and get color from random
length = 600/sides
width = (sides%20)+1
borderColor = colors[random.randint(0,12)]
fillColor = colors[random.randint(0,12)]
angle = 360/sides
makePolygon(sides,length, width, fillColor,angle,borderColor)
sides = int(input("Enter the number of sides, less 3 to exit."))
| true |
8ebc214fdf3e1c68d73df01640a3ed0422ae78e0 | MohammadRafik/algos_and_datastructures | /leetcode_30day_challenge/week2/min_stack.py | 1,066 | 4.125 | 4 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.min_index = []
self.list = []
def push(self, x: int) -> None:
self.list.append(x)
if self.min_index == []:
self.min_index.append(0)
elif self.list[-1] < self.list[self.min_index[-1]]:
self.min_index.append(len(self.list)-1)
def pop(self) -> None:
if len(self.list)-1 == self.min_index[-1]:
self.min_index.pop()
self.list.pop()
else:
self.list.pop()
def top(self) -> int:
if self.list:
return self.list[-1]
else:
return None
def getMin(self) -> int:
if self.min_index and self.list:
return self.list[self.min_index[-1]]
else:
return None
# Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())
| false |
48efb4754266b43608892f0aca35ca015648994b | serapred/algorithms | /sorting/insertion_sort.py | 846 | 4.28125 | 4 | def insertion_sort(collection):
"""
Pure pyton implementation of the insertion sort algorithm
@collection: some mutable collection of unordered items
@returns: same collection in ascending order
time complexity:
- lower bound omega(n)
- average theta(n^2)
- upper bound bigO(n^2)
space complexity:
- O(1) => in place
"""
for i in range(1, len(collection)):
# switch "<" with ">" to get descending order
while i > 0 and collection[i] < collection[i - 1]:
# swap current and previous element
collection[i], collection[i - 1] = collection[i - 1], collection[i]
i -= 1 # decrement counter
return collection
if __name__ == '__main__':
a = [2, 4, 12, 18, 5, 7, 9, 15, 12]
b = insertion_sort(a)
print(b)
| true |
9dfb65fedcc93b40b842ff3e4d304dd470d3732c | pedh/CLRS-Solutions | /codes/heapsort.py | 1,139 | 4.15625 | 4 | """
Heapsort.
"""
import random
def max_heapify(heap, index, heap_size):
"""Max-heapify."""
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and heap[left_index] > heap[index]:
largest = left_index
else:
largest = index
if right_index < heap_size and heap[right_index] > heap[largest]:
largest = right_index
if largest != index:
heap[index], heap[largest] = heap[largest], heap[index]
max_heapify(heap, largest, heap_size)
def build_max_heap(heap, heap_size):
"""Build max heap."""
for i in range(heap_size // 2 - 1, -1, -1):
max_heapify(heap, i, heap_size)
def heapsort(heap):
"""Heapsort."""
heap_size = len(heap)
build_max_heap(heap, heap_size)
print(heap)
for i in range(len(heap) - 1, 0, -1):
heap[0], heap[i] = heap[i], heap[0]
heap_size -= 1
max_heapify(heap, 0, heap_size)
def main():
"""The main function."""
array = list(range(20))
random.shuffle(array)
print(array)
heapsort(array)
print(array)
if __name__ == "__main__":
main()
| false |
d1e5bc78200728b2cb01a5c05aa0d87540d87375 | rewaaf/Convert-List | /convertList.py | 638 | 4.3125 | 4 | # with user input:
def convert(list_item):
list_item[-1] = 'and '+str(list_item[-1])
new_str = ''
new_str = ', '.join(str(item) for item in list_item)
return new_str
user_list = input('Hello dear, enter your list to convert it to string: ').split() #convert user input to list
print('your list is: ')
print(user_list)
print('your string is: ')
print(convert(user_list))
# without user input
"""
def convert():
list_item = ['apples', 'bananas', 'tofu', 'cats']
list_item[-1] = 'and '+str(list_item[-1])
new_str = ''
new_str = ', '.join(str(item) for item in list_item)
print(new_str)
convert()
"""
| false |
df431bbc0c4604391c1cbbbed7b37b6518d1a757 | pedr0diniz/cevpython | /Python_Aulas/aula2.13a - Laços de Repetição 1 - for.py | 1,451 | 4.15625 | 4 | #laço com variável de controle
#laço c no intervalo (1,10):
#dê um passo
#pega
#traduzindo:
#for c in range(1,10):
#passo()
#pega() #mesmo com o pega fora do laço, ele só será executado depois do laço
#laço c no intervalo (0,3):
#passo
#pula #evitando determinados números
#passo
#pega
#traduzindo:
#for c in range(0,3):
#passo()
#pula()
#passo()
#pega()
#laço c no intervalo(0,3):
#se moeda ou maçã
#pega
#passo
#pula
#pega
#passo
#pega
#traduzindo:
#for c in range(0,3):
#if moeda:
#pega
#passo
#pula
#pega
#passo
#pega
for c in range(1, 6): #ele NÃO CONSIDERA O ÚLTIMO NÚMERO
print('Oi') #só imprimiu 5x
print(c)
print('FIM')
print()
for c in range(6, 0, -1): #terceira casa é a iteração
print(c)
print('FIM')
print()
for c in range(0, 7, 2): #andando de 2 em 2 casas começando do 0
print(c)
print('FIM')
print()
n = int(input('Digite um número: '))
for c in range(0, n+1): #n+1 pra ele considerar o último número
print(c)
print('FIM')
print()
i = int(input('Início: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
for c in range(i, f+1, p):
print(c)
print('FIM')
sum = 0
for c in range(0, 4):
n = int(input('Digite um valor: '))
sum += n #sum = sum + n
if c < 3:
print('A soma parcial desses números é: {}'.format(sum))
print('A soma final desses números é: {}'.format(sum)) | false |
228ae00c8cfeaae3ef3950bdc2b24cbd1293f4bd | pedr0diniz/cevpython | /PythonExercícios/ex022 - Analisador de Textos.py | 1,379 | 4.34375 | 4 | # DESAFIO 022 - Crie um programa que leia o nome completo de uma pessoa e mostre:
#O nome com todas as letras maiúsculas;
#O nome com todas as letras minúsculas;
#Quantas letras ao todo (sem considerar espaços);
#Quantas letras tem o primeiro nome.
nome = str(input('Digite seu nome completo: '))
M = nome.upper()
m = nome.lower()
sp = nome.split() #separa minha string em um vetor com cada palavra separada. elimina os espaços.
tl = len(''.join(sp)) #pega todos os nomes do vetor acima e junta ele numa string só
ln1 = len(sp[0])
#para contar todas as letras também posso fazer:
#print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' '))), assim contando todos os espaços e os
#subtraindo da contagem
#para contar a quantidade de letras do primeiro nome, posso fazer:
#nome.strip() para tirar os espaços indesejados no começo e no final
#print('Seu primeiro nome tem {} letras'.format(nome.find(' '))) para encontrar o primeiro espaço no nome.
#a casa onde estiver o primeiro espaço será exatamente igual à quantidade de caracteres do primeiro nome.
#teoricamente seria uma casa a mais, mas como em python os vetores começam em 0, então dá certo.
print('''Seu nome completo todo em maiúsculas é: {}
Seu nome completo todo em minúsculas é: {}
Seu nome tem {} letras.
Seu primeiro nome é {} e tem {} letras.'''.format(M,m,tl,sp[0],ln1)) | false |
6ecb7851ed7b8756044306077f552efef5b8c411 | pedr0diniz/cevpython | /PythonExercícios/ex099 - Função que descobre o maior.py | 803 | 4.15625 | 4 | # DESAFIO 099 - Faça um programa que tenha uma função maior(), que receba vários PARÂMETROS com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o MAIOR e dizer quantos valores foram informados.
def maior(*num):
for nu in num:
numeros.append(nu)
if printa is True:
print(f"O maior número entre {numeros} é {max(numeros)}.")
print(f"Foram digitados {len(numeros)} números.")
numeros = []
printa = False
controle = 'S'
while controle == 'S':
n = int(input('Digite um número: '))
controle = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
while controle not in 'SN':
controle = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if controle == 'N':
printa = True
maior(n) | false |
3815e63031e53111c4056fa198e832d4a6e82776 | pedr0diniz/cevpython | /PythonExercícios/ex104 - Validando entrada de dados em Python.py | 706 | 4.15625 | 4 | # DESAFIO 104 - Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante à função input() do
#Python, só que fazendo a validação para aceitar apenas um valor numérico.
#Ex: n = leiaInt('Digite um n')
def leiaInt(frase):
ok = False #precisei criar esse boolean. seria ideal poder usar "if num.isnumeric() is False"
while ok is False:
num = str(input("Digite um número: "))
if num.isnumeric():
num = int(num)
ok = True
if ok is False:
print("\033[0;31mERRO! Digite um número inteiro válido!\033[m")
return num
n = leiaInt('Digite um número: ')
print(f'Você acabou de digitar o número {n}.') | false |
6b3d221210ac17f6514b0e627b25a76a54a2d5d3 | pedr0diniz/cevpython | /PythonExercícios/ex014 - Conversor de Temperaturas.py | 307 | 4.15625 | 4 | # DESAFIO 014 - Escreva um programa que coonverta uma temperatura digitada em ºC para ºF.
c = float(input('Digite a temperatura em ºC: '))
f = ((9*c)/5)+32
print('A temperatura de {}ºC corresponde a {}ºF.'.format(c,f))
#ou
print('A temperatura de {}ºC corresponde a {}ºF.'.format(c,((9*c)/5)+32)) | false |
95e19c84d5a8838e3d9fe33f9a47253118acd256 | raysales/treehouse-festival-level-up-your-code | /map.py | 690 | 4.46875 | 4 | # What does it do?
# map() applies a function to an iterable
flowers = ['sunflower', 'daisy', 'rose', 'peony']
# regular loop
plural = []
for flower in flowers:
if flower[-1] == 'y':
plural.append(flower[:(len(flower) -1)] + 'ies')
else:
plural.append(flower + 's')
print(plural)
# map()
def pluralize(word):
if word[-1] == 'y':
return word[:(len(word) -1)] + 'ies'
else:
return word + 's'
plural = map(pluralize, flowers)
print(plural)
print(list(plural))
# other built-in functions
length = list(map(len, flowers))
print(length)
# lambda functions
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda num: num * 2, nums))
print(doubled) | true |
d60913c8c04026085d1b8b30c9a5e1d1025de5dc | nafis195/Codepath-Intermediate-Software-Engineering | /Week1/1. S2 - UMPIRE_Practice.py | 222 | 4.3125 | 4 | # Bismillahir Rahmanir Rahim
# Session 2 - UMPIRE Practice
# Write a function that reverses a string.
# Example:
# Input: "hello"
# Output: "olleh"
userInput = input("Please enter a string: ")
userInput = userInput[::-1]
print(userInput) | false |
0847e5ba72fca9d6cb7dc07d5e92aa93222cd9aa | mtlam/ASTP-720_F2020 | /HW5/particle.py | 2,678 | 4.125 | 4 | '''
Michael Lam
ASTP-720, Fall 2020
Class to represent a point-mass particle
Also performs the integration
'''
import numpy as np
from coordinate import Coordinate
class Particle:
"""
Class that contains the coordinates and
mass of a point particle
In order to do the integration, it will
also keep track of velocity information
via the simple Verlet algorithm since
we don't particularly care about velocity
information and it's simpler.
"""
def __init__(self, index, m, cminus, c):
"""
Parameters
----------
index : int
Number labeling the particle
m : float
Mass of particle
cminus : Coordinate
Coordinate of particle at previous timestep
c : Coordinate
Coordinate of particle
"""
self.index = index
self.m = m
self.cminus = cminus
self.c = c
self.accels = list()
def __eq__(self, other):
""" Equate solely by the index """
if self.index == other.index:
return True
return False
def verlet_step(self, h=1):
"""
Parameters
----------
h : float
Timestep
Returns
-------
None
Updates the internal coordinates, does not
return anything
"""
# First, figure out the sum of the x and y accelerations independently
ax = np.mean(list(map(lambda coord: coord.x, self.accels)))
ay = np.mean(list(map(lambda coord: coord.y, self.accels)))
newx = 2*self.c.x - self.cminus.x + h**2 * ax
newy = 2*self.c.y - self.cminus.y + h**2 * ay
# Update both the past and the current step simultaneously
self.cminus, self.c = self.c, Coordinate(newx, newy)
# now delete the list of accelerations
self.accels = list()
return
def add_accel(self, accel):
"""
Add an acceleration, given as a coordinate, to the list
used to calculate the total update
Parameters
----------
accel : Coordinate
Using a Coordinate as a vector because why not
"""
self.accels.append(accel)
def get_index(self):
""" Return index of particle """
return self.index
def get_mass(self):
""" Return mass of particle """
return self.m
def get_coord(self):
""" Return coordinate of particle """
return self.c
def get_separation(self, other):
""" Return separaton between this particle and another Coordinate """
return self.c.get_distance(other.c)
| true |
31c2a5b3138eb55415adefcee51d7ac8ab982c6d | ArahamLag/pyfeb20repo | /script.py | 584 | 4.125 | 4 | import math
def get_number(number):
if isinstance(number, int):
print(" a number was passed to the function")
if number % 2 == 0:
print(' the number is even')
else:
print(' the number is odd')
if number < 0:
print("""the number is negative so the
square root is not returned""")
return 0
else:
return math.sqrt(number)
else:
print('passed argument is not a number \
please pass a number and try again')
return 0 | true |
ec6fa5468bc9a7e951606c74afd906077b3ad7e4 | changsquare/first | /practice8.py | 1,258 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 17:12:45 2019
@author: chang2
"""
'''
lambda expression
They are syntactically restricted to a single expression.
Semantically, they are just syntactic sugar for a normal function definition.
Like nested function definitions, lambda functions can reference variables from the containing scope.
'''
# Example 1
def make_increment(n):
'''
This function (make_increment) actually returns a function (lambda fx)!!
'''
return lambda x: x + n
f = make_increment(2)
'''
f is the lambda fxn returned by make_increment(2)
'''
print(f(8))
# Example 2
def make_sum():
return lambda x, y: x + y
g = make_sum()
print(g(33, 4))
'''
Example 2
'''
def takeSecond(elem):
return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key = takeSecond) #sort by the second element
print(random)
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
print(random)
random.sort(key = lambda elmnt: elmnt[1]) #sort by the second element
print(random)
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = lambda item: item[1])
print(pairs)
wordlist = ['world', 'hi', 'dog', 'cat', 'california', 'texas', 'tejas']
wordlist.sort(key = len)
print(wordlist) | true |
1ebb051f83721b594e644dfb8ba540d1f10c4f67 | HariAc/python-calculator | /calc.py | 663 | 4.28125 | 4 | operation = input('''
welcome to python calculator
+ for addition
- for subtraction
* for multiplication
/ for division
enter the operation= ''')
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
if operation == '+':
print('{} + {} = '.format(num1, num2))
print(num1 + num2)
elif operation == '-':
print('{} - {} = '.format(num1, num2))
print(num1 - num2)
elif operation == '*':
print('{} * {} = '.format(num1, num2))
print(num1 * num2)
elif operation == '/':
print('{} / {} = '.format(num1, num2))
print(num1 / num2)
else:
print('You have not typed a valid operator')
| true |
b1d98614995b6117e1029e008c801d64f54668ca | eldss-classwork/CSC110 | /Creating Modules/oldLady.py | 1,537 | 4.375 | 4 | # Evan Douglass
# HW 8: Children's song, the reprise
# Grade at challenge
'''This module defines several variables and methods used to print the
children's song "There was an Old Lady"'''
# Animals used in the song
ANIMALS = ('fly.', 'spider,', 'bird.', 'cat.',
'dog.', 'goat.', 'cow.', 'horse.')
# A list of the second line in each verse, and the final line in the song
LINES = ('I don\'t know why she swallowed the fly.',
'That wriggled and jiggled and tickled inside her.',
'How absurd to swallow a bird.',
'Imagine that to swallow a cat.',
'My, what a hog, to swallow a dog.',
'She just opened her throat and in walked the goat.',
'I don\'t know how she swallowed a cow.',
'She\'s dead, of course.',
)
# Title method
# No Parameters
def title():
'The title function prints the title to the song'
print('There was an Old Lady')
print()
# Verse method
# Parameter: the index of the verse
def verse(n):
'The verse function prints each verse to the song, seperated by blank lines.'
print('There was an old lady who swallowed a %s' % ANIMALS[n])
print(LINES[n])
if n == 0:
print('Perhaps she\'ll die.')
print()
elif 0 < n < len(ANIMALS)-1:
for animal in ANIMALS[n:0:-1]:
print('She swallowed the', animal[0:-1], 'to catch the',
ANIMALS[ANIMALS.index(animal)-1])
if ANIMALS[ANIMALS.index(animal)-1] in ANIMALS[0:2]:
print(LINES[ANIMALS.index(animal)-1])
print('Perhaps she\'ll die.')
print()
else:
print()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.