blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
104fac3bec6c7975673715d7a3d2594d6d8e9d63
|
AlphaCoderX/MyPythonRepo
|
/Assignment 1/RecipeConverter.py
| 1,157
| 4.125
| 4
|
#Programmer Raphael Heinen
#Date 1/19/17
#Version 1.0
print "-- Original Recipe --"
print "Enter the amount of flour (cups): ",
flour = raw_input()
print "Enter the amount of water (cups): ",
water = raw_input()
print "Enter the amount of salt (teaspoons): ",
salt = raw_input()
print "Enter the amount of yeast (teaspoons): ",
yeast = raw_input()
print "Enter the loaf adjustment factor (e.g. 2.0 double the size): ",
factor = raw_input()
#adjusts recipe based on user input factor
flour = float(flour) * float(factor)
water = float(water) * float(factor)
salt = float(salt) * float(factor)
yeast = float(yeast) * float(factor)
print " "
print "-- Modified Recipe --"
print "Bread Flour: %s cups." % flour
print "Water: %s cups." % water
print "Salt: %s teaspoons." % salt
print "Yeast: %s teaspoons." % yeast
print "Happy Baking!",
print " "
#converts current cup(s) measurement(s) to grams
flour2 = flour * 120
water2 = water * 237
salt2 = salt * 5
yeast2 = yeast * 3
print "-- Modified Recipe in Grams --"
print "Bread Flour: %s g." % flour2
print "Water: %s g." % water2
print "Salt: %s g." % salt2
print "Yeast: %s g." % yeast2
print "Happy Baking!",
| true
|
463fab4b59fd21609889666840b14b98e01a80bf
|
helloallentsai/leetcode-python
|
/1295. Find Numbers with Even Number of Digits.py
| 958
| 4.21875
| 4
|
# Given an array nums of integers, return how many of them contain an even number of digits.
# Example 1:
# Input: nums = [12,345,2,6,7896]
# Output: 2
# Explanation:
# 12 contains 2 digits (even number of digits).
# 345 contains 3 digits (odd number of digits).
# 2 contains 1 digit (odd number of digits).
# 6 contains 1 digit (odd number of digits).
# 7896 contains 4 digits (even number of digits).
# Therefore only 12 and 7896 contain an even number of digits.
# Example 2:
# Input: nums = [555,901,482,1771]
# Output: 1
# Explanation:
# Only 1771 contains an even number of digits.
# Constraints:
# 1 <= nums.length <= 500
# 1 <= nums[i] <= 10^5
from typing import List
class Solution:
def findNumbers(self, nums: List[int]) -> int:
nums = list(map(lambda num: str(num), nums))
evens = list(filter(lambda num: len(num) % 2 == 0, nums))
return len(evens)
x = Solution()
print(x.findNumbers([12, 345, 2, 6, 7896]))
| true
|
1934cd000cca0cbf14f5b286dbbf8c65fecc7f1f
|
seekindark/helloworld
|
/python/py-study/test-class-var.py
| 1,515
| 4.125
| 4
|
class A:
# x = [] # 定义在这里,表示类变量, 被所有实例化的对象公共使用
# y = 0
def __init__(self):
self.x = []
self.y = 0
pass
def add(self):
self.x.append('1')
self.y+=1
a = A()
a.add()
print("第一次示例化 CLASS A:")
print('a.x, a.y = ', a.x, ', ', a.y)
#print('A.x, A.y = ', A.x, ', ', A.y)
print('id(a, a.x, a.y) = ', id(a), ', ', id(a.x), ', ', id(a.y)) #id() 打印变量所对应的 对象的地址, 其实变量就是 表示对象的引用
#print('id(A, A.x, A.y) = ', id(A), ', ', id(A.x), ', ', id(A.y)) #
# 开始第2次实例化
b = A()
print("第二次示例化 CLASS A:")
print('b.x, b.y = ', b.x, ', ', b.y)
#print('A.x, A.y = ', A.x, ', ', A.y)
print('id(b, b.x, b.y) = ', id(b), ', ', id(b.x), ', ', id(b.y)) #id() 打印变量所对应的 对象的地址, 其实变量就是 表示对象的引用
#print('id(A, A.x, A.y) = ', id(A), ', ', id(A.x), ', ', id(A.y))
b.add()
print("修改 b:")
print('b.x, b.y = ', b.x, ', ', b.y)
#print('A.x, A.y = ', A.x, ', ', A.y)
print('id(a, a.x, a.y) = ', id(a), ', ', id(a.x), ', ', id(a.y)) #id() 打印变量所对应的 对象的地址, 其实变量就是 表示对象的引用
print('id(b, b.x, b.y) = ', id(b), ', ', id(b.x), ', ', id(b.y)) #id() 打印变量所对应的 对象的地址, 其实变量就是 表示对象的引用
#print('id(A, A.x, A.y) = ', id(A), ', ', id(A.x), ', ', id(A.y))
| false
|
6c0da654abdc01986b10d70f380f02b0f7800d29
|
seekindark/helloworld
|
/python/py-study/testlist.py
| 1,968
| 4.375
| 4
|
#
# define a function to print the items of the list
#
def showlist(team):
i = 0
for item in team:
# end= "" will not generate '\n' automatically
print("list[%d]=%s" % (i, item), end=" ")
i += 1
print("\n-------------------")
team = ['alice', 'bob', 'tom']
print(team)
print("size = ", len(team))
print("team[0]=%s, [1]=%s, [2]=%s, || [-1]=%s, [-2]=%s, [-3]=%s" %
(team[0], team[1], team[2], team[-1], team[-2], team[-3]))
showlist(team)
# append
team.append(4) # there is no type limited in a list !!
team.append("last-one")
showlist(team)
# insert
team.insert(0, 'insert0')
team.insert(-1, 'insert-1')
showlist(team)
# pop
team.pop()
team.pop(0)
team.pop(1) # pop out the item of the given index
showlist(team)
# replace
team[2] = 'jack' #直接赋值替换
team[3] = 'last'
showlist(team)
# list as one element of another list
team[-1] = team
print(team) # ['alice', 'tom', 'jack', [...]]
showlist(team) # list[0]=alice list[1]=tom list[2]=jack list[3]=['alice', 'tom', 'jack', [...]]
team[-1] = [1, 2, 3, 4]
print(team)
showlist(team)
print("team[-1][-1] = ", team[-1][-1])
"""
this is comment
this is comment
"""
print("""-----------------""")
team1, team2 = [1, 2, 3, 4], ['a', 'b', 'c', 'd']
team = team1 + team2
team1x = team1*3
print('team1={0}'.format(team))
print('team1x={0}'.format(team1x))
print('team[2:-1]=', team[2:-1])
print("""---------xx--------""")
print(team)
print(team[0::2]) # 每隔两步截取一个列表
print(team[0:4:2]) # 每隔两步截取一个列表
print(team[-1::-1]) # 如果步长为负数,那么就反向截取
print(team[-1::-2]) # 如果步长为负数,那么就反向截取
print("""---------xx end--------""")
if __name__ == '__main__':
print("""---------xxx--------""")
team = [1 ,2, 3]*2
showlist(team)
print("""---------xxx end--------""")
| true
|
8fb063a77d24fc0a4e30759ca867b24d4c448a56
|
sabbirDIU-222/Learb-Python-with-Sabbu
|
/loopExercize.py
| 1,483
| 4.46875
| 4
|
# for loop exersize in the systamatic way
# so we first work with the list
party = ['drinks','chicken','apple','snow','ice','bodka','rma','chess board']
for p in party[:4]:
print(p)
print(len(p))
print(sorted(p))
for n in "banana":
print(n)
# break statement to break the loop in our specifed item
alist = ["sabbir","mamun","ibrahim","moti","sagor","ridwan","yasin","nemo"]
#With the break statement we can stop the loop before it has looped through all the items
for l in alist:
print(l)
if l=="moti":
break
# for loop in range
# alll that time we should not use list
# so we need to contain a range to stop our loop
for x in range(10):
print(x)
# it is printing to strat 0 to 9
# so it has no start limit>?
# yah it have a start and stop limit
print("range method thake three perametr ")
print("one take start value , second take range or finishing point , and last want increment")
print("")
for c in range(1,6): # the range function default value is 0
print(c)
# 1 to 5 printing
print("\n")
print("range function start with 0 so need to print extended level that you desire")
for d in range(5,10,1):
print(d)
# 5 to 9 print
# nested for loop
# suppose we have two different type of list
print("\n")
print("nested for loop")
point = ["*",'**']
for i in point:
for j in alist:
print(i,j)
i = 1
while i<6:
print(i)
i += 1
| true
|
8722f4bb822695661283390262191645973fe50f
|
sabbirDIU-222/Learb-Python-with-Sabbu
|
/More Tuple.py
| 854
| 4.46875
| 4
|
# for singly making a tuple
aTuple = ("sabbit",) # we need a comma after entering one elements
print(aTuple)
print(type(aTuple)) # <class 'tuple'>
# but if we don't give any comma it will not be a tuple
bTuple = ("samiwon akter")
print(bTuple)
print(type(bTuple)) # <class 'str'>
# unpacking a tuple
numberTuple = (1,2,3,4,5)
a,b,c,d,e = numberTuple
print(a)
print(b)
print(c)
print(d)
print(e)
'''
1
2
3
4
5
'''
# swap two different tuple
stringtuple = ("ali","hasan")
numtuplr = (25,23)
print("before swaping ")
print(stringtuple)
print(numtuplr)
print("\n")
stringtuple , numtuplr = numtuplr , stringtuple
print(stringtuple)
print(numtuplr)
ATup = (1,2,23,4,5,6,57,77)
# we copy 6 and 57 from the tuple into a new tuplee
print(f"coping 6 an 57 from {ATup}")
newTuple = ATup[5:-1]
print(newTuple)
| false
|
0538dcce7066dd495345d9a8dadc9223d7d3afa4
|
sabbirDIU-222/Learb-Python-with-Sabbu
|
/SymmetricDifference.py
| 637
| 4.15625
| 4
|
'''
so i have a challenge that can make a new list from
two list make out what the difference
supppose we have two list
list1 = [1,2,3,4,5]
list2 = [12,3,4]
now in these two lists what the difference
5 is the different
it;s like the intersaction
'''
list1 = ['kalam','jabbar','borkot','jahangir','munsi abdur rouf','motiur']
list2 = ['kalam','jabbar','borkot','munsi abdur rouf']
set1 = set(list1)
se2 = set(list2)
list3 = list(set1.symmetric_difference(se2))
print(f"the officeres of birshrestho {list3}")
# the method of set is symmetric difference
# that's why we need set
| false
|
7d20e78c33f560812eac4f0f420b3035bdc6b322
|
sabbirDIU-222/Learb-Python-with-Sabbu
|
/Unpacking Arguments.py
| 928
| 4.21875
| 4
|
# so what is unpacking ugument
# i am surprised to know about the horriable things
# and that is , what i learn about the arbetery argument \
# or can i call it paking and unpaking
# so what i learn aboout variable argument \
'''
def _thisFunction(*args):
sum = 0
for n in range(0,len(args)):
sum = sum+args[n]
return sum
print(_thisFunction(10,20,30,40,50))
print(_thisFunction(1,2,3,4,5))
'''
# so this called packing to packing
# now the things
def helth_calculator(age,eatingapple,tosingCigr):
res = (100-age) + (eatingapple*3.25) - (tosingCigr * 2)
if res <= 100:
print("your condition is not good")
elif res>=100:
print("your health condition is goood")
print(res)
sabbuInfo = [23,2,14]
moonInfo = [22,10,0]
helth_calculator(*sabbuInfo) # that is called unpacking sequence
helth_calculator(*moonInfo)
| true
|
e143776f739ae3ded6226c494b5d8d13db2c17d6
|
sabbirDIU-222/Learb-Python-with-Sabbu
|
/calculatearea.py
| 744
| 4.21875
| 4
|
# this program represent that we are going to find some area
# calculate the area of a triangle
# take the
import math
print("calculate the area of triangle ")
base = float(input("base of triangle : "))
height = float(input("height of triangle : "))
_calculateTriArea = 0.5 * base * height
print(f"the area of rectangle is {_calculateTriArea}")
print("**********************************************")
# calculate the area of trapiziam
a = int(input("enter base : "))
b = int(input("enter second base : "))
h = float(input("enter vertical height : "))
areaTrapiziam = 0.5 *(a+b) * h
print(areaTrapiziam)
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.ceil(-45.17) : ", math.ceil(-45.17))
| false
|
30ecabffb4a77fdd09838ca872a01b14f72a08c1
|
ylee0908/Algorithm.py
|
/panlindrome_linkedlist.py
| 1,955
| 4.125
| 4
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def is_palindrome(self):
# Method 1:
# s = ""
# p = self.head
# while p:
# s += p.data
# p = p.next
# return s == s[::-1]
# Method 2:
# p = self.head
# s = []
# while p:
# s.append(p.data)
# p = p.next
# p = self.head
# while p:
# data = s.pop()
# if p.data != data:
# return False
# p = p.next
# return True
# Method 3
p = self.head
q = self.head
prev = []
i = 0
while q:
prev.append(q)
q = q.next
i += 1
q = prev[i-1]
count = 1
while count <= i//2 + 1:
if prev[-count].data != p.data:
return False
p = p.next
count += 1
return True
# Example palindromes:
# RACECAR, RADAR
# Example non-palindromes:
# TEST, ABC, HELLO
llist = LinkedList()
llist.append("R")
llist.append("A")
llist.append("D")
llist.append("A")
llist.append("R")
llist_2 = LinkedList()
llist_2.append("A")
llist_2.append("B")
llist_2.append("C")
print(llist.is_palindrome())
print(llist_2.is_palindrome())
© 2020 GitHub, Inc.
Terms
Privacy
Security
Status
Help
Contact GitHub
Pricing
API
Training
Blog
About
| false
|
e76737fb088ea69b73e34bf61037610d30e869d1
|
ccccclw/molecool
|
/molecool/measure.py
| 1,252
| 4.15625
| 4
|
"""
This module is for functions
"""
import numpy as np
def calculate_distance(rA, rB):
"""
Calculate the distance between two points.
Parameters
----------
rA, rB : np.ndarray
The coordinates of each point.
Return
------
distance : float
The distance between the two points
Examples
--------
>>> r1 = np.array([0.0,0.0,0.0])
>>> r2 = np.array([0.0,0.0,0.0])
>>> calculate_dist(r1, r2)
1.0
"""
if isinstance(rA, np.ndarray) is False or isinstance(rB, np.ndarray) is False:
raise TypeError("input should be numpy array")
d=(rA-rB)
distance=np.linalg.norm(d)
if distance == 0.0:
raise Exception("Two atoms are in the same point")
return distance
def calculate_angle(rA, rB, rC, degrees=False):
"""
Calculate the angle given three coordinates.
Parameter
---------
rA, rB, rC : np.ndarray
The coordinates of each point.
Return
______
angle : float
The angle given three coordinates
"""
AB = rB - rA
BC = rB - rC
theta=np.arccos(np.dot(AB, BC)/(np.linalg.norm(AB)*np.linalg.norm(BC)))
if degrees:
return np.degrees(theta)
else:
return theta
| true
|
6433e495fd2d47ee50910d166821502eab388856
|
mdk7554/Python-Exercises
|
/MaxKenworthy_A2P4.py
| 2,537
| 4.25
| 4
|
'''
Exercise: Create program that emulates a game of dice that incorporates betting and multiple turns. Include a functional
account balance that is updated with appropriate winnings/losses.
'''
import random
#function to generate a value from dice roll
def roll():
return int(random.randrange(1,7))
#function to get bet amount as input from user and update balance or exit game
def get_bet(bal):
while True:
bet = input("Current balance is ${}. Enter 'x' to exit or place your bet: ".format(bal))
if bet == 'x':
return 0,0
try: #try/except clause to catch invalid input from user
bet=int(bet)
if bet in range(0,bal+1):
new_bal=bal-int(bet)
return bet,new_bal
else:
print("Invalid amount. Try again.")
except ValueError:
print("Invalid amount. Try again.")
#function to control third roll option
def opt_roll(roll_sum,bal,bet):
while True:
opt=input("No luck. Do you want to double your bet for a third roll? Enter 1 for yes or 0 for no ")
try: #try/except to catch invalid input from user
opt=int(opt)
if opt==0:
return None
elif bal<bet:
print('Sorry you dont have enough for this bet.')
return None
elif opt==1:
return roll_sum + roll()
else:
print("Invalid entry. Try again.")
except ValueError:
print("Invalid entry. Try again.")
#initial balance
bal = 100
while bal>0: #begin game with while loop that ends when the users balance = 0
bet,bal = get_bet(bal) #get input bet from user
if bet==0 and bal==0: #exit game if user chooses
break
roll1= roll()+roll()
print('You rolled a {}'.format(roll1))
if roll1 == 7 or roll1==12:
print('You win!')
bal = bal+bet*3
elif roll1 != 7 and roll!=12:
roll2 = opt_roll(roll1,bal,bet) #third roll option
if roll2 == 7 or roll2 == 12:
print('You rolled a {}'.format(roll2))
print('You win!')
bal = bal+bet*4
elif roll2==None:
pass #pass and restart loop if user elects not to roll 3rd time
else:
print('You rolled a {}'.format(roll2))
print('Sorry, better luck next time.')
bal= bal-bet
else:
pass
print('Thanks for playing. Goodbye!')
| true
|
11a0db557909161e59c03ab75726f02e4275be5a
|
gammaseeker/Learning-Python
|
/old_repo/6.0001 Joey/sanity_check2.py
| 848
| 4.15625
| 4
|
annual_salary = 120000
portion_saved = .1
total_cost = 1000000
monthly_salary = (annual_salary / 12.0)
portion_down_payment = 0.25 * total_cost
current_savings = 0
returns = (current_savings * 0.4) / 12
overall_savings = returns + (portion_saved * monthly_salary)
months = 0
# Want to exit the loop when there is enough savings for a down payment
while current_savings < portion_down_payment:
current_savings += current_savings * (0.4 / 12) # Monthly interest
current_savings += portion_saved # Monthly savings
months += 1
print("It will take {} months to save!".format(months))
current_Saving=0
rate=0.04/12
monthly_savings = monthly_salary*0.1
i=0
while (current_Saving <= portion_down_payment):
current_Saving = current_Saving+(monthly_savings)*rate + monthly_savings
i=i+1
print(i)
| true
|
c5f3dcab578ef708da59fc2be131ef86cf6660e1
|
gammaseeker/Learning-Python
|
/old_repo/6.0001 Joey/sanity_check.py
| 623
| 4.15625
| 4
|
annual_salary = 120000
portion_saved = .1
total_cost = 1000000.0
monthly_salary = (annual_salary / 12.0)
portion_down_payment = 0.25 * total_cost
current_savings = 0
returns = (current_savings * 0.04) / 12
overall_savings = returns + (portion_saved * monthly_salary)
months = 0
# Want to exit the loop when there is enough savings for a down payment
while current_savings < portion_down_payment:
current_savings += current_savings * (0.04 / 12) # Monthly interest
current_savings += portion_saved # Monthly savings
months += 1
print("It will take {} months to save!".format(months))
| true
|
25a56640f12bd79448b0b5ba4de024441a00eb0d
|
alessandrogums/Desafios_Python_funcoes
|
/Exercicio.6_listaPyBr.py
| 1,833
| 4.1875
| 4
|
# Faça um programa que converta da notação de 24 horas para a notação de 12 horas. Por exemplo, o programa deve converter 14:25 em 2:25 P.M.
# A entrada é dada em dois inteiros. Deve haver pelo menos duas funções: uma para fazer a conversão e uma para a saída.
# Registre a informação A.M./P.M. como um valor ‘A’ para A.M. e ‘P’ para P.M. Assim, a função para efetuar as conversões terá um parâmetro formal para registrar se é A.M. ou P.M.
# Inclua um loop que permita que o usuário repita esse cálculo para novos valores de entrada todas as vezes que desejar.
def conversao_hora():
while True:
hrs = str(input('digite o número de horas:'))
while not hrs.isnumeric():
print('digite um número para validar o horário!')
hrs=str(input('digite o número de horas:'))
hrs=int(hrs)
while hrs>24 :
print('digitou errado!')
hrs = int(input('digite novamente o número de horas:'))
min = str(input('digite o número de minutos:'))
while not min.isnumeric():
print('digite um número para validar o horário!')
min = str(input('digite o número de minutos:'))
min=int(min)
while min>60:
print('digitou errado!')
min = int(input('digite novamente o número de minutos:'))
if min==60:
hrs=hrs+1
min=0
if hrs>12:
if hrs==24:
print(f'00:{min} PM')
else:
print(f'{hrs-12}:{min} PM')
elif hrs<=12:
print(f'{hrs}:{min} AM')
escolha = str(input('você quer continuar?[S]im ou [N]ao:')).strip().upper()[0]
if escolha=='N':
print('encerrando o programa...')
break
conversao_hora()
| false
|
e0a5c95ec996fd314a829b8f41043a0f3aaa9d4c
|
JanDimarucut/cp1404practicals
|
/prac_06/car_simulator.py
| 1,397
| 4.125
| 4
|
from prac_06.car import Car
MENU = "Menu:\nd) drive\nr) refuel\nq) quit"
def main():
print("Let's drive!")
name = input("Enter your car name: ")
my_car = Car(name, 100)
print(my_car)
print(MENU)
menu_choice = input(">>>").lower()
while menu_choice != "q":
if menu_choice == "d":
distance_to_driven = int(input("How many km do you wish to drive? "))
while distance_to_driven < 0:
print("Distance must be >= 0")
distance_to_driven = int(input("How many km do you wish to drive? "))
distance_driven = my_car.drive(distance_to_driven)
print("The car drove {}".format(distance_driven))
if my_car.fuel == 0:
print("and ran out of fuel")
elif menu_choice == "r":
print(my_car)
add_fuel = int(input("How many units of fuel do you wan to add to the car? "))
while add_fuel <= 0:
print("Fuel amount must be > 0")
add_fuel = int(input("How many units of fuel do you wan to add to the car? "))
my_car.add_fuel(add_fuel)
print("Added {} units of fuel".format(add_fuel))
else:
print("Invalid choice")
print(my_car)
print(MENU)
menu_choice = input(">>>")
print("Good bye {}'s driver".format(name))
main()
| true
|
210105f313227d23381e8ce2e0511df1ffec2637
|
JanDimarucut/cp1404practicals
|
/prac_04/list_exercises.py
| 2,647
| 4.40625
| 4
|
# 1
numbers = []
for i in range(5):
number = int(input("Number: "))
numbers.append(number)
# print("The first number is: ", numbers[0])
# print("The last number is: ", numbers[-1])
# print("The smallest number is: ", min(numbers))
# print("The largest number is: ", max(numbers))
# print("The average of the numbers is: ", sum(numbers) / len(numbers))
# 2
user_names = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExerState', 'InteractiveConsole', 'InterpreterInterface',
'StartServer', 'bob']
user_input = input("Please enter your username")
if user_input in usernames:
print("Access granted")
else:
print("Access denied")
# 3
names = ["Bob", "Angel", "Jimi", "Alan", "Ada"]
full_names = ["Bob Martin", "Angel Harlem", "Jimi Hendrix", "Alan Turing",
"Ada Lovelace"]
# for loop that creates a new list containing the first letter of each name
first_initials = []
for name in names:
first_initials.append(name[0])
print(first_initials)
# list comprehension that does the same thing as the loop above
first_initials = [name[0] for name in names]
print(first_initials)
# list comprehension that creates a list containing the initials
# splits each name and adds the first letters of each part to a string
full_initials = [name.split()[0][0] + name.split()[1][0] for name in
full_names]
print(full_initials)
# one more example, using filtering to select only the names that start with A
a_names = [name for name in names if name.startswith('A')]
print(a_names)
# use a list comprehension to create a list of all of the full_names
# Names printed in all capital letters
capital_names = []
all_full_names = [name.upper() for name in full_names]
capital_names.append(all_full_names)
print(capital_names)
# in lowercase format
lowercase_full_names = [name.lower() for name in full_names]
print(lowercase_full_names)
almost_numbers = ['0', '10', '21', '3', '-7', '88', '9']
# use a list comprehension to create a list of integers
# Numbers sorted from smallest to biggest
sorted_int = []
almost_numbers.sort()
sorted_int += almost_numbers
print(sorted_int)
# from the above list of strings
numbers = [int(almost_number) for almost_number in almost_numbers]
print(numbers)
# use a list comprehension to create a list of only the numbers that are
over_nine = []
bigger_number = [number for number in numbers if number > 9]
over_nine.append(bigger_number)
print(over_nine)
# greater than 9 from the numbers (not strings) you just created
big_numbers = [number for number in numbers if number > 9]
print(big_numbers)
| true
|
8110f3a49b6abc0b0d9d622ad5a47af30d447246
|
limjeongmin/p2_201611101
|
/w5Main_8(2).py
| 462
| 4.3125
| 4
|
def BMI():
height=input("input user height (m):")
weight=input("input user weight (kg):")
BMI=weight/(height*height)
print BMI
if BMI<=18.5:
res='Underweight'
elif 18.5<BMI<=23:
res='nomarlweight'
elif 23<BMI<=25:
res='ove weight'
elif 25<BMI<=30:
res='obesity'
elif 30<BMI<=35:
res='very obesity'
else:
res='extremly obesity'
return res
print BMI()
| false
|
a00f702483bab4e505f2c2cb7b7bc790d01beeeb
|
Zach-Wibbenmeyer/cs108
|
/lab05/spirograph.py
| 2,909
| 4.125
| 4
|
'''Using Python to draw a spirograph
March 5, 2015
Lab05 Exercise 2
Zach Wibbenmeyer (zdw3)'''
#Gains access to the turtle module
import turtle
#Gains access to the math module
import math
#Prompts the user to enter a choice if they would like to draw or not
choice = str(input('Would you like to draw a spirograph? (Y/n): '))
#Forever while loop
while True:
#If statement checking if choice is no
if choice == 'n' or choice == 'N':
print('Okay! Maybe some other time')
break
#Else if statement checking if choice is yes
elif choice == 'Y' or choice == 'y':
#Create a variable named window and make it the turtle screen
window = turtle.Screen()
#Create a turtle and name it zach
zach = turtle.Turtle()
#Prompts the user to enter the moving radius
mov_rad = float(input('Please enter a moving radius: '))
#Prompts the user to enter the fixed radius
fix_rad = float(input('Please enter a fixed radius: '))
#Prompts the user to enter the pen offset
pen_offset = float(input('Please enter the pen offset: '))
#Prompts the user to enter the color
color = str(input('Please enter the color: '))
#Creates a variable of the current time and initializes it to 0
current_time = 0.0
#Finds the x value
x = (fix_rad * mov_rad) * math.cos(current_time) + pen_offset * math.cos((((fix_rad + mov_rad) * current_time))/mov_rad)
#Finds the y value
y = (fix_rad * mov_rad) * math.sin(current_time) + pen_offset * math.sin((((fix_rad + mov_rad) * current_time))/mov_rad)
#Tells zach to change the speed to 10
zach.speed(10)
#Tells zach to pick the pen up
zach.penup()
#Tells zach to go to the x and y points
zach.goto(x,y)
#Tells zach to put the pen down
zach.pendown()
#Tells zach to change the pen color to what the user enters
zach.pencolor(color)
#While loop checking if current_time is less than 100
while current_time < 100:
#Redefines the x variable
x = (fix_rad * mov_rad) * math.cos(current_time) + pen_offset * math.cos((((fix_rad + mov_rad) * current_time))/mov_rad)
#Redefines the y variable
y = (fix_rad * mov_rad) * math.sin(current_time) + pen_offset * math.sin((((fix_rad + mov_rad) * current_time))/mov_rad)
#Tells zach to go to the new x and y points
zach.goto(x,y)
#Increments the current time
current_time += .1
#Tell the turtle window to remain open until clicked on
window.exitonclick()
#Else if statement checking if choice is something other than yes
elif choice != 'y' or choice != 'Y':
choice = str(input('Would you like to draw a spirograph? (Y/n): '))
| true
|
703a6f099c981601b87743d254d6b6661626fa6f
|
mronowska/python_code_me
|
/zadania_domowe/zadDom3.py
| 945
| 4.28125
| 4
|
men_name = input("Male name: ")
feature_positive = input("Positive feature of this man: ")
feature_negative = input("Negative feature of this man: ")
day_of_the_week = input("Day of the week: ")
place = input("Place: ")
animal = input("Animal: ")
print(
f"There was a man called {men_name}. In one hand he was {feature_positive}, but on the other hand also a little {feature_negative}.\nOne day, I think it was {day_of_the_week}, {feature_negative} lost him. When he was walking on the {place}, he met {animal}, which ate people for being {feature_negative}. That's how he died.")
print("\n\n")
print(
f"There was a man called {men_name}. In one hand he was {feature_positive}, but on the other hand also a little {feature_negative}.\nOne day, I think it was {day_of_the_week}, {feature_negative} lost him. When he was walking on the {place}, he met {animal}, which ate people for being {feature_negative}. That's how he died."[::-1])
| true
|
8df97a9d1609a30896b0a3342a44b11cc7fcce90
|
Mannuel25/py-projects
|
/all-python-codes/e-mail-scrapper/email.py
| 502
| 4.25
| 4
|
# file input for users
fname = input('Enter file name: ')
# if the enter key is pressed 'emailfile.txt' is the file automatically
if (len(fname) < 1): fname = 'emailfile.txt'
#file handle
fh = open(fname)
# a loop that prints out the email
for line in fh:
# parsing through
if not line.startswith('From '): continue
pieces = line.split()
email = pieces[1]
info1 = email.find('@')
info2 = email.find(' ', info1)
org = email[info1 + 1:info2]
print (org)
| true
|
f1e0b7caafb0e93735eeb2b8fda8ba152076607d
|
Mannuel25/py-projects
|
/all-python-codes/password-generator/password-generator-2/generate_password.py
| 1,523
| 4.34375
| 4
|
import secrets, string
def password_generator():
"""
A program that generates a secure random password
: return: None
"""
try:
# get the length of alphabets to be present in password
length_of_alphabets = int(input('\nEnter the length of alphabets (upper and lower case inclusive): '))
# get the length of digits to be present in password
length_of_digits = int(input('Enter the length of digits: '))
# get the length of special characters to be present in password
length_of_special_characters = int(input('Enter the length of special characters: '))
except ValueError:
print('Invalid Input!')
else:
# get the total password length
passwordLength = length_of_alphabets + length_of_digits + length_of_special_characters
# generate a password for user based on the total password length
securePassword = ''.join(secrets.choice(string.ascii_letters) for i in range(length_of_alphabets))
securePassword += ''.join(secrets.choice(string.digits) for i in range(length_of_digits))
securePassword += ''.join(secrets.choice(string.punctuation) for i in range(length_of_special_characters))
# make a list with the password
generated_password = list(securePassword)
# shuffle generated password
secrets.SystemRandom().shuffle(generated_password)
print('Your password of length {} is {}'.format(passwordLength,''.join(generated_password)))
password_generator()
| true
|
eb7d6522bdc0ed9b1a9a6533d84528f0bb27f78e
|
solankeganesh777/Python-Basics-for-data-science-project
|
/Matplotlib/Plotting.py
| 458
| 4.15625
| 4
|
# Matplotlib Plotting
#Plotting X and Y points
x=np.array([1,4,5,7])
y=np.array([5,3,9,5])
plt.plot(x,y)
plt.show()
print("\n")
#Plotting without line
x=np.array([1,4,5,7])
y=np.array([5,3,9,5])
plt.plot(x,y,'o')
plt.show()
print("\n")
# Multiple points
x=np.array([1,6,4,2,5,7])
y=np.array([5,3,8,9,3,5])
plt.plot(x,y)
plt.show()
print("\n")
# Default X points: here it takes xpoints defaultly as [0,1,2...]
y=np.array([5,3,9,5])
plt.plot(y)
plt.show()
| false
|
f38dcb8559ab8e18e3b5215d549e9193427061cc
|
solankeganesh777/Python-Basics-for-data-science-project
|
/Python basics/Iterator.py
| 666
| 4.21875
| 4
|
#Python Iterators
list=[1,2,3,4,5,6,7,8]
myit=iter(list)
print(next(myit))
print(next(myit))
print(type(myit))
print("\n")
name="Ganesh"
myit=iter(name)
print(next(myit))
print(next(myit))
print(type(next(myit)))
print(next(myit))
print(next(myit))
print(next(myit))
print("\n")
#Creation of iterator
class MyNumbers:
def __iter__(self):
self.a=1
return self
def __next__(self):
if self.a<=3:
x=self.a
self.a+=1
return x
else:
raise StopIteration
Myclass=MyNumbers()
myiter=iter(Myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
| false
|
8abed6121ee7847b3d076fa7c555db089ec3f483
|
wajdm/ICS3UR-5-05-Python
|
/addressing_mails.py
| 1,866
| 4.46875
| 4
|
# !/usr/bin/env python3
# Created by: Wajd Mariam
# Created on: December 2019
# This program formats the mailing address using given input.
def format_address(first_name, last_name, street_add, city,
province, postal_code, apt_number=None):
# returns formatted mailing address
if apt_number is not None:
address = first_name + " " + last_name + "\n" + apt_number + "-" \
"" + street_add + "\n" + city + " " + province + " " + postal_code
else:
address = first_name + " " + last_name + "\n" + street_add + "\n" + \
city + " " + province + " " + postal_code
return address
def main():
# this function gets user input and fromats it into mailing address.
# welcome statement.
print("")
print("This program formats your mailing address using given input")
print("Make sure all of your input is in upper case!")
print("")
apt_number = None
# getting input from user
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
question = input("Does your receiver have an apartment number? (y/n): ")
if question.upper() == "Y" or question.upper() == "YES":
apt_number = input("Enter the apartment number: ")
street_add = input("Enter the street address: ")
city = input("Enter the city: ")
province = input("Enter the province: ")
postal_code = input("Enter the postal code: ")
# process
if apt_number is not None:
address = format_address(first_name, last_name, street_add, city,
province, postal_code, apt_number)
else:
address = format_address(first_name, last_name, street_add,
city, province, postal_code)
# output
print("")
print(address)
if __name__ == "__main__":
main()
| true
|
ac566079a1f0b1c8b05a921253df65872f4d2201
|
tryingtokeepup/Sorting
|
/src/iterative_sorting/iterative_sorting.py
| 1,387
| 4.34375
| 4
|
# TO-DO: Complete the selection_sort() function below
def swapping_helper(index_a, index_b, arr):
# cool_dude = array
temp = arr[index_a]
arr[index_a] = arr[index_b]
arr[index_b] = temp
return arr
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
if cur_index != smallest_index:
arr = swapping_helper(smallest_index, cur_index, arr)
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# call my swap function
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# well, aggghhhhhh. i suck at variable names, so here. let's just assume that at the beginning, we are still wanting to swap.
swap_actually_happened = True
while swap_actually_happened:
swap_actually_happened = False
for i in range(0, len(arr) - 1): # remember to minus 1 so we don't go out of bounds
if arr[i] > arr[i+1]:
arr = swapping_helper(i, i+1, arr)
swap_actually_happened = True
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true
|
9a718e4a71ef9f2a19f9decc472d6fba57a5cb51
|
czwartaoslpoj/book-review-project
|
/templates/house_hunting.py
| 736
| 4.1875
| 4
|
//calculating how many months I need to save the money fo portion_down_payment
total_cost = int(input("The cost of your dream house: "))
portion_down_payment = total_cost/4
current_savings = 0
annual_salary= int(input("Your annual salary: "))
portion_saved = float(input("Portion of your salary to save as a decimal: "))
monthly_salary = annual_salary/12
percent_of_monthly_salary_to_save = monthly_salary * portion_saved
months=0
while current_savings < portion_down_payment:
investment_savings = (current_savings * 0.04) / 12
current_savings= current_savings+ percent_of_monthly_salary_to_save+ investment_savings
months +=1
if current_savings >= portion_down_payment:
print(months)
| true
|
e1a42bb8d1b00666fe1a9d2022d116fc879630eb
|
markellisdev/bangazon-orientationExercises1-6
|
/bangazon.py
| 2,605
| 4.15625
| 4
|
class Department(object):
"""Parent class for all departments
Methods: __init__, get_name, get_supervisor
"""
def __init__(self, name, supervisor, employee_count):
self.name = name
self.supervisor = supervisor
self.size = employee_count
def get_name(self):
"""Returns the name of the department"""
return self.name
def get_supervisor(self):
"""Returns the name of the supervisor"""
return self.supervisor
class HumanResources(Department):
"""Class representing Human Resources department
Methods: __init__, add_policy, get_policy, etc.
"""
def __init__(self, name, supervisor, employee_count):
super().__init__(name, supervisor, employee_count)
self.policies = set()
def add_policy(self, policy_name, policy_text):
"""Adds a policy, as a tuple, to the set of policies
Arguments:
policy_name (string)
policy_text (string)
"""
self.policies.add((policy_name, policy_text))
def get_policy(self):
return self.policies
class InformationTechnology(Department):
def __init__(self):
super().__init__(self, name, supervisor, employee_count)
self.languages = ()
def add_devLanguage(self, language_name):
"""Adds a language to the set of languages"""
class Marketing(Department):
"""Class representing Marketing department
Methods: __init__, add_materials, get_materials
"""
def __init__(self, name, supervisor, employee_count):
super().__init__(name, supervisor, employee_count)
self.materials = ()
def add_material(self, material_type):
self.materials.add(material_type)
marketing_department = Marketing("Marketing", "Jami Jackson", 3)
print("{0} is the head of the {1} Department, which has {2} employees".format(marketing_department.supervisor, marketing_department.name, marketing_department.size))
human_resources_dept = HumanResources("Human Resources", "Val Hovendon", 1)
human_resources_dept.add_policy("Code Of Conduct", "Covers employees, board members and volunteers")
human_resources_dept.add_policy("Hours Of Work", "Describes the number of hours full time employees are required to work")
print(human_resources_dept.policies)
CodeOfConduct_policy = {x: y for x, y in human_resources_dept.policies if "Code Of Conduct" in x}
print(type(CodeOfConduct_policy))
for k, v in CodeOfConduct_policy.items():
print("Please see {0}, to view our {1} policy which has the following desription: {2}".format(human_resources_dept.name, k, v))
| true
|
55f4e852fd8e90f8e3ab507f22a881a4a1e63181
|
zhufangxin/learn-python3
|
/Fractal_tree/fractal_tree.py
| 825
| 4.28125
| 4
|
"""
递归 绘制分形树
"""
import turtle
def draw_branch(branch_length):
"""
绘制分形树
"""
if branch_length > 5:
# 绘制右侧树枝
turtle.forward(branch_length)
print('向前', branch_length)
turtle.right(20)
print('向右20度')
draw_branch(branch_length - 15)
# 绘制左侧树枝
turtle.left(40)
print('向左40度')
draw_branch(branch_length - 15)
# 返回之前的树枝
turtle.right(20)
print('向右20度')
turtle.backward(branch_length)
print('向后', branch_length)
def main():
"""
主函数
"""
turtle.left(90)
draw_branch(40)
turtle.exitonclick()
if __name__ == '__main__':
main()
| false
|
9eea9265e1ace539b7498d06a98811dc189c3578
|
strawwhat/diary
|
/programming-three/three134.py
| 2,269
| 4.125
| 4
|
#!/usr/bin/python
# *-*coding:utf-8 *-*
"示例3-9 page134 redirect.py 重定向流到python对象"
"""
file-like objects that save standard output in a string and provide
standard input text a string ; redirect runs a passed-in function
with its output and input streams reset to these file-like class objects
类似文件的对象,用于在字符串中保存标准输出并提供
标准输入文本字符串; 重定向运行传入函数
其输出和输入流重新设置为这些类似文件的类对象
在Python中,任何在方法上与文件类似的对象都可以充当标准流。
它和对象数据类型无关,而取决于接口(有时被称为协议)即:
任何提供了类似于文件read方法的对象可以指定给sys.stdin,
以从该对象的read方法读取输入
任何定义了类似于文件write方法的对象可以指定给sys.stdout,
所有的标准输出将发送到该对象方法上
"""
import sys
class Output: #模拟输出文件
def __init__(self):
self.text = '' #新建空字符串
def write(self, string):
self.text += string #添加字节字符串
def writelines(self, lines): #在列表中添加每一行数据
for line in lines: self.write(line)
#模拟输入文件
class Input:
def __init__(self, input=''): #默认参数
self.text = input
def read(self, size=None): #保存新建字符串,可选参数
if size == None: #读取n个字节,或者所有字节
res, self.text = self.text, ''
else:
res, self.text = self.text[:size], self.text[size:]
return res
def readline(self):
eoln = self.text.find('\n') #查找下一个eoln的偏移位置
if eoln == -1: #清洗eoln,其值为-1
res, self.text = self.text, ''
else:
res, self.text = self.text[:eoln+1], self.text[eoln+1:]
return res
def redirect(function, pargs, kargs, input): #重定向stdin/out
savestreams = sys.stdin, sys.stdout #运行函数对象
sys.stdin = Input(input) #返回stdout文件
sys.stdout = Output()
try:
result = function(*pargs, **kargs) #运行带参数的函数
output = sys.stdout.text
finally:
sys.stdin, sys.stdout = savestreams #如果存在exc或者其他,重新存储数据
return (result, output) #如果不存在exc,返回结束
| false
|
24f6feeda30f66fddf433d9d4c0cd388b6509763
|
MrDeshaies/NOT-projecteuler.net
|
/euler_042.py
| 1,597
| 4.125
| 4
|
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
# so the first ten triangle numbers are:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# By converting each letter in a word to a number corresponding to its alphabetical position and
# adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10.
# If the word value is a triangle number then we shall call the word a triangle word.
#
# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand
# common English words, how many are triangle words?
import re
def load_words(filename):
f = open(filename, "r")
data = f.readline()
f.close()
# file looks like "BOB","MARY","JANE"
# split will keep an empty token at the front and end. Get rid of them
words = re.split(r'\W+',data)
words = words[1:len(words)-1]
return words
def compute_score(word):
A = ord("A")
return sum(ord(x.upper()) - A + 1 for x in word)
def generate_triangle(upper_limit):
triangle_numbers = []
i = 1
while True:
n = int((i * (i+1)) / 2)
triangle_numbers.append(n)
i += 1
if n > upper_limit:
break
return triangle_numbers
# compute the score for each word
words = load_words("p042_words.txt")
word_scores = [compute_score(x) for x in words]
# find the relevant triangle numbers
triangle_numbers = generate_triangle(max(word_scores))
# count how many words have a triangle score...
print(len([x for x in word_scores if x in triangle_numbers]))
| true
|
542759df80baa3bdc951931364e72aea52226305
|
amitkumar-panchal/ChQuestiions
|
/python/q01/Contiguous.py
| 1,558
| 4.28125
| 4
|
"""
Fiels: _items is a list of items
_size is number of items that can be stored
"""
## Contiguous(S) produces contiguous memory of size s
## and initializes all entries to None.
## Requires: s is positive
class Contiguous:
def __init__(self, s):
self._items = []
self._size = s;
for index in range(self._size):
self._items.append(None)
## repr(self) produces a strinng with the sequence of values.
## __repr__: contiguous -> Str
def __repr__(self):
to_return = "("
for index in range(self._size - 1):
if self.access(index) == None:
to_print = "None"
else:
to_print = self.access(index)
to_return = to_return + str(to_print) + ","
if self.access(self._size - 1) == None:
to_print = "None"
else:
to_print = self.access(self._size - 1)
return to_return + str(to_print) + ")"
## self == other produces the size of self
## size. Contiguous -> Int
def size(self):
return self._size
def __eq__(self, other):
if(self.size() != other.size()):
return False
else:
for pos in range(self.size()):
if self.access(pos) != other.access(pos):
return False
else:
return True
def access(self, index):
return self._items[index]
def store(self, index, value):
self._items[index] = value
| true
|
164e6ece6af8f27d2f6154414be81e602fc2c53b
|
Anushadsilva/python_practice
|
/List/list.pg5.py
| 489
| 4.21875
| 4
|
'''Write a Python program to extract specified size of strings from a give list of string values. Go to the editor
Original list:
['Python', 'list', 'exercises', 'practice', 'solution']
length of the string to extract:
8 '''
#Solution:
if __name__ == '__main__':
list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
list2 = []
usr = input("choose the length of string 6 or 4 or 9 or 8")
for ch in list1:
if len(ch) == int(usr):
list2.append(ch)
print(list2)
| true
|
e6e3fecae85caf717dd594e94096a717e9cd16b4
|
Anushadsilva/python_practice
|
/dictionary/dict_py6.py
| 575
| 4.125
| 4
|
'''Write a Python program to count the frequency in a given dictionary.
Original Dictionary:
{'V': 10, 'VI': 10, 'VII': 40, 'VIII': 20, 'IX': 70, 'X': 80, 'XI': 40, 'XII': 20}
Count the frequency of the said dictionary:
Counter({10: 2, 40: 2, 20: 2, 70: 1, 80: 1})'''
#Solution
if __name__ == '__main__':
dict1 = {'V': 10, 'VI': 10, 'VII': 40, 'VIII': 20, 'IX': 70, 'X': 80, 'XI': 40, 'XII': 20}
freq = 0
dict2 = {}
for x in dict1.values():
if x in dict2:
dict2[x] = dict2[x] + 1
else:
dict2[x] = 1
print(dict2)
| false
|
d68786a9942542808767b47b11919d0f7f7eaa6a
|
Anushadsilva/python_practice
|
/Functions/func_pg3.py
| 305
| 4.28125
| 4
|
#Write a Python function to find the Max of three numbers
def mx(x,y,z):
return max(x,y,z)
if __name__ == '__main__':
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
c =int(input("Enter the third number"))
print("max of the given numbers is: ", mx(a,b,c))
| true
|
579d6046604626afd901e8885bcce6de1a8fb09c
|
SinghReena/TeachPython3
|
/SayNamesMultipleTimes.py
| 591
| 4.21875
| 4
|
# SayNamesMultipleTimes.py - lets everybody print their name on the screen
# Ask the user for their name
name = input("Can I know your name please: ")
# Keep printing names until we want to quit
while name != "":
# Print their name 35 times
for x in range(35):
# Print their name followed by a space, not a new line
print(name, end = " ")
print() # After the for loop, skip down to the next line
# Ask for another name, or quit
name = input("Type another name, or just hit [ENTER] to quit: ")
print("Thanks for printing names 35 times!")
| true
|
ac96cf0e2ab8e77a576743b00c938e0d259aa089
|
TanmoyX/CodeStore-Cracking_The_Coding_Interview
|
/Chap2/2.1 - RemoveDuplicates/n2-sol.py
| 936
| 4.125
| 4
|
class Node:
def __init__(self, val):
self.data = val
self.next = None
def printLL(node):
while node != None:
print(node.data)
node = node.next
def insertNode(node, val):
if node == None:
return None
while node.next != None:
node = node.next
node.next = Node(val)
node.next.next = None
def removeDuplicates(node):
#This method has a time complexity of O(N^2) and space complexity of O(1) without using any temporary buffer
head = node
while node != None:
runner = node
while (runner.next != None):
if runner.next.data == node.data:
runner.next = runner.next.next
else:
runner = runner.next
node = node.next
return head
n = Node(4)
insertNode(n, 8)
insertNode(n, 1)
insertNode(n, 1)
insertNode(n, 5)
insertNode(n, 9)
printLL(n)
print()
printLL(removeDuplicates(n))
| true
|
dcc1cf9a1a3e14da5f1e39d9f11447d0354b39d9
|
Visorgood/CodeBasics
|
/Python/MergeSort.py
| 966
| 4.1875
| 4
|
def mergesort(array):
if len(array) == 1:
return array
else:
middle = len(array) / 2
half1 = mergesort(array[:middle])
half2 = mergesort(array[middle:])
mergedarray = merge(half1, half2)
return mergedarray
def merge(half1, half2):
mergedarray = []
lenhalf1 = len(half1)
lenhalf2 = len(half2)
i = 0
j = 0
while i < lenhalf1 and j < lenhalf2:
if half1[i] < half2[j]:
mergedarray.append(half1[i])
i += 1
else:
mergedarray.append(half2[j])
j += 1
if i < lenhalf1:
while i < lenhalf1:
mergedarray.append(half1[i])
i += 1
else:
while j < lenhalf2:
mergedarray.append(half2[j])
j += 1
return mergedarray
import random
array = []
for i in range(50):
array.append(random.randrange(100))
print "Array:", array
print "Sorted array:", mergesort(array)
| false
|
7f8be46a01d986de37906424a7c6e7e186ca30c3
|
Shivani3012/PythonPrograms
|
/conditional ass/ques33.py
| 484
| 4.375
| 4
|
#Write a Python program to convert month name to a number of days.
print("Enter the list of the month names:")
lname=[]
for i in range(0,12):
b=input()
lname.append(b)
#print(lname)
m=input("Enter the month name:")
ind=lname.index(m)
#print(ind)
if ind==0 or ind==2 or ind==4 or ind==6 or ind==7 or ind==9 or ind==11:
print("number of days in "+ m +" is 31")
elif ind==1:
print("number of days in febraury is 28/29")
else:
print("number of days "+m+" is 30")
| true
|
21d89fe0a3fbf5d59124847acd307845da9205ce
|
Shivani3012/PythonPrograms
|
/guessing a number.py
| 876
| 4.15625
| 4
|
print(" Welcome to the Guessing a Number Game ")
print("You have to guess a number if the number matches the random number")
print("you win the game else you will only get three chances")
name=input("Enter the user name")
import random
for i in range (1,4):
print("Chance",i)
r=random.randint(10,50)
h=int(input("Guess the number between the range 10 to 50:"))
if r>h:
print("Guessed number is",r)
print("The number you guessed is smaller then the number we guess.")
print("So sorry, you are losser .")
elif r<h:
print("The guessed number is",r)
print("The number you guessed is higher then the number we guess.")
print("So sorry, you are losser .")
else:
print("Guessed number is",r)
print("The number you guessed is equal to the number we guess.")
print("You win")
| true
|
53ca55ed41ad6b133f43f1951a52320980eed50d
|
Shivani3012/PythonPrograms
|
/conditional ass/ques6.py
| 419
| 4.15625
| 4
|
#Write a Python program to count the number of even and odd numbers from a series of numbers.
a=int(input("Enter the number of elements in the list"))
print("Enter the list")
l=[]
countev=0
countodd=0
for i in range(a):
b=int(input())
l.append(b)
for i in range(a):
if l[i]%2==0:
countev+=1
else:
countodd+=1
print("No. of even elements:",countev)
print("No. of odd elements:",countodd)
| true
|
52a686724c000189abcae44a27fc2e0eda9f4b70
|
Shivani3012/PythonPrograms
|
/conditional ass/ques35.py
| 212
| 4.40625
| 4
|
#Write a Python program to check a string represent an integer or not.
s=input("Enter the string")
a=s.isdigit()
#print(a)
if a==True:
print("This is an integer.")
else:
print("This is not an integer.")
| true
|
bd87a4ee20fdf0e51fad300f66b818f95a5d76dc
|
bend-is/pystudy
|
/basics/lesson_5/task_3.py
| 879
| 4.21875
| 4
|
"""
Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
Выполнить подсчет средней величины дохода сотрудников.
"""
MIN_SALARY = 20000
with open('task_3.txt') as f:
total_sal = 0
sal_count = 0
for line in f:
surname, salary = line.split()
salary = int(salary)
total_sal += salary
sal_count += 1
if salary < MIN_SALARY:
print(f"Employee {surname} has salary less then minimum salary ({salary})")
print(f"\nAverage employees salary is {total_sal / sal_count}")
| false
|
86c212bb843d178fc0744f9d0b0db790f8d8ba47
|
bend-is/pystudy
|
/basics/lesson_3/task_4.py
| 1,183
| 4.21875
| 4
|
"""
Программа принимает действительное положительное число x и целое отрицательное число y.
Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
"""
from typing import Union
def get_num_pow_v1(x: int, y: int) -> Union[int, float]:
return x ** y
def get_num_pow_v2(x: int, y: int) -> Union[int, float]:
if y == 0:
return 1
count = y if y >= 0 else y * -1
res = x
for _ in range(1, count):
res *= x
return res if y >= 0 else 1 / res
if __name__ == '__main__':
n_1 = n_2 = 0
while n_1 <= 0:
n_1 = int(input("Enter a positive number: "))
while n_2 >= 0:
n_2 = int(input("Enter a negative number: "))
print(f"{n_1}^{n_2} is {get_num_pow_v1(n_1, n_2)} (v1)")
print(f"{n_1}^{n_2} is {get_num_pow_v2(n_1, n_2)} (v2)")
| false
|
16c02f1a57a85d4e45879e71444e013a6092c395
|
bend-is/pystudy
|
/basics/lesson_1/task_5.py
| 1,388
| 4.15625
| 4
|
"""
Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает
фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите
численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
"""
earnings = int(input("Enter company earnings: "))
outgoings = int(input("Enter company outgoings: "))
if earnings > outgoings:
profit = earnings - outgoings
print(f"\nCompany works for profit. Profit is {profit}")
profitability = (profit / earnings) * 100
print(f"Profitability of company is {profitability:.2f}%\n")
employee_count = int(input("Enter company employee count: "))
print(f"\nProfit per employee is {profit / employee_count:.2f}")
if earnings == outgoings:
print("\nCompany works to zero")
else:
print("\nCompany works for loss")
| false
|
4112f792af4b4e1cd696891ebaa81dcd6868a4c1
|
KaanSerin/python_side_projects
|
/rock_paper_scissors_game.py
| 2,879
| 4.28125
| 4
|
import random
def welcomeMessage():
print("Welcome to my very basic rock, paper, scissors game!")
print('You can play as long as you want.')
print('Whenever you want to quit, just enter -1 and the game will end immediately.')
#Implementing the rules of rock paper scissors with if-else blocks
def decider(player_action, ai_action):
#Rock beats scissors
if player_action == '1' and ai_action == '3':
#player_score = player_score + 1
return True
elif ai_action == '1' and player_action == '3':
#ai_score = ai_score + 1
return False
#Paper beats Rock
elif player_action == '2' and ai_action == '1':
#player_score = player_score + 1
return True
elif ai_action == '2' and player_action == '1':
#ai_score = ai_score + 1
return False
#scissors beats paper
elif player_action == '3' and ai_action == '2':
#player_score = player_score + 1
return True
elif ai_action == '3' and player_action == '2':
#ai_score = ai_score + 1
return False
#Display the welcome messages
welcomeMessage()
#Possible actions
actions = {'1': 'Rock', '2': 'Paper', '3': 'Scissors'}
player_action = input('Enter a number | Rock(1), Paper(2), or Scissors(3): ')
#Scores of player an AI
player_score = 0
ai_score = 0
#Action of AI will be defined in the while loop
ai_action = None
#Game will continue until the user enters '-1' as their choice.
while player_action != '-1':
ai_action = str(random.randint(1, 3))
#Actions performed when the player wins
if decider(player_action, ai_action) == True:
player_score += 1
print('You won!')
print('Your move:', actions[player_action], "| AI's move:", actions[ai_action])
#Actions performed when the AI wins
elif decider(player_action, ai_action) == False:
ai_score += 1
print('AI won :(')
print('Your move:', actions[player_action], "AI's move:", actions[ai_action])
#Actions performed when it's a tie
else:
print("It's a tie!")
print('Your move:', actions[player_action], "AI's move:", actions[ai_action])
print("Your score:", player_score, "\nAI's score:", ai_score, "\n")
player_action = input('Enter a number | Rock(1), Paper(2), or Scissors(3): ')
#Ending the game
print("Game stopped.")
print("Your final score:", player_score, "\nAI's final score:", ai_score)
#End game messages
if player_score > ai_score:
print("You won the game! Thanks for playing! I hope you had a fun time.")
elif player_score == ai_score:
print("You tied! Feel free to try your luck later.")
else:
print("Thanks for playing! I hope you had a fun time... Even though you lost(hehehe)")
| true
|
d43a964b2eddddbfd01ad71ee356b7711f7945fd
|
s-ajensen/2017-18-Semester
|
/knockKnock/blackbelt.py
| 1,857
| 4.21875
| 4
|
# Samuel Jensen, Knock Knock Joke Blackbelt, 9/28/2017
# Checks user input, gets frustrated when user doesn't go with the joke, unnecessary recursion
# Get user's name
name = input("Hi what's your name?")
# Ask user if they want to hear a joke
hearJoke = input("Nice to meet you " + name + ", would you like to hear a knock knock joke?")
# Define asking function
def askJoke(response):
# If user says 'yes' continue joke
if response == "yes":
whoThere = input("Knock knock")
# Convert whoThere to lowercase in case user capitalized
whoThere = whoThere.lower()
# If user continues the joke, continue
if whoThere == "who's there" or whoThere == "who is there":
inquisition = input("The Spanish inquisition")
# Convert inquisition to lowercase in case user capitalized
inquisition = inquisition.lower()
# Check if user input continues the joke
if inquisition == "the spanish inquisition who" or inquisition == "the spanish inquisition who?":
print("No one expects the Spanish Inquisition!")
# If not, ragequit
else:
print("I don't think you really understand how these jokes work")
# Otherwise start again
else:
misunderstandJoke = input("Do you know how a knock knock joke works?")
askJoke(misunderstandJoke)
# If not, commend them, and quit
elif response == "no":
print("Good, anyone with any sense of humor wouldn't want to hear a knock knock joke")
return "no"
# If neither, chastise them for not being straightforward
else:
misunderstandYesNo = input("Please answer yes or no. Would you like to hear a knock knock joke?")
askJoke(misunderstandYesNo)
# Call function using user input
askJoke(hearJoke)
| true
|
f7b353f903f773892c834561b89e06b732cb61ca
|
x223/cs11-student-work-ibrahim-kamagate
|
/april11guidedpractice.py
| 861
| 4.25
| 4
|
# what does this function return ? This prints the x*2 which is 7*2
def print_only(x):
y = x * 2
print y
# how is this one different ? This does the same thing as the print function but you dont see it
def return_only(x):
y = x * 2
return y
# let's try to use our 2 functions
print "running print_only ..."# This prints whatever is in the quotes and it does the equation that is given an gives you the sum
print_only(7)
print "running return_only ..."# It does the samething as the one on line 12 but it doesn't print the sum
return_only(7)
print "printing print_only ..."# adding print mkes it also print none
print print_only(7)
print "printing return_only ..."#it only print whats n the quotes
return_only(7)
print "using print_only ..."#you can't add those two numbers
print_only(7) + 6
print "using return_only ..."
return_only(7) + 6
| true
|
90e995d7a410da9d546f1c3a2f687c9e12c74995
|
prasanth-vinnakota/python-gvp
|
/generator-fibonacci.py
| 358
| 4.125
| 4
|
def fibonacci(n):
a = 0
b = 1
for i in range(n):
yield a
a, b = b, a + b
size = None
try:
size = int(input("Enter size of fibonacci series: "))
if size == 0:
raise ValueError
except ValueError:
print("input must be a number and greater than 0")
exit(0)
for j in fibonacci(size):
print(j, end=" ")
| true
|
3c86b4be1943399afdee8e86a7e9d160b51ba1d2
|
ieee-saocarlos/exercicios-ia
|
/Vitorstraggiotti/Lista 3/ex_1_lista3_vitor.py
| 298
| 4.125
| 4
|
print "Este programa ira mostrar se uma palavra e um palindromo"
palavra = input("digite uma palavra entre aspas: ")
palavra_invertida = palavra[::-1]
if(palavra_invertida == palavra):
print "\n\nA palavra digitada e um palindromo"
else:
print "\n\nA palavra digitada nao e um palindromo"
| false
|
e9eea0d01e357b5e936f26e8b114d7657ba56b5f
|
luiz-ricardo-dev/Python
|
/aula2.py
| 796
| 4.15625
| 4
|
#Operadores Aritiméticos
a = int(input('Entre com o primeiro valor: '))
b = int(input('Entre com o segundo valor: '))
soma = a + b
subtracao = a - b
multiplicacao = a * b
divisao = a / b
resto = a % b
resultado =('Soma: {soma} '
'\nSubtração: {subtracao} '
'\nMultiplicação: {multiplicacao} '
'\nDivisão: {divisao} '
'\nResto: {resto}' .format(soma=soma,
subtracao=subtracao,
multiplicacao=multiplicacao,
divisao=divisao,
resto=resto))
print(resultado)
# print('Soma: ' + str(soma))
# print ('Subtração: ' + str(subtracao))
# print('Multiplicação: ' +str(multiplicacao))
# print('Divisão: ' +str(divisao))
# print('Resto de divisão: ' + str(resto))
| false
|
2cfe7c91405ec313dfed83e864bf6e18f5d8e276
|
jing1988a/python_fb
|
/900plus/FractionAdditionandSubtraction592.py
| 2,718
| 4.1875
| 4
|
# Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.
#
# Example 1:
# Input:"-1/2+1/2"
# Output: "0/1"
# Example 2:
# Input:"-1/2+1/2+1/3"
# Output: "1/3"
# Example 3:
# Input:"1/3-1/2"
# Output: "-1/6"
# Example 4:
# Input:"5/3+1/3"
# Output: "2/1"
# Note:
# The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
# Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
# The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
# The number of given fractions will be in the range [1,10].
# The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
class Solution:
def fractionAddition(self, expression):
"""
:type expression: str
:rtype: str
"""
eFormat=self.myFormat(expression)
l=len(eFormat)
if l ==0:
return 0
a, b = eFormat[0].split('/')
a = int(a)
b = int(b)
i=1
while i<l:
op=eFormat[i]
c , d=eFormat[i+1].split('/')
c=int(c)
d=int(d)
newA=0
if op=='+':
newA=a*d+c*b
else :
newA=a*d-c*b
newB=b*d
temp = self.maxDivide(a, b)
a=newA//temp
b=newB//temp
i+=2
temp=self.maxDivide(a , b)
a//=temp
b//=temp
return str(a)+'/'+str(b)
def myFormat(self , expression):
ans=[]
cur=[]
for e in expression:
if e in ['-' , '+']:
if cur:
ans.append(''.join(cur))
cur=[]
ans.append(e)
else:
cur.append(e)
else:
cur.append(e)
if cur:
ans.append(''.join(cur))
return ans
def maxDivide(self , a , b ):
if a>b:
a , b = b , a
i=b
while i>1:
if a%i==0 and b%i==0:
return i
i-=1
return 1
test=Solution()
print(test.fractionAddition("-1/2+1/2"))
| true
|
1e4e214385a54a8e225977e90172fe154dd2300a
|
jing1988a/python_fb
|
/lintcode_lyft/ReverseInteger413.py
| 558
| 4.125
| 4
|
# Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
#
# Example
# Given x = 123, return 321
#
# Given x = -123, return -321
class Solution:
"""
@param n: the integer to be reversed
@return: the reversed integer
"""
def reverseInteger(self, n):
# write your code here
flag=1
if n<0:
flag=-1
n=-n
# return int(str(n)[::-1])*flag
ans=0
while n:
ans=ans*10+n%10
n//=10
return ans*flag
| true
|
f8aef6ac6c5f8838b8fed96f3f36437c6560a423
|
Almr1209/idk
|
/ex32.py
| 1,001
| 4.59375
| 5
|
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a loop
for number in the_count:
print(f"This is count {number}")
# same as above, basically it's using the same format but different varaibles
for fruit in fruits:
print(f"A fruit of type: {fruit}s")
# also we can go through mixed lisits too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
# I don't know how to explain this, so sorry.
# New for me; therefore I cannot explain much besides what the book says
| true
|
a6ec7fbff14b620d8f2f7d227ac5818d82032892
|
Gustana/py-challenges
|
/learn/triangle.py
| 355
| 4.3125
| 4
|
height = int(input("Insert height :")) #5
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * * * *
limit = 1
while (limit<=height) :
star = limit
space = height
while (space >= limit) :
print(" ", end="")
space-=1
while (star >= 1) :
print("* ", end="")
star-=1
print("")
limit+=1
| false
|
6ca93d9a5fd4ab3654186883a427d7aa0bc02515
|
Valery-Bolshakov/learning
|
/theory/lesson_6.py
| 1,159
| 4.15625
| 4
|
print('Переменные\n')
a = 1 # создали переменную х и присвоили ей значение 1
y = 3 # int
u = 3.5 # float
my_var1 = 15
# определить тип переменной:
print('задали перменную класса - ', type(y))
print('задали перменную класса - ', type(u))
# Переменные являются регистрозависимыми:
x = 13
X = 14
print(x, X)
'''
Псевдоконстанты. их можно назначить, но нельзя переопределить где то в другом месте. Нужны для защиты каких то
данных от перезаписи. Например админский логин и пароль или путь подключения к БД
'''
TEST = 20
NAME = 123
'''Множественное присваивание переменных'''
g, h, j = (4, 7, 9)
print(g, h, j, '\n')
'''ПОМЕНЯТЬ МЕСТАМИ занчения переменных(используя методы работы с кортежами)'''
x = 1
y = 2
print(x, y)
x, y = y, x
print(x, y)
| false
|
e5db03cd5cde605a6fda0837ae334bfb247d231f
|
sarahoeri/Giraffe
|
/window.py
| 1,229
| 4.15625
| 4
|
# Tuples...don't change like in lists
even_numbers = (2, 4, 6, 8, 10, 12)
print(even_numbers[5])
# Functions
def sayhi(name, age) :
print("Hello " + name + " you are " + age)
sayhi("Nancy", "25")
sayhi("Christine", "27")
# Return Statement
def square(num) :
return num*num
print(square(8))
def cube(num) :
return num*num*num # return breaks out of the function
result = cube(8) # variable
print(result)
# If Statements
is_single = True
if is_single:
print("Head on to Tinder app")
else:
print("Meet your partner")
is_male = False
is_tall = True
if is_male and is_tall: # or tall
print("You are either male or tall or both")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("You are not a male but are tall")
else:
print("You are neither male or tall")
# Count number of even and odd numbers from a series of numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
count_even = 0
count_odd = 0
for x in numbers:
if x % 2 :
count_even += 1
else:
count_odd += 1
print("Number of even numbers is: " + str(count_even))
print("Number of odd numbers is: " + str(count_odd))
| true
|
9391c201f98ce42de5efc3c74cf6a32887901013
|
hyperskill/hs-test
|
/src/test/java/projects/python/coffee_machine/stage3/machine/coffee_machine.py
| 1,127
| 4.25
| 4
|
# Write your code here
water_amount = int(input('Write how many ml of water the coffee machine has:'))
milk_amount = int(input('Write how many ml of milk the coffee machine has:'))
coffee_amount = int(input('Write how many grams of coffee beans the coffee machine has:'))
N = int(water_amount / 200)
if N > milk_amount / 50:
N = int(milk_amount / 50)
if N > coffee_amount / 15:
N = int(coffee_amount / 15)
number_cups = int(input("Write how many cups of coffee you will need: "))
if number_cups == N:
print("Yes, I can make that amount of coffee")
elif N > number_cups:
print("Yes, I can make that amount of coffee (and even ", N-1," more than that)")
else:
print("No, I can make only ", N," cups of coffee")
#print("""Starting to make a coffee
#Grinding coffee beans
#Boiling water
#Mixing boiled water with crushed coffee beans
#Pouring coffee into the cup
#Pouring some milk into the cup
#Coffee is ready!""")
#
#
#print("For ", number_cups, " cups of coffee you will need:")
#print(200 * number_cups, " ml of water")
#print(50 * number_cups, " ml of milk")
#print(15 * number_cups, " g of coffee beans")
| true
|
78d06b6a9fb261085da55a1bdfbdc68443e61ecf
|
codegauravg/Python-Practice
|
/Hackerrank Problems/Prog2-If-Else.py
| 595
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""
Task
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird
"""
if __name__ == '__main__':
n = int(raw_input())
if n%2 != 0:
print "Wierd";
elif n%2==0 and n>=2 and n<=5:
print "Not Wierd";
elif n%2==0 and n>=6 and n<=20:
print "Wierd"
else:
print "Not Wierd"
| false
|
6886fb7cda4200f52e9021cba4b2989aa73d3b62
|
mybatete/Python
|
/Prime Number/prime.py
| 264
| 4.125
| 4
|
prime=True
num = input("Enter a Number: ")
if num <1:
print "Enter a Number Greater Than 1!!!"
exit()
for k in xrange(2,num):
if num % k == 0:
prime = False
break
if prime == True:
print num,"is a Prime Number"
else:
print num,"is NOT a Prime Number"
| false
|
8cd722978b4902fd1f5e803d37358ac481741a54
|
mybatete/Python
|
/seqBinSearch.py
| 1,873
| 4.25
| 4
|
"""
Program: seqBinSearch.py
Author : Charles Addo-Quaye
E-mail : caaddoquaye@lcsc.edu
Date : 01/31/2018
Description:
This program implements demo for both
sequential and binary search algorithms.
The program generates a random list of integers
and provides a menu for searching for numbers
in the list.
Input variables: List
Output variables: match, found
"""
import random
def main():
NUM=100
List = []
for num in xrange(NUM):
value = random.randint(0,50000)
List.append(value)
size = len(List)
print List
List.sort()
#print List
print "\n\nListed Database contains %d Records\n\n" % len(List)
#Create a List to store the returned Found item:
match = []
done = False
while not done:
response = raw_input("Exit Records Database? 'Y/N': ")
if response.upper() == "Y":
done = True
else:
query = input("Enter a Number: ")
found = seqSearch(List,size,query,match)
#found = binarySearch(List,size,query,match)
if found:
print "Query Number (%d) Found: %d at Position: %d\n" % (query, match[0],match[1])
else:
print "\n\n***No Record of the Number %s in Database***\n\n" % query
def binarySearch(List,size,query,match):
i = 0
first = 0
last = size - 1
found = False
while first <= last :
mid = (last + first)/2
print "Search iteration: %d\tMid-point: %d" % (i,mid)
i = i + 1
if query > List[mid]:
first = mid + 1
elif query < List[mid]:
last = mid - 1
else:
break
#first = last + 1
#last = first - 1
if query == List[mid]:
found = True
match.insert(0,List[mid])
match.insert(1,mid)
return found
def seqSearch(List,size,query,match):
i = 0
found = False
while i < size and query != List[i]:
print "Search iteration: %d" % (i)
i = i + 1
if i < size and query == List[i]:
found = True
match.insert(0,List[i])
match.insert(1,i)
return found
main()
| true
|
97cbad6efeed92d06082f371966262e15d6cdfe5
|
krissmile31/documents
|
/Term 1/SE/PycharmProjects/pythonProject/venv/TemperatureConverter.py
| 233
| 4.40625
| 4
|
print("Celsius to Fahrenheit temperature Converter!\n")
Celsius = float(input("Enter the temperature in Celsius: " ))
convert = (9/5) * Celsius + 32
print("\nCelsius: ", Celsius, "℃")
print(" Fahrenheit: " , convert, "℃")
| false
|
dff114f7caa3b803d85a634807ae4e38aa70a4e0
|
krissmile31/documents
|
/Term 1/SE/PycharmProjects/pythonProject/Tut2/Most Frequent Character.py
| 263
| 4.28125
| 4
|
from collections import Counter
#ask user input a string
stringCount = input("Enter a string: ")
#count char appearing most in that string
count = Counter(stringCount).most_common(1)
print("Character that appears most frequently in the string: " )
print(count)
| true
|
2ac298765900d155eab1e26560908a7efa884d45
|
IceMortyGod/icemortoos
|
/IceMorty Pro Calculator.py
| 1,167
| 4.1875
| 4
|
print("Welcome To Sub To Icemorty Facking Calculator:)")
x = int(input('Enter the first number pls: '))
y = int(input('Enter the second number: '))
yes = ("Good Job Facker :)")
no = ("fuck of facker 👿")
def add(x, y):
print(x + y)
def subtract(x, y):
print(x - y)
def multiply(x, y):
print(x * y)
def divide(x, y):
print(x / y)
instructions = """
Hey Noob Dumbass Wanna ADD? Ok Then Type A
Uh Facker Wanna SUBTRACT? Ok Nub Type S
STFU Nub Head Wanna MULTIPLY? Ok Facker Type M
Uh OH Facker Wanna DIVIDE? OK Dummy Type D
"""
print( instructions)
operation = input('Type letter here: ')
if operation == "A":
add(x, y)
elif operation == "S":
subtract(x, y)
elif operation == "M":
multiply(x, y)
elif operation == "D":
divide(x, y)
else:
print("yo facker this is wrong ya nub :(")
operation = input("Will you sub to icemorty Type yes Or no or facker die: ")
if operation == "yes":
input(yes)
elif operation == "no":
input(no)
else:
print("bruh facker i said to type yes or no not something else dumbass")
print("Special Thanks To Lolipop Link To HIs WEbsite Will Be Given Soon :) ")
| false
|
8dfcd3b7339f271409fa64ae63b4357c8692e990
|
adinimbarte/codewayy_python_series
|
/Python_Task6/Q.4/Q.4.py
| 283
| 4.15625
| 4
|
# taking string input
string = input("Enter the string from which you want to count number of 'at': ")
# counting occurence of "at" and printing
count=string.count("at")+ string.count("At")+ string.count("At") + string.count("AT")
print("'at'occured %d times in string." % count )
| true
|
d5d37cee9cdfcc9d9e949ed99da5dd70d723b536
|
SergiBaucells/DAM_MP10_2017-18
|
/Tasca_1_Python/src/exercici_5_python.py
| 417
| 4.125
| 4
|
numero1 = int(input("Número 1: "))
numero2 = int(input("Número 2: "))
numero3 = int(input("Número 3: "))
if numero1 < numero2 and numero1 < numero3:
mcd = numero1
elif numero2 < numero1 and numero2 < numero3:
mcd = numero2
else:
mcd = numero3
while True:
if numero1 % mcd == 0 and numero2 % mcd == 0 and numero3 % mcd == 0:
print("El mcd es", mcd)
break
else:
mcd -= 1
| false
|
c94fe10616b30c1291d5675772810fc0374fbc69
|
KeithWilliamsGMIT/Emerging-Technologies-Python-Fundamentals
|
/03-fizzbuzz.py
| 506
| 4.34375
| 4
|
# Author: Keith Williams
# Date: 21/09/2017
# This script iterates between the numbers 1 and 100.
# For each iteration there is a condition for each of the following:
# 1) For numbers which are multiples of both three and five print "FizzBuzz".
# 2) For multiples of three print "Fizz".
# 3) For multiples of five print "Buzz".
# 4) Otherwise print the number.
for i in range(1, 101):
if i%3 == 0 and i%5 == 0:
print("FizzBuzz")
elif i%3 == 0:
print("Fizz")
elif i%5 == 0:
print("Buzz")
else:
print(i)
| true
|
a406961c86682d5d15c0b6eaa25a187a33a8ae59
|
scoffers473/python
|
/uneven_letters.py
| 564
| 4.28125
| 4
|
#!/usr/bin/python3
"""
This takes an input word and prints out a count of uneven letters
for example in aabbc we have one uneven letter (c). In hello we have 3 (hme and o)
"""
import sys
from collections import Counter
def solution (S):
removal=0
counter = Counter(S)
for letters in S:
if counter[letters]%2 != 0:
removal += 1
return removal
def main (S):
ans = solution(S)
print(" For the word ",S, " we would have to remove ", ans," letters to make it even")
if __name__ == "__main__":
main(sys.argv[1])
| true
|
680528fefc54b25668e4e7fdb1ebc2cfc752f1ff
|
scoffers473/python
|
/days_offset.py
| 1,197
| 4.25
| 4
|
#!/usr/bin/python3
"""
This take an input number and works out the offset day based on this number
Days are Mon:1
Tue:2
Wed:3
Thu:4
Fri:5
Sat:6
Sun:7
So if i passwd an offset of 7 this would be a Sunday, a 5 a Friday, a 13 a Saturday, etc
"""
import sys
def solution (D,S):
# define tuple array - use day as day-1 so that it works easily with the modulus
days = ([0,"Sun"],[1,'Mon'],[2,"Tue"],[3,"Wed"],[4,"Thu"],[5,"Fri"],[6,"Sat"])
# Work out which day equates to this
which_day = S % 7
newday=0
# Find the starting day Integer
# (If Sun, add 7)
# Then add the day offset and get the modulus
# in order to determine the final day
for day in days:
if day[1] == D:
starting_day = day[0]
if starting_day == 0:
starting_day = 7
which_day = (S+starting_day)%7
break
# Now we have the final day, work out the day name
for day in days:
if day[0] == which_day:
return day[1]
def main (D,S):
ans = solution(D,S)
print(ans)
if __name__ == "__main__":
main(sys.argv[1],int(sys.argv[2]))
| true
|
0e55bc414b576a4a6962eaac939dd1709fcb04de
|
ksu-is/Congrats
|
/test_examples.py
| 269
| 4.125
| 4
|
# Python code to pick a random
# word from a text file
import random
# Open the file in read mode
with open("MyFile.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
# print random string
print(random.choice(words))
| true
|
3b4d4944bfe4a170225e0d213f327c89d890905d
|
lttviet/py
|
/bitwise/count_bits.py
| 337
| 4.15625
| 4
|
def count_bits(x: int) -> int:
"""Returns the number of bits that are 1.
"""
num_bit: int = 0
while x:
# if odd, right most bit is 1
num_bit += x & 1
# shift to the right 1 bit
x >>= 1
return num_bit
if __name__ == '__main__':
for i in (1, 2, 11):
print(i, count_bits(i))
| true
|
b81c76ba7cc637017c0432b6d9b0e527cd624fd3
|
tvanrijsselt/file-renamer
|
/main.py
| 1,058
| 4.15625
| 4
|
"""This main module calls the helper functions in the main-function, such that the right files in the right folder are changed."""
import os
from helperfunctions import ask_input_for_path, ask_input_base_filename, files_ending_with_chars
def main():
"""Main function to call the helper functions and
rename the files at the destination"""
path = ask_input_for_path()
base_filename = ask_input_base_filename()
file_end = files_ending_with_chars()
for count, filename in enumerate(os.listdir(path)):
if file_end is None or filename.endswith(file_end):
file_extension = filename.split('.')[-1]
full_name = f"{base_filename}_{count}.{file_extension}"
source = path + filename # Actual name of the file
destination = path + full_name # New name of the file
os.rename(source, destination) #rename function will rename the files
print("The filenames are changed. End of script")
if __name__ == '__main__':
main() # Calling main() function
| true
|
caedf25abc2fcbb1677d8743b9f50e254447bdd9
|
ahathe/some-a-small-project
|
/MyPython/test/StrBecome.py
| 320
| 4.15625
| 4
|
#!/usr/bin/env python
'make string become largest to smallest orade! '
num = list(raw_input("plaese input number!thank you!:"))
choice = raw_input("input you choice!,one or two:")
one = 'one'
two = 'two'
if choice == one:
num.sort()
print num
elif choice == two:
num.sort()
for x,i in enumerate(num):
print x,i
| true
|
f24817dc2ad44edbe7a094542da901122c7b941c
|
ahathe/some-a-small-project
|
/MyPython/test/Count.py
| 229
| 4.3125
| 4
|
#!/usr/bin/env python
def Count(count):
if ' ' in count:
count = count.split(' ')
lisT = ['+','-','*','/','%','**']
if count[1] in lisT:
Input = raw_input("input you want to count number and operator!:")
Count(Input)
| false
|
950c8785a6fe4cec2e491a1e1ca90a1651cae86d
|
ahathe/some-a-small-project
|
/MyPython/test/NumTest.py
| 1,626
| 4.25
| 4
|
#!/usr/bin/env python
'is input number to count mean and total'
empty = []
def Input():
while True:
num = raw_input("input you number to count mean!,input 'q' is going to quit!:")
if num == ('q' or 'Q'):
print 'rechoice input type,input or to count or remove or view!'
Choice()
else:
try:
number = float(num)
except ValueError:
print 'is not number,reinput!'
else:
if type(number) == type(1.2):
empty.append(number)
print empty
def Count():
length = len(empty)
total = sum(empty)
mean = float(total) / float(length)
print "is working!"
print 'the mean is %s' % mean
def Remove():
print 'what number you want to remove?!'
while True:
print 'make you choice ,input you want to remove that number! %s' % empty
remove = raw_input("input you want to remove float value!:")
if remove == ('q' or 'Q'):
Choice()
break
try:
move = float(remove)
except ValueError:
print 'invalid value ,plaese input int or float type!,thank you!'
else:
if move in empty:
empty.remove(move)
print 'is been removed %s' % move
print 'new number total is %s' % empty
break
else:
print "plaese input float type value!"
def View():
Count()
print 'the mean list is %s' % empty
def Choice():
while True:
choice = raw_input("input you choice,count or input or remove or view:").strip().lower()
string = ["input","count","remove","view"]
dict1 = {"input":Input,"count":Count,"remove":Remove,"view":View}
if choice not in string:
print "is invalid option,plaese choice input or count to make mean!"
else:
dict1[choice]()
Choice()
| true
|
1298ec09dc5cf5bbbe9ad19dd9a691e60e384b2c
|
JaclynStanaway/PHYS19a
|
/tutorial/lesson00/numpy-histograms.py
| 2,352
| 4.53125
| 5
|
"""
Author: Todd Zenger, Brandeis University
This program gives a first look at Numpy and
we plot our first plot.
"""
# First, we need to tell Python to bring in numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# np and plt are the standard shortcut names we give it
x = np.array([0,2,4,5])
# Some basic modifications
print(x)
print(x+5)
print(x**2)
# Now let's do some slicing to get specific elements
print("Without the first element")
print(x[1:])
print("Without the last two elements")
print(x[:4])
print(x[:-2]) # Negative index values means that we start going backwards
# There are also useful mathematical operations available to us
sinx = np.sin(x) # numpy uses radians
print("sin(x) is:")
print(sinx)
np.random.seed(900835)
# Now, let's turn our attention to plotting a histogram
# First, let's generate some random data
# See documentation online for this, but loc is the mean,
# scale is the standard deviation, and size is number of values
data = np.random.normal(loc=5.0, scale=1.0, size=20)
# Let's get some statistical information from this
mean_data = np.mean(data)
std_data = np.std(data, ddof=1) #ddof is set to 1 for the sample standard deviation
# Now let's get to plotting
# First we tell python to open up a figure
plt.figure()
plt.grid()
# Make the histogram
n, bins, patches = plt.hist(data, bins=5, ec="black")
# Now add labels for a presentable chart
plt.xlabel("Data Points")
plt.ylabel("Frequency")
plt.title("Histogram of Random Data")
# Now tell python to show this plot
plt.show()
print(mean_data)
print(std_data)
# Now, we can save it offline
#plt.savefig("firsthisto.png")
# Now what if we want a Gaussian fit?
# We will copy and paste, but notice there are changes at the histogram
# options and added a pdf below it
# First we tell python to open up a figure
plt.figure()
plt.grid()
# Make the histogram
n, bins, patches = plt.hist(data, bins=5, density=True, ec="black")
# We need to sort the data for statistics
sorted_data = np.sort(data)
# Add a fit to the histogram
data_pdf = norm.pdf(sorted_data, mean_data, std_data)
plt.plot(sorted_data, data_pdf, 'r--')
# Now add labels for a presentable chart
plt.xlabel("Data Points")
plt.ylabel("Frequency")
plt.title("Histogram of Random Data")
# Now tell python to show this plot
plt.show()
| true
|
ba522adf755c38008a07ac70acb9effcc2dafe1e
|
sonushakya9717/Hyperverge__learnings
|
/dsa_step_10/power_of_number.py
| 238
| 4.15625
| 4
|
def power_of_number(n,x):
if x==0:
return 1
elif x==1:
return n
else:
return n*power_of_number(n,x-1)
n=int(input("enter the number"))
x=int(input("enter the degree of no."))
print(power_of_number(n,x))
| true
|
b692121aa036155e4db1b52d93d8fcf4d879636d
|
sug5806/TIL
|
/Python/algorithm/fibonacci/fibo_recur.py
| 449
| 4.125
| 4
|
def fibo_recursion(n):
# base case
if n<= 1:
return 0
elif n==2:
return 1
return fibo_recursion(n-2) + fibo_recursion(n-1) # 꼬리 재귀 --> while문으로 치환가능
def fibo_iteration(n):
a = 0
b = 1
for _ in range(n-1):
a, b = b, a+b
return a
if __name__=="__main__":
for i in range(1, 11):
print(fibo_recursion(i), end=" ")
print(fibo_iteration(i), end=" ")
| false
|
bb596882dd9fdf844b7996063ba7c672eb7f908a
|
ipsorus/lesson_2
|
/string_challenges.py
| 2,148
| 4.125
| 4
|
# Вывести последнюю букву в слове
word = 'Архангельск'
def last_letter(word):
print(f'Последнняя буква в слове {word}: {word[-1]}')
#last_letter(word)
# Вывести количество букв "а" в слове
word = 'Архангельск'
def count_letters(word):
letters = []
res = 0
letters = list(word)
for letter in letters:
if letter == 'а':
res += 1
print(f'Количество букв \'а\' в слове: {res}')
#count_letters(word)
# Вывести количество гласных букв в слове
word = 'Архангельск'
def vowel(word):
vowel_list = ['а', 'о', 'у', 'э', 'е', 'ы', 'я', 'и']
vowel = 0
word_letters = list(word.lower())
for vowel_letter in word_letters:
if vowel_letter in vowel_list:
vowel += 1
print(f'Количество гласных букв в слове: {vowel}')
#vowel(word)
# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
def count_words(sentence):
words = sentence.split()
print(f'Количество слов в предложении: {len(words)}')
#count_words(sentence)
# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
def first_letter(sentence):
words = sentence.split()
for i in words:
print(i[0])
#first_letter(sentence)
# Вывести усреднённую длину слова.
from statistics import mean
sentence = 'Мы приехали в гости'
def average_word_len(sentence):
words_average_list = []
words = sentence.split()
for i in words:
words_average_list.append(len(i))
print(f'Средняя длина слова: {mean(words_average_list)}')
#average_word_len(sentence)
if __name__ == '__main__':
last_letter(word)
count_letters(word)
vowel(word)
count_words(sentence)
first_letter(sentence)
average_word_len(sentence)
| false
|
c0ce351076e780f0e59de674076758d093d7a362
|
1181888200/python-demo
|
/day3/10.py
| 1,131
| 4.28125
| 4
|
# 使用枚举类
# 更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能:
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May',
'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# value属性则是自动赋给成员的int常量,默认从1开始计数。
for name , member in Month.__members__.items():
print(name , '==>', member , ' , ', member.value)
# 如果需要更精确地控制枚举类型,可以从Enum派生出自定义类:
from enum import Enum , unique
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
# @unique装饰器可以帮助我们检查保证没有重复值。
print( Weekday.Mon )
print( Weekday['Tue'] )
print( Weekday['Tue'].value )
print ( Weekday(6) )
# 如果超出范围,则会报错
# print ( Weekday(7) )
# 可见,既可以用成员名称引用枚举常量,又可以直接根据value的值获得枚举常量。
| false
|
dffdaf2533949385d9f615e4f4f5d8883486ab0b
|
ulyvodka93/paradigmas
|
/.gitignore/Adivina_Numero.py
| 1,809
| 4.15625
| 4
|
# Ulises Thompson python3
import msvcrt
import random
MENSAJE1 = "El rango de numero a adivinar va desde el 1 hasta el?... "
MENSAJE2 = "Ingresa cuántas oportunidades habrá para adivinar el numero... "
MENSAJE3 = "Cuál es el número?... "
def pedirNumero(mensaje):
"""Retorna un numero ingresado por el usuario"""
ingreso = 0
numero = False
while not numero :
try:
ingreso = int(input(mensaje))
numero = True
except ValueError:
print("\n Solo numeros por favor:")
except KeyboardInterrupt:
print("\n Hasta luego!")
exit()
except:
print("\n Error imprevisto")
exit()
return ingreso
def generar_numero(a=0):
rango = random.randint(1, a) # Se genera el número al azar a partir del rango especificado
return rango
def main():
cont = 0 # Contador para cerrar el ciclo
m = pedirNumero(MENSAJE1)
n = generar_numero(m)
b = pedirNumero(MENSAJE2)
cont = int(cont)
while cont != b:
x = pedirNumero(MENSAJE3)
if x == n: # Si el número es correcto, se termina el ciclo
cont = b
print("Felicidades es correcto")
else: # Si el número ingresado es incorrecto, se acumenta el contador y se disminuyen las oportunidades
cont += 1
print("Numero equivocado, Tiene ", b - cont, " oportunidad más")
print("El número es ", n) # para terminar se imprime el numero oculto
print("GAME OVER")
if __name__ == "__main__":
main()
msvcrt.getch() # Mantiene la ventana de ejecución abierta hasta presionar cualquier tecla
| false
|
b732cda25aed23b3a2f629b89bccf286cf16c62c
|
mrvrbabu/MyPycode
|
/Python Developer Bootcamp/Section5-Python_Loops/1.for_loops_pt-1.py
| 472
| 4.4375
| 4
|
# ----------------------------------------------------------------------- #
# --------------- ** For Loops ** -------------------------- #
# Example 1 - DRY - Do not repeat yourself
# n = 3
# for (i=0, i<=n,):
# print(i)
# i += 1
for x in range(10):
print(x + 1)
print("\n")
for number in range(5):
print(f"The code has ran for {number} times")
print("\n")
for a in range(5, 15):
print(a)
print("\n")
for b in range(100, 200, 10):
print(b)
| true
|
24a8c11de8abacaf180b9e99452ddf3e7adc17d6
|
mrvrbabu/MyPycode
|
/Python Developer Bootcamp/Section4-Python_Logic-Control_Flow/21.Conditional_statements.py
| 621
| 4.46875
| 4
|
# ----------------------------------------------------------------------- #
# --------------- ** Control Statements ** ---------------------------- #
"""
if (boolean expression):
execute the statements
"""
# ******************** Example Check for a single condition *******************
temperature = int(input("Pleae enter the current temperature: "))
print("You have entered the temperature as : ", temperature)
if temperature > 32:
print("Temperature is high")
else:
print("The tempature is low and it is ", temperature)
# ************ Checking for two conditions *********************************
| true
|
d0d29d933e69c997308480233cd114b6e10e188d
|
mrvrbabu/MyPycode
|
/Python Developer Bootcamp/Section5-Python_Loops/4.iterables.py
| 342
| 4.125
| 4
|
# ----------------------------------------------------------------------- #
# --------------- ** Iterables ** -------------------------------------- #
# *** Example 1
print(type(range(4)))
for char in "Welcome Home":
print(char)
# *** Example 2
for somethin in ["Coffee", "Play with the cat", "Walk the dog"]:
print(somethin)
| true
|
7a3d476958d7a43f3545000557bd7c66990e2ab6
|
faustfu/hello_python
|
/def01.py
| 1,281
| 4.5
| 4
|
# 1. Use "def" statement with function name, parameters and indented statements to declare a function.
# 2. Use "return" statement with data to return something from the function.
# 3. If there is no "return" statement, the function will return "None".
# 4. All parameters are references.
# 5. Parameters could be assigned by locations or by names.
# 6. Papameters could have defaults.
# 7. Default values of parameters are calculated when declaration.
# 8. Use "*<name>" to collect dynamic parameters as a tuple.
# 9. Use "**<name>" to collect dynamic naming parameters as a dictionary.
# 10. First string statement of a function is its description(docstring).
# 11. Docstring could be accessed by help() or <function name>.__doc__
def do_nothing():
pass
def agree():
return True
def echo(anything):
anything.append("go")
return ",".join(anything)
def attack(a, b = "me"):
return a + ' attacked ' + b
def print_more(req, *args):
'First parameter is required!'
print("required parameter", req)
print("rest parameters", args)
do_nothing()
yes = ["ok"]
if agree():
print(echo(yes))
else :
print("not ok")
print(yes)
print(attack("Bob", "Ada"))
print(attack(b = "Bob", a = "Ada"))
print(attack("Bob"))
print_more(1,2,3)
help(print_more)
| true
|
e240fabceddd8c71f1a81d400582a996bbd0ac07
|
avbpk1/learning_python
|
/circle_area.py
| 251
| 4.4375
| 4
|
# Program to accept radius and calculate area and circumference
radius = float(input("Please Enter Radius:"))
pi = 22/7
area = pi * radius**2
circumference = pi * 2 * radius
print(f"Area is : {area}")
print(f"Circumference is : {circumference}")
| true
|
2c95c3f1109bd296b05896f637a61c155f2ef6d8
|
avbpk1/learning_python
|
/assignments.py
| 476
| 4.125
| 4
|
# This is assignment 1
# Program to take input from user until 0 is entered and print average. Negative input to be ignored
total = 0
cnt = 0
while True:
num = int(input("Please enter a number (Entering Zero will terminate) : "))
if num == 0:
break
elif num < 0:
continue
else:
total += num
cnt += 1
if cnt == 0:
print(f"No numbers entered.")
else:
print(f"Average of the entered numbers is {total/cnt}")
| true
|
9f1190f69f2799fd18d2e86845f794643761d4c2
|
avbpk1/learning_python
|
/20May_ass4.py
| 568
| 4.1875
| 4
|
# -- ass4 -- use map to extract all alphabets from each string in a list. Use map and a function
def ext_alpha(word_str):
new_word = ''
for c in word_str:
if c.isalpha():
new_word += c
return new_word
words = ['Ab12c','x12y2','sdfds33&']
for word in words:
alpha_extract = map(ext_alpha,word)
print(alpha_extract)
# gives following output -- please explain
# <map object at 0x000001C3B608ED90>
# <map object at 0x000001C3B608ED30>
# <map object at 0x000001C3B608EDC0>
#
# Process finished with exit code 0
| true
|
43aa1410040d47341dab6e09813c0820f38d3f97
|
LalithaNarasimha/Homework2
|
/Solution2.py
| 1,062
| 4.21875
| 4
|
# Code that compute the squares and cubes for numbers from 0 to 5,
# each cell occupies 20 spaces and right-aligned
numbers = [ 0, 1, 2, 3, 4, 5]
place_width = 20
header1 = 'Number'
header2 = 'Square'
header3 = 'Cube'
print('\nSolution 1\n')
print(f' {header1: >{place_width}} {header2: >{place_width}} {header3: >{place_width}}')
for num in numbers:
print(f' {num: >{place_width}} {num ** 2: >{place_width}} {num**3: >{place_width}} ')
# Code that use the formula to calculate and print the Fahrenheit temperature
celsius_value = [-40, 0, 40, 100]
f = 0
print('\nSolution 2\n')
for value in celsius_value:
f = (9/5 * value) + 32
print(f'Fahrenheit temperature for Celsius scale {value} is {f}')
# Code that input three integers from the user and print the sum and average of the numbers
input_seq = [1000, 2000, 4000]
total = 0
seq = 0
average = 0
print('\nSolution 3\n')
for input in input_seq:
total = total + input
seq = seq + 1
average = total/seq
print(f'The sum {total:,d} ')
print(f'The average is {average:,.2f}')
| true
|
ef47c071219b5964290c6802f8006a639abf1955
|
amylearnscode/CISP300
|
/Lab 8-5.py
| 2,270
| 4.1875
| 4
|
#Amy Gonzales
#March 21, 2019
#Lab 8-5
#This program uses while loops for input validation and calculates
#cell phone minute usage
def main():
endProgram = "no"
minutesAllowed = 0
minutesUsed = 0
totalDue = 0
minutesOver = 0
while endProgram=="no":
minutesAllowed = getAllowed(minutesAllowed)
minutesUsed = getUsed(minutesUsed)
totalDue, minutesOver = calcTotal(minutesAllowed, minutesUsed, totalDue, minutesOver)
printData(minutesAllowed, minutesUsed, totalDue, minutesOver)
endProgram = raw_input("Do you want to end the program? yes or no")
while not (endProgram=="yes" or endProgram=="no"):
print "Please enter a yes or no"
endProgram = raw_input("Do you want to end the program? (Enter no to process a new set of scores): ")
def getAllowed(minutesAllowed):
minutesAllowed = input("Enter minutes allowed between 200 and 800: ")
while minutesAllowed < 200 or minutesAllowed > 800:
print "Minutes must be between 200 and 800. "
minutesAllowed= input("Enter minutes allowed between 200 and 800: ")
return minutesAllowed
def getUsed(minutesUsed):
minutesUsed = input("Enter number of minutes used: ")
while minutesUsed < 0:
print "Please enter minutes of at least 0"
print "How many minutes were used?"
return minutesUsed
def calcTotal(minutesAllowed, minutesUsed, totalDue, minutesOver):
extra = 0
if minutesUsed <= minutesAllowed:
totalDue = 74.99
minutesOver = 0
print "You were not over your minutes"
elif minutesUsed>= minutesAllowed:
minutesOver = minutesUsed - minutesAllowed
extra = minutesOver*.20
totalDue = 74.99 + extra
print "You were over your minutes by ", minutesOver
return totalDue, minutesOver
def printData(minutesAllowed, minutesUsed, totalDue, minutesOver):
print "----Monthly Use Report-----"
print "Minutes allowed were: ", minutesAllowed
print "Minutes used were: ", minutesUsed
print "Minutes over were: ", minutesOver
print "Total due is: ", totalDue
main()
| true
|
97b54f212f883ae8625888c5c3fedebdd761caa9
|
ShizhongLi/Data-Analysis
|
/investigate texts and calls/Task1.py
| 988
| 4.1875
| 4
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务1:
短信和通话记录中一共有多少电话号码?每个号码只统计一次。
输出信息:
"There are <count> different telephone numbers in the records."
"""
call_number_list_of_texts, answer_number_list_of_texts, timestamp_list_of_texts = zip(*texts)
call_number_list_of_calls, answer_number_list_of_calls, timestamp_list_of_calls, during_time_of_calls = zip(*calls)
set_of_all_numbers = set(call_number_list_of_texts) | set(answer_number_list_of_texts) | set(call_number_list_of_calls) | set(answer_number_list_of_calls)
print('There are {} different telephone numbers in the records.'.format(len(set_of_all_numbers)))
| false
|
82fc95d5d86f08c337f3823f0bd147c142f8c69e
|
floydnunez/Project_Euler
|
/problem_004.py
| 852
| 4.21875
| 4
|
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import math
def check_palindrome(number):
is_palindrome = True
str_num = str(number)
size = len(str_num)
half_size = math.floor(size/2)
for index in range(0, half_size + 1):
char_1 = str_num[index]
char_2 = str_num[size - index-1]
if char_1 != char_2:
is_palindrome = False
return is_palindrome
print(check_palindrome(21923))
all = []
for xx in range(999, 1, -1):
for yy in range(999, 1, -1):
val = xx * yy
if check_palindrome(val):
print("first:", xx, "second:", yy, "=", val)
all.append(val)
print(max(all))
#answer: 906609
| true
|
9b6ed13e70dcb0706ea37b9c4d36b8e838d7965a
|
swaroopsaikalagatla/Python
|
/python5.py
| 267
| 4.125
| 4
|
def maximum(a,b,c):#function
list=[a,b,c]#statement 1
return max(list)#statement 2
x=int(input("Enter the first number : "))
y=int(input("Enter the second number :"))
z=int(input("Enter the third number :"))
print("biggest number is :",maximum(x,y,z))
| true
|
acdda0fa4bceeaf72b4b94836f606591b7141a6c
|
joook1710-cmis/joook1710-cmis-cs2
|
/assignment1.py
| 2,319
| 4.3125
| 4
|
#Created a variable and defined my name.
myName = "Joo Ok Kim"
print myName
#Created a variable and defined my age.
myAge = 16.4
print myAge
#Created a variable and defined my height.
myHeight = 1.65
print myHeight
#Created a variable and defined the length of a sqaure.
lengthOfSquare = 4
print lengthOfSquare
#Created a variable and defined the length of a rectangle.
lengthOfRectangle = 8
print lengthOfRectangle
#Created a variable and defined the height of the rectangle.
heightOfRectangle = 16
print heightOfRectangle
#Created a variable and defined my age in months.
monthInYears = 12
myAgeInMonths = monthInYears * myAge
print myAgeInMonths
#Created a variable and defined the years I would live.
yearsToCome = 80
yearsToLive = myAge + yearsToCome
print yearsToLive
#Created a variable and defined my height in feet.
myHeightInFeet = 5.4
print myHeightInFeet
#Created a variable and defined the average height of a Korean.
koreanFemaleHeight = 1.62
differenceInHeight = myHeight - koreanFemaleHeight
print differenceInHeight
#Created a variable and defined the area of the square.
areaOfSquare = 4 *4
print areaOfSquare
#Created a variable and defined half of the cube.
halfOfCube = 0.5 * 16 * 4
print halfOfCube
#Created a variable and defined the area of the rectangle.
areaOfRectangle = lengthOfRectangle * heightOfRectangle
print areaOfRectangle
#Created a variable and defined one ninth of the area of the rectangle.
ninthAreaOfRectangle = 0.11 * areaOfRectangle
print ninthAreaOfRectangle
#Created a message.
print "Hello, it's me, " + myName + "." + " I am " + str(myAge) + " years old. " + " I am " + str(myHeightInFeet) + " feet tall. " + " I am " + str(myHeight) + " tall in meters. " + " Staticstically speaking, I can live up to " + str(yearsToLive) + " years. "
#Created another message.
print " My age in months is " , str(myAgeInMonths),"." , " Korean female's average height is " , str(koreanFemaleHeight) , " in meters." , " I like squares. The length of the square I created is " , str(lengthOfSquare), "." , " I like rectangles too. The length of the rectangle I created is " , str(lengthOfRectangle),"." , " The area of my rectangle is " , str(areaOfRectangle), "."
#Created a varirable and printed the smiley faces.
smileyFace = ";)"
print smileyFace * int(10000)
| true
|
1362a39f7084df60f86894c00c920958a6bc5ad1
|
indykiss/DataStructures-Algos
|
/Leetcode/Python Easies/Replace_digits_w_chars.py
| 532
| 4.1875
| 4
|
# Replace All Digits with Characters
# Input: s = "a1c1e1"
# Output: "abcdef"
# Explanation: The digits are replaced as follows:
# - s[1] -> shift('a',1) = 'b'
# - s[3] -> shift('c',1) = 'd'
# - s[5] -> shift('e',1) = 'f'
class Solution:
def replaceDigits(self, s: str) -> str:
res = ''
for i in range(len(s)):
if i % 2 == 0:
res += s[i]
else:
char = chr(ord(s[i-1]) + int(s[i]))
res += char
return res
| false
|
95e1b9576d1227e9bbe48ad5045c65f55605fb8e
|
indykiss/DataStructures-Algos
|
/Leetcode/Python Easies/Anagram_mappings.py
| 878
| 4.15625
| 4
|
# Find Anagram Mappings
# You are given two integer arrays nums1 and nums2 where nums2 is
# an anagram of nums1. Both arrays may contain duplicates.
# Return an index mapping array mapping from nums1 to nums2 where
# mapping[i] = j means the ith element in nums1 appears in nums2 at index j.
# If there are multiple answers, return any of them.
# An array a is an anagram of an array b means b is made by
# randomizing the order of the elements in a.
# Input: nums1 = [84,46], nums2 = [84,46]
# Output: [0,1]
class Solution:
def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]:
arr = []
dict2 = {}
for j in range(len(nums2)):
dict2[nums2[j]] = j
for i in range(len(nums1)):
idx = dict2[nums1[i]]
arr.append(idx)
return arr
| true
|
efaabae63cbd556d6e1a3d52a1bb39d61a163fab
|
Zahidsqldba07/codingbat-programming-problems-python
|
/Solutions/string-2/end_other.py
| 579
| 4.1875
| 4
|
# Given two strings, return True if either of the strings appears at
# the very end of the other string, ignoring upper/lower case differences
# (in other words, the computation should not be "case sensitive").
# Note: s.lower() returns the lowercase version of a string.
# end_other('Hiabc', 'abc') → True
# end_other('AbC', 'HiaBc') → True
# end_other('abc', 'abXabc') → True
def end_other(a, b):
shorter = a.lower()
longer = b.lower()
if len(a) > len(b):
shorter = b.lower()
longer = a.lower()
return longer[-len(shorter):] == shorter
| true
|
55ea429df48b2ae917a8239f40e1a12acad1179d
|
yasu094/learning-python
|
/10-calendars.py
| 1,139
| 4.15625
| 4
|
import calendar
# print a text calendar (week start day is Sunday)
c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(2020, 1, 0, 0)
print (str)
# create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.SUNDAY)
str = hc.formatmonth(2020, 1)
print (str)
# loop over the days of a month
# zeroes mean that the day of the week is in an overlapping month
for i in c.itermonthdays(2020, 2):
print (i)
# The Calendar module provides useful utilities for the given locale,
# such as the names of days and months in both full and abbreviated forms
for name in calendar.month_name:
print (name)
for day in calendar.day_name:
print (day)
# first Wednesday of every month
print ("First Wednesday of the month:")
for m in range(1,13):
cal = calendar.monthcalendar(2020, m)
weekone = cal[0]
weektwo = cal[1]
if weekone[calendar.WEDNESDAY] != 0:
firstwednesday = weekone[calendar.WEDNESDAY]
else:
# if the first wednesday isn't in the first week, it must be in the second
firstwednesday = weektwo[calendar.WEDNESDAY]
print ("%10s %2d" % (calendar.month_name[m], firstwednesday))
| true
|
fc74fe344919966935cef5b6eb206e92564af881
|
nseetim/Hackerrank_challenges
|
/String_Validators.py
| 2,562
| 4.34375
| 4
|
'''
Python has built-in string validation methods for basic data.
It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False
str.isalpha()
This method checks if all the characters of a string are alphabetical (a-z and A-Z).
>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False
str.isdigit()
This method checks if all the characters of a string are digits (0-9).
>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False
str.islower()
This method checks if all the characters of a string are lowercase characters (a-z).
>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False
str.isupper()
This method checks if all the characters of a string are uppercase characters (A-Z).
>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False
Task
You are given a string .
Your task is to find out if the string contains: alphanumeric characters, alphabetical characters, digits,
lowercase and uppercase characters.
Input Format
A single line containing a string .
Constraints
0 < len(string) < 1000
Output Format
In the first line, print True if has any alphanumeric characters. Otherwise, print False.
In the second line, print True if has any alphabetical characters. Otherwise, print False.
In the third line, print True if has any digits. Otherwise, print False.
In the fourth line, print True if has any lowercase characters. Otherwise, print False.
In the fifth line, print True if has any uppercase characters. Otherwise, print False.
Sample Input
qA2
Sample Output
True
True
True
True
True
'''
def get_datatype(user_input_string):
print(any(each_character.isalnum() for each_character in user_input_string))
print(any(each_character.isalpha() for each_character in user_input_string))
print(any(each_character.isdigit() for each_character in user_input_string))
print(any(each_character.islower() for each_character in user_input_string))
print(any(each_character.isupper() for each_character in user_input_string))
user_input_string=str(input())
get_datatype(user_input_string)
'''For those who who would love a shorter cut, you could
use the "eval" method'''
user_input=str(input())
For each_test in ("isalnum","isalpha","isdigit","islower",
"isupper"):
print(any(eval("i."+each_test+"()") for i in user_input))
| true
|
819f06ff47d9843a78fb41d30b6960ab7c77c710
|
PapaGateau/Python_practicals
|
/089-Safe_list_get/safe_list_get.py
| 629
| 4.15625
| 4
|
def recuperer_item(liste, index):
"""function to get and element form a list using its index
incorrect indexes are protected and will return an error string
Args:
liste ([list]): [list searched]
index ([int]): [index of searched element]
Returns:
[str]: [list element or error string]
"""
if index > len(liste) - 1 or index < -len(liste):
return "Index {} hors de la liste".format(index)
else:
return liste[index]
# liste = ["Julien", "Marie", "Pierre"]
# print(recuperer_item(liste, 0))
# print(recuperer_item(liste, 5))
# print(recuperer_item(liste, -13))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.