blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8dc33b0291f00e04734c54e2b5d66b45260144b9 | Jeevanantham13/Python | /palindrome.py | 232 | 4.09375 | 4 | num=int(input("enter the number"))
c=num
rev=0
while(num>0):
rem=num%10
rev=(rev*10)+(rem)
num=num//10
print("the reversed num:",rev)
if(c==rev):
print("its a palindrome")
else:
print("its not a palindrome") |
aeacf191277ccc20bb75496acb42253a1456e434 | Hao-HOU/LearnPython3theHardWay | /code/ex19.py | 1,055 | 3.9375 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
def call_function_ways(count, arg):
print(f"{count}:", {arg})
count = 0
arg = "10种么?"
call_function_ways(count, arg)
call_function_ways(count + 1, "我觉得可以!")
call_function_ways(2, 67)
call_function_ways(count + 3, len(arg))
temp = input("输入一个整数试试:")
call_function_ways(temp, int(temp))
call_function_ways(f"{arg}", 5)
|
95e099e035ade30eac662e546b901e08ce1e0962 | RobertoRosa7/python | /py_intro_to_python/fila.py | 585 | 4 | 4 | # -*- coding: utf-8 -*-
from collections import deque
def fila():
'''
Trabalhando com filas - deque
se for inserido mais do que o limite o primeiro elemento será removido
append() - adiciona no final
appendleft() - adiciona no inicio
pop() - remover elemento no final da fila
popleft() - remover no inicio da fila
'''
fila = deque(maxlen=4)
fila.append(1)
fila.append(2)
fila.append(3)
fila.append(4)
fila.append(5)
# fila.popleft()
# fila.pop()
print(fila)
fila()
|
d3d111088b67b12e04e0b2620c2836d545e70057 | TapanManu/Py-Ton | /strings/duplicate_letters.py | 168 | 3.75 | 4 | str=input('get the string')
ls=[x for x in str]
dup=list(set(ls))
if len(dup)==len(ls):
print("string has unique letters only")
else:
print("string has repetitions")
|
374faafae9b7e6da34f4ed24eba1706a5b0878eb | johnklee/algprac | /hackerrank/graph/medium/journey-to-the-moon.py | 3,383 | 3.609375 | 4 | #!/usr/bin/env python
r'''
https://www.hackerrank.com/challenges/journey-to-the-moon/problem
'''
import math
import os
import random
import re
import sys
class Node:
def __init__(self, v):
self.v = v
self.neighbors = set()
self.visit = False
def addN(self, n):
if n not in self.neighbors:
self.neighbors.add(n)
n.addN(self)
def __hash__(self):
return hash(self.v)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.v == other.v
def n(self):
for n in self.neighbors:
yield n
def dfs(self):
from collections import deque
root = self
root.visit = True
nlist = deque()
nlist.append(root)
vlist = []
while len(nlist) > 0:
node = nlist.popleft()
vlist.append(node.v)
for n in node.n():
if not n.visit:
nlist.append(n)
n.visit = True
return vlist
# Complete the journeyToMoon function below.
def journeyToMoon(n, astronaut):
ndict = {}
cty_list = []
# Create graph
for a, b in astronaut:
if a not in ndict:
ndict[a] = Node(a)
if b not in ndict:
ndict[b] = Node(b)
ndict[a].addN(ndict[b])
# Search disjoin set
for node in ndict.values():
if not node.visit:
cty_list.append(node.dfs())
print('Group-{}: {}'.format(node.v, cty_list[-1]))
# Other distinct countury
for i in range(n):
if i not in ndict:
cty_list.append(set([i]))
print('Total {} unique countries...{}'.format(len(cty_list), cty_list))
# Calculate unique pairs
if len(cty_list) == 1:
return 0
elif len(cty_list) == 2:
return len(cty_list[0]) * len(cty_list[1])
else:
cty_len_list = map(len, cty_list)
psum = cty_len_list[0] * cty_len_list[1]
nsum = cty_len_list[0] + cty_len_list[1]
for i in range(2, len(cty_len_list)):
psum += nsum * cty_len_list[i]
nsum += cty_len_list[i]
return psum
#print("{}".format(journeyToMoon(5, [(0, 1), (2, 3), (0, 4)])))
#print("{}".format(journeyToMoon(4, [(0, 2)])))
import unittest
class FAT(unittest.TestCase):
def setUp(self):
pass
def test_01(self):
tdatas = [
(5, [(0, 1), (2, 3), (0, 4)], 6),
(4, [(0, 2)], 5)
]
for n, astronaut, a in tdatas:
r = journeyToMoon(n, astronaut)
self.assertEqual(a, r, 'Expect={}; Real={}'.format(a, r))
def test_02(self):
tid = [1]
tdatas = []
for id in tid:
with open('journey-to-the-moon.t{}'.format(id), 'r') as fh:
na, pn = fh.readline().strip().split(' ')
astronaut = []
for i in range(int(pn)):
astronaut.append(map(int, fh.readline().split(' ')))
with open('journey-to-the-moon.a{}'.format(id), 'r') as fh2:
tdatas.append((int(na), astronaut, int(fh2.readline())))
for n, astronaut, a in tdatas:
r = journeyToMoon(n, astronaut)
self.assertEqual(a, r, 'Expect={}; Real={}\n{}'.format(a, r, astronaut))
|
c2bc9309ea47292a8a79355d41c82a6de822b905 | shuchita-rahman/HakkerRank | /sWAP cASE Solution.py | 272 | 4 | 4 | def swap_case(s):
newstring =''
for a in s:
if (a.isupper()) == True:
newstring+=(a.lower())
elif (a.islower()) == True:
newstring+=(a.upper())
else:
newstring+= a
return newstring
|
0fa541dc157ce16ad55e5211e88459eaaccc67b9 | SatishMurthy/Python-Practice | /Hackerrank scripts.py | 3,468 | 4.125 | 4 | # #Polar Coordinates
#
# import cmath
#
# cnum = input('Enter complex number a+ij: ')
#
# #complex(input())
#
# polarcoord = cmath.polar(complex(cnum))
#
# for n in polarcoord:
# print(round(n,3))
# #Average of distinct numbers from a given set of numbers
# def average(array):
# # your code goes here
# distinctset = set(array)
# distinctnum = len(distinctset)
# return (sum(distinctset)/distinctnum)
#
# if __name__ == '__main__':
# n = int(input())
# arr = list(map(int, input().split()))
# result = average(arr)
# print(result)
#Given sets of integers, and , print their symmetric difference in ascending order.
# The term symmetric difference indicates those values that exist in either or but do not exist in both.
# if __name__ == '__main__':
# n = int(input())
# l1 = list(map(int, input().split()))
# setn=set(l1)
# m = int(input())
# l2=list(map(int, input().split()))
# setm=set(l2)
#
# symmdiff = list((setn.union(setm)).difference((setn.intersection(setm))))
# symmdiff.sort()
# for i in symmdiff:
# print (i)
'''
There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers.
You like all the integers in set A and dislike all the integers in set B.
Your initial happiness is 0. For each i integer in the array, if i E A , you add 1 to your happiness.
If i E B, you add -1 to your happiness. Otherwise, your happiness does not change.
Output your final happiness at the end.
'''
# if __name__ == '__main__':
# n,m = map(int, input().split())
# numlist = list(map(int, input().split()))
# setA = set(map(int, input().split()))
# setB = set(map(int, input().split()))
# happiness = 0
#
# for i in numlist:
# if i in setA:
# happiness += 1
# elif i in setB:
# happiness -= 1
#
# print (happiness)
#########################################################################
# if __name__ == '__main__':
# n = int(input())
# stamplist = []
# for i in range(n):
# country = input()
# stamplist.append(country)
#
# print(len(set(stamplist)))
#########################################################################
# from collections import defaultdict
# if __name__ == '__main__':
# n,m = map(int, input().split())
#
# A = []
# B = []
# for i in range(n):
# word = input()
# A.append(word)
# for j in range(m):
# word = input()
# B.append(word)
#
# d=defaultdict(list)
# for w in B:
# if w in A:
# w_index = [i for i,x in enumerate(A,1) if x==w]
# # print(w_index)
# for x in w_index:
# d[w].append(x)
# else:
# if w not in d:
# d[w].append(-1)
# # print (w+' done')
#
# print (d)
# for i,v in d.items():
# print (*v)
# for j in v:
# print (*j)
# print()
##### NAMED TUPLE ######
from collections import namedtuple
student=namedtuple('student','ID MARKS CLASS NAME')
stunum = int(input())
markidx = list(input().split()).index('MARKS')
totalmarks = 0
for m in range(stunum):
totalmarks += int(list(input().split())[markidx])
print (round(totalmarks/stunum,2))
##### NAMED TUPLE ######
##### ORDERED DICTIONARY ######
from collections import OrderedDict
items=int(input())
|
90e88f861fddc5ce39e21028f2ae7f72fd2dae94 | vikkiorrikki/Google-calendar-Mongo | /work.py | 6,272 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
import httplib2
import os
import time
import datetime
import itertools
from operator import itemgetter
from pymongo import MongoClient
def main():
client = MongoClient('localhost', 27017)
db = client['calendar-data']
mongo_calendars = db.calendars
empty = mongo_calendars.count() == 0
print ('Base is empty:', empty)
print("Welcome to your personal planner!")
print("You can choose between these calendars:")
num_list = mongo_calendars.find()
count = 0
for cal in num_list:
print(cal['summary'], count)
count+=1
print("---------- 1 ----------")
print(" STATISTICS")
print("-----------------------")
var = int(input("Choose your calendar number [0,1,2...n]\n"))
calendar_list = mongo_calendars.find()
calendar = calendar_list[var]
print (calendar['summary'], " is chosen")
days = int(input("How many days do you want to see? [1,2...]\n"))
today = datetime.datetime.now().date() # utc - формат
print('now is ', today)
events = calendar['events']
events.sort(key=itemgetter('start'))
for i in itertools.repeat(None, days):
tomorrow = today + datetime.timedelta(days=1)
for event in events:
overflow = False
start_date = datetime.datetime.strptime(event['start'][:16], "%Y-%m-%dT%H:%M")
if start_date.date() >= today and start_date.date() < tomorrow:
overflow = True
end_date = datetime.datetime.strptime(event['end'][:16], "%Y-%m-%dT%H:%M")
print('\tevent \"'+event['title']+'\" from [', event['start'], '] for [', end_date - start_date, ']')
else:
if overflow is True:
break;
today = tomorrow
print('next is', today)
print("---------- 2 ----------")
print(" INTERSECTION")
print("-----------------------")
first = int(input("Choose your first calendar number [0,1,2...n]\n"))
second = int(input("Choose your second calendar number [0,1,2...n]\n"))
first_times = []
second_times = []
calendar_list = mongo_calendars.find()
first_calendar = calendar_list[first]
first_events = first_calendar['events']
for event in first_events:
time_tuple = datetime.datetime.strptime(event['start'][:19], "%Y-%m-%dT%H:%M:%S"), datetime.datetime.strptime(event['end'][:19], "%Y-%m-%dT%H:%M:%S")
first_times.append(time_tuple)
first_times.sort(key=itemgetter(0))
second_calendar = calendar_list[second]
second_events = second_calendar['events']
for event in second_events:
time_tuple = datetime.datetime.strptime(event['start'][:19], "%Y-%m-%dT%H:%M:%S"), datetime.datetime.strptime(event['end'][:19], "%Y-%m-%dT%H:%M:%S")
second_times.append(time_tuple)
second_times.sort(key=itemgetter(0))
intersections = []
for time1 in first_times:
for time2 in second_times:
t_from = time2[0]
t_to = time2[1]
if time1[0] > time2[0]:
t_from = time1[0]
if time1[1] < time2[1]:
t_to = time1[1]
difference = t_to - t_from
if difference.total_seconds() > 0:
intersection_tuple = t_from, t_to, difference
intersections.append(intersection_tuple)
intersections.sort(key=itemgetter(0))
for stamp in intersections:
print(stamp[0], '--', stamp[1], '[', stamp[2], ']')
print("-------optimized--------")
length = len(intersections)-1
i = 0
while i<length:
j = i+1
if intersections[j][0] <= intersections[i][0] and intersections[j][1] >= intersections[i][1]:
del intersections[i]
length-=1
i=-1
else:
if intersections[i][0] <= intersections[j][0] and intersections[i][1] >= intersections[j][1]:
del intersections[j]
length-=1
i=-1
else:
if intersections[j][0] < intersections[i][0] and intersections[j][1] > intersections[i][0]:
new_tuple = intersections[j][0],intersections[i][1],intersections[i][1]-intersections[j][0]
intersections.append(new_tuple)
del intersections[i]
del intersections[j]
length-=1
i=-1
else:
if intersections[j][0] < intersections[i][1] and intersections[j][1] > intersections[i][1]:
new_tuple = intersections[i][0],intersections[j][1],intersections[j][1]-intersections[i][0]
intersections.append(new_tuple)
del intersections[i]
del intersections[j]
length-=1
i=-1
i+=1
for stamp in intersections:
print(stamp[0], '--', stamp[1], '[', stamp[2], ']')
print("---------- 3 ----------")
print(" PLANNING")
print("-----------------------")
day_events = 0
date = input("Choose your date [year-month-day][2017-12-30]\n")
date_stamp = datetime.datetime.strptime(date[:10], "%Y-%m-%d").date()
for stamp in intersections:
if stamp[0].date() == date_stamp:
day_events -= stamp[2].total_seconds()
print(day_events/3600, 'hours of total intersections')
length = len(first_times)-1
i=0
first_sum = 0
while i<length:
if first_times[i][0].date() == date_stamp:
if first_times[i][0] < first_times[i+1][0] and first_times[i][1] > first_times[i+1][1]:
del first_times[i+1]
length -= 1
i-=1
else:
if first_times[i][1] > first_times[i+1][0] and first_times[i][1] < first_times[i+1][1]:
new_tuple = first_times[i][0], first_times[i+1][1]
del first_times[i]
del first_times[i]
first_times.insert(i, new_tuple)
length -= 1
i-=1
i+=1
for time in first_times:
if time[0].date() == date_stamp:
first_sum += (time[1] - time[0]).total_seconds()
length = len(second_times)-1
i=0
second_sum = 0
while i<length:
if second_times[i][0].date() == date_stamp:
if second_times[i][0] < second_times[i+1][0] and second_times[i][1] > second_times[i+1][1]:
del second_times[i+1]
length -= 1
i-=1
else:
if second_times[i][1] > second_times[i+1][0] and second_times[i][1] < second_times[i+1][1]:
new_tuple = second_times[i][0], second_times[i+1][1]
del second_times[i]
del second_times[i]
second_times.insert(i, new_tuple)
length -= 1
i-=1
i+=1
for time in second_times:
if time[0].date() == date_stamp:
second_sum += (time[1] - time[0]).total_seconds()
print((first_sum+second_sum)/3600, 'hours of events total')
total_time = (day_events + first_sum + second_sum)/3600
if 24-total_time <= 0:
print ('sorry, you have no time left')
else:
print (24 - total_time, 'hours is free that day')
if __name__ == '__main__':
main() |
a4d0cbc66717476eb3382200b4ea71e60e732c01 | wpgalmeida/tic-tac-toe-python-playground | /tests/apps/test_judge.py | 3,695 | 3.5625 | 4 | from unittest import TestCase
from tic_tac_toe_python_playground.apps.core.judge import check_end_game
class Test(TestCase):
def test_should_win_in_row_1(self):
fake_actual_board_to_be_tested = [["X", "X", "X"], [3, 4, 5], [6, 7, 8]]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_row_2(self):
fake_actual_board_to_be_tested = [[0, 1, 2], ["X", "X", "X"], [6, 7, 8]]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_row_3(self):
fake_actual_board_to_be_tested = [
[0, 1, 2],
[3, 4, 5],
["X", "X", "X"],
]
self.assertTrue(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_col_1(self):
fake_actual_board_to_be_tested = [
["X", 1, 3],
["X", 4, 5],
["X", 7, 8],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_win_in_col_1(self):
fake_actual_board_to_be_tested = [
["X", 1, 2],
["X", 4, 5],
[6, 7, 8],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_col_2(self):
fake_actual_board_to_be_tested = [
[0, "X", 2],
[3, "X", 5],
[6, "X", 8],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_win_in_col_2(self):
fake_actual_board_to_be_tested = [
[0, 1, 2],
[3, "X", 5],
[6, "X", 8],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_col_3(self):
fake_actual_board_to_be_tested = [
[0, 1, "X"],
[3, 4, "X"],
[6, 7, "X"],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_win_in_col_3(self):
fake_actual_board_to_be_tested = [
[0, 1, 2],
[3, 4, "X"],
[6, 7, "X"],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_diagonal(self):
fake_actual_board_to_be_tested = [
["X", 1, 2],
[3, "X", 5],
[6, 7, "X"],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_win_in_diagonal(self):
fake_actual_board_to_be_tested = [
["X", 1, 2],
[3, 4, 5],
[6, 7, "X"],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
def test_should_win_in_reverse_diagonal(self):
fake_actual_board_to_be_tested = [
[0, 1, "X"],
[3, "X", 5],
["X", 7, 8],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_win_in_reverse_diagonal(self):
fake_actual_board_to_be_tested = [
[0, 1, 2],
[3, "X", 5],
["X", 7, 8],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
def test_should_end_game_for_draw(self):
fake_actual_board_to_be_tested = [
["X", "O", "X"],
["O", "X", "O"],
["O", "X", "O"],
]
self.assert_(check_end_game(fake_actual_board_to_be_tested))
def test_should_not_end_game(self):
fake_actual_board_to_be_tested = [
["X", "O", 2],
["O", "X", "O"],
["O", "X", "O"],
]
self.assertFalse(check_end_game(fake_actual_board_to_be_tested))
|
47bfc900304f2e4435908d08e278d16723820358 | etfrer-yi/Python-Reddit-Webscraper- | /Python Reddit Webscraper/reddit_word_cloud.py | 631 | 3.765625 | 4 | # Code to generate the word cloud taken from
# https://towardsdatascience.com/simple-wordcloud-in-python-2ae54a9f58e5
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
def plot_cloud(wordcloud):
plt.figure(figsize=(40, 30))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
def generate_cloud(text):
wordcloud = WordCloud(
width = 500,
height = 500,
random_state=1,
background_color='salmon',
colormap='Pastel1',
collocations=False,
stopwords = STOPWORDS
).generate(text)
return wordcloud |
9b561c8b8eba0f3af33b7319ddc19b5509f3a990 | everaldobass/curso-python3 | /8-curso-cod3r-python/pacote/tipos/01-for.py | 257 | 3.796875 | 4 |
# for i in range(10):
# print(i)
# for a in range(1, 100, 2):
# print(a)
#num = [1, 2, 3, 4, 5]
# for n in num:
# print(n)
produto = {
"nome": "Caneta",
"preco": 2.50,
"desc": 0.5
}
for can in produto:
print(can, "==>", produto[can])
|
f4f99a5f55db9f43a2d507f2ada6a2f85c98af87 | ctc316/algorithm-python | /Lintcode/G_Practice/OAs/1646. CheckWords.py | 702 | 3.640625 | 4 | class Solution:
"""
@param s:
@param str:
@return: Output whether this combination meets the condition
"""
def checkWord(self, s, str):
dict = set(str)
stack = []
visited = set()
if s not in dict:
return False
stack.append(s)
visited.add(s)
while stack:
word = stack.pop()
if len(word) == 1:
return True
for i in range(len(word)):
next = word[:i] + word[i + 1:]
if next not in dict or next in visited:
continue
visited.add(next)
stack.append(next)
return False
|
75190a2a508e622e875e0ac23a7976a686e8df01 | giabao2807/python-study-challenge | /basic-python/module-package/my_math.py | 862 | 4.1875 | 4 | print('--- start of my_math ---')
PI = 3.14159
E = 2.71828
message = 'My math module'
def sum(start, *numbers):
'''Calculate the sum of unlimited number
Params:
start:int/float, the start sum
*numbers:int/float, the numbers to sum up
Return: int/float
'''
for x in numbers:
start += x
return start
def sum_range(start, stop, step=1):
''' Calculate the sum of intergers
Params:
start:int, start range number
stop:int, stop range number
step:int, the step between value
Returns: int
'''
sum = 0
for i in range(start, stop, step):
sum += i
return sum
def fact(n):
'''Calculate the factorial of n
Params:
n:int
Return: int
'''
p = 1
for i in range(1, n + 1):
p *= i
return p
print('--- end of my_math ---') |
96bc7a96b0ff902c79737d1f7186432383e8f12c | MS-87/Daily-Coding | /20180528 - Talking Clock/talkclock.py | 2,760 | 4.0625 | 4 | """
Description
No more hiding from your alarm clock! You've decided you want your computer
to keep you updated on the time so you're never late again.
A talking clock takes a 24-hour time and translates it into words.
Input Description
An hour (0-23) followed by a colon followed by the minute (0-59).
Output Description
The time in words, using 12-hour format followed by am or pm.
"""
hour = {
'00' : "Twelve",
'01' : "One",
'02' : "Two",
'03' : "Three",
'04' : "Four",
'05' : "Five",
'06' : "Six",
'07' : "Seven",
'08' : "Eight",
'09' : "Nine",
'10' : "Ten",
'11' : "Eleven",
'12' : "Twelve",
'13' : "One",
'14' : "Two",
'15' : "Three",
'16' : "Four",
'17' : "Five",
'18' : "Six",
'19' : "Seven",
'20' : "Eight",
'21' : "Nine",
'22' : "Ten",
'23' : "Eleven",
'24' : "Twelve",
}
MinF = {
'0' : "Oh",
'1' : "",
'2' : "Twenty",
'3' : "Thirty",
'4' : "Fourty",
'5' : "Fifty",
'6' : "Sixty",
'7' : "Seventy",
'8' : "Eighty",
'9' : "Ninety",
}
MinS = {
'0' : "",
'1' : "One",
'2' : "Two",
'3' : "Three",
'4' : "Four",
'5' : "Five",
'6' : "Six",
'7' : "Seven",
'8' : "Eight",
'9' : "Nine",
'10' : "Ten",
'11' : "Eleven",
'12' : "Twelve",
'13' : "Thirteen",
'14' : "Fourteen",
'15' : "Fifteen",
'16' : "Sixteen",
'17' : "Seventeen",
'18' : "Eighteen",
'19' : "Nineteen",
}
time_in = input("Input time: ")
inhour = time_in.split(':')[0]
in_mtens = time_in.split(':')[1][0]
in_mones = time_in.split(':')[1][1]
sentence = "It's " + hour[inhour]
if (in_mtens == "0") & (in_mones == "0") :
None #do nothing
elif in_mtens != "1":
sentence += (" " + MinF[in_mtens])
sentence += (" " + MinS[in_mones])
else:
sentence += (" " + MinS["1" + in_mones])
meridian = "AM"
if int(inhour) > 11:
meridian = " PM"
sentence += (meridian)
print(sentence)
"""
Sample Input data
00:00
01:30
12:05
14:01
20:29
21:00
Output:
It's Twelve AM
It's One Thirty AM
It's Twelve Oh Five PM
It's Two Oh One PM
It's Eight Twenty Nine PM
It's Nine PM
"""
"""
#Smarter way:
import sys
from num2words import num2words
def clock_To_String(time):
split_time = time.split(":",2)
end = "am"
if int(split_time[0]) >= 12:
end = "pm"
split_time[0] = str(int(split_time[0]) - 12)
if int(split_time[0]) == 0:
split_time[0] = "12"
print ("it's %s%s%s%s" %
(num2words(int(split_time[0])) + " ",
"" if int(split_time[1]) >= 10 or int(split_time[1]) == 0 else "oh ",
"" if int(split_time[1]) == 0 else num2words(int(split_time[1])) + " "
,end))
clock_To_String(sys.argv[1])
""" |
883458c8a596b0d4c6f5bbd80185072b6710280a | lkogant1/Python | /while_armstr.py | 259 | 4 | 4 | #armstrong number or not
#sum of each digit cubes is equal to the given number
#eg: 153
x
n = int(input("number: "))
t = n
s = 0
while(n>0):
d = n%10
s = s+(d*d*d)
n = int(n/10)
if(s == t):
print("Armstrong number")
else:
print("Not an Armstrong number") |
b170ad3edf29ed96b06dc64fc4eb746aa992e7c6 | cabbageGG/study_ | /python/test_python_grammar/test_mysql.py | 1,340 | 3.578125 | 4 | #-*- coding: utf-8 -*-
# author: li yangjin
import MySQLdb
"""
MYSQL:用法
host
string, host to connect
user
string, user to connect as
passwd
string, password to use
db
string, database to use
port
integer, TCP/IP port to connect to
"""
conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123456",db="test",port=3306)
cursor = conn.cursor()
# cursor.execute('create table user1(id varchar(20) PRIMARY KEY , name varchar(20), score int)')
cursor.execute(r"insert into user1 values ('A-001', 'Adam', 95)")
cursor.execute(r"insert into user1 values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user1 values ('A-003', 'Lisa', 78)")
conn.commit()
def get_score_in(low, high):
# 返回指定分数区间的名字,按分数从低到高排序
sql = 'select name from user1 where score>=%s and score<=%s ORDER BY score ;' % (low, high)
print (sql)
cursor.execute(sql)
ret = cursor.fetchall()
print (ret)
return [i[0] for i in ret]
# 测试:
assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)
print('Pass')
cursor.close()
conn.close()
|
acf9947ef51f668bc986b97444f2f3f927d78aa7 | kenji-tolede/Travaux-python | /EXO 16.py | 255 | 3.9375 | 4 | m1 = input('entrez 1er mot')
m2 = input('entrez le 2eme mot')
def hamming_distance(m1, m2):
distance = 0
for i in range(len(m1)):
if m1[i] != m2[i]:
distance += 1
return distance
print(hamming_distance(m1,m2)) |
cd5fff209d684ffffb01a035bd0632b08ef529ff | sunsunza2009/Image-Classifier-Web-GUI | /Flask Train Server/CNN/model.py | 1,037 | 3.546875 | 4 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
def getModel(numClass,shape):
# Building the model
model = Sequential()
# 3 convolutional layers
model.add(Conv2D(32, (3, 3), input_shape = shape))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
# 2 hidden layers
model.add(Flatten())
model.add(Dense(128))
model.add(Activation("relu"))
model.add(Dense(128))
model.add(Activation("relu"))
# The output layer with N neurons, for N classes
model.add(Dense(numClass))
model.add(Activation("softmax"))
# Compiling the model using some basic parameters
model.compile(loss="sparse_categorical_crossentropy",
optimizer="adam",
metrics=["accuracy"])
return model |
f60343b59b05c8cd1461b6f65775135ac0986a42 | qiwsir/LearningWithLaoqi | /PythonBase/08program.py | 384 | 3.515625 | 4 | #coding:utf-8
class Person:
def __init__(self, name):
self.name = name
def height(self, m):
h = dict((["height", m],))
return h
class Student(Person):
def score(self, mark):
result = {self.name: mark}
return result
if __name__ == "__main__":
tom = Student("Tom")
print(tom.height(2.0))
print(tom.score("A+")) |
6091e9a8988cd0ba5dcad05369ad459524740286 | daniel-reich/turbo-robot | /Pf2kDoCRvEL8qzKTs_22.py | 1,625 | 4.25 | 4 | """
Create a function that takes in the size of the line and the number of people
waiting and places people in an _S-shape_ ordering. The demonstration below
will make it clear:
# Ordering numbers 1-15 in a [5,3] space.
order_people([5, 3], 15) ➞ [
[1, 2, 3],
[6, 5, 4],
[7, 8, 9],
[12, 11, 10],
[13, 14, 15]
]
If there is extra room, leave those spots blank with a `0` filler.
# Ordering numbers 1-5 in a [4, 3] space.
order_people([4, 3], 5) ➞ [
[1, 2, 3],
[0, 5, 4],
[0, 0, 0],
[0, 0, 0]
]
If there are too many people for the given dimensions, return `"overcrowded"`.
order_people([4, 3], 20) ➞ "overcrowded"
### Examples
order_people([3, 3], 8) ➞ [
[1, 2, 3],
[6, 5, 4],
[7, 8, 0]
]
order_people([2, 4], 5) ➞ [
[1, 2, 3, 4],
[0, 0, 0, 5]
]
order_people([2, 4], 10) ➞ "overcrowded"
### Notes
* Always start the ordering on the upper-left corner.
* If the **S-shape** concept doesn't make sense, try writing down some of these examples on a piece of paper and tracing a pencil through the numbers in order.
"""
def order_people(lst, people):
if lst[0]*lst[1]<people:
return "overcrowded"
llst=[ [] for r in range(lst[0])]
cnt=0
for i in range (1,lst[0]*lst[1],lst[1]):
for m in range(i,i+lst[1]):
if m>people:
llst[cnt].append(0)
else:
llst[cnt].append(m)
cnt+=1
return list(map(lambda x : x[::-1] if llst.index(x)%2==1 else x, llst ))
|
55097e6dcb4da8743b4ac5dc86dcd573bea033b0 | ghoshrohit72/Algorithm-Hub | /UsingPython/EvenFibonacciNumbers.py | 580 | 3.890625 | 4 | '''
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
'''
def fib(n):
if n==1:
return 1
elif n==2:
return 2
else:
return fib(n-2)+fib(n-1)
i=1
sum=0
while fib(i) <= 4000000:
if fib(i)%2==0:
sum=sum+fib(i)
#print(sum)
i=i+1
print(sum)
|
e8f209a256dd7776de56ea8f5c7c46619e96fc7a | AbhinavRobinson/RSA-over-SHA | /generate_keys.py | 1,507 | 3.875 | 4 | """
! Set of Functions to Generate Keys
Generates private and public key pair
p_num1 = first prime
p_num2 = second prime
key_size = define key size (128 bits : default)
"""
# Imports random for randomint generation
import random
def generate(p_num1, p_num2, key_size=128):
n = p_num1 * p_num2
tot = (p_num1 - 1) * (p_num2 - 1)
e = generatePublicKey(tot, key_size)
d = generatePrivateKey(e, tot)
return e, d, n
# Generates public key
def generatePublicKey(tot, key_size):
e = random.randint(2**(key_size-1), 2**key_size - 1)
g = gcd(e, tot)
while g != 1:
e = random.randint(2**(key_size-1), 2**key_size - 1)
g = gcd(e, tot)
return e
# Generates private key
def generatePrivateKey(e, tot):
d = egcd(e, tot)[1]
d = d % tot
if d < 0:
d += tot
return d
# Euclidian GCD
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
# Greatest Comman Divisor
def gcd(e, tot):
temp = 0
while True:
temp = e % tot
if temp == 0:
return tot
e = tot
tot = temp
# Check if num is prime
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num & 0x01 == 0:
return False
n = int(num ** 0.5)
for i in range(3, n, 2):
if num % i == 0:
return False
return True
# End Of generate_keys.py |
614911c74484505d486575f79a4ca954d5ccc81d | rodri0315/pythonCSC121 | /chapter9/dictionary_example.py | 638 | 4.03125 | 4 | players = dict(
Messi='forward',
Pique='Defender',
Xavi='Midfielder',
Valdez='Goalie')
for key in players:
print(f"FCBarcelona player: {key}")
print("____")
for key in players:
print("{} plays as a {}".format(key, players[key]))
# will return everything in dictionary
print(players.items())
for [k, v] in players.items():
print("Name: {}, Position: {}".format(k, v))
print(players.get('Neymar', 'Player not in list yet'))
print(players.get('Messi', 'player exist in list'))
player = players.pop('Valdez', 'Not a player')
print(players.items())
# add
players['Valdez'] = player
print(players.items())
|
16ab8dab4f6eec4c8ab668fa6aeb434c6f95f5e4 | hmaryam/Thinkful_codes | /Lesson2_1.py | 1,371 | 4.03125 | 4 | Write a function to ask what style of drink a customer likes
import random
questions = {
"strong": "Do ye like your drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finish?"}
ingredients = {
"strong": ["glug of rum", "slug of whisky", "splash of gin"],
"salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"],
"bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"],
"sweet": ["sugar cube", "spoonful of honey", "spash of cola"],
"fruity": ["slice of orange", "dash of cassis", "cherry on top"]
}
user_favorate =[]
def find_user_favorate():
for kind in range(len(questions.values())):
user_input = raw_input(questions.values()[kind])
if user_input in ('y','yes'):
user_favorate.append(questions.keys()[kind])
print ''
else:
print ''
return user_favorate
def final_drink_ingridiants(user_favorate):
print 'your final drink will be:'
for b in range(len(user_favorate)):
drink_ingredients = random.choice(ingredients[user_favorate[b]])
print drink_ingredients
if __name__ == '__main__':
favorate_kinds = find_user_favorate()
final_drink_ingridiants(user_favorate)
|
ee4833ed599e2c9ddbd1711a946e3e4e1f6ead40 | allegheny-college-expressioneers/while-while-west-practical-solution | /1_temperature_converter.py | 537 | 4.28125 | 4 | def to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
def to_fahrenheit(celsius):
return 9/5 * celsius + 32
temperature = input('Enter a temperature value: ')
unit = input('Enter the temperature\'s unit: ')
if unit == 'C' or unit == 'c':
print(f'The temperature is {round(to_fahrenheit(int(temperature)))} F.')
elif unit == 'F' or unit == 'f':
print(f'The temperature is {round(to_celsius(int(temperature)))} C.')
else:
print(f"Unit '{unit}' was not recognized as either Celsius or Fahrenheit. Sorry!")
|
c0b69a21cebcf47e0d2b26ed26960283d3c51442 | lgrant146/JetbrainsPython | /Problems/Desks/main.py | 257 | 3.796875 | 4 | # put your python code here
group1 = int(input())
group2 = int(input())
group3 = int(input())
desk1 = group1 // 2 + group1 % 2
desk2 = group2 // 2 + group2 % 2
desk3 = group3 // 2 + group3 % 2
total_desks = desk1 + desk2 + desk3
print(total_desks)
|
26b2f4b00a8b6ea2a2f7a55225545c6dd458532b | CarolineWinter/gothic | /data_processing/test_spacy.py | 1,723 | 3.65625 | 4 | """
Testing basic concepts & tools before doing our main analysis.
"""
import re
from collections import defaultdict
from oed_color import color_words
import spacy
nlp = spacy.load('en')
def tokenize_text():
"""
This function generates a list of tokens with punctuation and spaces removed.
"""
text_tokens = []
# open and read file
text = open("./corpora/ShelleyMary_Frankenstein_Gutenberg.txt")
for row in text:
row = re.sub("[^a-zA-Z]", " ", row).lower()# removes anything not alpha
tokens = nlp(row)# splits string
# adds row tokens to master list
text_tokens.extend(tokens)
return text_tokens
def word_type(tokens, color_words):
"""
Classifies the words in the corpus into types (e.g. noun, verb, adj), then
creates dictionaries for each with positions of the word as the values.
"""
nouns = []
adjectives = []
verbs = []
# seperates tags into tuples in format ( word, tag)
# loop through and add to appropriate list
for pos, token in enumerate(tokens):
l_token = token.lemma_
if l_token in color_words:
if token.pos_ == 'NOUN':
nouns.append((l_token, pos))
if token.pos_ == 'VERB':
adjectives.append((l_token, pos))
if token.pos_ == 'ADJ':
verbs.append((l_token, pos))
return nouns, adjectives, verbs
def main():
tokens = tokenize_text()
print(tokens)
nouns, adjectives, verbs = word_type(tokens, color_words)
# print("Color words as nouns:", nouns)
# print("Color words as adjectives:", adjectives)
# print("Color words as verbs:", verbs)
if __name__ == "__main__":
main()
|
40ef1fa0538d453a6f95ddc9bc422d0e6c19136f | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/bxtnaa002/question1.py | 758 | 3.984375 | 4 | # question1.py
# author: bxtnaa002
# assignment 7
words = []
word = input("Enter strings (end with DONE):\n") # create a list containing words and DONE is inputed to terminate the growth of the list
while word != "DONE":
words.append(word)
word = input("")
unique = [] #create a new list
for word in words: #loop through all the words in the list created from inputed words
if word not in unique: #if the word does not already appear in the new list, add it
unique.append(word)
else: #else if it does already appear, continue to the next word
continue
print("\nUnique list:")
print("\n".join(unique)) #print the new list containing the words appearing only once. |
6650fa86f62f3cc472c3c79b71ba1c736eeec2e6 | ntupenn/exercises | /hard/272.py | 1,451 | 3.828125 | 4 | """
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k <= total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
Hint:
Consider implement these two helper functions:
getPredecessor(N), which returns the next smaller node to N.
getSuccessor(N), which returns the next larger node to N.
Try to assume that each node has a parent pointer, it makes the problem much easier.
Without parent pointer we just need to keep track of the path from the root to the current node using a stack.
You would need two stacks to track the path in finding predecessor and successor node separately.
"""
import collections
def closestKValues(root, target, k):
stack = []
res = collections.deque()
while root or stack:
while root:
stack.append(root)
root = root.left
node = stack.pop()
root = node.right
if len(res) < k:
res.append(node.val)
else:
if abs(node.val - target) < abs(res[0] - target):
res.popleft()
res.append(node.val)
else:
return list(res)
return list(res)
|
bbdef09bfee0b8623d6a84271f23174ad14a1589 | M0use7/python | /LeetCode/最长公共前缀.py | 281 | 3.59375 | 4 | """__author__ = 唐宏进 """
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
n = len(strs)
for item in strs:
for _ in range(n):
item[n] ==
|
d0faec85f786686f341e6affc51e5406772880b4 | enu93/ElephantGame | /drawing_shapes.py | 993 | 3.546875 | 4 | import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 350), 0, 32)
color = (255, 255, 0)
# polygon ponts
points = [(20, 120), (140, 140), (10,30)]
# circle points
position = (300, 176)
radius = (60)
# ellipse points
rectangle = (140, 180, 50, 190)
# draw line
pos1 = (20, 20)
pos2 = (150, 134)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.lock()
# draw rectangel with RGB color
pygame.draw.rect(screen, (140, 240, 130), Rect((100, 100), (130, 170)))
# draw polygon
pygame.draw.polygon(screen, color, points)
# draw circle
pygame.draw.circle(screen, color, position, radius)
# draw ellipse
pygame.draw.ellipse(screen, color, rectangle)
# draw line
pygame.draw.line(screen, color, pos1, pos2, 10)
screen.unlock()
pygame.display.update()
|
d0ea6e7381beed60aa921331c5b9cb9f51ba7f9d | Liganggooo/Work_File | /python/Python1/File.py | 530 | 3.796875 | 4 | f = open('text.txt','r')
# f.write('abc')
# content = f.read()
#将文件存入一个列表中然后对列表进行遍历
lines = f.readlines()
for line in lines:
print(line.strip())
# print(content)
f.close
#免关闭文件式阅读文件方法
# filename = 'text.txt'
# with open(filename) as f:
# content = f.read()
# print(content)
# #写入文件、追加文件位置
# with open(filename,'a') as f:
# f.write('123')
# with open(filename,'r') as f:
# content = f.read()
# print(content)
|
9c177c7016c9edf051297633de926ed2e9b13039 | JamieRRobillardSr/stpd | /challenges/ch06/6-5.py | 203 | 3.578125 | 4 | l1 = [ "The", "fox", "jumped", "over", "the", "fence", "." ]
s1 = ""
for word in l1:
if (word == "."):
s1 = s1.strip()
s1 += word
else:
s1 += word + " "
print(s1)
|
9dd0100eef6551a5d7973a20fa38c0810341edf8 | At0m07/python | /dz1.py | 844 | 4.5 | 4 | #1.Поработайте с переменными, создайте несколько, выведите на экран,
#запросите у пользователя несколько чисел и строк и сохраните в переменные,
#выведите на экран.
print("Добро пожаловать!")
a = 5
b = 10
print ("Вывод переменных a и b:",a,b)
number = int(input("Введите первое число:"))
string = input("Введите слово:")
number2 = int(input("Введите второе число:"))
string2 = input("Введите второе слово:")
number3 = int(input("Введите третье число:"))
string3 = input("Введите третье слово:")
print (number,string,number2,string2,number3,string3)
|
a1bb6be4882167b0692406b13d3c8ba562e39262 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/522.py | 1,668 | 3.625 | 4 | #!/opt/local/bin/python
import sys
from itertools import count
def get_next_position(position_it, robot):
while True:
try:
next = position_it.next()
except StopIteration:
return None
if next[1] == robot:
return next[0]
input_it = iter(sys.stdin.readlines())
T = int(input_it.next())
for case in range(T):
_sequence = input_it.next().split()
sequence = zip([int(i) for i in _sequence[2::2]], _sequence[1::2])
position = {'O': 1, 'B': 1}
robot_it = {'O': iter(sequence), 'B': iter(sequence)}
next_position = {'O': get_next_position(robot_it['O'], 'O'), 'B': get_next_position(robot_it['B'], 'B')}
action_it = iter(sequence)
try:
action = action_it.next()
acted = False
for i in count(1):
# print 'status: (%3d, %3d)' % (position['O'], position['B'])
for robot in 'O', 'B':
if not next_position[robot] == None:
if action[0] == position[robot] and action[1] == robot:
acted = True
# print 'robot %s pushed button %s in round %s' % (robot, position[robot], i)
elif position[robot] < next_position[robot]:
position[robot] += 1
elif position[robot] > next_position[robot]:
position[robot] -= 1
if acted:
next_position[action[1]] = get_next_position(robot_it[action[1]], action[1])
action = action_it.next()
acted = False
except StopIteration:
print 'Case #%s: %s' % (case + 1, i)
|
6463cd932456a519035862ff3e76a35e3943a2f9 | zhaoyang6943/Python_JiChu | /day05/03 运算符.py | 1,655 | 4.28125 | 4 | # 学习的思路:什么是?为什么要有这个?
# 1. 算术运算符
# print(111 + 3)
# print(type(100 - 3.1))
#
# print(10 / 3) # 带小数
# print(10 // 3) # 只保留整数部分
#
# print(10 % 3) # 取余
#
# print(10 ** 3) # 代表10的3次方
# 2. 比较运算符
# print(1 > 3)
#
# print(1 == 1)
#
# print(10 >= 10)
# print(10 <= 3)
# name=input('your name')
# print('agen' == name)
# 3. 赋值运算符
# 3.1 增量赋值
# age = 18
# age += 1 # age = age +1
# print(age)
# age-=1
# age*=3
# age/=2
# age**=3
# 3.2 链式赋值
# x=10
# y=x
# z=y
z=y=x=10 # 链式赋值
print(x,y,z)
print(id(x),id(y),id(z))
# 3.3 交叉赋值
m=10
n=20
# 交叉值
# temp =m
# m=n
# n=temp
m,n=n,m # 一行代码搞定多行代码
print(m ,n)
# 3.4 解压赋值
salaries=[111,222,333,444,555] # 解压缩
# mon1=salaries[0]
# mon2=salaries[1]
# mon3=salaries[2]
# mon4=salaries[3]
# mon5=salaries[4]
# 解压赋值
mon1,mon2,mon3,mon4,mon5=salaries # 对应的变量名少一个不行,多一个不行!
print(mon1)
print(mon2)
print(mon3)
print(mon4)
print(mon5)
# 需求:一个列表中有30个值,但是想要取出前3个值,怎么做?
x,y,z,*_=salaries # *_,剩下的所有的。(ps:“_”变量名不要用下划线,代表一般是废弃的变量)
print(x,y,z)
print(_)
# 需求:取后三个值?
*_,x,y,z=salaries
# 需求,取中间的呢?-------不行~
# 需求,可以取两头的值,不能取中间的值。
x,*_,y,z=salaries
print(x,_,y,z)
# 需求,解压字典呢?
d={"a":123,"b":456,"c":789,"d":"abc","e":"edf"}
x,y,z,*_=d # 解压出来的是字典的key值
print(x,y,z,_)
|
1a62e2eb3cac117b0f23fb0acb9b35e29b3a8006 | AmyrSam/lab-test | /lab-test | 1,196 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
Soalan 1:
def countSetBits(n):
count = 0
while (n):
count += n & 1
n >>= 1
return count
i = input("Enter the number: ")
print(countSetBits(int(i)))
Soalan 2:
import collections
s = input("Enter your word: ")
print(collections.Counter(s).most_common(1)[0])
Soalan 3:
text= input("Enter your text")
# printing original string
print ("The original string is : " + text)
# using split()
# to count words in string
res = len(text.split())
# printing result
print ("The number of words in string are : " + str(res))
soalan 4a)
def print_arguments(function):
print("The argument is", function)
y = function + 2
return y
result = print_arguments(3)
print("This will return",result)
4b)
def multiply_output(function):
y = function*2
return y
result = multiply_output(3)
print("This will return",result)
4c)
def augment_function(function, decorators):
print("The argument is", function)
y = function + 2
return y
x = decorators*2
return x
result = augment_function(3,6)
print("This will return",result)
# In[ ]:
|
95d5211974ca6ac985f55b05f22ca1ff225ea0a6 | Edw10/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,548 | 3.84375 | 4 | #!/usr/bin/python3
"""
this module define the square
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
this is the square class
"""
def __init__(self, size, x=0, y=0, id=None):
"""this initialice a square"""
super().__init__(size, size, x, y, id)
def __str__(self):
"""this is the str representation"""
return ('[Square] (' + str(self.id) + ') ' +
str(self.x) + '/' + str(self.y) +
' - ' + str(self.width))
@property
def size(self):
"""size getter"""
return self.width
@size.setter
def size(self, value):
"""size setter"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""
update the attributes
"""
if args:
i = 0
for args in args:
if i == 0:
self.id = args
if i == 1:
self.width = args
self.height = args
if i == 2:
self.x = args
if i == 3:
self.y = args
i += 1
elif kwargs:
for key, value in kwargs.items():
setattr(self, key, value)
def to_dictionary(self):
"""
return a dictionary representation
"""
return {"id": self.id,
"size": self.size,
"x": self.x,
"y": self.y
}
|
5c99a76b5445fbdc3f6c3c350eee95b27ec93fdc | Ellen172/UFU-Python | /For range.py | 494 | 4 | 4 | #imprimindo os numeros primos, dentro de uma tupla
primos = (1, 3, 5, 7, 11, 13)
for k in primos :
print(k)
#cria uma tupla de 0 a 5, sem incluir o 5, atraves de uma p.a
r = tuple (range (0, 5))
print("r = ", r)
#a tupla é gerada a cada 2 numeros
l = tuple (range (0, 10, 2))
print("l =", l)
#cria uma tupla de 0 a 99
for a in range (0, 100) :
print(a)
#imprimindo os numeros primos
for k in range(0, len(primos)) :
print(primos[k]) #k anda nos indices da tupla |
7307c88244801bfe9cdc0fd12ac9a9e75b176842 | jgartsu12/my_python_learning | /python_data_structures/tuples/remove_elements.py | 1,468 | 4.59375 | 5 | # Three Ways to Remove Elements from a Python Tuple
# tuples are immutable so original is not having anything removed but the new ones will be new tuples with elements removed
# real world situation u didnt create the tuple but working with outsdie library with collection and cant ctrl tuple is what u have to work w/
# if changing tuple constantly .. then ask self should this be a list [] ??
post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published')
# FIRST WAY : reassignment: Removing Elements From End
# slice - returns element u want to keep
post = post[:-1] # this will take everything but the last element
print(post) #=> prints everything but 'published' and 'some cool content'
# second way: remove elements from beginning
post = post[1:]
print(post) # => ('Intro guide to Python', 'Some cool python content', 'published')
# 3rd way: removing specific element (messy/not suggested) ~ cast to different data type
# reassigment and convert to list
# casting into tuple into a list
post = list(post) # bad idea => say u dont change it back to a tuple and call fns that only works w/ tuple u get bugs due to diff data types
post.remove('published')
post = tuple(post) # converts/ casts back to tuple with published removed
print(post) # prints ['Python Basics', 'Intro guide to Python', 'Some cool python content', 'published']
# now we can treat tuple like a lists since now it is a list
|
12ebff9127351880383916e47e85aac753b9051a | muhil77/Project-One | /prime_check.py | 314 | 4.1875 | 4 | # this function checks if a number is prime
def prime_checker(num):
flag = True
for divisor in range(2, num / 2):
if num % divisor ==0:
flag = False
return flag
return flag
number_to_check = int(raw_input("Enter number to check "))
print prime_checker(number_to_check)
|
6af7045d8f10d43395571fbeeed07d25a4908b27 | YannTorres/Python-mundo1e2 | /Desafios/10ConversorMoeda.py | 183 | 3.65625 | 4 | a = float(input('Há quantos reais em sua carteira? R$'))
print(f'Com R${a:.2f} você pode comprar US${a/5.47:.2f}')
print(f'Com R${a:.2f} você pode comprar EU€{a/6.62:.2f}')
|
3d76a9121810c1270ff2e3e4cf5c7339714d14be | Nafsan/hackerrank-python | /Detect Floating Point Number.py | 1,087 | 3.9375 | 4 | # for _ in range(int(input())):
# string = input()
# plus = string.count('+')
# minus = string.count('-')
# plus_minus = plus + minus
# dot = string.count('.')
# dot_index = string.find('.')
# flag = 0
# if plus_minus > 1:
# flag = 1
# elif string.isalpha() is True:
# flag = 1
# elif dot_index == len(string) - 1 or dot > 1 or dot < 1:
# flag = 1
# elif plus_minus == 0 or string[0] == '+' or string[0] == '-':
# if dot == 1:
# string = string.replace('.', '')
# for i in range(plus_minus, len(string)):
# if string[i].isnumeric() is True:
# flag = 0
# else:
# flag = 1
# break
# if flag == 0:
# print(True)
# else:
# print(False)
for _ in range(int(input())):
s = input()
try:
value = float(s)
flag = 0
except ValueError:
flag = 1
if flag ==0 and s.count('.') == 0:
flag = 1
if flag == 0:
print(True)
else:
print(False)
|
0b34fbae6a35a1c851e5bf83a10ae9dcecc79329 | FHJXS/PythonStudy | /Eclipse/Test/Day6.py | 735 | 3.546875 | 4 | # -*- coding: UTF-8 -*-
'''
Created on 2018��2��10��
@author: www60
'''
import re
def func1():
"""
A|B可以匹配A或B,所以(P|p)ython可以匹配'Python'或者'python'。
^表示行的开头,^\d表示必须以数字开头。
$表示行的结束,\d$表示必须以数字结束。
"""
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m)
print(m.group(0)) # 匹配整个字符串
print(m.group(1)) # 按照区域切割获取字符串
print(m.group(2))
print(re.split(r'\s+', 'a b c'))
print(re.split(r'[\s\,]+', 'a,b, c d'))
print(re.split(r'[\s\,\;]+', 'a,b;; c d'))
pass
def test():
func1()
pass
if __name__ == '__main__':
test()
pass
|
fb01898a36c5abc5124aee0464d33b9cdc90f592 | marandmath/programming_challenges | /Advent of Code Programs/2015/Day 2/Day 2.py | 1,194 | 3.765625 | 4 | import numpy as np
file_name = "input.txt"
# Due to efficiency we will use a list consisting of lists / rows instead of
# numpy arrays! For more read this SO article:
# https://stackoverflow.com/questions/568962/how-do-i-create-an-empty-array-matrix-in-numpy
matrix = []
with open(file_name) as f_obj:
dimensions_list = f_obj.readlines()
for line in dimensions_list:
flag = False
temp_dimension = ''
temp_row = []
for char in line:
if flag:
temp_dimension = ''
if char.isdigit():
flag = False
temp_dimension += str(char)
elif char == 'x':
flag = True
temp_row.append(int(temp_dimension))
else:
temp_row.append(int(temp_dimension)) # This is the eol condition
# That is when the 'character iteration' meets the end of the
# line variable!
matrix.append(temp_row)
total_area = 0.0
for row in matrix:
products = [row[0]*row[1], row[1]*row[2], row[0]*row[2]]
total_area += 2*np.sum(products)+min(products)
print(f"The elves will need {total_area} square meters of wrapping paper")
|
5ec0125828d0ddcea457b758ccaef36f73ea0bbc | christian-townsend/capstone-project | /Machine Learning/generateData.py | 5,353 | 3.65625 | 4 | import random
skills = []
projects = []
groups = []
units = [9785, 9786, 10004, 10005, 10098, 11522]
#update below variables
maxGroupsPerProject=2
unitsPerProject = 2
minStudentsPerGroup=3
maxStudentsPerGroup = 5
skillsPerProject = 6
skillsPerGroup = 8
totalGroups = 50
totalProjects = 100
pointsFactorPerSkillMatch = 8
pointsForPreference = 12
pointsForGroupSize = 10
class Project:#Project constructor class
skills = []
relevantUnits = []
supervisorPreferences = []
projectGroupSize=None
projectNumber=None
available = True
numGroupsForProject=None
numGroupsAllocated=0
def __init__(self, skills, projectNumber):
self.skills= []
self.relevantUnits = []
self.supervisorPreferences = []
self.projectNumber=projectNumber#allocate project number
self.projectGroupSize=random.randint(minStudentsPerGroup,maxStudentsPerGroup)#randomise ideal number of students for project
self.numGroupsForProject=random.randint(1,maxGroupsPerProject)#randomise how many groups can work on project
for i in range(0,unitsPerProject):#add n appropriate units for project
self.relevantUnits.append(units[random.randint(0,len(units)-1)])
for x in range(0,skillsPerProject):#add n required skills to project
self.skills.append(skills[random.randint(0,(len(skills)-1))])
for k in range(0, 3):#add 3 supervisor preferences to project
self.supervisorPreferences.append(random.randint(0,totalGroups))
class StudentGroup:#StudentGroup constructor class
skills=[]
groupPreferences=[]
groupSize=None
allocatedProject=random.randint(0,totalProjects)
groupUnit=None
groupNumber=0
def __init__(self, skills, groupNumber):
self.skills=[]
self.groupPreferences=[]
for i in range(0,3):#add 3 random preferences
self.groupPreferences.append(random.randint(0,totalProjects))
for x in range(0,skillsPerGroup):#add 3 random skills
self.skills.append(skills[random.randint(0,(len(skills)-1))])
self.groupNumber = groupNumber#give group a number
self.groupSize=random.randint(minStudentsPerGroup,maxStudentsPerGroup)#allocate random number of students to group
self.groupUnit = units[random.randint(0,len(units)-1)]#allocate group to a unit
def AllocateProjects():#allocate projects to groups
for i in range(len(groups)):
bestScore=0
for k in range(len(projects)):
if groups[i].groupUnit not in projects[k].relevantUnits:#check if group is eligible for project - unit code
continue
if not projects[k].available:#check if project is available - num of groups already allocated
continue
score=sum(el in groups[i].skills for el in projects[k].skills)*pointsFactorPerSkillMatch#check how many skills match and score
if projects[k].projectGroupSize == groups[i].groupSize:
score=score+pointsForGroupSize
if projects[k].projectNumber in groups[i].groupPreferences:#check group preferences and score
score=score+pointsForPreference
if groups[i].groupNumber in projects[k].supervisorPreferences:#check supervisor preferences and score
score=score+pointsForPreference
if score > bestScore:
bestScore = score
groups[i].allocatedProject=projects[k].projectNumber#allocate highest scoring project
projects[groups[i].allocatedProject].numGroupsAllocated+=1#increment number of groups allocated to project
if projects[groups[i].allocatedProject].numGroupsAllocated==projects[groups[i].allocatedProject].numGroupsForProject:#set project to unavailable if allocation limit reached
projects[groups[i].allocatedProject].available=False
def WriteToFile():
for i in range(0,len(groups)):
formattedGroupSkills=' '.join(groups[i].skills)
string_ints = [str(int) for int in groups[i].groupPreferences]
formattedGroupPreferences=' '.join(string_ints)
for j in range(0, len(projects)):
string_ints = [str(int) for int in projects[j].supervisorPreferences]
formattedProjectPreferences=' '.join(string_ints)
formattedProjectSkills=' '.join(projects[j].skills)
string_ints = [str(int) for int in projects[j].relevantUnits]
formattedUnits = ' '.join(string_ints)
print(groups[i].groupNumber,groups[i].groupUnit,formattedGroupSkills,formattedGroupPreferences,
projects[j].projectNumber,formattedUnits,formattedProjectSkills,formattedProjectPreferences,groups[i].allocatedProject==projects[j].projectNumber,sep=',')
#driver code
with open('sampleskills.txt') as f:#read sample skills file to skills array
skills = f.read().splitlines()
for j in range(0,totalProjects):#generate n projects and store in list of objects
projects.append(Project(skills, j))
for x in range(0,totalGroups):#generate n groups and store in groups[]
groups.append(StudentGroup(skills, x))
AllocateProjects()
WriteToFile()
##rand timestamp
##academic sponsor preferences
##units - done
##groups per project - done
##group size - done
|
28f6f7f02adac77df95dc3d83e133a469a66bd70 | mfkiwl/midi_studio_hw | /scripts/output_imp.py | 684 | 3.671875 | 4 | # Find the output resistance (impedance at DC) and Thevanin voltage of a circuit
# Supply the script with V1 measured with R1 across the ouput and V2 with R2
# across the output
# The script gives output resistance and Thevanin voltage.
import sys
import numpy as np
if len(sys.argv) != 5:
sys.stderr.write("arguments are V1 R1 V2 R2\n")
sys.exit(1)
V1=float(sys.argv[1])
R1=float(sys.argv[2])
V2=float(sys.argv[3])
R2=float(sys.argv[4])
#R=(V1*R1*R2-V2*R2)/(R1*V2-V1*R2)
#V=(V1*R+V1*R1)/R1
A=np.array([
[V1,-R1],
[V2,-R2]
])
b=np.array([
[-R1*V1],
[-R2*V2]
])
rv=np.linalg.solve(A,b)
R=rv[0]
V=rv[1]
print("R=%e" % (R,))
print("V=%e" % (V,))
sys.exit(0)
|
eef5e94d1625baa4187da6a79d2b47be10391449 | Mierln/Computer-Science | /William/Blackjack.py | 5,220 | 3.578125 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
playing = True
class Cards:
def __init__(self, suits, ranks):
self.suits = suits
self.ranks = ranks
def __str__(self):
return f"{self.ranks} of {self.suits}"
class Deck:
def __init__(self):
self.deck = []
for a in suits:
for b in ranks:
self.deck.append(Cards(a, b))
def __str__(self):
deck_com = ""
for card in self.deck:
deck_com += '\n' + card.__str__()
return("Deck:" + deck_com)
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self,card):
self.cards.append(card)
self.value += values[card.ranks]
def adjust_for_ace(self):
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
class Chips:
def __init__(self):
self.total = 1000
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
chips.bet = int(input('How many chips would you like to bet? '))
except ValueError:
print('Sorry, a bet must be an integer!')
else:
if chips.bet > chips.total:
print("Sorry, your bet can't more than",chips.total)
else:
break
def hit(deck,hand):
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck,hand):
global playing # to control an upcoming while loop
while True:
x = input("\nWould you like to Hit or Stand? Enter 'h' or 's' ")
if x[0].lower() == 'h':
hit(deck,hand) # hit() function defined above
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
else:
print("Sorry, please try again.")
continue
break
def show_some(player,dealer):
print("\nDealer's Hand:")
print(" <card hidden>")
print(dealer.cards[0])
print("\nPlayer's Hand:")
for card in player_hand.cards:
print(card)
def show_all(player,dealer):
print("\nDealer's Hand:")
for card in dealer_hand.cards:
print(card)
print("Dealer's Hand =", dealer.value)
print("\nPlayer's Hand:")
for card in player_hand.cards:
print(card)
print("Player's Hand =",player.value)
def player_busts(player,dealer,chips):
print("Player busts!")
chips.lose_bet()
def player_wins(player,dealer,chips):
print("Player wins!")
chips.win_bet()
def dealer_busts(player,dealer,chips):
print("Dealer busts!")
chips.win_bet()
def dealer_wins(player,dealer,chips):
print("Dealer wins!")
chips.lose_bet()
def push(player,dealer):
print("Dealer and Player tie! It's a push.")
print("\n"*100)
print('Welcome to BlackJack! Get as close to 21 as you can without going over!\nDealer hits until she reaches 17. Aces count as 1 or 11 (auto).\nStarting Balance: 1000\n')
deck = Deck()
for _ in range(30):
deck.shuffle()
player_chips = Chips()
while True:
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
take_bet(player_chips)
show_some(player_hand,dealer_hand)
while playing:
hit_or_stand(deck,player_hand)
show_some(player_hand,dealer_hand)
if player_hand.value > 21:
player_busts(player_hand,dealer_hand,player_chips)
break
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck,dealer_hand)
show_all(player_hand,dealer_hand)
if dealer_hand.value > 21:
dealer_busts(player_hand,dealer_hand,player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand,dealer_hand,player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand,dealer_hand,player_chips)
else:
push(player_hand,dealer_hand)
print("\nYour balance",player_chips.total)
if player_chips.total == 0:
print("YOU HAVE NO BALANCE LEFT")
break
new_game = input("\nWould you like to play another hand? Enter 'y' or 'n' ")
if new_game[0].lower()=='y':
playing=True
continue
else:
print("Thanks for playing!")
break |
05f01f142978c681ea3b20f70f578d5b15ad01a1 | devyani143/if-else | /chocolate.py | 196 | 4.125 | 4 | # num=int(input("enter a number"))
# if num%3==0 and num%5==0:
# print("chocolate")
# elif num%3==0:
# print("choco")
# elif num%5==0:
# print("late")
# else:
# print("dairy milk") |
44f8ca34f3e3959f767f91390c8f49b716bcde1f | 356108814/algorithm | /twitter.py | 2,919 | 4 | 4 | # coding: utf-8
# letcode 355
from typing import List
class ID:
index = 0
class Tweet:
def __init__(self, tweetId):
ID.index += 1
self.tweetId = tweetId
self.time = ID.index
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.userTweets = {}
self.userFollows = {}
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
tweet = Tweet(tweetId)
if userId not in self.userTweets:
self.userTweets[userId] = []
if tweetId not in self.userTweets[userId]:
self.userTweets[userId].append(tweet)
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
tweets = []
if userId in self.userTweets:
selfTweets = self.userTweets[userId]
for tweet in selfTweets:
tweets.append(tweet)
if userId in self.userFollows:
followeeIds = self.userFollows[userId]
for followeeId in followeeIds:
if followeeId in self.userTweets:
for tweet in self.userTweets[followeeId]:
tweets.append(tweet)
# 排序
tweets.sort(key=lambda tweet: tweet.time, reverse=True)
latest = []
for t in tweets[0: 10]:
latest.append(t.tweetId)
return latest
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId != followeeId:
if followerId not in self.userFollows:
self.userFollows[followerId] = []
if followeeId not in self.userFollows[followerId]:
self.userFollows[followerId].append(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId != followeeId:
if followerId in self.userFollows:
followeeIds = self.userFollows[followerId]
if followeeIds:
if followeeId in followeeIds:
for v in followeeIds:
if v == followeeId:
followeeIds.remove(v)
break
# Your Twitter object will be instantiated and called as such:
obj = Twitter()
obj.postTweet(1,1)
param_2 = obj.getNewsFeed(1)
obj.follow(1, 2)
obj.unfollow(1,2) |
c9945262a44a8c9c9779cef5a5307d1e8c46455c | nekapoor7/Python-and-Django | /GREEKSFORGREEKS/String/remove_duplicate.py | 191 | 4.0625 | 4 | #Remove all duplicates from a given string in Python
from collections import OrderedDict
def removechar(s):
return "".join(OrderedDict.fromkeys(s))
s = input()
print(removechar(s))
|
7b82acf9062f85b1eab73194be3b7f90f4bce660 | Dark5Matter/GradeCalculator | /gradecalculator.py | 5,112 | 4.46875 | 4 | #!/usr/bin/env python3.5
print ("now using Python 3.5\n")
#on 17th October 2017
#by Benjamin ********
#This program first takes in the values from the CSV file from memory, then places the values in RAM to await the next time the values will be used.
#The computer will then either deem the data replacable or read the data in RAM and send it to the CPU
#Next, computer will then get the next instruction add 1 to the program counter
import csv
def importData(file):
"This function will read in a CSV file and split each row into separate Lists"
#Create empty Lists(with sensible names) to match the columns/fields in the CSV source file
listOne = []
listTwo =[]
listThree = []
#Open the file using the path provided and assign to a variable for reference
with open(file,"r") as filename:
#Set reader up to parse a CSV file
reader = csv.reader(filename)
for row in reader:
listOne.append(row[0])
listTwo.append(row[1])
listThree.append(row[2])
return (listOne, listTwo, listThree)
def calcPercentage (courseMark, examMark):
percentList=[]
for index in range (0, 11):
sum = int(courseMark[index]) + int(examMark[index]) #calculate percentage
percentage = sum/150
percentage = round(percentage*100,2)
percentList.append(percentage)
return percentList #return the percentage to the main program
def findGrade (percentage):
#use the percentage to then find what grade the pupil had achieved
if percentage>= 70 :
grade = "A"
elif percentage >= 60:
grade = "B"
elif percentage >=50:
grade = "C"
elif percentage >= 45:
grade = "D"
else:
grade = "No Grade"
return grade
def display (percentage, grade, name):
print ("{0} got {1} with {2}%!".format(name, grade, percentage))#display the grade and percentage
def writeCSVFile(fp,lst1,lst2,lst3,lst4,lst5):
"This procedure opens a disc file from its full filepath and writes all list contents to it"
with open(fp, "w") as myFile:
for index in range(0, 11):
myFile.write("{0},{1},{2},{3},{4}\n".format(lst1[index],lst2[index],lst3[index],lst4[index], lst5[index])) # Write each record to file on a new line
def findMax (list):
"search list for maximum value, report and return to a variable"
max = list[0] # set max to item in pos 0
for i in range(0,len(list)-1): # for each item in list
if list[i]>max: # if the item at i > found max
max = list[i] # set max to the item at i
return max
def input_grade(prompt): # prompt is the prompt you want to show to the user
# returns the grade in uppercase or "Error" if an incorrect grade is entered. Modify the grades list as desired
grades = ["A", "B", "C", "D", "E", "F"] # valid grades
uppercase = input (prompt).upper() # get the input and make it uppercase
if uppercase not in grades: # if the entered grade is invalid
return "Error"
else: # if the entered grade is valid
return uppercase
def countOccurrence (li):
total = 0
_desired_grade = "" # temporary variable to loop until the user provides a valid input
_grade_found = False # temporary variable to loop until the user provides a valid input
while _grade_found == False: # exit when _grade_found is True and _desired_grade is an actual grade
_desired_grade = input_grade("Enter the grade you're looking for ") # user input
if (_desired_grade != "Error"): # valid input, no error
_grade_found = True # set to True and exit the loop
search = _desired_grade # the grade the user wants to find
for i in range(0,len(li)):
if li[i] == search : #check if the item in the list is the grade that the user wants
total = total + 1 #add 1 to the total when the item is the grade the user wants
print ("The program found {0} {1}s".format(total, search)) #display how many of the grade there is
return total
#Main program
while True:
Name =[]
examMark = []
courseMark = []
percentageList = []
gradeList = []
name, examMark, courseMark = importData("/home/bdavidson106/Assessment/AssessmentNames.csv")
percentageList = calcPercentage(courseMark, examMark)
for index in range(0, 11):
grade = findGrade(percentageList[index])
gradeList.append(grade)
display(percentageList[index], gradeList[index], name[index])
writeCSVFile("/home/bdavidson106/Assessment/AssessmentNames.csv", name, courseMark, examMark ,percentageList, gradeList)
maxCourse = findMax (courseMark)
maxExam = findMax (examMark)
maxPercent = findMax (percentageList)
print("Highest coursework mark was ", maxCourse,"\n Largest exam mark was ", maxExam, "\n Largest overall percentage was ", maxPercent)
ocurrences = countOccurrence (gradeList)
|
aac9d91104bcd6ba36b7fd195031fda637411d7f | TSmithJr/Python-Projects | /HW1/Volume.py | 2,098 | 4.375 | 4 | # Volume.py
"""
MIS 15-01
This program computes the volume of a bottle
with two cylinders, and a cone in between them.
It uses the volume of a cylinder formula and
the volume of a cone section formula.
Our output for volume is going to be different
because of math functions for pi. The example
volume was not completely accurate because it
used a global/normal variable for pi. The inch
value is the only value that changed, the meter
value remains the same.
"""
import math # import math functions for the use of pi
def main(): # define main
# assign radius 1 and 2, make them floats, acquire user input
r1 = float(input("Enter r1(in inches): "))
r2 = float(input("Enter r2(in inches): "))
# assign height 1,2,3, make them floats, acquire user input
h1 = float(input("Enter h1(in inches): "))
h2 = float(input("Enter h2(in inches): "))
h3 = float(input("Enter h3(in inches): "))
print() # print line for spacing
# printing bottom and top radius with 2 decimal places
print("Bottom radius: " + "%.2f" % r1 + " Inches")
print("Top radius: " + "%.2f" % r2 + " Inches")
# printing all 3 heights with 2 decimal places
print("Height of bottom cylinder: " + "%.2f" % h1 + " Inches")
print("Height of top cylinder: " + "%.2f" % h2 + " Inches")
print("Height of cone: " + "%.2f" % h3 + " Inches")
print() # print line for spacing
# formula section
cylinderOneVolume = math.pi * r1 ** 2 * h1
cylinderTwoVolume = math.pi * r2 ** 2 * h2
radiusCone = (r1 ** 2 + (r1 * r2) + r2 ** 2)
volumeCone = math.pi * ((radiusCone * h3) / 3)
volume = cylinderOneVolume + cylinderTwoVolume + volumeCone
# conversion from cubic inches to cubic meters, according to google
meter_conversion = volume / 61023.744
# printing the final output with format according to assignment sheet
print("Volume of bottle is: " + "%.2f" % volume + " Cubic Inches or "
+ "%.4f" % meter_conversion + " Cubic Meters")
main() # call main
|
6b38a9410196c7c3c1fffe7912f56f6cdd4de454 | santoshgawande/PythonPractices | /for.py | 1,295 | 4.59375 | 5 | #For loop : If we know how much loop will run then used
for i in range(5):
print(i)
#print('\n') #extra just see proper output
#For using String
for letter in 'Names':
print(letter, end =" ")
print('\n')
#For using List sequence :
# This is the better way about performance than using index
list1 = [1,2,3,'hello']
for l in list1:
print(l, end=" ")
print('\n')
# using List index
list2 =[1,3,4,56,7,8,90,'hjk',5.6]
for i in range(len(list2)):
print(list2[i], end=" ")
print('\n')
#enumerate() : used to access element and index of the list at the same time.
list3 = [1,4,5,6,7,'hi','hello','g']
for i,ele in enumerate(list3):
print(i,ele, end=" ")
print('\n')
#For using Range():
for i in range(10):
print(i,end = " ")
print('\n')
for i in range(1,10):
print(i, end=" ")
print('\n')
# For using Range(start, end, step=1)
for i in range(1,10,2):
print(i, end=" ")
print('\nrevese for loop \n')
#For using negative : decrement for loop
for i in range(5, -1, -1):
print(i, end=' ')
print('\nreverse()')
#For using reversed():
list4 = ['hi',3,4,56,7,8]
for i in reversed(list4):
print(i, end=" ")
print('\n')
#For using zip()
list5 = [2,3,6,7,8,9]
list6 = ['hi','hello','good night','morning']
for i,j in zip(list5,list6):
print(i,j)
|
af092923bfa57369e8f041b3dcbbab2a9d64e2bc | Aasthaengg/IBMdataset | /Python_codes/p02257/s497783881.py | 270 | 3.671875 | 4 | import math
def is_prime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return n != 1
n = int(input())
answer = 0
for _ in range(0, n):
m = int(input())
if is_prime(m):
answer = answer + 1
print(answer)
|
3c8e572ff2e500b9498a94449a1197ee728a6c30 | abzalmyrzash/webdev2019 | /week 10/hackerrank/nested lists.py | 609 | 3.8125 | 4 | def alphabetic_order(a, b):
if a[0] > b[0]:
return 1
elif a[0] < b[0]:
return -1
else:
return 0
if __name__ == '__main__':
arr = []
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
arr.append([name, score])
arr.sort(alphabetic_order)
min = 100
second = 100
for i in arr:
if i[1] < min:
second = min
min = i[1]
elif i[1] < second and i[1] != min:
second = i[1]
for i in arr:
if i[1] == second:
print(i[0]) |
85f4167f393e5cebd92480eb53fc55525aa328fc | ducsuus/RoK-Calc | /logic.py | 833 | 3.984375 | 4 | # Reign Of Kings Calculator Logic
# A list of all the block types, linking to a list of all the materials needed to craft that block.
blocks = {"block" : [["stone", 2], ["wood", 100]],
"cobble" : [["stone", 30]]
}
# The parameters needed
user_block = str(input("Block: "))
user_perimeter = int(input("Perimeter: "))
user_height = int(input("Height: "))
# If details are valid
if user_block in blocks:
# Print out the calculated details
print("\n\n\n========\nBlocks And Materials\n========")
block_count = user_perimeter * 4 * user_height
print("Total Blocks: " + str(block_count))
materials = blocks[user_block]
# Work and print out the total number of blocks and materials
for i in materials:
i[1] *= block_count
print(i[0] + ": " + str(i[1]))
|
651690ba4aec0e434be792a3dcf7c118c0321763 | kktkyungtae/TIL | /Algorithm/2019.01/2019.01.24/Practice/10_if흐름제어4(X).py | 1,171 | 4.09375 | 4 | # 다음의 결과와 같이 가상의 두 사람이 가위 바위 보 중 하나를 내서 승패를 가르는 가위 바위 보 게임을 작성하십시오.
# 이 때 ["가위", "바위", "보"] 리스트를 활용합니다.
import random
Man = {'가위':1, '바위':2, '보':3}
Man1 = [random.choice(Man)]
Man2 = [random.choice(Man)]
print(f'{Man1[0]} {Man2[0]}')
# if Man1[0] == '가위' and Man2[0] =='보':
# print("Result : Man1 Win!")
# elif Man1[0] == '가위' and Man2[0] =='바위':
# print("Result : Man2 Win!")
# elif Man1[0] == '가위' and Man2[0] =='가위':
# print("Result : Drow")
# elif Man1[0] == '바위' and Man2[0] =='바위':
# print("Result : Drow")
# elif Man1[0] == '바위' and Man2[0] =='가위':
# print("Result : Man2 Win!")
# elif Man1[0] == '바위' and Man2[0] =='바위':
# print("Result : Drow")
# elif Man1[0] == '보' and Man2[0] =='가위':
# print("Result : Man2 Win!")
# elif Man1[0] == '보' and Man2[0] =='바위':
# print("Result : Man1 Win!")
# elif Man1[0] == '보' and Man2[0] =='보':
# print("Result : Drow")
|
8c48fa4f8d7579eb738614acc3218a015eab1ce8 | liidenee/Python-test-example | /tests/test_class_inheritance.py | 190 | 3.640625 | 4 | from code.class_inheritance import Teacher
x = Teacher('Amy', 'Harrot', 1979)
assert x.get_name() == 'Amy Harrot', 'Name should be "Amy Harrot"'
assert x.get_year() == 1989, 'Year should be 1989' |
7546695afa4e62b727d293399866bdc6d74a0e90 | Guilherme-Artigas/Python-intermediario | /Aula 12.5 - Exercício 40 - Aquele clássico da Média/ex040_.py | 355 | 3.703125 | 4 | n1 = float(input('Digite a 1º nota: '))
n2 = float(input('Digite a 2º nota: '))
media = (n1 + n2) / 2
if media < 4.9:
print('Média: {}'.format(media))
print('REPROVADO!')
elif (media > 5.0) and (media < 6.9):
print('Média: {}'.format(media))
print('RECUPERAÇÃO!')
else:
print('Média: {}'.format(media))
print('APROVADO!')
|
a1a7e5faad35847f22301b117952e223857d951a | nestorsgarzonc/leetcode_problems | /6.zigzag_convertion.py | 1,459 | 4.375 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
"""
"""
1158 / 1158 test cases passed.
Status: Accepted
Runtime: 88 ms
Memory Usage: 13.9 MB
"""
# Solution brute force
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
arrResult = [[] for i in range(numRows)]
counter = 0
numRows -= 1
reverse = False
for i in s:
if counter == numRows:
reverse = True
if counter == 0:
reverse = False
if counter < numRows and reverse == False:
arrResult[counter].append(i)
counter += 1
if counter > 0 and reverse == True:
arrResult[counter].append(i)
counter -= 1
myResult = ''
for i in arrResult:
myResult.join(i)
return myResult
|
ae58132685b2d3fcb924b3d7a0a4b3f66d4b1238 | klm127/rpio-cli-state-machine | /src/Game/GameStart.py | 3,403 | 3.84375 | 4 | """
The starting state for the game.
Shows some text and spinners to introduce the player to the game.
When space-bar is pressed or when the text is finished scrolling, loads up the MapState to begin game.
Extends src.Game.Map.GameStates.Game
"""
from src.Game.GameStates import Game
from src.Game import TitleScreenObjects
from src.StateMachine.Commands import Command
from src.Game.MapState import MapState
class GameStart(Game):
def __init__(self, program, display):
Game.__init__(self, program, display)
self.game_objects.append(TitleScreenObjects.TextScroll("Game Time!!!", 0.3))
wave_num = 1
wave_rising = True
for i in range(0, 16):
self.game_objects.append(GameStart.wave_generator(i, wave_num))
if wave_num == 4:
wave_rising = False
if wave_num == 1:
wave_rising = True
if wave_rising:
wave_num += 1
else:
wave_num -= 1
self.commands.add(Command(self, Game.is_key_cb("press", "Key.space"), GameStart.next_state))
def done(self, scroll_text):
"""
Called by the instances of TextScroll in TitleScreenObjects.
Lets this state know that the text scrolls are done scrolling.
GameStart looks at which text scroll is done, then creates the next one.
:param scroll_text: The calling scroll text object
:type scroll_text: class src.Game.Map.TitleScreenObjects.TextScroll
"""
if scroll_text.text == "Game Time!!!":
self.game_objects.append(TitleScreenObjects.TextScroll("You are a one-eyed pirate! " + chr(1)+chr(2)))
elif scroll_text.text == "You are a one-eyed pirate! " + chr(1) + chr(2):
self.game_objects.append(TitleScreenObjects.TextScroll("Fumble through the maze! "))
@staticmethod
def wave_generator(x, num):
"""
Returns new instances of `TitleScreenObjects.spinner` to rotate some characters that give the
vague appearance of being waves, in keeping with the pirate theme.
:param x: The x on the display, either 1 or 2, to place them (they all start at y=1)
:type x: int
:param num: The interval time between frame changes
:type num: float
"""
if num == 1:
return TitleScreenObjects.Spinner(x, 1, ['^', '-', '.', '-'], 1)
elif num == 2:
return TitleScreenObjects.Spinner(x, 1, ['-', '.', '-', '^'], 1)
elif num == 3:
return TitleScreenObjects.Spinner(x, 1, ['.', '-', '^', '-'], 1)
elif num == 4:
return TitleScreenObjects.Spinner(x, 1, ['-', '^', '-', '.'], 1)
@staticmethod
def next_state(state, inp):
"""
Called by a `Command` through an `effect` callback.
Triggered by space bar on the title screen.
Sets self.program.state to a `MapState` instance, passing the same display this state used to `MapState`
Neither parameter is actually used, but this is the structure of a command callback.
:param state: The calling state (will be self)
:type state: extends class src.StateMachine.States.State
:param inp: The input - will be a key dict
:type inp: dict
"""
state.program.state = MapState(state.program, state.display)
state.end_state()
|
86dd565b040bc3969a49ccc07b3b7d0d69e72289 | vladosfedulov/DES | /main.py | 844 | 3.53125 | 4 | # name Владислав
ROUNDS = 16
KEY = 'Bладислав'
text = 'Куй железо не отходя от кассы'
block = []
key_position = 0
while ROUNDS > len(KEY):
KEY += KEY
if (len(text) % 2) == 1:
text = text + ' '
for i in range(0, len(text), 2):
block.append(text[i:i + 2])
def cript(b, k):
return [i[1] + chr(ord(i[0]) ^ ord(k[0])) for i in b]
def decript(b, k):
return [chr(ord(i[1]) ^ ord(k[0])) + i[0] for i in b]
print('\nШифрование текста:\n')\
for i in range(0, ROUNDS):
block = cript(block, KEY[key_position])
print("Раунд: ", i, " ", block)
key_position += 1
print('\nДешифрование текста:\n')
for i in range(0, ROUNDS):
key_position -= 1
block = decript(block, KEY[key_position])
print("Раунд: ", i, " ", block)
|
a9d8e157a246d03d7252c752de3f1a8367d0c26e | plammens/python-introduction | /Fundamentals I/String basics/Concatenation/task.py | 224 | 4.28125 | 4 | # ----- concatenation -----
name = "Bob" # modify this
age = "42" # modify this
# substitute <name> with the contents of name and age (using the variables!)
print("My name is " + name + " and I'm " + age + " years old")
|
66a84c837c393eb0fd3bf118980831845561ae1d | ctrl-nivedha/backtracking-sudoku | /sudoku_backtracker/sudoku-backtracker.py | 2,413 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 19:48:46 2020
@author: Mro
"""
row= False
col= False
board = [
[0,3,0,0,0,5,0,8,0],
[0,5,0,0,0,9,0,0,0],
[0,0,0,0,2,0,0,3,0],
[3,0,0,0,0,0,0,9,0],
[0,0,5,0,0,0,6,0,0],
[0,9,0,0,0,0,0,0,8],
[0,1,0,0,3,0,0,0,0],
[7,0,0,2,0,0,0,0,0],
[0,4,0,0,0,0,0,2,0]
]
#print board
def printboard(bo):
for i in range(len(bo)):
if(i==3 or i==6):
print("---------------------")
for j in range(len(bo[i])):
if(j==3 or j==6):
print("|", end=' ')
print(bo[i][j], end=' ')
print(end='\n')
#check emmpty
def checkempty(bo):
global row, col
for i in range(len(bo)):
for j in range(len(bo[i])):
if bo[i][j]==0:
row=i
col=j
return True
return False
#backtracking func
def solve(bo):
global row, col
if checkempty(bo):
x=row
y=col
else:
return True
for i in range(1,10):
#check row
if (checkrow(bo,x,y,i) and checkcol(bo,x,y,i) and checkbox(bo,x,y,i)):
bo[x][y]=i
if solve(bo):
return True
else:
bo[x][y]=0;
return False
#check column
#checkcol()
#check box
#checkbox()
def checkrow(bo,x,y,n):
for j in range(len(bo[x])):
if bo[x][j]==n and j!=y:
return False
return True
def checkcol(bo,x,y,n):
for i in range(len(bo)):
if bo[i][y]==n and i!=x:
return False
return True
def checkbox(bo,x,y,n):
a = x // 3
b = y // 3
for i in range(a*3, a*3 + 3):
for j in range(b * 3, b*3 + 3):
if bo[i][j] == n and (i,j) != (a,b):
return False
return True
#main
def main():
printboard(board)
solve(board)
print("----------------------------------")
print('\n')
print("----------------------------------")
printboard(board)
main() |
3c8d173582166f5a5f6a7e15f6c9b59687c6ed00 | s1monLee/CodingChallenge | /LeetCode/Python3/1512_Number_of_Good_Pairs.py | 678 | 3.515625 | 4 | """
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
"""
"""
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
pair = 0
for i, n in enumerate(nums):
for j in range(i+1,len(nums)):
if n == nums[j]:
pair+=1
return pair
"""
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
num = 0
pair = {}
for i in nums:
if i in pair:
num += pair[i]
pair[i] += 1
else:
pair[i] = 1
return num
|
9db50e34cc5777797536a0ececee2760be9be747 | yize11/1808 | /14day/07-默认参数.py | 135 | 3.765625 | 4 | def a(b,c=100):
for i in range(b,c):
if i%3 == 0 and i%5 == 0:
print(i)
b = int(input('请输入数字'))
a(b)
|
17523829e6e1e93c53320b897ca889b9d846058f | isbirukov/diff_courses | /Deep_Learning_2019_2020_base_flow/3.3_homework_sum_diag_even_elements.py | 663 | 3.875 | 4 | """
Напишите функцию, которая находит сумму четных элементов на главной диагонали квадратной матрицы
(именно чётных элементов, а не элементов на чётных позициях!).
Если чётных элементов нет, то вывести 0. Используйте библиотеку numpy.
Входные данные -- квадратный np.ndarray.
"""
import numpy as np
def diag_2k(a):
#YOUR CODE
diag = np.diag(a)
result = 0
for el in diag:
if el % 2 == 0:
result += el
return result |
b465071b74da54e33626f6a8777ceb8801146b2c | L316645200/_Python | /fluent_python_eg/9 、符合Python风格的对象/9.5 格式化显示.py | 813 | 3.59375 | 4 | brl = 1/2.43
print(brl)
print(format(brl, '0.4f'))
print('1 BRL = {rate:0.2f} USD'.format(rate=brl))
# 格式规范微语言为一些内置类型提供了专用的表示代码。
# 比如,b 和 x 分别表示二进制和十六进制的 int 类型,f 表示小数形式的 float 类 型,而 % 表示百分数形式
print(format(42, 'b'))
print(format(2/3, '.1%'))
# 格式规范微语言是可扩展的,因为各个类可以自行决定如何解释 format_spec 参数。
# 例如, datetime 模块中的类,它们的 __format__ 方法使用的格式代码与 strftime() 函数一样。
# 下面是内 置的 format() 函数和 str.format() 方法的几个示例:
from datetime import datetime
now = datetime.now()
print(now)
print(format(now, '%H:%M:%S'))
print("It's now {:%I:%M %p}".format(now))
|
f5fa95227eaa5c0bf63de562fdb2d8306407e1d4 | manishakoirala/python | /sums_loop.py | 240 | 3.609375 | 4 | print("input data :")
N=input()
listnum1 =[]
listnum2 =[]
for i in range(N) :
listnum1.append(input())
for x in range(N):
listnum2.append(input())
print("output data:")
for j in range(N):
sumn=listnum1[j]+listnum2[j]
print(sumn)
|
3d73044416539da2865987a64c43325c589e15a5 | RJD02/Joy-Of-Computing-Using-Python | /Assignments/Week-12/Assignment12_2.py | 1,182 | 3.734375 | 4 | '''
Ramesh and Suresh have written GATE this year. They were not prepared for the exam.
There were only multiple choice questions. There were 5 options for each question listed 1,2,3,4,5.
There was only one valid answer. Each question carries 1 mark and no negative mark.
Ramesh and Suresh are so sure that there is no question that both of them have answered correctly, i.e,
one of them has given invalid answer.
Now Ramesh wants to know how well he has done the GATE. Given the answers of both Ramesh and Suresh,
You should tell me what the maximum marks that Ramesh can get.
Input Format:
Line1 - Number of Questions in the GATE Exam
Line2 - List of Answers given by Ramesh(Answer no given then its represented by ‘.’)
Line3 - List of Answers given by Suresh (Answer no given then its represented by ‘.’)
Output Format:
Maximum score for Ramesh
Input:
6
1 2 3 4 5 1
1 2 2 2 5 1
Output
2
'''
def solve():
n = int(input())
ramesh = input().split()
suresh = input().split()
count = 0
for i in range(n):
if ramesh[i] != suresh[i] and ramesh[i] != '.':
count += 1
print(count)
return
solve()
|
721ff59cc46883b8ea41fa9563d7031a382c550f | tchdesde/cloud-developer | /bikeshare.py | 11,038 | 4.4375 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTHS_DATA = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
DAYS_DATA = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze.
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
try:
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
city = input('Please enter the name of the city you would like to analyze (Chicago, New York City or Washington) : ').lower()
if city not in CITY_DATA:
print('\nInvalid city name!\n')
continue
else:
break
# TO DO: get user input for month (all, january, february, ... , june)
while True:
month = input('Which month would you like to analyze? January, Feburary, March, April, May, June or ALL : ').lower()
if month not in MONTHS_DATA:
print('\nInvalid month name!\n')
continue
else:
break
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input('Which day would you like to analyze? Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday or ALL : ').lower()
if day not in DAYS_DATA:
print('\nInvalid day name!\n')
continue
else:
break
print('-'*60)
print('Your selection is that\nCity : {} , Month : {} , Day : {} '.format(city.title(),month.title(),day.title()))
print('-'*60)
return city, month, day
except Exception as e:
print('An exception has been occurred : {}'.format(e))
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
try:
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['End Time'] = pd.to_datetime(df['End Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = MONTHS_DATA.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
except Exception as e:
print('An exception has been occurred during loading data: {}'.format(e))
def time_stats(df, city):
"""Displays statistics on the most frequent times of travel according to city selected."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
try:
common_month_num = df['Start Time'].dt.month.mode()[0]
common_month = MONTHS_DATA[common_month_num-1].title()
print('The most common month in', city.title(), 'is:', common_month.title())
except Exception as e:
print('An exception has been occurred while displaying most common moth : {}'.format(e))
# TO DO: display the most common day of week
try:
common_day_of_week = df['day_of_week'].mode()[0]
print('The most common weekday in', city.title(), 'is:',common_day_of_week.title())
except Exception as e:
print('An exception has been occurred while displaying most common moth day of week: {}'.format(e))
# TO DO: display the most common start hour
try:
common_start_hour = df['hour'].mode()[0]
print('The most common starting hour in', city.title(), 'is:',common_start_hour)
except Exception as e:
print('An exception has been occurred while displaying most common start hour: {}'.format(e))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df, city):
"""Displays statistics on the most common stations and trip according to city selected."""
print('\nCalculating The Most common Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
try:
common_start_station = df['Start Station'].mode()[0]
common_start_station_amount = df['Start Station'].value_counts()[0]
print('The most commonly used start station in', city.title(), 'is:',common_start_station, 'and was used', common_start_station_amount, 'times.')
except Exception as e:
print('An exception has been occurred while displaying most commonly used start station : {}'.format(e))
# TO DO: display most commonly used end station
try:
common_end_station = df['End Station'].mode()[0]
common_end_station_amount = df['End Station'].value_counts()[0]
print('The most commonly used end station in', city.title(), 'is:',common_end_station, 'and was used', common_end_station_amount, 'times.')
except Exception as e:
print('An exception has been occurred while displaying most commonly used end station: {}'.format(e))
# TO DO: display most frequent combination of start station and end station trip
try:
common_trip = df.loc[:, 'Start Station':'End Station'].mode()[0:]
common_trip_amt = df.groupby(["Start Station", "End Station"]).size().max()
print('The most frequent combination of start station and end station trip is:\n', common_trip, '\n and was driven', common_trip_amt,'times')
except Exception as e:
print('An exception has been occurred while displaying most frequent combination of start station and end station trip : {}'.format(e))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df, city):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
try:
df['Time Delta'] = df['End Time'] - df['Start Time']
total_time_delta = df['Time Delta'].sum()
print('The total travel time :', total_time_delta)
except Exeption as e:
print('An exception has been occurred while displaying total travel time: {}'.format(e))
# TO DO: display mean travel time
try:
total_mean = df['Time Delta'].mean()
print('The mean travel time :', total_mean)
except Exception as e:
print('An exception has been occurred while displaying mean travel time: {}'.format(e))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df,city):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
try:
print('The counts of user types in', city.title(), 'are as follows:\n', df['User Type'].value_counts())
except Exception as e:
print('An exception has been occurred while displaying counts of user type: {}'.format(e))
# TO DO: Display counts of gender
try:
print('The counts of gender in', city.title(), 'are as follows:\n',df['Gender'].value_counts())
except Exception as e:
print('An exception has been occurred while displaying counts of gender: {}'.format(e))
# TO DO: Display earliest, most recent, and most common year of birth
try:
earliest_year = df['Birth Year'].min()
most_recent_year = df['Birth Year'].max()
most_common_year = df['Birth Year'].mode()
print('The earliest, most recent, and most common year of birth in', city.title(), 'is:\n' 'The earliest birth date is:', int(earliest_year),'\n' 'The most recent birth date is:', int(most_recent_year),'\n' 'The most common year of birth is:', int(most_common_year))
except Exception as e:
print('An exception has been occurred while displaying earliest, most recent, and most common year of birth: {}'.format(e))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_data(df):
"""Raw data is displayed upon request by the user."""
raw_data = 0
try:
while True:
answer = input("Do you want to see the raw data? Please type Yes or No : ").lower()
if answer not in ['yes', 'no']:
print('\nInvalid answer!\n')
continue
elif answer == 'yes':
print(df.iloc[raw_data : raw_data + 15])
raw_data += 15
while True :
again = input("Do you want to see more 15 lines of raw data? Please type Yes or No : ").lower()
if again not in ['yes', 'no']:
print('\nInvalid answer!\n')
continue
elif again == 'yes':
print(df.iloc[raw_data : raw_data + 15])
raw_data += 15
else:
break
break
else:
break
except Exception as e:
print('An exception has been occurred while displaying raw data : {}'.format(e))
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, city)
station_stats(df, city)
trip_duration_stats(df, city)
user_stats(df,city)
display_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main() |
2a08949e93681d7e2d36812e1f617172696396b2 | IvanRado/AI | /LinearRegression/systolic.py | 1,148 | 3.78125 | 4 | if __name__ == "__main__":
# Example computing systolic blood pressure from age and weight
# The data (x1, x2, x3) are for each patient
# x1 is the systolic blood pressure
# x2 is the age in years
# x3 is the weight in pounds
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('mlr02.xls')
X = df.as_matrix()
# Visualize x1 vs x2
plt.scatter(X[:,1], X[:,0])
plt.show()
# Visualize x1 vs x3
plt.scatter(X[:,2], X[:,0])
plt.show()
# Add bias term
df['ones'] = 1
Y = df['X1']
X = df[['X2', 'X3', 'ones']]
# Consider three cases: x2 only, x3 only, x2 and x3. Compare the R^2 values
X2only = df[['X2', 'ones']]
X3only = df[['X3', 'ones']]
def calc_r2(X, Y):
w = np.linalg.solve(X.T.dot(X), X.T.dot(Y))
yhat = X.dot(w)
ss_res = np.sum((Y-yhat)**2)
ss_total = np.sum((Y-Y.mean())**2)
r2 = 1 - ss_res/ss_total
return r2
print("R2 for x2 only:", calc_r2(X2only, Y))
print("R2 for x3 only:", calc_r2(X3only, Y))
print("R2 for x2 and x3:", calc_r2(X, Y)) |
88f69835ee782f7489758cd4a2e07887eab2e2b9 | SACHSTech/livehack-1-python-basics-BrianLi15 | /problem1.py | 598 | 4.625 | 5 | ----------------------------------------------------------------------
Name: problem1.py
Purpose:
Given the user input of celsius, it can convert the celsius temperature to fahrenheit
Author: Li.B
Created: 07/12/2020
----------------------------------------------------------------------
#This gets the user input for celsius
celsius_input = float(input("What is the temperature in celsius?: "))
#This converts celsius to fahrenheit
fahrenheit = (celsius_input * 9/5) + 32
#This prints out the temperature in fahrenheit
print("This is your temperature in fahrenheit: " + str(fahrenheit)) |
4d009a61f55252eb2414efdf12f721eba62ee8e4 | kateleecheng/Python-for-Everybody-Specialization | /2_Python Data Structures/Week_4_Class2.py | 517 | 3.578125 | 4 | #Week_4_Class2.py
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)
print(a)
t=[9,41,12,3,74,15]
print(t[1:3]) # up to but not including!!
print(t[:4])
print(t[3:])
print(t[:])
stuff=list() #list with nothing
stuff.append('book')
stuff.append(99)
print(stuff)
stuff.append('cookie')
print(stuff)
friends=['Joseph','Glenn','Sally']
friends.sort()
print(friends)
print(friends[1])
nums=[3,41,12,9,74,15]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
print(sum(nums)/len(nums))
|
29dfe80b2342dce80aae715e71acce4c2d66769f | benedictuttley/CM1101-Project | /game.py | 1,944 | 4.21875 | 4 | #This is the main game engine
# prints current room (example : print_room(rooms["Room1"])
def print_room(room):
print()
print(room["name"].upper())
print()
print(room["description"])
print()
# takes a dictionary of exits and a direction returns the name of the exit it leads to
# example ( exit_leads_to(rooms["Room1"]["exits"], "south"))
def exit_leads_to(exits, direction):
return rooms[exits[direction]]["name"]
# prints a line of a menu of exits. arguments are the name of the exit and the
# name of the room it leads to. example ("east","Room2")
def print_exit(direction, leads_to):
print("GO " + direction.upper() + " to " + leads_to + ".")
# prints actions available to the player (add actions)
def print_menu(exits):
print("You can:")
for direction in exits:
print_exit(direction, exit_leads_to(exits, direction))
print("What do you want to do?")
# checks if the exit is valid returns True if valid else False
# example: is_valid_exit(rooms["room1"]["exits"], "north") == True
def is_valid_exit(exits, chosen_exit):
return chosen_exit in exits
# updates the current room based on the direction (example execut_go("east"))
def execute_go(direction):
global current_room
if direction in current_room["exits"].keys():
new_position = current_room["exits"][direction]
current_room = rooms[new_position]
print(rooms[new_position]["name"])
else:
print("You cannot go there.")
# prints the menu of actions using print_menu() function.
#It then prompts the player to type an action. (add actions)
def menu(exits):
print_menu(exits)
user_input = input("> ")
normalised_user_input = normalise_input(user_input)
return normalised_user_input
# returns the room the player will move in.
#example (move(rooms["Room1"]["exits"], "north")---> rooms["Room4"])
def move(exits, direction):
return rooms[exits[direction]]
|
93fa43b7deb4ad79e0e1ff8ba3b84fb3609f3e32 | benbendaisy/CommunicationCodes | /python_module/examples/881_Boats_to_Save_People.py | 1,131 | 3.96875 | 4 | from typing import List
class Solution:
"""
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
"""
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
l, r = 0, len(people) - 1
boats = 0
while l < r:
if people[l] + people[r] <= limit:
l, r = l + 1, r - 1
else:
r -= 1
boats += 1
return boats |
6400fad3abb28af292e4898d793f32449ea3a5da | WirKekc/prject1 | /stepik.org/stringIn.py | 221 | 3.546875 | 4 | a = input()
b = input()
s = set()
if a.find(b) == -1:
print(a.find(b))
else:
for i in range(len(a)):
if a.find(b,i) != -1:
s.add(a.find(b, i))
s = sorted(list(s))
print(*s, sep=" ")
|
f7639f508f734bc21e58fa27b134618cdf88e724 | Naimulnobel/uri-online-judge | /problem8.py | 216 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 31 15:23:55 2019
@author: Student Mct
"""
a=input('Employee Number ')
b=input()
c=input()
amount=int(b)*float(c)
print('NUMBER =',a)
print('SALARY = U$',amount) |
83207c6c395fb6864dbe9b48add827620166ace9 | Unit26/EpicPython | /23_get_parity.py | 171 | 3.859375 | 4 | def fun(x):
if x % 2 == 0:
return ' чётное '
else:
return ' нечётное '
x = int(input('Введите число: '))
print(fun(x))
|
79b5b843ea30a444569f75af0b5fd848be9d294e | vinija/LeetCode | /81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.py | 696 | 3.5625 | 4 | class Solution:
def search(self, nums: List[int], target: int) -> bool:
start = 0
end = len(nums) -1
while start <= end:
mid = (start + end)//2
if target in [nums[mid], nums[start], nums[end]]:
return True
elif nums[mid] == nums[start] or nums[mid] == nums[end]:
end -=1
start +=1
elif nums[start]<=nums[mid]:
if nums[start]<target<nums[mid]: end=mid-1
else: start=mid+1
else:
if nums[mid]<target<nums[end]: start=mid+1
else: end=mid-1
return False |
936324de85562d3841be2253c56c52088602f22a | Quarantinex/Hackerrank_Python_Algorithm | /Repeated_Sting.py | 164 | 3.671875 | 4 | def repeatedString(s, n):
x,y = divmod(n,len(s))
return s[:y].count("a")*(x+1) + s[y:].count("a")*x
s = input()
n = int(input())
print(repeatedString(s, n)) |
bc3061ba4c5af24e3923d20fec9fb1ec15539d9c | meltemtokgoz/Sentence-Or-Not-Context-free-grammar | /code/assignment3.py | 5,380 | 3.640625 | 4 | import random
# find necessary comment line number
def find_line_num(path):
start_vocab = 0
start_rule = 0
with open(path) as f:
for line in f:
start_vocab += 1
if '# Vocabulary. There is no rule for rewriting the terminals.' in line:
break
with open(path) as f:
for line in f:
start_rule += 1
if '# Pronoun = Pronoun ' in line:
break
return start_vocab, start_rule
# word_dict = { 'word' : 'word_type'} example : {'ate': 'Verb', 'floor' : 'Noun'}
def word_and_type_dict(path,start_vocab):
word_dict = {}
word_list =[]
with open(path) as f:
line_num = 0
for line in f:
line_num += 1
if line_num > start_vocab:
if line != "\n":
token = line.strip().split()
word_dict[token[1]] = token[0]
word_list.append(token[1])
return word_dict, word_list
# rule_dict = {'NP VP': 'S', 'Verb NP': 'VP' ...}
def rules(path, start_vocab, start_rule):
rule_dict ={}
with open(path) as f:
line_num = 0
for line in f:
line_num += 1
if line_num > start_rule:
if line_num < start_vocab:
if line != "\n":
token = line.strip().split()
first_part = token[0]
second_part = ""
x = 0
for i in token[1:]:
x += 1
if x < len(token)-1:
second_part = second_part + i + " "
else:
second_part = second_part + i
rule_dict[second_part] = first_part
return rule_dict
# generate random sentence function
def random_sentence(sent_count, sent_length, word_list):
out_file = open("output.txt", "w")
for x in range(sent_count):
sentence = ""
for i in range(sent_length):
new_word = random.choice(word_list)
sentence = sentence + new_word + " "
out_file.write(sentence+"\n")
out_file.close()
# cyk parser algorithm
def cyk_parser(c_r, c_c, matrix, sentence, rule_dict, word_dict, sent_len):
token = sentence.strip().split()
if (c_r + c_c) <= (sent_len-1):
if c_r == 0:
matrix[c_r][c_c].append(word_dict[token[c_c]])
if word_dict[token[c_c]] in rule_dict.keys():
matrix[c_r][c_c].append(rule_dict[word_dict[token[c_c]]])
else:
temp_c = c_c
temp_r = c_r
for i in range(c_r):
if temp_c + temp_r <= len(sentence)-1:
if len(matrix[i][c_c]) != 0:
for temp_word_1 in matrix[i][c_c]:
first_item = temp_word_1
if len(matrix[temp_r-1][temp_c+1]) != 0:
for temp_word_2 in matrix[temp_r-1][temp_c+1]:
second_item = temp_word_2
temp_pair = first_item+" "+second_item
if temp_pair in rule_dict.keys():
matrix[c_r][c_c].append(rule_dict[temp_pair])
temp_c += 1
temp_r -= 1
if c_r == len(matrix)-1:
true_or_false = 0
for temp_word_3 in matrix[c_r][c_c]:
if temp_word_3 == 'S':
true_or_false += 1
break
print(sentence.strip())
if true_or_false > 0:
print("Result : It's a grammatically correct sentence.")
else:
print("Result : It's not a grammatically correct sentence.")
return matrix
def main():
# read the input file
path = "cfg.gr"
start_vocab, start_rule = find_line_num(path)
# created dictionary to word and rule
word_dict, word_list = word_and_type_dict(path, start_vocab)
rule_dict = rules(path, start_vocab, start_rule)
# parameter sentence length and count
sent_length = 5
sent_count = 2
# generated sentence
random_sentence(sent_count, sent_length, word_list)
# read the output file and call cyk parser function to all sentences
with open("output.txt") as f:
for line in f:
if line != "\n":
matrix = [[[] for x in range(sent_length)] for y in range(sent_length)]
len_s = len(line.strip().split())
print("-----------------------------------------------")
for current_row in range(len_s):
for current_column in range(len_s):
matrix = cyk_parser(current_row, current_column, matrix, line, rule_dict, word_dict, len_s)
# prints cyk table if you want to see
'''
k = sent_length-1
while k >= 0:
if k == 0:
print(matrix[k])
else:
print(matrix[k][0:(sent_length-k)])
k -= 1
'''
if __name__ == '__main__':
main() |
ced3c790c3d8d19a451c078e57db8da76d3b2a50 | paigetruelove/AirOvalCode | /graph_maker.py | 5,558 | 4.03125 | 4 | import pandas as pd
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import datetime
import matplotlib.dates as mdates
def getdata(daysToGet):
"""
This function imports the CSV file which contains the sensor data, and selects a specified data timeframe to create a graph.
daysToGet -- This argument specifies the number of days to retrieve data (i.e 1 would get you yesterdays data).
The timeframe has been specified as being midnight to midnight (i.e. 0,0,0).
"""
# Importing the CSV file which contains the PM data
print(datetime.datetime.now())
print("Importing CSV")
publishData = pd.read_csv("~/Desktop/home_air_qual_publishdata.csv", parse_dates=["datetime"])
# Sense check - making sure any data which is over 100 is dropped (to avoid publishing/Tweeting sensor errors etc.)
publishData = publishData[publishData["pmten"] <100]
publishData = publishData[publishData["pmtwofive"] <100]
# Gets the data from the specified time window i.e. how many days back you want to go (e.g. 1 or 7)
print("Calculating dates")
midnight = datetime.time(0,0,0)
startdate = datetime.datetime.now() - datetime.timedelta(days=daysToGet)
windowstart = datetime.datetime.combine(startdate.date(), midnight)
windowend = windowstart + datetime.timedelta(days=daysToGet)
plotPublishData = publishData[publishData["datetime"] > windowstart]
plotPublishData = plotPublishData[plotPublishData["datetime"] < windowend]
# Creates graph based on yesterdays days (i.e 1 day ago)
if (daysToGet == 1):
createdailygraph(windowstart, plotPublishData)
# Creates graph based on the last week of data (i.e 7 days ago)
if (daysToGet == 7):
createweeklygraph(windowstart, windowend, plotPublishData)
def createdailygraph(windowstart, plotDailyData):
"""
This function creates a daily graph using yesterday's recorded data.
windowstart -- This argument is the beginning of the timeframe.
plotDailyData -- This is the dataframe to be plotted.
"""
# States which style to plot graphs in
plt.style.use('dark_background')
print("Creating plot")
fig, ax = plt.subplots(2)
fig.suptitle("Moving Average (MA) Daily Particulate Matter Concentration: " + windowstart.strftime("%d/%m/%Y"))
# Specifying how many points the moving average (ma) moves in
ma = 50
plotDailyData = plotDailyData.set_index(pd.DatetimeIndex(plotDailyData["datetime"]))
# Subgraph 1 (PM 10 Graph)
ax[0].plot(plotDailyData.index, plotDailyData["pmten"].rolling(ma).mean(), color="orange")
# Adding/Manipulating graph labels
ax[0].set(ylabel="µg/m3")
ax[0].axes.xaxis.set_ticklabels([]) # This hides the x labels on the first graph to avoid overlapping
ax[0].legend(["PM 10", "PM 10 MA"], bbox_to_anchor=(1.3, 0.5))
# Subgraph 2 (PM 2.5 Graph)
ax[1].plot(plotDailyData.index, plotDailyData["pmtwofive"].rolling(ma).mean(), color="lightblue")
# Adding/manipulating graph labels
ax[1].xaxis.set_major_formatter(mdates.DateFormatter('%H:00')) # Formatting the x label to show hours in 24 hour format
ax[1].set(xlabel="Hour (24)", ylabel="µg/m3")
labels1 = ax[1].get_xticklabels()
plt.setp(labels1, rotation=45, horizontalalignment='right')
ax[1].legend(["PM 2.5", "PM 2.5 MA"], bbox_to_anchor=(1.3, 0.5))
# Saving a png file of the graph
fig.savefig("dailymagraph.png", dpi=200, bbox_inches="tight")
def createweeklygraph(windowstart, windowend, plotWeeklyData):
"""
This function creates a weekly graph using the previous week's recorded data.
windowstart -- This argument is the beginning of the timeframe.
windowend -- This argument is the end of the timeframe.
plotWeeklyData -- This is the dataframe to be plotted.
"""
# States which style to plot graphs in
plt.style.use('dark_background')
fig, ax = plt.subplots(2)
fig.suptitle("Moving Average (MA) Weekly Particulate Matter Concentration: " + windowstart.strftime("%d/%m/%Y - ") + windowend.strftime("%d/%m/%Y"))
# Specifying how many points the moving average (ma) moves in
ma = 200
plotWeeklyData = plotWeeklyData.set_index(pd.DatetimeIndex(plotWeeklyData["datetime"]))
# Subgraph 1 (PM 10 Graph)
ax[0].plot(plotWeeklyData.index, plotWeeklyData["pmten"], color="orange", alpha=0.7)
ax[0].plot(plotWeeklyData.index, plotWeeklyData["pmten"].rolling(ma).mean(), color="white")
# Adding/manipulating graph labels
ax[0].set(ylabel="µg/m3")
ax[0].axes.xaxis.set_ticklabels([]) # This hides the x labels on the first graph to avoid overlapping
ax[0].legend(["PM 10", "PM 10 MA"], bbox_to_anchor=(1.3, 0.5))
# Subgraph 2 (PM 2.5 Graph)
ax[1].plot(plotWeeklyData.index, plotWeeklyData["pmtwofive"], color="lightblue", alpha=0.7)
ax[1].plot(plotWeeklyData.index, plotWeeklyData["pmtwofive"].rolling(ma).mean(), color="white")
# Adding/manipulating graph labels
ax[1].set(xlabel="Day", ylabel="µg/m3")
labels1 = ax[1].get_xticklabels()
ax[1].xaxis.set_major_formatter(mdates.DateFormatter('%a')) # Formating date to show day in abbreviated format (i.e. Mon, Tue...)
plt.setp(labels1, rotation=45, horizontalalignment='right')
ax[1].legend(["PM 2.5", "PM 2.5 MA"], bbox_to_anchor=(1.3, 0.5))
# Saving a png file of the graph
fig.savefig("weeklygraphwithma.png", dpi=200, bbox_inches="tight") |
1e8137947f4de94f5fde222e3f09154cea837880 | Computational-Physics-Research/Computational-Physics-1 | /PythonProgramming/Homework 08/wood_10.2.py | 1,038 | 3.828125 | 4 | """
Problem 2
Hypersphere Volume
"""
import numpy as np
import numpy.random as ran
import matplotlib.pyplot as plt
# main function definition
def multisphere_volume(n_dims, n_samples, radius = 1):
# initialize some working params
n_iter = 0
points = 0
while n_iter < n_samples:
# generate random point in space & inc. iteration count
r_list = ran.random(n_dims)
n_iter += 1
# add point if inside sphere
if np.sum(r_list**2) < 1:
points += 1
return 2**n_dims/n_iter*points
# function calling & plotting
dim_list = [i for i in range(1, 11)]
vol_list = [multisphere_volume(dim, 100000) for dim in dim_list]
plt.plot(dim_list, vol_list)
plt.title("Volumes of Multidimensional Spheres (r = 1)")
plt.xlim(0,11)
plt.ylim(0,6)
plt.xlabel("Number of Dimensions")
plt.ylabel("Volume")
plt.show()
# printing everything
for dim, vol in zip(dim_list, vol_list):
print(f"{dim}-dimensions")
print(f"calculated volume: {vol:0.3f}\n")
|
83127d3519a1e00413bcb56a3034c348337ad522 | JohnKearney2020/python | /class.py | 928 | 4.25 | 4 | #print("I\'m a string")
#concatinating
#print("Hello" + " world")
#escape symbols
# print('I\'m a string')
# print('I\'m a \t\t\t\t string')
# print('I\'m a \v\v\v\v string')
#print("hello \nworld")
# name = "John"
# lname = "Kearney"
# output = "Good morning {student1} {student2}".format(student1=name,student2=lname)
# print(output)
#f strings - these are the newer standard
# student1 = "John"
# student2 = "Diego"
# output = f'hello world {student1} {student2}'
#print(output)
# print(type(student1))
# test = "5"
# print(isinstance(test, int))
# consolelog = input("Enter your name: ")
# output = f'Hello {consolelog}.'
# dataType = str(type(consolelog))
# print(output + "The data type is: " + dataType)
input_number_from_user = input("Insert a number: ")
print(type(input_number_from_user))
casted_output = int(input_number_from_user)
print(type(casted_output))
some_math = casted_output * 7
print(some_math) |
0800ff57bb7170cb49ac6546fbbc64bba5ce2fe3 | DanielMartinez79/Algorithms | /AlgLab1F.py | 3,871 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 19:02:37 2017
@author: Danny
This lab compares the average and worst case performance of linear and binary search
"""
import random
import time
import math
#linear search
def linear(arr, key):
for x in range(0, len(arr)):
if (arr[x] == key):
#print("Found!")
return
#print ("Not found!")
return
#binary search
def bins(start,end,key,arr):
#gets middle element
mid = (end - start)/2 + start
mid = int(mid)
#subarray is larger than 1
if (end > start):
#middle element is key
if (key == arr[mid]):
#print("Found!")
return
#key is larger than middle element
elif (key > arr[mid]):
#search 2nd half of array
bins(mid +1, end, key, arr)
#key is smaller than middle element, so search 1st half of array
else: bins (start, mid-1, key, arr)
#subarray is size 1
else:
#single element is the key
if (arr[start] == key):
#print("Found!")
return
#else: print("Not in the array!")
mylist =[] #new list
number = input("Enter a number: ") #number of elements in the list
number = int(number) #casting to int
for x in range(0,number):
mylist.append(random.randint(-1000,1001)) # adding random numbers to list
mylist = sorted(mylist) #sort list
print("Part A: Calculating average time of linear and binary search")
loop = 500 #number of times to execute loop
start = time.time()
for x in range(0,loop):#perform linear search 500 times
linear(mylist,random.randint(-1000,1001)) #search for a random element
end = time.time()
timer1 = (end-start)/loop #average time it took for 1 linear search
print("Average running time of linear search: ", timer1)
avg1 = timer1/number #time of 1 instruction
#same process as above with binary search
start = time.time()
for x in range(0,loop):
bins(0, len(mylist)-1,random.randint(-1000,1001),mylist)
end = time.time()
timer2 = (end - start)/loop #average time of 1 binary search
print("Average running time of binary search: ", timer2)
avg2 = timer2/math.log(number, 2) #time of 1 instruction
avg = (avg1+ avg2)/2 #average time of 1 instruction
print("\nPart B: Calcutlating worst case time of linear and binary search")
mylist =[] #clearing list
notInList = 50000 # a number that is not in the list
for x in range(0,10000): #inserting 10000 elements into list
mylist.append(random.randint(-1000,1001))
mylist = sorted(mylist) #sort list
print("Worst case linear when n = 10^5")
start = time.time()
for x in range(0,loop):
linear(mylist,notInList)#searching for a number that is not in the list
end = time.time()
print((end - start)/loop) #average time of 1 worst case linear search
#same process as above with binary search
print("Worst case binary when n = 10^5")
start = time.time()
for x in range(0,loop):
bins(0, len(mylist)-1,notInList,mylist)
end = time.time()
print((end - start)/loop)
count = 1000000 #number of elements in list
wclin = (avg*count) #worst case linear search with 10^6 elements
print("\nEstimated worst-case linear when n = 10^6: ", wclin)
wcbin = (avg*math.log(count,2)) #worst case binary search with 10^6 elements
print("Estimated worst-case binary when n = 10^6: ", wcbin)
mylist = [] #clear list
for x in range(0,count):
mylist.append(random.randint(-1000,1001))
mylist = sorted(mylist)
#same process as before with 10^6 elements
print("\nWorst case linear when n = 10^6")
start = time.time()
for x in range(0,loop):
linear(mylist,notInList)
end = time.time()
print((end - start)/loop)
print("Worst case binary when n = 10^6")
start = time.time()
for x in range(0,loop):
bins(0, len(mylist)-1,notInList,mylist)
end = time.time()
print((end - start)/loop) |
9096b7a3e5687e4fe126743e84b588d0449fd1f4 | julienemo/exo_headfirst | /2-phraseomatic.py | 1,121 | 3.71875 | 4 | # this program generates random phrases structured as
# verb+adj+noun
# where each part is chosen randomly from their given list
import random
# import the fonction that otherwise in not
# automatically include
# then the three lists
# NB Atom encourages putting both brackets alone
# instead of on the same row as content
# NB also Atom prefers white space around operators
verbs = [
'Leverage', 'Sync', 'Target', 'Gamify', 'Offline', 'Crowd-sourced',
'24/7', 'Sync', 'Target', 'Gamify',
'Offline', 'Crowd-sourced', '24/7', 'Lean-in', '30,000 foot'
]
adjectives = [
'A/B Tested', 'Freemium', 'Hyperlocal', 'Siloed', 'B-to-B',
'Oriented', 'Cloud-based', 'API-based'
]
nouns = [
'Early Adopter', 'Low-hanging Fruit', 'Pipeline', 'Splash Page',
'Productivity', 'Process', 'Tipping Point', 'Paradigm'
]
# randomly choose an element from each list
# this later can be rolled in a loop
# but is it worth the effort for only three
# hmmm...
verb = random.choice(verbs)
adjective = random.choice(adjectives)
noun = random.choice(nouns)
print(verb + ' ' + adjective + ' ' + noun)
|
851d71b875500739081a505d0f404e3364013c5c | sreedhar9999/python-first | /lagnum.py | 118 | 3.890625 | 4 | x=int(raw_input())
y=int(raw_input())
z=int(raw_input())
if(x>y>z):
print(x )
elif(y>x>z):
print(y)
else:
print(z)
|
169e82d04d9086d2f3f1195bb04d16830fe28d02 | gclegg4201/python | /input3_while.py | 153 | 4.09375 | 4 | print("INPUT THREE NUMBERS")
a=float(input('A:'))
b=float(input('B:'))
c=float(input('C:'))
x=0
while True:
y=a*x*x+b*x+c
print("x =",x,"y =",y)
x+=1
|
40775417e7ba92bfa3c083c2e3d495390c5724e7 | Aasthaengg/IBMdataset | /Python_codes/p03080/s133965546.py | 266 | 3.6875 | 4 | def main():
_ = int(input())
s = input().rstrip()
r, b = 0, 0
for c in s:
if c == "R":
r += 1
else:
b += 1
if r > b:
print("Yes")
else:
print("No")
if __name__ == "__main__":
main() |
f8a8da2c8b2162cb5b629083e023211c4c504773 | FaizIkhwan/Competitive-Programming | /Al-Khawarizmi/2014/h.py | 199 | 3.640625 | 4 | t = int(input())
for i in range(t):
inp = str(input())
if list(inp) == list(reversed(inp)):
print('Case #{}: Yes'.format(i+1))
else:
print('Case #{}: No'.format(i+1))
|
24a8d2229edae8f55ec33137112200bb334815bc | Ydeh22/CRPM | /crpm/quantilenorm.py | 588 | 3.796875 | 4 | """ quantile normalize matricies by rows """
def quantilenorm(matrixlist):
""" normalizes matricies to have corresponding rows with similar distributions
Args:
matrixlist: a list of 2D array-like objects all with same number of rows.
Returns:
A matrix list of the transformed original matricies.
"""
# - check input -
#assert input is a list
if not isinstance(matrixlist, list):
print("Error quantilenorm: input is not a list")
return None
#assert elements of list are arraylike
for elem in
return matrixlist
|
e3566deed8917f4354670b3e2ef5d999d5ab12fa | chinmairam/Python | /regex14.py | 756 | 3.8125 | 4 | import re
print(re.search(r"[a-zA-Z]{5}", "a ghost"))
print(re.search(r"[a-zA-Z]{5}", "a scary ghost appeared"))
print(re.findall(r"[a-zA-Z]{5}", "a scary ghost appeared"))
print(re.findall(r"\b[a-zA-Z]{5}\b", "A scary ghost appeared"))
print(re.findall(r"\w{5,10}", "I really like strawberries"))
print(re.findall(r"\w{5,}", "I really like strawberries"))
print(re.search(r"s\w{,20}", "I really like strawberries"))
def long_words(text):
pattern = r"\w{7,}"
result = re.findall(pattern, text)
return result
print(long_words("I like to drink coffee in the morning.")) # ['morning']
print(long_words("I also have a taste for hot chocolate in the afternoon.")) # ['chocolate', 'afternoon']
print(long_words("I never drink tea late at night.")) # []
|
46cf731f6d28256f3e52114b23946d529a116400 | jems-lee/adventofcode | /2019/day03.py | 2,923 | 3.734375 | 4 | from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def __add__(self, other):
return Point(
self.x + other.x,
self.y + other.y
)
def __sub__(self, other):
return Point(
self.x - other.x,
self.y - other.y
)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def manhatten_distance(self, other):
new = self - other
return abs(new.x) + abs(new.y)
def read_file_as_string(file_name="data03.txt"):
with open(file_name) as datafile:
data = datafile.read()
return data
def split_string_into_list_of_tuples(one_wire_string):
wire = [(x[0], int(x[1:])) for x in one_wire_string.split(',')]
return wire
def create_grid(m, n):
grid = [
[[0, 0] for i in range(n)] for j in range(m)
]
return grid
def expand_path(path_tuples, grid, path_num=0):
m = len(grid)
n = len(grid[1])
intersections = []
path = list()
path.append(Point(0, 0))
step = 0
for (direction, magnitude) in path_tuples:
for i in range(magnitude):
previous_point = path[-1]
if direction == "R":
point_change = Point(x=1, y=0)
elif direction == "U":
point_change = Point(x=0, y=1)
elif direction == "L":
point_change = Point(x=-1, y=0)
elif direction == "D":
point_change = Point(x=0, y=-1)
else:
raise IndexError(f"Not R, U, L, or D, it was {direction}")
new_point = previous_point + point_change
grid_point = grid[m // 2 + new_point.y][n // 2 + new_point.x]
step += 1
grid_point[path_num] = step
if grid_point[0] != 0 and grid_point[1] != 0:
# print(f"grid point: {grid_point}")
intersections.append(Point(grid_point[0], grid_point[1]))
path.append(new_point)
return grid, intersections
def main():
data = read_file_as_string("data03.txt")
both_wires = data.split()
wire1 = split_string_into_list_of_tuples(both_wires[0])
wire2 = split_string_into_list_of_tuples(both_wires[1])
grid = create_grid(10000, 10000)
grid, intersections = expand_path(wire1, grid, path_num=0)
print(f"intersections after 1: {intersections}")
grid, intersections = expand_path(wire2, grid, path_num=1)
print(f"intersections after 2: {intersections}")
print(min([point.manhatten_distance(Point(0, 0)) for point in intersections]))
# grid, intersections = expand_path_on_grid(grid, path1)
# print(intersections)
# grid, intersections = expand_path_on_grid(grid, path2)
# print(intersections)
# intersections = find_intersections(path1, path2)
# print(intersections)
if __name__ == "__main__":
main()
|
237d12a50601b6a5438d63ea9ccb0cbd3de8ff3b | sohom-das/Python-Practice | /LPTHW - Ex17.py | 1,122 | 3.6875 | 4 | from sys import * #importing function from the sys module
from os.path import * #importing function from os.path module
script, from_file, to_file = argv #get argv command line arguments (when executing the file) and assigning it three variables
in_file = open(from_file).read() #Opening the file, from where data will be copied. And storing the data in a variable
print(f"The input file is {len(in_file)} bytes long") #printing the length of the file
print(f"Does the file exists: {exists(to_file)}") #using the exists function, to chech whether the file exists or not.
out_file = open(to_file, 'w') #opening destination file in write mode
out_file.write(in_file) #coping all the data stored in the variable *data*
print("Alright all done!")
out_file.close() #finally, closing the file
|
fa2856baf58fe22a47c900bba3bd85b5867d0deb | polku/python_stuff | /timeout.py | 935 | 3.625 | 4 | #!/usr/bin/python3
"""
Mechanism to timeout if a function takes too much time
"""
import random
import signal
import time
from functools import wraps
class TimeoutException(Exception):
pass
def sig_handler(signum, frame):
raise TimeoutException()
def timeout(delay):
def timeout_sec(func):
@wraps(func)
def wrapper(*args, **kwargs):
signal.setitimer(signal.ITIMER_REAL, delay)
return func(*args, **kwargs)
return wrapper
return timeout_sec
@timeout(5)
def my_function():
x = random.randint(1, 10)
print('Will sleep for {} seconds'.format(x))
time.sleep(x)
def main():
signal.signal(signal.SIGALRM, sig_handler)
while True:
try:
my_function()
print(' Function finished.')
except TimeoutException:
print(' Function too long. Interrupting.')
if __name__ == '__main__':
main()
|
07e157319c6c33c155fb096996d0514c365128d8 | kahlb/btce_calcs | /btce_portfolio.py | 1,475 | 4.03125 | 4 | #!/usr/bin/env python2.7
# this software calculates the current value of your portfolio
# author kahlb, ltc donations welcome :) LSRLVCerfwbAxBEyZJ4JtcZPdVwxc4zWs2
fee=0.2
feecalc=1-(fee/100) #makes the fee easier to calc. Just multiply with this value.
currnumber = input("Enter the number of different currencies in your portfolio: ")
# This contains the list of the currencies which will be calculated:
currlist = []
# This contains the prices to the currencies. It's always a pair, so pricelist[1] belongs to currlist[1]:
pricelist = []
# This reads the amount of currencies, for as many currencies as given in currnumber:
for n in range(currnumber):
currlist.append(input("Enter the amout of currency {} in your portfolio: ".format(n+1)))
# Does the same as above, but reads the prices.
for n in range(currnumber):
pricelist.append(input("Enter the price of currency {} to Bitcoin: ".format(n+1)))
btcprice = input("Enter the current Bitcoin Price: ") # Reads price for bitcoin. No currency specified by intention.
portfolio = 0
# This calculates the value of the portfolio in bitcoin, considering the fees for every necessary transaction.
for n in range(currnumber):
portfolio = portfolio+(currlist[n]*pricelist[n]*feecalc)
capital = portfolio*btcprice*feecalc # This converts the bitcoins into another currency (USD, EUR, RUR or whatever you like)
print(portfolio)
print('Your portfolio is worth {} (when transaction fee is {} percent)'.format(capital, fee))
|
d7483fee3f38bcff15ab34d1f5768479f22605c6 | iGoWithYou/Laboratories | /lab1.1.py | 269 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 16:01:09 2019
@author: Mati
"""
from math import*
x = 56
z = 0
while x <= 100:
y = 2*(x**2) + 2*x + 2
print('for x = ',x,'function value y = ',y)
x = x+1;
z = z + y;
print('function y total value = ',z) |
0f934c3c6a3429ae1b044ebc04c3e64dcba83c64 | fikrirazor/bigramindo | /tesbigram/testbigram2.py | 611 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 23:44:06 2019
@author: Rozan
"""
#countofwords
#menghitung jumlah kata
W = ("saya","makan","nasi","goreng","di","rumah")
jumlahdata = {}
pw=len(W)
for i in range (pw):
if W[i] in jumlahdata:
jumlahdata[W[i]] += 1
else:
jumlahdata[W[i]] = 1
#menghitung jumlah kata 2
from collections import Counter
counts = Counter(W)
print(counts)
#menghitung jumlah kata 3
def countWords(A):
dic={}
for i in A:
if not i in dic:
dic[i] = A.count(i)
return dic
dic = countWords(W)
sorted_items=sorted(dic.items())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.