blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a0690ab38ff550e8c49c2d2c16c189acc0650e72 | ptdk1020/PasswordStrength | /scripts/feature_maps.py | 3,103 | 3.765625 | 4 | """This file contains feature extracting and data enrichment functions"""
import string
from zxcvbn import zxcvbn
def length(password):
return len(password)
def num_lowercase(password):
"""Count the number of lower case letter"""
lower_alphabet = string.ascii_lowercase
count = 0
for letter in password:
if letter in lower_alphabet:
count += 1
return count
def num_uppercase(password):
"""Count the number of upper case letter"""
upper_alphabet = string.ascii_uppercase
count = 0
for letter in password:
if letter in upper_alphabet:
count += 1
return count
def num_digits(password):
"""Count the number of digits"""
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
count = 0
for letter in password:
if letter in digits:
count += 1
return count
def num_specials(password):
"""Count the number of special characters"""
return len(password)-num_lowercase(password)-num_uppercase(password)-num_digits(password)
def first_lower(password):
"""returns 1 first letter is a lowercase letter, 0 otherwise"""
lower_alphabet = string.ascii_lowercase
if password[0] in lower_alphabet:
return 1
else:
return 0
def first_upper(password):
"""returns 1 first letter is an uppercase letter, 0 otherwise"""
upper_alphabet = string.ascii_uppercase
if password[0] in upper_alphabet:
return 1
else:
return 0
def first_digit(password):
"""returns 1 first letter is a digit, 0 otherwise"""
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if password[0] in digits:
return 1
else:
return 0
def first_special(password):
"""returns 1 first letter is a special character, 0 otherwise"""
if first_lower(password) == 0 and first_upper(password) == 0 and first_digit(password) == 0:
return 1
else:
return 0
def last_lower(password):
"""returns 1 last letter is a lowercase letter, 0 otherwise"""
lower_alphabet = string.ascii_lowercase
if password[-1] in lower_alphabet:
return 1
else:
return 0
def last_upper(password):
"""returns 1 last letter is an uppercase letter, 0 otherwise"""
upper_alphabet = string.ascii_uppercase
if password[-1] in upper_alphabet:
return 1
else:
return 0
def last_digit(password):
"""returns 1 last letter is a digit, 0 otherwise"""
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if password[-1] in digits:
return 1
else:
return 0
def last_special(password):
"""returns 1 last letter is a special character, 0 otherwise"""
if last_lower(password) == 0 and last_upper(password) == 0 and last_digit(password) == 0:
return 1
else:
return 0
def zxcvbn_score(password):
"""returns the zxcvbn score"""
return zxcvbn(password)['score']
def unique_chars(password):
"""returns the number of unique characters in the string"""
return len(set(password))
|
b1af5a819fec8f7af33372db4917f731076ac37e | z1223343/Leetcode-Exercise | /014_435_Non-overlappingIntervals.py | 1,669 | 3.984375 | 4 | """
5 level solutions:
1. brute force. It takes me half a day to understand
2. DP (using starting points)
3. DP (using ending points)
4. Greedy Algorithm (starting points)
5. Greedy Algorithm (ending points)
1. time O(2**n) space O(n)
2. time O(n**2) space O(n)
3. time O(n**2) space O(n)
4. time O(nlogn) space O(1)
5. time O(nlogn) space O(1)
"""
"""
About Greedy Algorithm:
The idea of greedy algorithm is to pick the locally optimal move at each step, that will lead to the globally optimal solution.
"""
# Greedy Approach (sort starting points)
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key=lambda x:x[0])
result = 0 # 这个result是舍弃的数量,即需要删除的数量
prev = None
for curr in intervals:
if prev and prev[1]>curr[0]:
result += 1
if prev[1]>curr[1]:
prev = curr
else:
prev = curr
return result
# Greedy Approach (sort ending points)
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key=lambda x:x[1])
result = 0
prev = None
for curr in intervals:
if (not prev) or prev[1] <= curr[0]:
result += 1 # result means 保留
prev = curr
return len(intervals) - result
"""
此题leetCode解答撰写者是个棒槌。不要细看。理解思路就好。
""" |
92d782d7fc8227c42c4d17be5f5f399f1a681943 | garderobin/Leetcode | /leetcode_python2/lc221_maximal_square.py | 1,897 | 3.5625 | 4 | # coding=utf-8
from abc import ABCMeta, abstractmethod
class MaximalSquare:
__metaclass__ = ABCMeta
@abstractmethod
def maximal_square(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
class MaximalSquareImplRotateArray(MaximalSquare):
"""
DP巧思:连续的and条件想想是否可以转化为min, 连续的or条件想想是否可以转化为max
这种滚动数组的构造方式,非常适合矩阵DP某个点的极值只跟自己左边和上边邻居相关,而不与右边或者下边邻居相关的情况
如果与四个方向都相关,应该就用记忆化搜索(不管是递归还是排过序的非递归)
另一题非常相似:li77: longest common subsequence
"""
def maximal_square(self, matrix):
if not any(matrix):
return 0
n, m = len(matrix), len(matrix[0])
f = [[0] * m, [0] * m] # f[i][j] = max square side length whose right bottom corner is position (i, j)
# 这里绝对不能写成f = [0 for _ in xrange(m), 0 for _ in xrange(m)]
# 一旦写成后一种,接下来就不能用二维数组正常引用f[a][b] = c去改了, 因为这个时候f[a][b]是一个immutable的int
max_side_length = 0
for i in xrange(n):
f[i % 2][0] = int(matrix[i][0])
max_side_length = max(max_side_length, f[i % 2][0]) # 多重循环的时候, 写完一定要仔细检查去max/min的位置是不是缺了少了
for j in xrange(1, m):
if matrix[i][j] == '1':
f[i % 2][j] = 1 + min(f[(i - 1) % 2][j], f[i % 2][j - 1], f[(i - 1) % 2][j - 1]) # j千万不要再除余啦
max_side_length = max(max_side_length, f[i % 2][j])
else:
f[i % 2][j] = 0
return max_side_length * max_side_length
|
a6ae8faf9e0e9f5eef62f62260ab150aaa4f6027 | wzygadlo/Python_Tools | /dog.py | 671 | 3.859375 | 4 | '''
How to make a valid dict key:
__hash__
__eq__ or __cmp__
But! I still recommend using ONLY
int
str
tuple of int and/or str
or other immutable things that are easy to compare
'''
class Dog(object):
def __init__(self, name):
self.name = name
def __repr__(self):
fmt = '{}(name={!r})'
return fmt.format(type(self).__name__, self.name)
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
def bark(self):
print 'Woof! %s is barking' % (self.name,)
a = Dog('Fido')
b = Dog('Fido')
c = Dog('Clifford')
d = {}
d[a] = 'my dog'
|
839680394b8e424e8ef4a6e4318788f0fbfd32f0 | chrisreddersen/Character-non-repeat | /first_non_repeat.py | 341 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 07:22:01 2019
@author: creddersen
"""
def first_non_repeating_letter(string):
list = [i.lower() for i in string]
for i in range(len(list)):
if list.count(list[i]) == 1:
return string[i]
return ""
|
01331f451354e8537ee85542d1c419261658ca2a | francescaberkoh/Ass6 | /Assignment6b.py | 4,967 | 3.640625 | 4 | '''
Created on May 19, 2019
@author: Francesca
'''
from tkinter import*
import random
root = Tk()
deck = []
#Make deck of cards
for suit in ["of_spades", "of_clubs", "of_diamonds", "of_hearts"]:
for v in range(1,14):
deck.append([v,suit])
dealerdeck = []
playerdeck = []
#Making the player's hand
while len(playerdeck) < 3:
random.shuffle(deck)
p = deck.pop()
if p not in playerdeck:
playerdeck.append(p)
Pcard1 = playerdeck[0]
Pcard2 = playerdeck[1]
Pcard3 = playerdeck[2]
players = Pcard1[0] + Pcard2[0]
#Making the dealers hand
while len(dealerdeck) < 3:
random.shuffle(deck)
d = deck.pop()
if d not in dealerdeck or playerdeck:
dealerdeck.append(d)
print(playerdeck, dealerdeck)
print(Pcard1, Pcard2, Pcard3)
Dcard1 = dealerdeck[0]
Dcard2 = dealerdeck[1]
Dcard3 = dealerdeck[2]
dealers = Dcard1[0] + Dcard2[0]
You = Label(root, text = "You have these cards:"+ " " + str(Pcard1) + " " + str(Pcard2) + " Your cards make a combined total of:" + " " + str(players))
You.grid(row=0, column=2)
#Making a function that displays card face for player
photo= PhotoImage(file = str(Pcard1[0]) +"_"+ str(Pcard1[1]) + ".png")
photo = photo.subsample(2,2)
test = Label(root, image = photo)
test.grid(row=1, column =1)
photo1= PhotoImage(file = str(Pcard2[0]) +"_"+ str(Pcard2[1]) + ".png")
photo1 = photo1.subsample(2,2)
test1 = Label(root, image = photo1)
test1.grid(row=1, column =2)
photo2= PhotoImage(file = str(Pcard3[0]) +"_"+ str(Pcard3[1]) + ".png")
photo2 = photo2.subsample(2,2)
test2 = Label(root, image = photo2)
Action = Label(root, text= "Would you like to Hit or Stay?")
TextBox = Entry(root)
Action.grid(row=2, column = 1)
TextBox.grid(row=3, column =1)
def show():
test2.grid(row=1, column =3)
def send ():
userinput = TextBox.get()
if players < 21:
if userinput == "hit":
current = Pcard1[0] + Pcard2[0] + Pcard3[0]
player_result = Label(root, text= "You now have:" + " " + str(current) + " " + "With these cards:" + " " + str(Pcard1) + " " + str(Pcard2) + " "+ str(Pcard3))
player_result.grid(row=4, column =1)
show()
dealer_result = Label(root, text= "Dealer has:" + " " + str(Dcard1) + " " + str(Dcard2) + " " + str(Dcard3) + " " + "The dealer has a combined total of:"+ " "+ str(dealers))
dealer_result.grid(row=5, column =1)
if current < 21 and dealers < 21 :
if dealers == current:
Tie = Label(root, text = "It's a tie!")
Tie.grid(row=6, column =1)
if current < dealers:
DealerWins = Label(root, text = "Dealer Wins :(")
DealerWins.grid(row=6, column =1)
if current > dealers:
playerwins = Label(root, text = "You Win!")
playerwins.grid(row=6, column =1)
else:
if current > 21:
DealerWins3 = Label(root, text = "You Busted! Dealer Wins :(")
DealerWins3.grid(row=6, column =1)
elif dealers> 21:
playerwins3 = Label(root, text = "Dealer Busted! You Win!")
playerwins3.grid(row=6, column =1)
else:
dealer_result = Label(root, text= "Dealer has:" + " " + str(Dcard1) + " " + str(Dcard2) + " " + str(Dcard3) + " " + "The dealer has a combined total of"+ " "+ str(dealers))
dealer_result.grid(row=4, column =1)
if players < 21 and dealers < 21 :
if dealers == players:
Tie = Label(root, text = "It's a tie!")
Tie.grid(row=5, column =1)
if players < dealers:
DealerWins = Label(root, text = "Dealer Wins :(")
DealerWins.grid(row=5, column =1)
if players > dealers:
playerwins = Label(root, text = "You Win!")
playerwins.grid(row=5, column =1)
else:
if players > 21:
DealerWins3 = Label(root, text = "You Busted! Dealer Wins :(")
DealerWins3.grid(row=5, column =1)
elif dealers> 21:
playerwins3 = Label(root, text = "Dealer Busted! You Win!")
playerwins3.grid(row=5, column =1)
else:
if players == 21:
BlackJack = Label(root, text="BlackJack!")
BlackJack.grid(row=4, column =1)
else:
Over = Label(root, text="You BUST!")
Over.grid(row=4, column =1)
sendb = Button (root, text = "Check", command = send)
sendb.grid(row=3, column =2)
root.mainloop() |
1efec82b035fab09319d5ba75843a453def198d4 | Faranheit15/Hacktoberfest-2020 | /property decorator.py | 605 | 3.84375 | 4 | class Celsius:
def __init__(self,temperature=0):
self.temperature=temperature
def to_fahrenheit(self):
return (self.temperature*1.8)+32
@property
def temperature(self):
print("Getting value...")
return self._temperature
@temperature.setter
def temperature(self,value):
print("Setting value...")
if value<-273.15:
raise ValueError("Temperature below -273 is not possible")
self._temperature=value
human=Celsius(37)
print(human.temperature)
print(human.to_fahrenheit())
coldest_thing=Celsius(-300)
|
2855fde258319f7b790e55f719fe4788d945a280 | zouhuigang/handwriting | /test-plus.py | 2,357 | 3.65625 | 4 | class sort(object):
def __init__(self,name):
self.name = name
self.iter = 0
self.max_iter = 0
self.score = 0
self.total_score = 0
self.avg_score = 0
def add_items(self):
if self.score > 0.5:
self.iter += 1
self.total_score += self.score
return
def print_items(self):
print('姓名:', self.name, ' 单字匹配度:', self.score, ' 单字匹配成功次数:', self.iter, ' 最大匹配度次数:', self.max_iter)
return
def print_result(self):
self.avg_score = self.total_score/10
print('姓名:', self.name, ' 单字匹配成功次数:', self.iter, ' 最大匹配度次数:', self.max_iter, ' 平均匹配度', self.avg_score)
def add_max_iter(prop,k):
for sort in sort_lists:
if sort.score == prop:
sort.max_iter += 1
print('第', k+1, '次最高匹配度为:', sort.name, sort.score)
def result_writer():
for sort in sort_lists:
if sort.avg_score > 0.5:
print('\n\t该句话为%s所写' % sort.name)
def get_sore(url,k):
with open(url,'r') as fd:
flists = fd.readlines()
prop=0.0
for i in range(len(flists)):
sort_lists[i].score = float(flists[i][14:-1])
sort_lists[i].add_items()
if prop < float(flists[i][14:-1]):
prop = float(flists[i][14:-1])
add_max_iter(prop,k)
return
if __name__=='__main__':
GYC = sort('GYC')
LJS1 = sort('LJS1')
LJS2 = sort('LJS2')
WTK = sort('WTK')
YZQ = sort('YZQ')
NYK = sort('NYK')
sort_lists = [GYC, LJS1, LJS2, WTK, YZQ, NYK]
name=['白', '日', '依', '山', '尽', '黄', '河', '入', '海', '流']
for i in range(10):
url='E:\\笔迹识别\\' + name[i] + '.txt'
print('=======================================================================================')
get_sore(url,i)
for sort in sort_lists:
sort.print_items()
print('=======================================================================================')
print('最终结果:')
for sort in sort_lists:
sort.print_result()
result_writer()
|
7d58b82d60cef48068b879e63e6e86f7ab86a2dd | Alex760164/python_advanced | /home_works/home_work_2/main.py | 361 | 3.515625 | 4 | from src.circle import Circle
from src.point import Point
if __name__ == '__main__':
# Testing libraries of Point and Circle
small_circle = Circle(Point(12, 12), 425)
big_circle = Circle(Point(9, 1), 10293.4)
if (small_circle < big_circle):
print('Test #1 is OK')
if (small_circle == small_circle):
print('Test #2 is OK')
|
8b0808bcbf323756364a221c75c75c8b332529c3 | Logirdus/py_lessons | /stepic_4_modules/ring_perimeter.py | 190 | 3.6875 | 4 | '''
Программа расчета периметра круга с использованием модуля math
'''
from math import pi
radius = float(input())
print(2 * pi * radius) |
b0ce2ad95582f41d4d910c5fd74d37fa688b39a9 | WASSahasra/sclPython | /Select. Not Select 1st.py | 157 | 4 | 4 | x=int(input("Enter Mark 1 "))
y=int(input("Enter Mark 2 "))
if x>=50 and y>=50:
print("You Are Selected")
else:
print("You Are Not Selected")
|
1e6ef71cb07175699473a356977a93fec39985ab | JTMaher2/RunCode-Solutions | /Just_a_ord_friend/Just_a_ord_friend.py | 278 | 3.75 | 4 | #!/usr/bin/env python3
import sys
import string
sum = 0
valid_chars = set(string.ascii_letters.replace("_", ""))
with open(sys.argv[1]) as fileInput:
for line in fileInput:
for c in line:
if c in valid_chars:
sum += ord(c)
print(sum) |
40f00677c885b0377c7b7a3975356493a4575643 | samyuktahegde/Python | /datastructures/stack/stack_using_queues_1.py | 995 | 3.9375 | 4 | # class Queue:
# def __init__(self):
# self.items = []
# def isEmpty(self):
# return self.items == []
# def enqueue(self, item):
# self.items.insert(0,item)
# def dequeue(self):
# return self.items.pop()
# def size(self):
# return len(self.items)
class Stack:
def __init__(self):
self.q1 = []
self.q2 = []
def push(self, data):
self.q2.insert(0,data)
if len(self.q1)>0:
while len(self.q1)>0:
self.q2.insert(0, self.q1.pop())
# print(self.q1, self.q2)
self.q1, self.q2 = self.q2, self.q1
# print(self.q1, self.q2)
def pop(self):
if len(self.q1)>0:
return self.q1.pop()
else:
return -1
def print_stack(self):
print(self.q1)
stack = Stack()
stack.push(2)
stack.push(3)
stack.push(4)
stack.print_stack()
print(stack.pop())
|
f1fe296a849c5565d120b04d4354f10afd3dfa91 | evanakat/rockpaperscissors | /rockpaperscissors.py | 1,977 | 4.125 | 4 | import random
lives = 3
count = 0
print('*type either rock, paper, or scissors*')
while lives > 0:
print(f"**You have {lives} lives, play wisely**")
player1 = input('Make your move: ').lower()
if player1 == "quit":
break
rand_num = random.randint(0,2)
if rand_num == 0:
player2 = 'rock'
elif rand_num == 1:
player2 = 'scissors'
elif rand_num == 2:
player2 = 'paper'
print("The computer played: ", player2)
if player1 == 'rock':
if player2 == 'scissors':
print('You win!')
count += 1
print(count,' wins')
if player2 == 'paper':
print('Computer wins!')
lives -= 1
if lives < 1:
play_again = input('Do you want to play again? (y/n) ')
if play_again == 'y':
lives += 3
if player2 == 'rock':
print('Redo!')
elif player1 == 'paper':
if player2 == 'rock':
print('You win!')
count += 1
print(count,' wins')
if player2 == 'scissors':
print('Computer wins!')
lives -= 1
if lives < 1:
play_again = input('Do you want to play again? (y/n) ')
if play_again == 'y':
lives += 3
if player2 == 'paper':
print('Redo!')
elif player1 == 'scissors':
if player2 == 'rock':
print('Computer wins!')
lives -= 1
if lives < 1:
play_again = input('Do you want to play again? (y/n) ')
if play_again == 'y':
lives += 3
if player2 == 'paper':
print('You win!')
count += 1
print(count,' wins')
if player2 == 'scissors':
print('Redo!')
else:
print('You spelled something wrong...')
print('Hope you had some fun! Game over!')
|
47aa735208551e408f949a72451dd6320fec67d4 | rscai/python99 | /python99/lists/p127.py | 679 | 3.734375 | 4 | # Group the elements of a set into disjoint subsets.
# a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons?
# Write a predicate that generates all the possibilities via backtracking.
from python99.lists.p126 import combination
# group l into len(nums) subsets, nums imply number of groups respectively
def group(l, nums):
if len(nums) == 1:
return [combination(l, nums[0])]
first_group = combination(l, nums[0])
return [[first_group_element] + remain_group_e
for first_group_element in first_group
for remain_group_e in group(list(set(l)-set(first_group_element)), nums[1:])
]
|
35adbbd493f1b4aa219be240535195ca00e31a65 | Iranaphor/PythonGame_RPG | /Python Game - RPG/RPG - V1/RPG-V1-001.py | 182 | 3.640625 | 4 | import time
import datetime
i = 10
while ( i < 11 ):
print ("i:", i)
i = i - 1
time.sleep(0.5)
# print (datetime.datetime.now().time())
if (i < 1):
i = 10
|
16d98ef7cc0be54ec7568f35c1e5dbcc9f000360 | JLevins189/Python | /Labs/Lab4/Lab9Ex10.py | 503 | 3.859375 | 4 | def remove_substring(my_str1, indice1, indice2):
str = ""
my_str1.replace(" ", "")
for counter in range(0,indice1):
str += my_str1[counter]
for counter in range(indice2+1,len(my_str1)):
str += my_str1[counter]
print(str)
my_str1 = input("Input a string")
indice1 = int(input("Input a element number range start to be removed from"))
indice2 = int(input("Input a element number range end to be removed from"))
remove_substring(my_str1, indice1, indice2)
|
245725e4aabda18373d9ace8fbef9898319291ee | JIANG09/LearnPythonTheHardWay | /ex3.py | 796 | 4.40625 | 4 | # coding=utf-8
print("I will now count my chickens:") # print a sentence
print('Hens', 25 + 30 / 6) # print a name, with a calculation after it.
print("Rooster", 100 - 25 * 3 % 4) # same as above
print("Now I will count the eggs:") # count eggs:
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) # a calculation
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7) # a boolean expression
print("What is 3 + 2?", 3 + 2) # print a question, with a calculation after it.
print("What is 5 - 7?", 5 - 7) # same as above
print("Oh, that's why it's false.")
print("How about some more.")
print("Is it greater?", 5 >= 2) # print a question, with a boolean value after it.
print("Is it greater or equal?", 5 >= 2) # same as above
print("Is it less or equal?", 5 <= 2) # same as above
|
e084786bc60c730ed6466aa176a08fe5009113ac | mgirardin/Project-Euler-Solutions | /Solutions_Python/P014.py | 1,195 | 3.96875 | 4 | records = [-1 for x in range(0, 1000000)] # guarda tamanhos de chains já conhecidos
class collatz: # classe para guardar o número analisado e o tamanho de sua chain
iterations = 0
number = 0
def apply(self):
apply_collatz(self, self.number)
return 1
def apply_collatz(init, num): # processo de collatz
global records
if num < 1000000 and records[num] != -1:
init.iterations += records[num]
records[init.number] = init.iterations
return 1
init.iterations += 1
if num == 1:
records[init.number] = init.iterations
return 1
elif num % 2 == 0:
return apply_collatz(init, int(num/2))
else:
return apply_collatz(init, 3*num + 1)
max_length = 0
biggest_chain_number = 0
for number in range(1, 1000000): #loop pelos números até 1 milhão para calcular tamanho da chain
collatz_inst = collatz()
collatz_inst.number = number
collatz_inst.apply()
size = collatz_inst.iterations
if size > max_length:
max_length = size
biggest_chain_number = number
print(biggest_chain_number)
|
288cbb797c03c5c9053acc02e04a302a4c174e80 | PepAnalytics/Python | /homework3/second.py | 511 | 3.859375 | 4 |
def new_func(**kwargs):
for key, value in kwargs.items():
print(f"{key} is {value}")
firstname = (input('Enter the name: '))
lastname = (input('Enter the lastname: '))
email = (input('Enter the email: '))
country = (input('Enter the country: '))
age = (input('Enter your age: '))
phone = (input('Enter the phone number: '))
new_func(Firstname=firstname, Lastname=lastname, Email =email, Country=country, Age=age, Phone_number=phone)
print(new_func())
new_func()
|
11ecec2bc2d11ff40d2f80414b249189facc54aa | mouday/SomeCodeForPython | /python_psy_pc/python基础/pandasTest.py | 381 | 3.640625 | 4 | import pandas as pd
#基于numpy
csv=pd.read_csv("bricks.csv",index_col=0)
print(csv)
print(csv.nation)#获取列
print(csv["nation"])
csv["note"]=[1,2,3,4,5,6,7,8,9]#新加列
print(csv)
csv["densty"]=csv["area"]/csv['peple']
print(csv)
print(csv.loc["ch"])#获取行数据
print(csv["nation"].loc["ch"])#获取元素
print(csv.loc["ch"]["nation"])
print(csv.loc["ch","nation"])
|
acef4b985d230567ce62ea81f22a7f00a98997f5 | udhayprakash/PythonMaterial | /python3/04_Exceptions/16_warnings.py | 713 | 3.703125 | 4 | #!/usr/bin/python3
"""
Purpose: Handling warnings
"""
import warnings
for each_attribute in dir(warnings):
if not each_attribute.startswith("_"):
print(each_attribute)
print()
warnings.warn("This is not good practice 1")
# Adding filter to display on specific warnings
warnings.filterwarnings(
"ignore",
".*do not.*",
)
warnings.warn("This warning will be displayed")
warnings.warn("Do not show this message")
print()
try:
# To throw exception when error warning is present
warnings.simplefilter("error", UserWarning)
warnings.warn("This is not good practice 2")
except UserWarning as ex:
print(repr(ex))
except Exception as ex:
print("Unhandled Exception", repr(ex))
|
6f1c0f06923b751eaf302a53151e9d100f1c2a12 | lordofsraam/cloaked_happiness | /sideways.py | 671 | 4.21875 | 4 | def PrintSideWays(stringy):
maxlen= 0
tokens = stringy.split()
#Find the longest word in the string (so we know how many times to iterate down)
for h in tokens:
if len(h) > maxlen:
maxlen = len(h)
#We never actually use the lines variable but it could be used to return the 2d array instead of just print the string
lines = []
for i in range(0,maxlen):
line = []
for j in range(0,len(tokens)):
if ((i) >= len(tokens[j])):
line.append(' ')
else:
line.append(tokens[j][i])
print ' '.join(line)
lines.append(line)
PrintSideWays("This string is all matrixy. I made this because I got really bored :(")
|
e961eae4ed9fe0d275569b5446e80026537537f5 | baralganesh/Python-Simple-Programs | /06_ListComprehensions.py | 802 | 4.3125 | 4 | import random
main_list = []
# Length of list can be anywhere between 10 digits to 20
length_main_list = random.randint(10,20)
# Get numbers randomly from 1 to 100 and add to the main_list
# Now main_list created and can be play araound
while len(main_list) <= length_main_list:
main_list.append(random.randint(1,100))
# Now main list is created and is in the memory
# _______________LIST COMPREHENSION__________
# Subset of all even numbers:
even_list = [num for num in main_list if num %2 ==0]
odd_list = [num for num in main_list if num %2 != 0]
doubles_list = [num*2 for num in main_list]
print ("_____MAIN LIST_____")
print (main_list)
print (f"\nList of even numbers: \n{even_list}")
print (f"\nList of odd numbers: \n{odd_list}")
print (f"\nList of doubles numbers: \n{doubles_list}")
|
ca3a386f53a4188c14157684d129133a9bd007be | EUD-curso-python/control-de-flujo-admspere | /control_de_flujo.py | 5,877 | 4.0625 | 4 | """Guarde en lista `naturales` los primeros 100 números naturales (desde el 1)
usando el bucle while
"""
S = 1
naturales = []
while S < 101:
naturales.append(S)
S += 1
print("\n\tLos primeros 100 números naturales desde 1 ==> ",naturales)
"""Guarde en `acumulado` una lista con el siguiente patrón:
['1','1 2','1 2 3','1 2 3 4','1 2 3 4 5',...,'...47 48 49 50']
Hasta el número 50.
"""
accumulated = []
for S in range(2, 52):
cadena=''
for P in range(1, S):
cadena = cadena + ' ' + str(P)
accumulated.append(cadena[1:])
print("\t\nAcumulado de una lista con el siguiente patrón '1', '1 2', '1 2 3', '1 2 3 4', '1 2 3 4 5', '1 2 3 4 5 6' Hasta [50] : \n",accumulated)
"""Guarde en `suma100` el entero de la suma de todos los números entre 1 y 100:
"""
suma100 = 0
for S in naturales:
suma100 = S +suma100
print("\nLa suma Total de todos los números entre 1 y 100 es : " ,suma100)
"""Guarde en `tabla100` un string con los primeros 10 múltiplos del número 134,
separados por coma, así:
'134,268,...'
"""
table100 = ''
for i in range(1, 11):
table100 = table100 + ',' + str( i * 134)
table100 = str(table100[1:])
print("\n\tLos 10 Primeros Multiplos de 134\n\t" ,table100)
"""Guardar en `multiplos3` la cantidad de números que son múltiplos de 3 y
menores a 300 en la lista `lista1` que se define a continuación (la lista
está ordenada).
"""
lista1 = [12, 15, 20, 27, 32, 39, 42, 48, 55, 66, 75, 82, 89, 91, 93, 105, 123, 132, 150, 180, 201, 203, 231, 250, 260, 267, 300, 304, 310, 312, 321, 326]
Base = [S for S in lista1 if S % 3 == 0 and S < 300]
multiples3 = len(Base)
print("\n\tCantidad de números que son múltiplos de 3 y menores a 300",multiples3)
"""Guardar en `regresivo50` una lista con la cuenta regresiva desde el número
50 hasta el 1, así:
[
'50 49 48 47...',
'49 48 47 46...',
...
'5 4 3 2 1',
'4 3 2 1',
'3 2 1',
'2 1',
'1'
]
"""
regressive = []
for S in range(50, 0, -1):
cadena=''
for P in range(S, 0, -1):
cadena = cadena + ' ' + str(P)
regressive.append(cadena[1:])
print("\n\tLista de cuenta regresiva desde el número 50 hasta el 1",regressive)
"""Invierta la siguiente lista usando el bucle for y guarde el resultado en
`invertido` (sin hacer uso de la función `reversed` ni del método `reverse`)
"""
lista2 = list(range(1, 70, 5))
invested = []
for a in range(71, 0, -5):
invested.append(a)
invested = invested[1:]
print(invested)
"""Guardar en `primos` una lista con todos los números primos desde el 37 al 300
Nota: Un número primo es un número entero que no se puede calcular multiplicando
otros números enteros.
"""
cousins = []
Inicio = 37
while Inicio <= 300:
cont =1
x = 0
while cont <= Inicio:
if Inicio % cont ==0:
x = x+1
cont = cont + 1
if x == 2:
cousins.append(Inicio)
Inicio = Inicio + 1
print("\n\tLista de todos los números primos desde el 37 al 300 ",cousins)
"""Guardar en `fibonacci` una lista con los primeros 60 términos de la serie de
Fibonacci.
Nota: En la serie de Fibonacci, los 2 primeros términos son 0 y 1, y a partir
del segundo cada uno se calcula sumando los dos anteriores términos de la serie.
[0, 1, 1, 2, 3, 5, 8, ...]
"""
fibonacci= [0,1]
for i in range(2, 60):
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print("\n\tLista con los primeros 60 términos de la secuencia de Fibonacci ",fibonacci)
"""Guardar en `factorial` el factorial de 30
El factorial (símbolo:!) Significa multiplicar todos los números enteros desde
el 1 hasta el número elegido.
Por ejemplo, el factorial de 5 se calcula así:
5! = 5 × 4 × 3 × 2 × 1 = 120
"""
factorial = 1
for i in range(1, 31):
factorial = factorial * i
print("\n\tel factorial de Numero [ 30 ] = ",factorial)
"""Guarde en lista `pares` los elementos de la siguiente lista que esten
presentes en posiciones pares, pero solo hasta la posición 80.
"""
lista3 = [941, 149, 672, 208, 99, 562, 749, 947, 251, 750, 889, 596, 836, 742, 512, 19, 674, 142, 272, 773, 859, 598, 898, 930, 119, 107, 798, 447, 348, 402, 33, 678, 460, 144, 168, 290, 929, 254, 233, 563, 48, 249, 890, 871, 484, 265, 831, 694, 366, 499, 271, 123, 870, 986, 449, 894, 347, 346, 519, 969, 242, 57, 985, 250, 490, 93, 999, 373, 355, 466, 416, 937, 214, 707, 834, 126, 698, 268, 217, 406, 334, 285, 429, 130, 393, 396, 936, 572, 688, 765, 404, 970, 159, 98, 545, 412, 629, 361, 70, 602]
pairs = []
for S in range(0, 81):
if S % 2 == 0:
pairs.append(lista3[S])
print("\n\tlista que esten presentes en posiciones pares, pero solo hasta la posición 80",pairs)
"""Guarde en lista `cubos` el cubo (potencia elevada a la 3) de los números del 1 al 100.
"""
cubes = []
for S in range(1, 101):
cubes.append(S ** 3)
print("\n\tel cubo (potencia elevada a la 3) de los números del 1 al 100",cubes)
"""Encuentre la suma de la serie 2 +22 + 222 + 2222 + .. hasta sumar 10 términos y guardar resultado en variable `suma_2s`
"""
Inicio = 0
for S in range(0, 11):
P = 10 ** S * (10 - S) * 2
Inicio = P + Inicio
suma_2s = Inicio
print("\n\tSuma de la serie 2 + 22 + 222 + 2222 + .. hasta sumar 10 términos = ",suma_2s)
"""Guardar en un string llamado `patron` el siguiente patrón llegando a una cantidad máxima de asteriscos de 30.
*
**
***
****
*****
******
*******
********
*********
********
*******
******
*****
****
***
**
*
"""
A = '*\n'
B = '******************************\n'
C = '*'
for S in range(2, 30):
C = '*'
C = C * S
A = A + C + '\n'
print(A)
for S in range(29, 0, -1):
C = '*'
C = C * S
B = B + C + '\n'
print(B)
pattern = A + B
pattern = pattern[:-1]
print("\n\tpatrón llegando a una cantidad máxima de asteriscos de 30 ", pattern)
End = '100%'
print("Casi Que No ....!!!!: \"¿Acabo?\"")
print('En Verdad Termine: \'¡ Por Fin !\'')
print("\n\tTerminamos" ,End)
|
aae1e2239b71e463b772a36d70bf360c868d9037 | rdonati/course_registration | /register.py | 1,557 | 3.515625 | 4 | import time
import platform
from pynput.keyboard import Key, Controller
from tkinter import *
num_of_courses = 5
def print_data():
crns = []
for i in range(num_of_courses):
crns.append(entries[i].get())
for i in range(num_of_courses):
print("{}: {}".format(i + 1, entries[i].get()))
def submit():
crns = []
for i in range(num_of_courses):
crns.append(entries[i].get())
keyboard = Controller()
#Checks OS to make sure correct keys are pressed to navigate between screens
if(platform.system() == "Darwin"):
keyboard.press(Key.cmd)
keyboard.press(Key.tab)
keyboard.release(Key.cmd)
keyboard.release(Key.tab)
else:
keyboard.press(Key.alt)
keyboard.press(Key.tab)
keyboard.release(Key.alt)
keyboard.release(Key.tab)
time.sleep(1.5)
for i in range(num_of_courses):
keyboard.type(crns[i])
keyboard.press(Key.tab)
keyboard.release(Key.tab)
def select_all(event):
event.widget.selection_range(0, END)
w = Tk()
w.title("Course Registration Helper")
w.resizable(height = False, width = False)
#Creates labels
labels = []
for i in range(num_of_courses):
labels.append(Label(w, text = "CRN {}: ".format(i + 1)))
#Creates input
entries = []
for i in range(num_of_courses):
entries.append(Entry(w))
submit = Button(w, text = "Submit", command = submit)
#Shows labels
for i, label in enumerate(labels):
label.grid(row = i, column = 0)
#Shows input
for i, entry in enumerate(entries):
entry.grid(row = i, column = 1)
entry.bind("<FocusIn>", select_all)
submit.grid(row = num_of_courses, column = 0)
w.mainloop() |
700413b6761ca37f71e0b66b782137ec95d92f1b | kssgit/Meerithm | /김성수/프로그래머스 LV2/타겟 넘버.py | 796 | 3.765625 | 4 | # 타겟 넘버
# DFS 사용하여 모든 경우의 수를 구했다.
answer = 0
def solution(numbers, target):
global answer
dfs(0,numbers,target,0)
return answer
def dfs(indx , numbers, target, value):
global answer
if indx == len(numbers) and target == value:
answer +=1
return
if indx == len(numbers):
return
dfs(indx+1,numbers,target,value+numbers[indx])
dfs(indx+1,numbers,target,value-numbers[indx])
numbers =[1, 1, 1, 1, 1]
target = 3
# 다른 사람 풀이
def solution(numbers, target):
if not numbers and target == 0 :
return 1
elif not numbers:
return 0
else:
return solution(numbers[1:], target-numbers[0]) + solution(numbers[1:], target+numbers[0])
print(solution(numbers,target)) |
bd6cbe865dec3d1d176cd0a56f27d3b594c1ba12 | ole511/hello_world | /57二叉树的下一个结点.py | 1,407 | 3.765625 | 4 | '''
给定一个二叉树其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
'''
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:return
# 先找是否存在右子树,存在的话找右子树的最左结点
# 注意这里有一个概念不要搞错,如果结点没有左子树,那么先遍历到的是根(该结点)而不是该结点的右子树的最左结点!!
if pNode.right:
pNode=pNode.right
while pNode.left:
pNode=pNode.left
return pNode
# 没有右子树,并且该结点是父结点的左子树,直接返回父结点
if pNode.next and pNode==pNode.next.left:
return pNode.next
# 没有右子树,并且该结点是父节点的右子树,一直向上推,直到找到不是父节点的右节点的结点。返回该结点的父节点,画图理解。
if pNode.next:
while pNode.next and pNode==pNode.next.right:
pNode=pNode.next
return pNode.next
return
|
cd1841d1a03f8b285808ee2a2522fbc6ddd0c25a | Uxooss/Lessons-Hellel | /Lesson_09/9.1 - Numeric_sys_convert.py | 1,716 | 4.1875 | 4 | '''
Написать функцию для перевода десятичного числа в другую систему исчисления (2-36).
Небольшая подсказка. В этой задаче вам понадобится:
- список
- метод `revers()` (или срез [::-1], или вместо `revers()` использовать `insert()` тогда не
придётся разворачивать список), чтоб развернуть список, метод `join()`
- строка `ascii_uppercase` из модуля `string` (её можно получить если сделать импорт
`from string import ascii_uppercase`), она содержит все буквы латинского алфавита.
'''
from string import ascii_uppercase
def digit_2_letter(val):
if val > 9: # цифры от 0 до 9, остаются цифрами
return ascii_uppercase[val-10] # цифры от 10 и далее, переводятся в буквы (А=11, В=12 и т.д.)
else:
return str(val) # ф-ия возвращает полученный символ.
def num_convert(num, x):
val_lst = []
res = ''
if num == 0:
val_lst.append(num)
while num > 0:
val_lst.append(num % x)
num = num // x
rev_lst = val_lst[::-1]
for x in rev_lst:
res = res + digit_2_letter(x)
return res
num = int(input('\nВведите число:\t\t\t\t'))
x = int(input('Введите систему исчисления:\t'))
print('\nРезультат перевода:\t', num_convert(num, x))
|
b3a15dd3c088c07156d98e6f14a333042993f578 | Priyanka29598/guvi | /test13.py | 161 | 3.71875 | 4 | j=int(input())
iscomposite=0
for i in range(2,j):
if(j%i==0):
iscomposite=1
break
if(iscomposite==1):
print("no")
else:
print("yes")
|
d8c9c717e225cbdcf6c9ffcf8cb5e42494f936d5 | j4robot/master-python | /FreeCodeCamp/ScientificComputingWithPython/main.py | 890 | 4.25 | 4 | #This is a course on Scientific Computing Using Python
array = [(x ** 2) for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ]
#print(array)
raw = [1, 2, 1, 3, 2, 1, 4, 5]
#print(set(raw))
def max_num(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print(max_num(5, 1, 3))
print(__name__)
a = float(input('Enter first number: '))
b = float(input('Enter second number: '))
c = input('Enter an operator: ')
'''
This is a comment for the method.
'''
def calculate(num_a, num_b, op):
if op == '+':
return num_a + num_b
elif op == '-':
return num_a - num_b
elif op == '*' or op.lower() == 'x':
return num_a * num_b
elif op == '/':
return num_a / num_b
print(calculate(a, b, c))
|
23d1e58bd35d8421c646569a7a058c78169aa7a1 | kevinr78/Todo-List | /Todo.py | 4,193 | 4.21875 | 4 | # todo list
def todo_list(list1):
user = False
while not user:
add_items = input("Enter the things to todo :")
list1.append(add_items)
add_more = input("Do you to add more items (Y/N) : ").upper()
if add_more == "Y":
while add_more == "Y":
add_items = input("Enter the things to todo :")
list1.append(add_items)
add_more = input("Do you to add more items (Y/N) : ").upper()
if add_more == "N":
user = True
break
elif add_more == "N":
user = True
break
else:
print("Enter a valid input")
add_more = input("Do you to add more items (Y/N) : ").upper()
if add_more == "N":
user = True
break
print("List is created ")
def display(list1):
if len(list1) == 0:
print("List is empty")
add_task = input("Do you want to add items to your list (Y/N) : ").upper()
if add_task == "Y":
todo_list(list1)
else:
if add_task == "N":
exit()
else:
for items in list1:
print("-->", items)
def remove_task(list1):
if len(list1) != 0:
remove_more_task = False
while not remove_more_task:
while len(list1) != 0:
enume_list = enumerate(list1)
print(list(enume_list))
index_of_obj = int(input("Select index of the task which is to be removed"))
list1.pop(index_of_obj)
print("new list is :", list1)
ask_user = input("do you want to remove more task (Y/N) : ").upper()
if ask_user == "N":
remove_more_task = True
remove_more_task = True
print("List is empty")
else:
if len(list1) == 0:
print("List is empty")
add_task = input("Do you want to add items to your list (Y/N) : ").upper()
if add_task == "Y":
todo_list(list1)
else:
print("Enter a valid input")
def sort_task(list1):
print("list sorted in order is :")
for cards in sorted(list1):
print("-->", cards)
def main():
list1 = []
print("******TODO LIST******")
opr_done = False
while not opr_done:
print("Select the operation you want to perform\n"
"1)CREATE A TODO LIST\n"
"2)DISPLAY THE LIST \n"
"3)SORT THE LIST\n"
"4)REMOVE A TASK FROM THE LIST\n ")
operation = int(input("Enter the option number of operation to be performed :"))
if operation == 1:
todo_list(list1)
elif operation == 2:
display(list1)
elif operation == 3:
sort_task(list1)
else:
remove_task(list1)
opr_again = input("Do you want to continue('Y/N') :").upper()
if opr_again == "Y":
while opr_again == "Y":
print("Select the operation you want to perform\n"
"1)CREATE A TODO LIST\n"
"2)DISPLAY THE LIST \n"
"3)SORT THE LIST\n"
"4)REMOVE A TASK FROM THE LIST\n ")
operation = int(input("Enter the option number of operation to be performed :"))
if operation == 1:
todo_list(list1)
elif operation == 2:
display(list1)
elif operation == 3:
sort_task(list1)
else:
remove_task(list1)
opr_again = input("Do you want to continue('Y/N') :").upper()
if opr_again == "N":
opr_done = True
break
elif opr_again == "N":
opr_done = True
exit()
else:
print("Enter a valid input")
if __name__ == '__main__':
main()
|
39b4ab8cbbeca3cd3eef2193f6f93c3d7c7961ce | ronaldaguerrero/practice | /python2/python/OOP/methods.py | 431 | 3.578125 | 4 |
class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
guido = User("Guido van Rossum", "guido@python.com")
monty = User("Monty Python", "monty@python.com")
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance) # output: 300
print(monty.account_balance) # output: 50
|
6d22df32346e30824d1eb464e297db2e6d7d3417 | rupaku/codebase | /python basics/inheritance.py | 1,225 | 4.40625 | 4 | ''' inhertance
By using inheritance, we can create a class which uses all the properties and behavior of another class.
The new class is known as a derived class or child class, and the one whose properties are acquired is
known as a base class or parent class.
It provides re-usability of the code.
'''
class User:
def sign_in(self):
print('logged in')
class Wizard(User):
def __init__(self,name,power):
self.name=name
self.power=power
def attack(self):
print(f'attacking with power {self.power}')
class Archer(User):
def __init__(self,name,num_of_arrows):
self.name=name
self.num_of_arrows=num_of_arrows
def attack(self):
print(f'attacking with power {self.num_of_arrows}')
wizard1=Wizard('rupa',500)
archer1=Archer('ram',400)
wizard1.attack()
archer1.attack()
#output
# attacking with power 500
# attacking with power 400
''' isinstance
returns whether an object is an instance of a class or subclass
'''
print(isinstance(wizard1,Wizard)) #True since wizard1 obj is instance of class Wizard
print(isinstance(wizard1,User)) #True since it is subclass of User
print(isinstance(wizard1,object)) #True base class is object |
2df99932dd0861afb5159edade898ad92e89e926 | pureforce/bread_buying_problem | /bread_buying_problem.py | 8,012 | 4.21875 | 4 | """
Author: Jani Bizjak
E-mail: janibizjak@gmail.com
Date: 15.04.2020
Updated on: 20.04.2020
Python version: 3.7
Assumptions 1: Solution assumes that given sellers list is ordered by the arrival day of sellers. Otherwise a list
sorting needs to be done first.
Assumption 2: I assume input arguments are valid and therefore don't check for None values, strings instead of integers.
Idea of the solution: There needs to be one piece of bread per day for the duration of experiment. We can represent the
task as grid of dimensions #merchants * #days. We populate the matrix with prices for each merchant on the days that his
bread is available, if a bread from a merchant is not available on a selected day we assign infinite value to it. Each
column thus shows prices of different bread available on that day, if a column only has "inf" values, it means that
solution does not exist. To find a optimal solution we start in the last column. We find the merchant with lowest price,
if multiple merchants have same price on that day we select the one that is up-most. After we have a merchant selected
we go left as far as possible (either to the day when he arrives or another merchant provides bread with lower price).
When we change the merchant we again go up as far as possible and then left, repeating the process until we are in the
top left corner. This gives us solution with lowest price and fewest number of merchants, but the problem is that this
solution favours buying bread as late as possible (since we go from right to left). In order to fix this, we move
through selected merchants from left to right, but now we buy as much bread from the first selected merchant (if the
price is the same). After we are in the bottom right corner again, we have lowest price, with fewest merchants and most
stale bread (strange, villagers, preferring stale over fresh bread :))
The time complexity of the algorithm is O(m * n) + O(m) = O(m * n), where m is # of days and n is # of sellers.
From right to left (assuming bread lasts 3 days)
1. | 5 5 5 i i i i i |->| 5 5 5 i i i i i |->| 5 5 5 i i i i i |->| x x x i i i i i |
2. | i i 5 5 5 i i i |->| i i 5 5 5 i i i |->| i i 5 5 5 i i i |->| i i 5 5 5 i i i |
3. | i i i 4 4 4 i i |->| i i i 4 4 4 i i |->| i i i x x 4 i i |->| i i i x x 4 i i |
4. | i i i i 4 4 4 i |->| i i i i 4 4 4 i |->| i i i i 4 4 4 i |->| i i i i 4 4 4 i |
5. | i i i i i 4 4 4 |->| i i i i i x x x |->| i i i i i x x x |->| i i i i i x x x |
This gives us solution [3, 0, 2, 0, 3], minimum price and lowest #of merchants but not the stalest of bread.
1. | y y y i i i i i |->| y y y i i i i i |->| y y y i i i i i |
2. | i i - - - i i i |->| i i - - - i i i |->| i i - - - i i i |
3. | i i i 4 4 4 i i |->| i i i y y y i i |->| i i i y y y i i |
4. | i i i i - - - i |->| i i i i - - - i |->| i i i i - - - i |
5. | i i i i i 4 4 4 |->| i i i i i 4 4 4 |->| i i i i i 4 y y |
This gives us [3, 0, 3, 0, 2], lowest price, lowest # merchants, stalest bread.
"""
def calculate_purchasing_plan_old(total_days, sellers, starting_bread=10):
"""
total_days : positive int
sellers : list of tuple (day, price)
starting_bread : int, optional
"""
# Initialize total_days, price of starting bread is 0, the rest should be infinity, since we don't have bread.
# Each day is saved as a tuple (seller_index, arrival_day, price), it makes it easier to count purchases later.
cost_of_day = [(0, 0, 0)] * min(starting_bread, 30) + [(-1, 0, float('inf'))] * (
total_days - min(starting_bread, 30))
# Buy bread from each seller if his price is lower than current cost of bread for that day.
for i in range(len(sellers)):
# Maximum number of bread that can be bought from a seller is 30 or less if we get free bread before.
for j in range(sellers[i][0], min(sellers[i][0] + 30, total_days)):
cost_of_day[j] = min([cost_of_day[j], ((i + 1,) + sellers[i])], key=lambda t: t[2])
# Go through price of bread per day and count how many pieces we buy from each seller.
purchases = [0] * (len(sellers) + 2)
for best_seller in cost_of_day:
purchases[best_seller[0]] += 1
if purchases[-1] != 0: # Check if there is any stale bread
return None
return purchases[1:-1] # Value at 0 is starting bread, value at -1 is days with stale bread
def print_matrix(cost_matrix):
for i in range(len(cost_matrix)):
for j in range(len(cost_matrix[i])):
print("%4s " % cost_matrix[i][j], end="|")
print()
def calculate_purchasing_plan(total_days, sellers, starting_bread=10, best_before_date=30, debug = False):
"""
total_days : positive int
sellers : list of tuple (day, price)
starting_bread : int, optional
best_before_date : positive int, (how long the bread lasts)
debug : boolean, (prints cost matrix)
"""
# create cost_matrix of (sellers+1) x total_days
cost_matrix = [[0] * starting_bread + [float('inf')] * (total_days - min(starting_bread, best_before_date))]
for merchant in sellers:
cost_matrix.append(
[float('inf')] * (merchant[0]) + # Add inf before
[merchant[1]] * min(best_before_date, (total_days - merchant[0])) + # Add merchant price
[float('inf')] * (total_days - merchant[0] - min(best_before_date, (total_days - merchant[0])))) # Add inf after
if debug:
print_matrix(cost_matrix)
current_merchant = len(sellers)
current_day = total_days - 1
best_merchant = current_merchant
merchant_of_the_day = [0] * total_days
new_merchant = True # If the merchant changes, we want to go as far up as possible
while current_day >= starting_bread:
best_price = cost_matrix[best_merchant][current_day]
# go up as far as you can
for best_merchant_index in range(current_merchant, -1, -1):
tmp = cost_matrix[best_merchant_index][current_day]
# go up only if price is lower
if tmp < best_price or (tmp <= best_price and new_merchant): # Up only if lower price or new merchant
# print("Better merchant found %3s with price %3s <= %3s" % (best_merchant_index, tmp, best_price))
best_merchant = best_merchant_index
best_price = tmp
new_merchant = True
merchant_of_the_day[current_day] = best_merchant # Save from which merchant we buy bread on selected day
current_day -= 1 # go left one step
if best_price == float('inf'):
if debug:
print("Plan not feasible on day %5s" % current_day)
return None
new_merchant = False # No new merchant for the previous day yet
# At this point we have fewest # merchants and lowest price. We need to make another walk from left to right to buy
# bread as soon as possible.
buying_plan = [0] * (len(sellers) + 1) # +1 is because initial bread is accounted for in the matrix
current_merchant = 0
current_day = 0
while current_day < total_days:
# If cost of current merchant is the same as cost of the merchant of the day, buy from current, since we buy
# bread from him earlier (because merchants are sorted by their arrival day)
if cost_matrix[current_merchant][current_day] > cost_matrix[merchant_of_the_day[current_day]][current_day]:
current_merchant = merchant_of_the_day[current_day]
buying_plan[current_merchant] += 1
current_day += 1
return buying_plan[1:] # First value shows initial bread.
if __name__ == "__main__":
print("2",calculate_purchasing_plan(60, [(10, 200), (15, 100), (35, 500), (50, 30)])) # Example
|
671989d16dc3068938516858ba12cc6806fa0e90 | LeBoucEtMistere/Website-Monitor | /stats.py | 2,941 | 3.75 | 4 | from threading import Lock
from time import time
from collections import Counter
class Stats:
""" An object that holds data over a specific timeframe and computes stats on this data.
It can be accessed from multiple threads safely.
"""
def __init__(self, timeframe):
""" the constructor of the class
Parameters:
timeframe (int): The timeframe in seconds over which it computes the stats
"""
self.timeframe = timeframe
self.lock = Lock()
self.data = []
def _get_data_in_timeframe(self):
""" A method that return the data points inside the timeframe and clean the internal data list from the older data points.
Returns:
recent_data (list<dict>): The data that falls inside the timeframe.
"""
t = time()
recent_data = []
if len(self.data) == 0:
return None
for d in self.data:
if t - d["timestamp"] < self.timeframe:
recent_data.append(d)
self.data = recent_data
return recent_data
def get_stats(self):
""" A method that computes and returns the current stats over the timeframe.
Returns:
t (tuple): The stats including in this order: timeframe, percentage of availability, max response time, avg response time, a Counter of status_codes
"""
with self.lock:
recent_data = self._get_data_in_timeframe()
availability = 0
response_times = []
codes = []
for d in recent_data:
if d["request_success"] and d["status_code"] < 500:
availability += 1
if d["request_success"]:
response_times.append(
d["response"].elapsed.total_seconds())
codes.append(d["status_code"])
if availability == 0:
return self.timeframe, 0., 0., 0., None
return self.timeframe, availability * 100 / len(recent_data), max(response_times), sum(response_times)/len(response_times), Counter(codes)
def get_availability(self):
""" A method that computes and returns the current availability over the timeframe.
Returns:
availability (int): The percentage of availability over the timeframe.
"""
with self.lock:
recent_data = self._get_data_in_timeframe()
if recent_data is None:
return None
availability = 0
for d in recent_data:
if d["request_success"] and d["status_code"] < 500:
availability += 1
return availability * 100 / len(recent_data)
def add_data(self, data):
""" A method that adds data to the stat object, in a thread safe way.
Parameters:
data (dict): A dictionnary representing a data point.
"""
with self.lock:
self.data.append(data)
|
af790ae66271a50e94e6a5c908b968c508fe78ef | mickulich/PythonCourse | /ex2/compare_a_b.py | 426 | 4.125 | 4 | # -*- coding: utf-8 -*-
# Данный сценарий сравнивает два целых числа,
# и опередляет наименьшее из двух чисел, или же
# их равенство
a = input(u'Input integer a: ')
b = input(u'Input integer b: ')
if a<b:
print 'a - the smallest of two numbers'
elif a==b:
print 'a and b are equal'
else:
print 'b - the smallest of two numbers' |
457c61ff372fed2cfb1353580df8ad2637482389 | Satelee/EthicalHacking | /20. Learn Python Intermediate/197. TernaryOperator.py | 500 | 4.0625 | 4 | ## 197. Ternary Operator ##
# can also be called 'conditional expressions'
# is an operation that evaluates to something based on the condition being true or not
# same as an if-else statement, but it is a shortcut
# condition_if_true if condition else condition_if_false
# if checks condition, if it is true it will do 'condition_if_true' ottherwise it will do 'condition_if_false'
is_friend = True
can_message = "message allowed" if is_friend else "not allowed to message"
print(can_message) |
da244fed9ab59c645f7de69cdb2dc3f4580b5c6e | HelenMaksimova/new_python_lessons | /lesson_05/task_5.5.py | 673 | 3.921875 | 4 | # Представлен список чисел. Определить элементы списка, не имеющие повторений.
# Сформировать из этих элементов список с сохранением порядка их следования в исходном списке
from random import randint
num_lst = [randint(1, 10) for _ in range(15)]
uniq_nums = set()
tmp = set()
for item in num_lst:
if item not in tmp:
uniq_nums.add(item)
else:
uniq_nums.discard(item)
tmp.add(item)
result = [element for element in num_lst if element in uniq_nums]
print(num_lst)
print(result)
|
6c2042743217958d31b17978acc15c586268e007 | rushirg/30-day-leetcoding-challenge | /june-leetcoding-challenge/week-1/reverse-string.py | 917 | 3.765625 | 4 | """
Week 1 - Problem 4
Reverse String
https://leetcode.com/problems/reverse-string/solution/
"""
# method 1
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
stringLength = len(s)
for i in range(stringLength//2):
tmp = s[stringLength - i - 1]
s[stringLength - i - 1] = s[i]
s[i] = tmp
# method 2
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s = s.reverse()
# method 3
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i = 0
j = len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i+=1
j-=1 |
23200ee2b9758733d935e01ef8f5bbaf45c2b9da | blont714/Project-Euler | /Problem 7.py | 548 | 3.78125 | 4 | import math
def main():
prime_number_list = []
number = 2
while(len(prime_number_list)<10001):
if judge_prime(number):
prime_number_list.append(number)
number += 1
print(prime_number_list[-1])
def judge_prime(number):
if number%2==0 and number!=2:
return False
for i in range(2, math.floor(math.sqrt(number))+1):
if number%i==0:
return False
return True
if __name__ == "__main__":
main()
#出力結果: 104743
#実行時間: 0.277s
|
e067a959a436055f10df5cb2bc92d1d34af7c39b | vovo255/PygameOnlineChess | /Сервер/Chess.py | 1,137 | 3.546875 | 4 | import chess
LETTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
NUMBERS = ['1', '2', '3', '4', '5', '6', '7', '8']
class Board(chess.Board):
def __init__(self):
super().__init__()
def pos_to_lett(self, y, x):
return LETTERS[x] + NUMBERS[y]
def move_piece(self, x1, y1, x2, y2):
letter_move1 = self.pos_to_lett(x1, y1)
letter_move2 = self.pos_to_lett(x2, y2)
move_str = letter_move1 + letter_move2
move = chess.Move.from_uci(move_str)
if move in self.legal_moves:
self.push(move)
return True, move_str
move = chess.Move.from_uci(move_str + 'q')
if move in self.legal_moves:
self.push(move)
return True, move_str
return False, ''
def cell(self, i, j):
square = chess.square(j, i)
piece = self.piece_at(square)
if piece is None:
return ' '
piece = piece.symbol()
if piece == piece.upper():
piece = 'w' + piece
else:
piece = 'b' + piece.upper()
return piece
|
bd214182ab114232335522dfc6fbbcb99e3bde24 | kyeeh/holbertonschool-machine_learning | /supervised_learning/0x0D-RNNs/7-bi_output.py | 2,844 | 3.9375 | 4 | #!/usr/bin/env python3
"""
RNN module
"""
import numpy as np
class BidirectionalCell:
"""
Represents a bidirectional cell of an RNN
"""
def __init__(self, i, h, o):
"""
class constructor
- i: dimensionality of the data
- h: dimensionality of the hidden state
- o: dimensionality of the outputs
Creates the public instance attributes Whf, Whb, Wy,
bhf, bhb, by that represent the weights and biases of the cell
- Whf and bhf are for the hidden states in the
forward direction
- Whb and bhb are for the hidden states in the
backward direction
- Wy and by are for the outputs
"""
self.Whf = np.random.randn(h+i, h)
self.Whb = np.random.randn(h+i, h)
self.Wy = np.random.randn(h * 2, o)
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
def softmax(self, z):
"""Compute softmax values for each sets of scores in x"""
e_z = np.exp(z)
return e_z / e_z.sum(axis=1, keepdims=True)
def forward(self, h_prev, x_t):
"""
calculates the hidden state in the forward direction
for one time step
- x_t: numpy.ndarray of shape (m, i) that contains the
data input for the cell
- m: batch size for the data
- h_prev: numpy.ndarray of shape (m, h) containing the
previous hidden state
Returns: h_next, the next hidden state
"""
h_next = np.tanh(np.matmul(np.hstack((h_prev, x_t)), self.Whf)
+ self.bhf)
return h_next
def backward(self, h_next, x_t):
"""
calculates the hidden state in the backward direction
for one time step
- x_t: numpy.ndarray of shape (m, i) that contains the
data input for the cell
- m: batch size for the data
- h_next: numpy.ndarray of shape (m, h) containing the
next hidden state
Returns: h_pev, the previous hidden state
"""
h_prev = np.tanh(np.matmul(np.hstack((h_next, x_t)), self.Whb)
+ self.bhb)
return h_prev
def output(self, H):
"""
calculates all outputs for the RNN:
- H: numpy.ndarray of shape (t, m, 2 * h) that contains
the concatenated hidden states from both directions,
excluding their initialized states
- t: number of time steps
- m: batch size for the data
- h: dimensionality of the hidden states
Returns: Y, the outputs
"""
T, m, h2 = H.shape
Y = []
for t in range(T):
y = self.softmax(np.matmul(H[t], self.Wy) + self.by)
Y.append(y)
return np.array(Y)
|
5d1c3e31a993543a63a2e8fd43ddf8577a6676f3 | brennanmk/Battleship | /ships.py | 4,113 | 4.1875 | 4 | class ship: # parent ship class, written by Hank Pham & Brennan Miller-Klugman
# constructor takesin ship name as a parameter
def __init__(self, shipName, RowStart, columnStart, RowEnd, columnEnd, isSunk=False, creatingShip=False):
self.name = shipName
self.ShipRowStart = RowStart
self.ShipcolumnStart = columnStart
self.ShipRowEnd = RowEnd
self.ShipcolumnEnd = columnEnd
self.sunk = isSunk
self.created = creatingShip
def getSunk(self):
return self.sunk
def setSunk(self, isSunk):
self.sunk = isSunk
def getName(self): # get function for ship name
return self.name
def setName(self, shipName): # set function for ship name
self.name = shipName
# function to set the ships posistion
def setShipPos(self, RowStart, columnStart, RowEnd, columnEnd):
self.ShipRowStart = RowStart
self.ShipcolumnStart = columnStart
self.ShipRowEnd = RowEnd
self.ShipcolumnEnd = columnEnd
def printLocation(self): # function to display the ships location
print(" %s is at location (%s,%s) to (%s, %s)." % (
self.name, self.ShipcolumnStart, self.ShipRowStart, self.ShipcolumnEnd, self.ShipRowEnd))
def isCreated(self): # function to determine if the ship has been created
return self.created
def setCreated(self): # function to determine if the ship has been created
self.created = not self.created
def getStartColumn(self):
return self.ShipcolumnStart
def getStartRow(self):
return self.ShipRowStart
def getEndColumn(self):
return self.ShipcolumnEnd
def getEndRow(self):
return self.ShipRowEnd
class carrier(ship): # carrier is a class with the parent class ship
def __init__(self, RowStart, columnStart, RowEnd, columnEnd): # constructor for carrier class
self.size = 5
ship.__init__(self, "Carrier", RowStart,
columnStart, RowEnd, columnEnd)
def getSize(self): # function to return the ship size
return self.size
def setSize(self, size): # function to change the ship size
self.size = size
class battleShip(ship): # battleShip is a class with the parent class ship
# constructor for battleShip class
def __init__(self, RowStart, columnStart, RowEnd, columnEnd):
self.size = 4
ship.__init__(self, "BattleShip", RowStart,
columnStart, RowEnd, columnEnd)
def getSize(self): # function to display the ship size
return self.size
def setSize(self, size): # function to change the ship size
self.size = size
class cruiser(ship): # cruiser is a class with the parent class ship
def __init__(self, RowStart, columnStart, RowEnd, columnEnd): # constructor for cruiser class
self.size = 3
ship.__init__(self, "Cruiser", RowStart,
columnStart, RowEnd, columnEnd)
def getSize(self): # function to return ship size
return self.size
def setSize(self, size): # function to change ship size
self.size = size
class submarine(ship): # submarine is a class with the parent class ship
# constructor for the submarine class
def __init__(self, RowStart, columnStart, RowEnd, columnEnd):
self.size = 3
ship.__init__(self, "Submarine", RowStart,
columnStart, RowEnd, columnEnd)
def getSize(self): # function to return the ships size
return self.size
def setSize(self, size): # function to change the ships size
self.size = size
class destroyer(ship): # destroyer is a class with the parent class ship
# constructor for the destroyed class
def __init__(self, RowStart, columnStart, RowEnd, columnEnd):
self.size = 2
ship.__init__(self, "Destroyer", RowStart,
columnStart, RowEnd, columnEnd)
def getSize(self): # function to return ship size
return self.size
def setSize(self, size): # function to change ship size
self.size = size
|
6016322b5b3a920b06f307b8a05312dff9acef54 | maxfraser/learnpython | /exercises/excercise5.py | 213 | 3.640625 | 4 | import random
number1 = int(random.randint(1,100))
number2 = int(random.randint(1,100))
print(number1)
print(number2)
if (number1*number2 > 1000):
print(number1+number2)
else:
print(number1*number2)
|
d56ba21f9519d40cc920ff5b9500641b6786f21b | olinkaz93/Algorithms | /Interview_Examples/Leetcode/234_PalindromeLinkedList.py | 1,705 | 4.09375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# we keep fast runner and slow runner
# fast runner goes to the end of the list
# when it reaches , the point of slow runner will reverse the list
#then compare the values
class Solution(object):
def reverse(self, node):
if node == None:
return None
current = node
previous = None
while (current != None):
next_node = current.next
current.next = previous
previous = current
current = next_node
head = previous
return head
def isPalindrome(self, head):
if head == None:
return False
if head.next == None:
return True
slow_runner = head
fast_runner = head
while (fast_runner != None and fast_runner.next != None):
fast_runner = fast_runner.next.next
slow_runner = slow_runner.next
sorted_half_linked_list = self.reverse(slow_runner)
fast_runner = head
slow_runner = sorted_half_linked_list
#print(slow_runner.val)
#print(slow_runner.next.val)
#print("MAIN",head)
#print("SORTED",sorted_half_linked_list)
while(slow_runner != None):
if fast_runner.val != slow_runner.val:
return False
slow_runner = slow_runner.next
fast_runner = fast_runner.next
return True |
ccf32ecc16c0a41df727156cc94a0226cf04424e | alicekykwan/ProjectEuler-First-100 | /pe052.py | 693 | 3.65625 | 4 | from collections import *
from itertools import *
from random import *
from time import *
from functools import *
from fractions import *
from math import *
'''
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits,
but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
def main():
for i in range(1,7):
print(i/7.)
for i in count(1):
c = Counter(str(i))
if all(Counter(str(i*j))==c for j in range(2,7)):
print(i)
break
start = time()
print('\n\n')
print(main())
print('Program took %.02f seconds' % (time()-start)) |
2fbaa17d89760232d2f7f52ccc85b350b2d04eca | tigervanilla/Guvi | /even_to_odd.py | 112 | 3.78125 | 4 | n=int(input())
if n%2: print('1')
else:
ans=1
while not n%2:
ans*=2
n//=2
print(ans) |
77f56ec4f72c22aa6b8d3d58d36ca3d7f94a6779 | coolmich/py-leetcode | /solu/241. Different Ways to Add Parentheses.py | 970 | 3.546875 | 4 | from collections import defaultdict
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
def compute(operator, i1, i2):
if operator == '+': return i1+i2
if operator == '-': return i1-i2
if operator == '*': return i1*i2
def helper(cache, input):
if input in cache: return cache[input]
res = []
for i in range(len(input)):
if input[i] in ('+', '-', '*'):
l, r = helper(cache, input[:i]), helper(cache, input[i+1:])
for ll in l:
for rr in r:
res.append(compute(input[i], ll, rr))
if not res:
res.append(int(input))
cache[input] = res
return res
cache = defaultdict(list)
helper(cache, input)
return cache[input]
|
a0783664ed040e7414af0932a87191d2afecfb72 | shubhangiranjan11/Hackaifelse | /if else6.py | 153 | 4.09375 | 4 | user=int(input("any number"))
if user%2==0:
print("even number")
elif user!=2:
print("odd number")
else:
print("number is not working")
|
5f8f75bb7f45503ec40381ed37796da5477f0a34 | digicosmos86/MicroInventor_Hugo | /content/unit1/lesson7.files/binary.py | 209 | 3.9375 | 4 | def int_to_bin(num):
return bin(num)[2:]
def str_to_bin(string):
return [bin(ord(ch))[2:].zfill(8) for ch in string]
if __name__ == "__main__":
print(int_to_bin(123))
print(str_to_bin("123")) |
b3ff0fa25546436ba0dc27f50520d6514f46299c | sajjad0057/Practice-Python | /DS and Algorithm/Max_Pairwise_product.py | 1,383 | 3.765625 | 4 | # n = int(input("Enter The no of array length : "))
# num = []
# for i in range(n):
# x = int(input())
# num.append(x)
# result = 0
# for i in num:
# for j in num:
# if i != j:
# x = i*j
# if x>=result:
# result = x
#
# print("Maximum Pairwise product :",result)
# def max_pairwise_product_naive(a):
# result = 0
# for i in a:
# for j in a:
# if i != j:
# x = i*j
# if x>=result:
# result = x
# return result
'''
Best solution below :
'''
def max_pairwise_product_naive(a):
result = 0
for i in range(len(a)):
for j in range(i+1,len(a)):
result = max(result,a[i]*a[j])
return result
def max_pairwise_product_fast(a):
index_1 = 0
for i in range(1,len(a)):
if a[i]>a[index_1]:
index_1 = i
index_2 = 0
for j in range(1,len(a)):
if a[index_1] != a[j] and a[j]>a[index_2]:
index_2 = j
return a[index_1]*a[index_2]
n = int(input("Enter The no of array length : "))
num = []
for i in range(n):
x = int(input())
num.append(x)
print("max_pairwise_product_first ---->",max_pairwise_product_fast(num))
print("max_pairwise_product_naive ---->",max_pairwise_product_naive(num))
|
cf61dd32ca2eb55f400b002c812fe022ac187e2d | Usernamebart/python_course_by_adrian_gonciarz | /hw_day6.py | 2,351 | 4.0625 | 4 | #Zadanie2 - oblicznie BMI
# Napisz metodę calculate_bmi, która przyjmie 2 parametry:
# • Wagę w kilogramach
# • Wzrost w metrach
# I zwróci wartość współczynnika BMI dla tych danych https://pl.wikipedia.org/wiki/Wska%C5%BAnik_masy_cia%C5%82a
# Policz współczynnik BMI dla następujących danych:
# • Waga 80.3 kg, wzrost 1.80m
# • Waga 119.9 kg, wzrost 1.71m
def calculate_bmi(kg, m):
return kg / m**2
kg1 = 80.3
m1 = 1.80
kg2 = 119.9
m2 = 1.71
your_bmi1 = calculate_bmi(kg1, m1)
your_bmi2 = calculate_bmi(kg2, m2)
print(f'With your weight {kg1}kg and your height {m1}m your BMI is: ', round(your_bmi1,2))
print(f'With your weight {kg2}kg and your height {m2}m your BMI is: ', round(your_bmi2,2))
#Zadanie3 - ryzyko chorób
# Napisz metodę która przyjmie wartość współczynnika BMI i wydrukuje status naszej wagi zgodnie z tabelą w artykule
# Wikipedii jako:
# • Niedowaga
# • Optimum
# • Nadwaga
# • Otyłość
def weight_status(bmi):
if bmi < 18.5:
print('With given BMI your weight status is: Underweight')
elif 18.5 <= bmi < 24.50:
print('With given BMI your weight status is: Optimum')
elif 24.50 <= bmi < 30.0:
print('With given BMI your weight status is: Overweight')
else:
print('With given BMI your weight status is: Obesity')
weight_status(26)
#Zadanie4 - Napisz skrypt, który zapyta użytkownika o wagę i wzrost następnie wydrukuje
#informację o statusie wagi (niedowaga/optimum/nadwaga/otyłość)
height = float(input('Tell me what is your height (in meters, eg. 1.75): '))
weight = float(input('And now tell me what is your weight (in kilos, eg. 70.0): '))
your_bmi = weight / height**2
if your_bmi < 18.5:
print(f'With your height {height}m and weight {weight}kg your BMI is', round(your_bmi,2), 'so you are underweight :(')
elif 18.5 <= your_bmi < 24.50:
print(f'With your height {height}m and weight {weight}kg your BMI is', round(your_bmi,2), 'so you have optimum weight :)')
elif 24.50 <= your_bmi < 30.0:
print(f'With your height {height}m and weight {weight}kg your BMI is', round(your_bmi,2), 'so you are overweight :(')
else:
print(f'With your height {height}m and weight {weight}kg your BMI is', round(your_bmi,2), 'so you have obsity! :(')
|
b2b6097c171d98bcceb1660013430787ef81e23f | nidamirza9/Python-for-Data-Science | /Learn_Basic.py | 3,217 | 4.15625 | 4 | ##Learn python.org
#Nida Mirza
#5CE-1-->30
#Learn the Basic:
##1.Hello, World!
print('\n---------------------------\n')
print('Nida Mirza')
print('5CE-1')
x=1
if x==1:
print("Enroll-no:180630107030")
print('\n---------------------------\n')
print('---------------------------\n')
print('\nA:')
myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)
print('\nB:')
one = 1
two = 2
three = one + two
print(three)
hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)
print('\nC:')
# change this code
mystring = "hello"
myfloat = 10.0
myint = 20
# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
print('\n---------------------------\n')
##List:
print('---------------------------\n')
print('\nA:')
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist:
print(x)
print('\nB:')
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# write your code here
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("Nida ")
strings.append("Mirza ")
second_name = names[1]
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
print('\n---------------------------\n')
print('---------------------------\n')
print('\nA:')
remainder = 11 % 3
print(remainder)
print('\nB:')
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
print('\nC:')
lotsofhellos = "Nida " * 3
print(lotsofhellos)
print('\nD:')
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
print('\nE:')
print([1,2,] * 2)
print('\nF:')
x = object()
y = object()
# TODO: change this code
x_list = [x] * 10
y_list = [y] * 10
big_list = x_list + y_list
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")
print('\n---------------------------\n')
print('---------------------------\n')
print('String formatting--> ')
print('\nA:')
name = "Nida"
age = 20
print("%s is %d years old." % (name, age))
print('\nB:')
data = ("Nida", "Mirza", 57.9)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
print('\n---------------------------\n')
print('---------------------------\n')
print("A:")
n='Nida Mirza'
print(len(n))
print('\nB:')
k="Nidaaa"
print('String index: %s',%k)
print(k.index("a"))
print('\nC:')
k="Nidaaaa"
print('String count of %s'%k)
print(k.count("a"))
print('\nD:')
astring = "Nida Mirza!"
print(astring[3:7])
print(astring[3:7:1])
|
7da3b90e5cb269ac3c67e3af296aeba1a60e4bed | ChiniGumy/ejercicios-espol | /Examen 2016 1S Mejora/Tema 1/Tema 1.py | 2,505 | 3.5 | 4 | from os import write
def cargar_datos(nombre_archivo):
diccionario_datos = {}
archivo_datos = open(nombre_archivo, "r")
lineas = archivo_datos.readlines()
archivo_datos.close() # depues de un readlines ya se puede cerrar el archivo, ya que no se lo llama despues
diccionario_datos["M"] = int(lineas[0])
diccionario_datos["Corta"] = float(lineas[1])
diccionario_datos["Larga"] = float(lineas[2])
diccionario_datos["Infinitivo"] = float(lineas[3])
return diccionario_datos
#print(cargar_datos("costos.txt"))
def calcular_costos(datos, nombre_archivo):
archivo_texto = open(nombre_archivo, "r")
suma_total = 0
for linea in archivo_texto:
palabras = linea.replace(".","").strip().split(" ") # el metodo replace() remplaza caracteres en un string, los deseados tendran que ponerse adentro como argumentos
for palabra in palabras:
if palabra.endswith("ar") or palabra.endswith("er") or palabra.endswith("ir"): # el metodo endswith() valida si un string termina con: # lo que se ponga en el argumento
suma_total += datos["Infinitivo"]
elif len(palabra) <= datos["M"]:
suma_total += datos["Corta"]
else:
suma_total += datos["Larga"]
archivo_texto.close()
return round(suma_total, 2)
#print(calcular_costos(cargar_datos("costos.txt"), "texto.txt"))
def cambiar_mensaje(datos, nombre_archivo1, nombre_archivo2):
archivo1 = open(nombre_archivo1 ,"r")
archivo2 = open(nombre_archivo2, "w")
longitud_maxima = datos["M"] - 1
for linea in archivo1:
palabras = linea.strip().split(" ")
for palabra in palabras:
if "." not in palabra:
if len(palabra) > datos["M"]:
archivo2.write(f"{palabra[:longitud_maxima]}#") # estoy tomando los caracteres de palabra del indice 0 a longitd_maxima( datos["M"] - 1 )
else:
archivo2.write(palabra)
else:
palabra = palabra.replace(".","")
if len(palabra) > datos["M"]:
archivo2.write(f"{palabra[: longitud_maxima]}#END")
else:
archivo2.write(f"{palabra}END")
archivo2.write(" ")
archivo2.write("\n")
archivo1.close()
archivo2.close()
cambiar_mensaje(cargar_datos("costos.txt"),"texto.txt","texto traducido.txt")
|
6cc8734c2b5441af7b058c263c386f224b9f654e | aspadm/labworks | /module1-2/roots_protect2.py | 2,067 | 3.75 | 4 | # Кириллов Алексей, ИУ7-22
# Защита уточнений корней, метод касательных
from math import sin, cos
def f(x):
#return x*2-4
return sin(x)
def fs(x):
return cos(x)
a, b = map(float, input('Задайте границы отрезка: ').split())
eps = float(input('Задайте точность по х: '))
max_iter = int(input('Максимальное число итераций: '))
if (f(a) >= 0 and f(b) >= 0) or (f(a) < 0 and f(b) < 0):
print('Невозможно вычислить: некорректные границы, f(a)=',f(a),'f(b)=',f(b))
x = a
xprev = b
iter_count = 0
while abs(xprev - x) > eps:
if iter_count == max_iter:
print('Значение 1 не найдено за',max_iter,'итераций')
break
xprev = x
x = x - f(x)/fs(x)
#print(iter_count,x)
if x > b or x < a:
print('Касательная 1 указывает за пределы интервала({:5.6})'.format(x))
break
iter_count += 1
eps_real = abs(xprev - x)
if eps_real <= eps:
print('Корень найден за {:} итераций, x = {:5.6f}; \
f(x) = {:2.1g}, погрешность = {:2.1g}'.format(iter_count, x, f(x) ,eps_real))
else:
x = b
xprev = a
iter_count = 0
while abs(xprev - x) > eps:
if iter_count == max_iter:
print('Значение 2 не найдено за',max_iter,'итераций')
break
xprev = x
x = x - f(x)/fs(x)
#print(iter_count,x)
if x > b or x < a:
print('Касательная 2 указывает за пределы интервала({:5.6})'.format(x))
break
iter_count += 1
eps_real = abs(xprev - x)
if eps_real <= eps:
print('Корень найден за {:} итераций, x = {:5.6f}; \
f(x) = {:2.1g}, погрешность = {:2.1g}'.format(iter_count, x, f(x) ,eps_real))
|
9e474c42dbc89428d1ef919d7bfb01c978984f57 | Syase4ka/SomePythonExercises | /theVolumeOfLiquid.py | 749 | 4.21875 | 4 |
""" Calculates the volume of liquid held in a disposable cup
"""
import math
def cone_volume (bottom_radius, top_radius, height):
""" Calculates the volume of liquid held in a disposable cup
Arguments:
bottom_radius - bottom radius of a truncated cone (float)
top_radius - top radius of a truncated cone (float)
height - height of a truncated cone (float)
Returns:
Volume of a truncated cone (float)
Doctest is accurate to 2 decimal places
>>> round (cone_volume(2,3,10),2)
198.97
>>> round (cone_volume(3,4,15),2)
581.19
>>> round (cone_volume(5,5,20),2)
1570.8
"""
volume = math.pi/3*height*(bottom_radius**2+bottom_radius*top_radius+top_radius**2)
return volume
|
974e81f2c1e786c86e6f2e2170b1c62a175b6f30 | ankeetshankar/D04 | /HW04_ch08_ex05.py | 1,921 | 4.71875 | 5 | # Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 5 for the task.
# Please do provide function calls that test/demonstrate your
# function.
#Exercise 8.5. A Caesar cypher is a weak form of encryption that involves “rotating” each letter by
#a fixed number of places. To rotate a letter means to shift it through the alphabet, wrapping around
#to the beginning if necessary, so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’.
#To rotate a word, rotate each letter by the same amount. For example, “cheer” rotated by 7 is “jolly”
#and “melon” rotated by -10 is “cubed”. In the movie 2001: A Space Odyssey, the ship computer
#is called HAL, which is IBM rotated by -1.
#Write a function called rotate_word that takes a string and an integer as parameters, and returns
#a new string that contains the letters from the original string rotated by the given amount.
#You might want to use the built-in function ord, which converts a character to a numeric code, and chr, which converts numeric codes to characters. Letters of the alphabet are encoded in alphabetical
#order, so for example:
#
#
#
#>>>ord('c') - ord('a')
#2
#Because 'c' is the two-eth letter of the alphabet. But beware: the numeric codes for upper case
#letters are different.
#Potentially offensive jokes on the Internet are sometimes encoded in ROT13, which is a Caesar
#cypher with rotation 13. If you are not easily offended, find and decode some of them. Solution:
#http: // thinkpython2. com/ code/ rotate. py .
#
def rotate_word(string,rotator_number):
z =""
#This function takes in two parameters string and rotator_number.
for x in range(0,len(string)):
temp = chr((ord(string[x]))+rotator_number)
z = z + temp
continue
return z
def main():
print('rotate_word')
print ("\n")
rotate_word("Ankeet",3)
if __name__ == '__main__':
main()
|
d541b716ce8bd9951812e58d2cb714246c8b3a7a | Mighel881/SimplePasswordGen | /PwGen.py | 530 | 3.65625 | 4 | #importing shit
import random, string
#PEE PEE POO POO
#raw_input asking for user input to return as a string, then convert into an integer
password_length = int(input("HOW LONG DO U LIKE THEM?"))
#POO POO PEE PEE
password_characters = string.digits + string.punctuation
#sets a blank list (of strings, individual characters, but strings)
password = []
#LMAO PEEPEE
for x in range(password_length):
#hacker coder stuff lol
password.append(random.choice(password_characters))
#doing stuff lmao
print(''.join(password))
|
4d5bb399813631e9bf77c5cdd2a18ba51bfdcd24 | shadmanhiya/Python-Projects- | /hourrate.py | 813 | 4.1875 | 4 |
"""
Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours.
Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input
to read a string and float() to convert the string to a number. Do not worry about error checking the user input -
assume the user types numbers properly.
"""
hrs = input("Enter Hours:")
h = float(hrs)
try:
rt = input ("Enter Rate: ")
r = float(rt)
except:
print("Error! Enter Numeric Values!!!")
quit()
if h <= 40:
pay = h * r
elif h > 40:
nh = h - 40
pay = (h - nh) * r
np = nh * (r * 1.5)
npay = pay + np
print("Has to pay: ", npay) |
1d3e8fb09df2ab1a5c8934598b599c75621931c5 | nlakritz/codingbat-python-solutions | /logic-2/lone_sum.py | 199 | 3.71875 | 4 | def lone_sum(a, b, c):
subtract = 0
if a == b or a == c:
subtract += a
if b == a or b == c:
subtract += b
if c == a or c == b:
subtract += c
sum = a+b+c
return sum - subtract
|
b0e9db768d8b1ec351971dc26c531a0b9c98a928 | PlumpMath/exercises-for-programmers | /python/ex-6.py | 456 | 4 | 4 | # 퇴직 계산기
import datetime
current_age = int(input('What is yout current age? '))
retire_age = int(input('At what age would you like to retire? '))
left_years = retire_age - current_age
current_year = datetime.date.today().year
retire_year = current_year + left_years
print('You have ' + str(left_years) + ' years left until you can retire.')
print('It\'s ' + str(current_year) + ', ' +
'so you can retire in ' + str(retire_year) + '.')
|
7a767cc5d9e9641f4bd309d99a7b58285dad5fa6 | Trietptm-on-Coding-Algorithms/projecteuler-1 | /Problem2.py | 996 | 4.21875 | 4 | #! /usr/bin/env python
from math import sqrt
"""\
Project Euler problem 2
Even Fibonacci numbers
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 even_fibonacci_elements(n=3, limit_term=33):
# Every third term in the Fibonacci sequence is even; so there is no need to calculate every
# single term.
# Also, any nth Fibonacci term can be expressed by
# F(n) = ((phi)^n - (-phi)^(-n))/sqrt(5)
fib_elem = 0
phi = (1 + sqrt(5))/2
while n <= limit_term:
fib_elem = (phi**n - (-phi)**(-n))/sqrt(5)
print n, fib_elem
yield fib_elem
n += 3
sum_of_even_fibs = 0
for elem in even_fibonacci_elements():
sum_of_even_fibs += elem
print sum_of_even_fibs |
7720c6fb1d6a14ed37a2179ea1b5c69cb54f1e8e | fubst0318/webscrawl_cn | /multiprocessing_content/mulpStart.py | 256 | 3.609375 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
这是一个multiprocessing的模块开始模块
'''
from multiprocessing import Pool
def f(x):
return x * x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
|
035c04836fe664bb17d15d560d77f16debd19737 | padth4i/beginner-scripts | /hangman.py | 919 | 4.09375 | 4 | import time
from random_word import RandomWords
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
# Return a single random word
r = RandomWords()
word = r.get_random_word()
guesses = ''
turns = 10
misses = ''
while turns > 0:
failed = 0
print("Misses so far: " + misses)
for char in word:
if char in guesses:
print(char, end=' ')
else:
print("_", end=' ')
failed += 1
if failed == 0:
print("Congratulations! You won!")
break
guess = input("Please, guess a character:")
guesses += guess
if guess not in word:
turns -= 1
misses +=guess
print("Wrong")
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Lose")
else:
print("Great Guess!")
|
d9d766e9113248a329930156b5757fa499e09bfb | iamgbn-git/git-hub-exercises | /Solutions/_rectangle_class.py | 416 | 4.34375 | 4 | #Question 53
'''Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
Hints:
Use def methodName(self) to define a method.'''
class Rectangle:
def __init__(self, l , w):
self.length = l
self.width = w
def area(self):
print(self.length*self.width)
rectangle = Rectangle(2,4)
rectangle.area()
|
708b9695866ad97f2b61c60cf8ccce811de006d5 | ISSOtm/1234-golf | /program_stats.py | 654 | 3.71875 | 4 | #!/usr/bin/python3
import sys
import string
banned_chars = "'\"0123456789"
illegal_chars = []
char_count = 0
line_id = 0
with open(sys.argv[1], "rt") as in_file:
for line in in_file:
line_id = line_id + 1
col_id = 0
for char in line:
col_id = col_id + 1
if char in banned_chars:
illegal_chars.append((char, line_id, col_id))
elif not char in string.whitespace:
char_count = char_count + 1
if illegal_chars:
print("Illegal characters were found!")
for pair in illegal_chars:
print("{} @ line {}, column {}".format(*pair))
else:
print("The program is valid!")
print("It also contains {} characters.".format(char_count))
|
332159b5701af9fcf781bb62a8575b749f565717 | vany-oss/python | /pasta para baixar/netcha/exer 41classifcao de ateletas.py | 494 | 3.71875 | 4 | from datetime import date
actual = date.today().year
nasc = int(input('Data do seu nascimento '))
idade = actual - nasc
print(f'O ateleta tem {idade} anos.')
if idade <= 9:
print('Classificaçao: Mirim.')
elif idade <= 15:
print('Classificação Infantil.')
elif idade <= 19:
print('Classificação Junior.')
elif idade <= 25:
print('Classificação Senior.')
else:
print('Classificação Master.')
#pg que classifica os ateleta conforme a sua idade usanda if e el 5 veses |
2ba26b307e6cd11e7e813b0c74e899f54983c919 | tummybunny/py-tetris | /Tetris.py | 9,459 | 3.5625 | 4 | """
By Alexander Yanuar Koentjara - my attempt to learn Python by creating simple app
"""
import pygame
from random import randrange
from pygame.locals import *
from pygame.draw import lines, line
displaySize = width, height = (240, 400)
blockSize = 20
score = 0
level = 1
downTick = 30
class RecyclingColors:
from pygame.color import THECOLORS as c
colors = [ c['darkseagreen3'], c['firebrick'], c['mediumpurple3'], c['deepskyblue1'],
c['gray'], c['gold4'], c['mediumorchid4'], c['azure4'] ]
def __init__(self):
self.current = 0
def next(self):
c = RecyclingColors.colors[self.current]
self.current = (self.current + 1) % len(RecyclingColors.colors)
return c
class Checkers:
def __init__(self, blocks):
self.blocks = blocks
def draw(self, surface, x, y):
def darken(rgb, d = 40):
return max(rgb - d, 0)
def lighten(rgb, d = 40):
return min(rgb + d, 255)
maxV = len(self.blocks)
maxH = len(self.blocks[0])
for py in range(maxV):
for px in range(maxH):
col = self.blocks[py][px]
if col:
shadow = Color(*[darken(col[i]) for i in range(3)])
bright = Color(*[lighten(col[i]) for i in range(3)])
bx = (x + px) * blockSize
by = (y + py) * blockSize
r = Rect(bx + 1, by + 1, blockSize - 1, blockSize -1)
surface.fill(col, r)
lines(surface, shadow, False, [(bx, by), (bx, by + blockSize - 1),
(bx + blockSize - 1, by + blockSize - 1)])
lines(surface, bright, False, [(bx, by), (bx + blockSize - 1 , by),
(bx + blockSize - 1, by + blockSize - 1)])
class Board(Checkers):
def __init__(self, blocks):
Checkers.__init__(self, blocks)
def draw(self, surface, block):
minX = 99
maxX = 0
for y in range(block.shape.dim):
for x in range(block.shape.dim):
if block.shape.blocks[y][x]:
minX = min(x, minX)
maxX = max(x, maxX)
maxV = len(self.blocks)
maxH = len(self.blocks[0])
for px in range(maxH):
if block.x + minX <= px <= block.x + maxX:
surface.fill((20, 20, 20), Rect(px * blockSize, 0, blockSize, maxV * blockSize))
line(surface, (30, 30, 30), (px * blockSize, 0), (px * blockSize, maxV * blockSize))
for py in range(maxV):
line(surface, (30, 30, 30), (0, py * blockSize), (maxH * blockSize, py * blockSize))
super().draw(surface, 0, 0)
class Shape(Checkers):
def __init__(self, data = None, color = Color(0, 0, 0)):
if not data:
data = [[]]
self.dim = max(len(data), max([len(d) for d in data]))
blocks = Shape.__emptyBlocks(self.dim)
rows = 0
for row in data:
cols = 0
for v in row:
blocks[rows][cols] = color if v else 0
cols += 1
rows += 1
self.color = color
Checkers.__init__(self, blocks)
def __emptyBlocks(slot):
return [[0 for _ in range(slot)] for _ in range(slot)]
def clone(self, color = None):
c = color if color else self.color
s = Shape(0, c)
s.blocks = [ [ c if col else 0 for col in row ] for row in self.blocks ]
s.dim = self.dim
return s
def rotateRight(self):
bl = Shape.__emptyBlocks(self.dim)
for py in range(self.dim):
for px in range(self.dim):
bl[px][self.dim - 1 - py] = self.blocks[py][px]
self.blocks = bl
return self
def rotateLeft(self):
bl = Shape.__emptyBlocks(self.dim)
for py in range(self.dim):
for px in range(self.dim):
bl[self.dim - 1 - px][py] = self.blocks[py][px]
self.blocks = bl
return self
def draw(self, surface, x, y):
super().draw(surface, x, y)
def checkBound(self, board, x, y):
maxV = len(board)
maxH = len(board[0])
for py in range(self.dim):
for px in range(self.dim):
if self.blocks[py][px]:
vx = x + px
vy = y + py
if 0 <= vy < maxV and 0 <= vx < maxH:
if board[vy][vx]:
return False
else:
return False
return True
def mark(self, board, x, y):
maxV = len(board)
maxH = len(board[0])
global score
score += 10
for py in range(self.dim):
for px in range(self.dim):
vy = py + y
vx = px + x
if 0 <= vy < maxV and 0 <= vx < maxH and self.blocks[py][px]:
board[vy][vx] = self.color
for row in range(maxV - 1, 0, -1):
complete = 0
while True:
filled = True
for col in range(maxH):
if not board[row][col]:
filled = False
break
if filled:
del board[row]
board.insert(0, [ 0 for _ in range(maxH) ])
complete += 1
else:
break
if complete:
global level
score += 100 * (complete ** 2)
level = int(score / 1000) + 1
class Blocks:
def __init__(self, board, x, y, shape):
self.board = board
self.x = x
self.y = y
self.shape = shape
def checkBound(self, x, y, shape = None):
if not shape:
shape = self.shape
return shape.checkBound(self.board, x, y)
def draw(self, surface):
self.shape.draw(surface, self.x, self.y)
def down(self):
if self.checkBound(self.x, self.y + 1):
self.y += 1
return True
else:
self.shape.mark(self.board, self.x, self.y)
return False
def right(self):
if self.checkBound(self.x + 1, self.y):
self.x += 1
def left(self):
if self.checkBound(self.x - 1, self.y):
self.x -= 1
def rotateRight(self):
if self.checkBound(self.x, self.y, self.shape.clone().rotateRight()):
self.shape.rotateRight()
def rotateLeft(self):
if self.checkBound(self.x, self.y, self.shape.clone().rotateLeft()):
self.shape.rotateLeft()
def drop(self):
while self.down():
pass
return True
def main():
shapes = [
Shape([[1, 1], [1, 1]]),
Shape([[], [1, 1, 1, 1]]),
Shape([[1, 1, 1], [1]]),
Shape([[1], [1, 1, 1]]),
Shape([[1, 1], [0, 1, 1]]),
Shape([[0, 1, 1], [1, 1]]),
Shape([[0, 1, 0], [1, 1, 1]]),
]
hBlocks = int(width / blockSize)
vBlocks = int(height / blockSize)
center = int(hBlocks / 2) - 2
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode(displaySize)
pygame.display.set_caption('Tetris')
pygame.mouse.set_visible(False)
font = pygame.font.Font(None, 20)
background = pygame.Surface(screen.get_size())
background = background.convert()
rc = RecyclingColors()
board = [[ 0 for _ in range(hBlocks)] for _ in range(vBlocks)]
repeat = True
ticks = 0
current = 0
gameBoard = Board(board)
spawn = True
def randomShape():
return shapes[randrange(0, len(shapes))].clone(rc.next())
while repeat:
if spawn:
spawn = False
if current:
del current
current = Blocks(board, center, 0, randomShape())
if not current.checkBound(current.x, current.y):
# game over
repeat = False
current = 0
ticks += 1
clock.tick(30)
background.fill((0, 0, 0))
if current:
gameBoard.draw(background, current)
current.draw(background)
text = font.render("Level %s Score %s" % (level, score), 1, (255, 255, 255))
background.blit(text, (1, 1))
if ticks % (downTick - level * 2) == 0:
if not current.down():
spawn = True
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_q:
current.rotateLeft()
elif event.key == K_w or event.key == K_KP5:
current.rotateRight()
elif event.key == K_LEFT or event.key == K_KP4:
current.left()
elif event.key == K_RIGHT or event.key == K_KP6:
current.right()
elif event.key == K_DOWN or event.key == K_KP2:
current.down()
elif event.key == K_SPACE or event.key == K_KP0:
spawn = current.drop()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
repeat = False
screen.blit(background, (0, 0))
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
|
75f769c4efeb620a4a5ff4645955b7181d302da8 | andrewtammaro10/TicTacToe | /Tammaro TicTacToe.py | 5,771 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 31 20:48:40 2021
@author: drewtammaro
"""
position = input( "Choose a position: " )
print( position )
spaces = ['A1','B1','C1','A2','B2','C2','A3','B3','C3']
#{space: '_' for space in board}
board = dict.fromkeys(spaces)
#board = {boardlist: '_' for boardlist[0:8]}
print(board)
P1 = 'X'
P2 = 'O'
def ttr(board,start):
if None in board.values():
position = input( "Choose a position: " )
print( position )
if position in board:
print('Real spot broseph')
else:
print('Thats not gonna get it done')
else:
print('The game is a tie')
board = [ ['-','-','-'], ['-','-','-'], ['-','-','-']]
for i in range(0,3): print(board[i])
def ttt():
board = [ ['-','-','-'], ['-','-','-'], ['-','-','-']]
count = 0
for i in range(10):
if count == 9:
print("The game is a tie. How fun!")
break
else:
if (count % 2 == 0):
turn = 'X'
else:
turn = 'O'
for i in range(0,3): print(board[i])
print(count)
position = input( "Choose a position: " )
if position == 'A1':
if board[0][0] == '-':
board[0][0] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'B1':
if board[0][1] == '-':
board[0][1] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'C1':
if board[0][2] == '-':
board[0][2] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'A2':
if board[1][0] == '-':
board[1][0] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'B2':
if board[1][1] == '-':
board[1][1] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'C2':
if board[1][2] == '-':
board[1][2] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'A3':
if board[2][0] == '-':
board[2][0] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'B3':
if board[2][1] == '-':
board[2][1] = turn
count += 1
else:
print("Position taken")
count = count
continue
elif position == 'C3':
if board[2][2] == '-':
board[2][2] = turn
count += 1
else:
print("Position taken")
count = count
continue
else:
print("Invalid board position cuh")
continue
if wincheck(board):
for i in range(0,3): print(board[i])
print("Winner!")
break
else:
continue
# else:
# print("The game is a tie. How fun!")
def wincheck(board):
# top row
if board[0][0] == 'X' and board[0][1] == 'X' and board[0][2] == 'X':
return True
elif board[0][0] == 'O' and board[0][1] == 'O' and board[0][2] == 'O':
return True
# middle row
elif board[1][0] == 'X' and board[1][1] == 'X' and board[1][2] == 'X':
return True
elif board[1][0] == 'O' and board[1][1] == 'O' and board[1][2] == 'O':
return True
# bottom row
elif board[2][0] == 'X' and board[2][1] == 'X' and board[2][2] == 'X':
return True
elif board[2][0] == 'O' and board[2][1] == 'O' and board[2][2] == 'O':
return True
# left column
elif board[0][0] == 'X' and board[1][0] == 'X' and board[2][0] == 'X':
return True
elif board[0][0] == 'O' and board[1][0] == 'O' and board[2][0] == 'O':
return True
# middle column
elif board[0][1] == 'X' and board[1][1] == 'X' and board[2][1] == 'X':
return True
elif board[0][1] == 'O' and board[1][1] == 'O' and board[2][1] == 'O':
return True
# right column
elif board[0][2] == 'X' and board[1][2] == 'X' and board[2][2] == 'X':
return True
elif board[0][2] == 'O' and board[1][2] == 'O' and board[2][2] == 'O':
return True
# diagonal
elif board[0][0] == 'X' and board[1][1] == 'X' and board[2][2] == 'X':
return True
elif board[0][0] == 'O' and board[1][1] == 'O' and board[2][2] == 'O':
return True
# anti diagonal
elif board[0][2] == 'X' and board[1][1] == 'X' and board[2][0] == 'X':
return True
elif board[0][2] == 'O' and board[1][1] == 'O' and board[2][0] == 'O':
return True
else:
return False
|
cf194dd4a902b25fa8f0c36e89b3c52dd42afb53 | gdwyer3/Minesweeper_ML | /Generate.py | 2,513 | 3.59375 | 4 | import json
import random
import time
str_index = 0
bomb_count = 5
class Generator():
def __init__(self, bomb_count, height, width):
self.bomb_count = bomb_count
self.height = height
self.width = width
self.board = [[0 for i in range(width)] for j in range(height)]
for i in range(bomb_count):
while True:
loc = (random.randint(0, len(self.board)-1),random.randint(0, len(self.board[0])-1))
if self.board[loc[0]][loc[1]] != 9:
self.board[loc[0]][loc[1]] = 9
break
self.display_board()
self.numerize()
self.display_board()
def numerize(self):
for y in range(len(self.board)):
for x in range(len(self.board[0])):
self.assign_number(y, x)
def assign_number(self, Ys, Xs):
if self.board[Ys][Xs] == 9:
return
num = 0
startX = max(0,Xs-1)
startY = max(0,Ys-1)
endX = min(len(self.board[0])-1, Xs+1)
endY = min(len(self.board)-1, Ys+1)
for y in range(startY, endY+1):
for x in range(startX, endX+1):
if self.board[y][x] == 9:
num += 1
self.board[Ys][Xs] = num
def display_board(self):
for i in range(len(self.board)):
print('')
for j in range(len(self.board[0])):
print(self.board[i][j], end=" ")
print(" ")
def getSafeSq(self):
"""
returns coordinates of a safe square of form: (x,y)
"""
c, i = max([(c, i) for i, c in enumerate(self.stringify()) if c < '9'])
return (int(i / self.width), i % self.width)
def stringify(self):
"""return 1d string representation of generated board"""
ret = ""
for y in range(len(self.board)):
for x in range(len(self.board[0])):
ret += str(self.board[y][x])
return ret
def writeToJson(self, jsonFile):
data = {}
data["dim"] = str(self.height) +"," +str(self.width)
data["bombs"] = str(self.bomb_count)
loc = self.getSafeSq()
data["safe"] = str(loc[0]) + "," + str(loc[1])
data["board"] = self.stringify()
with open(jsonFile, 'w') as output:
json.dump(data, output)
G = Generator(15, 10, 10)
G.writeToJson("test3.json") |
04c43ec0339b2c18da755586f81841fd81c2ca4d | sadique720/python-basics | /P.P.P/if else elif.py | 183 | 4 | 4 | x=int(input("enter a number"))
if (x==1):
print("One")
elif (x==2):+
print("Two")
elif (x==3):
print("Three")
elif (x==4):
print("Four")
else:
print("Wrong input") |
277a66889972517c48b0d969a888d2a27229a60c | surender-karu/HackerRankProblems | /arrays/repeated_str.py | 555 | 3.640625 | 4 | s = 'a'
a = 10
def repeatedString(s, n):
str_len = len(s)
if str_len == 1 and s == 'a':
return n
count_a_in_str = 0
for c in s:
if c == 'a':
count_a_in_str = count_a_in_str + 1
if count_a_in_str == 0:
#no a in s
return 0
num_repeats = n // str_len
tail_str_len = n % str_len
remaining = 0
for i in range(tail_str_len):
if s[i] == 'a':
remaining = remaining + 1
return num_repeats * count_a_in_str + remaining
print(repeatedString(s, 10)) |
c54b88dea51a0e2ce5c1ae9dab5357e5628f73fb | B-Weyl/AdventOfCode | /Day9/sol.py | 676 | 3.53125 | 4 | import sys
def main():
s = input()
total = 0
skip = False
garbage = False
answer = 0
x = 0
for c in s:
if skip:
skip = False
continue
if c == '!':
skip = True
continue
if garbage and c == '>':
garbage = False
continue
elif garbage:
x += 1
continue
if c == '<':
garbage = True
continue
if c == '{':
total += 1
answer += total
continue
elif c == '}':
total -= 1
continue
print(answer)
print(x)
main() |
f8d8da479204fbe0b197b7f9fa4f8de3ac4fe8dd | Lucas01iveira/curso_em_video-Python | /Exercício_50.py | 323 | 3.828125 | 4 | def main():
s_par = 0
par = []
for i in range(6):
n = int(input('Digite um numero inteiro: '))
if n%2 == 0:
s_par += n
par.append(n)
print('Voce digitou {} números pares: {}'.format(len(par),par))
print('A soma desses valores eh igual a {}'.format(s_par))
main() |
153298e4b323b0188ab6d657943338d64c4d811e | miguelsh410/networking_down_under | /manchester_encoding.py | 1,854 | 3.96875 | 4 | """
Manchester Encoding
Sends a message across a wire using Manchester Encoding.
"""
import time
import RPi.GPIO as GPIO
# Data channel to transmit on
DATA_CHANNEL = 12
# Speed between transitions
CLOCK_SPEED = .005
BITS_IN_A_BYTE = 8
# Setup the pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(DATA_CHANNEL, GPIO.OUT)
# Put the pin high so we have a known starting state, and
# wait for a bit, so we know this isn't part of the message
GPIO.output(DATA_CHANNEL, GPIO.HIGH)
time.sleep(CLOCK_SPEED * 4)
GPIO.output(DATA_CHANNEL, GPIO.LOW)
time.sleep(CLOCK_SPEED * 4)
# The Message
my_message = b'This is a secret message'
# Loop through each letter/byte in the message
for my_byte in my_message:
# Loop through each bit in the byte.
# Starting at 7 down to 0
for bit_pos in range(BITS_IN_A_BYTE - 1, -1, -1):
# Take a 1 and shift into our bit position.
# Compare to the data, any value left means we have a 1 in that position
# 0100 0000
bit = (1 << bit_pos) & my_byte
# A 1 could be 1, 2, 4, 8, 16, 32, 64, or 128 position
if bit != 0:
# A one is represented by a low to high transition
# Go low, wait, go high, wait
GPIO.output(DATA_CHANNEL, GPIO.LOW)
time.sleep(CLOCK_SPEED)
print("1", end='')
GPIO.output(DATA_CHANNEL, GPIO.HIGH)
time.sleep(CLOCK_SPEED)
else:
# A zero is represented by a high to low transition
# Go high, wait, go low, wait
GPIO.output(DATA_CHANNEL, GPIO.HIGH)
time.sleep(CLOCK_SPEED)
print("0", end='')
GPIO.output(DATA_CHANNEL, GPIO.LOW)
time.sleep(CLOCK_SPEED)
# print(bit, end="")
print(" - {:3} - {:}".format(my_byte, chr(my_byte)))
time.sleep(CLOCK_SPEED * 4)
GPIO.cleanup()
|
766beb5086ba910ccb6ac72dee65aa669e8f3339 | jgrynczewski/testowanie_waw | /0_exceptions.py | 716 | 3.984375 | 4 | import math
def circle_area(r):
if type(r) not in [int, float]:
return "Podales nieprawidlowy typ. Podaj liczbe"
elif r < 0:
return "Kolo o takim promieniu nie istnieje."
else:
return math.pi*r**2
# print(circle_area(1))
# print(circle_area(0))
# print(circle_area(-1))
# print(circle_area(2+5j))
# print(circle_area(True))
# print(circle_area("asd"))
def circle_area(r):
try:
if r < 0:
raise Exception("Promien nie moze byc ujemny")
return math.pi*r**2
except:
return "Cos poszlo nie tak"
print(circle_area(1))
print(circle_area(0))
print(circle_area(-1))
print(circle_area(2+5j))
print(circle_area(True))
print(circle_area("asd")) |
fc36d45540747a3e7007cb0fa605a1621ffc9d7b | paul0920/leetcode | /question_leetcode/5_6.py | 738 | 3.984375 | 4 | def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
if not s:
return s
max_len = 0
start = 0
for i, char in enumerate(s):
start_1, len_1 = is_valid_palindrome(i, i, s)
if len_1 > max_len:
start = start_1
max_len = len_1
start_2, len_2 = is_valid_palindrome(i, i + 1, s)
if len_2 > max_len:
start = start_2
max_len = len_2
return s[start:start + max_len]
def is_valid_palindrome(start, end, s):
while 0 <= start and end < len(s):
if s[start] != s[end]:
break
start -= 1
end += 1
return start + 1, end - 1 - start
s = "babad"
print longestPalindrome(s)
|
54d331e05d671bc05e26ed4f96770bda5682b0b0 | Jakoma02/pyGomoku | /pygomoku/models/tile_generators.py | 5,507 | 3.5 | 4 | """
A module of helper board-related (mostly tile-generating)
functions
"""
from .constants import Direction
def horizontal_generator(board):
def row_generator(r):
for c in range(board.size):
yield board[r][c]
for row in range(board.size):
yield row_generator(row)
def vertical_generator(board):
def col_generator(c):
for r in range(board.size):
yield board[r][c]
for col in range(board.size):
yield col_generator(col)
def diagonal_a_generator(board):
def diag_generator(i):
if i < board.size: # Left triangle
_range = range(i + 1)
else: # Right triangle
_range = range(i - board.size + 1, board.size)
for r, c in zip(_range, reversed(_range)):
yield board[r][c]
for i in range(2 * board.size - 1):
yield diag_generator(i)
def diagonal_b_generator(board):
def diag_generator(i):
if i < board.size: # Left triangle
row_range = range(i + 1)
col_range = range((board.size - 1) - i, board.size)
else: # Right triangle
i -= board.size - 1
row_range = range(i, board.size)
col_range = range(board.size - i)
for r, c in zip(row_range, col_range):
yield board[r][c]
for i in range(2 * board.size - 1):
yield diag_generator(i)
def all_tiles(board):
for x in range(board.size):
for y in range(board.size):
yield board[x][y]
def all_empty_tiles(board):
"""
Generates all empty tiles, row by row
:param board:
:return:
"""
for tile in all_tiles(board):
if tile.empty():
yield tile
def all_generators(board):
"""
Generates tiles in all directions and return them with the directions
:param board:
:return: tuple of generator 'line' and Direction 'direction'
"""
generators = [
(Direction.HORIZONTAL, horizontal_generator(board)),
(Direction.VERTICAL, vertical_generator(board)),
(Direction.DIAGONAL_A, diagonal_a_generator(board)),
(Direction.DIAGONAL_B, diagonal_b_generator(board))
]
for direction, generator in generators:
for line in generator:
yield line, direction
def neighbors(board, x, y):
"""
Generator of all neighbors of given position that are within bounds.
:param size: size of the board
:param x: x coordinate
:param y: y coordinate
"""
for i in range(x - 1, x + 2):
if i < 0:
continue
if i >= board.size:
continue
for j in range(y - 1, y + 1):
if j < 0:
continue
if j >= board.size:
continue
if (i, j) == (x, y):
# This is me
continue
yield (i, j)
def is_valid(board, x, y):
return \
0 <= x < board.size and \
0 <= y < board.size
def direction_neighbors(board, direction, x, y):
"""
Returns the two neighboring tiles' coordinates
in the given direction, if they are valid
"""
if direction == Direction.HORIZONTAL:
dir_neighbors = [(x - 1, y), (x + 1, y)]
elif direction == Direction.VERTICAL:
dir_neighbors = [(x, y - 1), (x, y + 1)]
elif direction == Direction.DIAGONAL_A:
dir_neighbors = [(x - 1, y - 1), (x + 1, y + 1)]
elif direction == Direction.DIAGONAL_B:
dir_neighbors = [(x - 1, y + 1), (x + 1, y - 1)]
result = list(filter(lambda pos: is_valid(board, pos[0], pos[1]),
dir_neighbors))
return result
def close_tiles(board, x, y):
# At most 2
for i in range(-2, 3):
for j in range(-2, 3):
nx, ny = (x + i, y + j)
if not is_valid(board, nx, ny):
continue
if (nx, ny) != (x, y):
yield board[nx][ny]
def is_close_to_filled(board, x, y):
for tile in close_tiles(board, x, y):
if not tile.empty():
return True
return False
relevant_usage_var = 0
def relevant_tiles(board):
global relevant_usage_var
relevant_usage_var += 1
yielded_any = False
for tile in all_empty_tiles(board):
if is_close_to_filled(board, tile.x, tile.y):
yielded_any = True
yield tile
if not yielded_any:
# Return the tile in the middle
center_coord = board.size // 2
yield board[center_coord][center_coord]
def relevant_usage():
global relevant_usage_var
return relevant_usage_var
def next_in_direction(board, tile, direction):
x, y = tile.x, tile.y
if direction == Direction.HORIZONTAL:
nx, ny = (x + 1, y)
elif direction == Direction.VERTICAL:
nx, ny = (x, y + 1)
elif direction == Direction.DIAGONAL_A:
nx, ny = (x + 1, y + 1)
elif direction == Direction.DIAGONAL_B:
nx, ny = (x + 1, y - 1)
if is_valid(board, nx, ny):
return board[nx][ny]
return None
def prev_in_direction(board, tile, direction):
x, y = tile.x, tile.y
if direction == Direction.HORIZONTAL:
nx, ny = (x - 1, y)
elif direction == Direction.VERTICAL:
nx, ny = (x, y - 1)
elif direction == Direction.DIAGONAL_A:
nx, ny = (x - 1, y - 1)
elif direction == Direction.DIAGONAL_B:
nx, ny = (x - 1, y + 1)
if is_valid(board, nx, ny):
return board[nx][ny]
return None
|
b6c816eb9bdbbc9381ff96d7c282dc703f162ff7 | avkramarov/gb_python | /lesson1/Задание4.py | 462 | 4.0625 | 4 | # Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.
user_number = int(input("Введите число >>>"))
max = 0
while user_number > 0:
a = user_number % 10
user_number //= 10
if a > max:
max = a
print(max)
|
ba33ce6940599e88acb5a239c6d0893a19068b6e | RobinHou0516/Homework | /print/name3.py | 148 | 3.625 | 4 | name='Robin Kawensanna Smartest Unrivalled'
age='14'
grade='9th'
grade.title
school='JXFLS'
print('My name is '+name+'. I am a '+age+' year old '+grade+' grader at '+school+'.')
|
8852fd4d0ec513515df38a65f6b8458b2940a7df | amitmtm30/PythonCode | /Function/FunctionArgument.py | 465 | 3.890625 | 4 | # There are three types of argument in python :
# 1. Positional Argument
# 2. Keyword Argument
# 3. Default Argument
####################### Positional Argument #############################
def sum(a, b):
print("The sum is : ", a + b)
#sum (100,50) # Here value is assigened to 100 and b is 50
sum (50, b=10)
################################################################
def wish(name, msg):
print("Hello", name, msg)
wish("Amit", msg="Good Evening",) |
b05a6dbf105cab661aa6d2ed45ff408e8d14f903 | funfoolsuzi/coding_dojo_essence | /python_oop_demo/store.py | 844 | 3.640625 | 4 | from product import Product
class Store(object):
def __init__(self, location, owner):
self.location = location
self.owner = owner
self.products = []
def add_product(self, prod):
self.products.append(prod)
return self
def remove_product(self, prodname):
for p in self.products:
if p.name == prodname:
self.products.remove(p)
return self
def inventory(self):
for p in self.products:
p.display_info()
print
def __repr__(self):
return "<Store object {}, owner {}>".format(self.location, self.owner)
if __name__ == "__main__":
s1 = Store("Lynnwood", "Li")
s1.add_product(Product("banana", 10, "1 lb", "sun"))
s1.add_product(Product("watermelon", 3, "1.5 lb", "west"))
s1.inventory()
|
d2a5fc977e7e9ade75e1e49bbf7aa5fd2a209a32 | adriene-tien/ProblemSolving | /LeetCode/Easy/ValidParentheses.py | 1,146 | 3.90625 | 4 | # LeetCode Easy
# Valid Parentheses Question
# O(n) time complexity
# O(n) space complexity as we use trackStack. Worst case for space is that every character is a left bracket
# so trackStack is fully populated with all characters of s, but is still able to return false at the end
class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
rightBrackets = ["}", "]", ")"]
if s[0] in rightBrackets:
return False
leftBrackets = ["{", "[", "("]
trackStack = [s[0]]
for i in range(1, n):
if len(trackStack) == 0 and s[i] in rightBrackets:
return False
if s[i] in leftBrackets:
trackStack.append(s[i])
elif s[i] == "}" and trackStack[-1] == "{":
trackStack.pop()
elif s[i] == "]" and trackStack[-1] == "[":
trackStack.pop()
elif s[i] == ")" and trackStack[-1] == "(":
trackStack.pop()
else:
return False
if len(trackStack) == 0:
return True
|
e56c653e8748a10d1f321ac658a8fa5c05a579a0 | hiroshima-arc/aws_sam_python_hands-on | /sam-app/fizz_buzz/fizz_buzz.py | 462 | 3.703125 | 4 | class FizzBuzz:
@staticmethod
def generate(number):
value = number
if value % 3 == 0 and value % 5 == 0:
value = 'FizzBuzz'
elif value % 3 == 0:
value = 'Fizz'
elif value % 5 == 0:
value = 'Buzz'
return value
@staticmethod
def iterate(count):
array = []
for n in range(count):
array.append(FizzBuzz.generate(n + 1))
return array
|
9fccd657b7a78186528213f15fb03e5e278635dd | marloncard/byte-exercises | /04-iteration-3/iteration3.py | 1,268 | 4.4375 | 4 | #!/usr/bin/env python3
"""
* Create a variable and assign it to the array below
[2, 34, 12, 29, 38, 1, 12, 8, 8, 9, 29, 38, 8, 9, 2, 3, 7, 10, 12, 8, 34, 7]
* Write a function that will take in this variable
* It will return the median number in the array
* It will return the average of that array
* It will return the number that occurs most frequently in the array
Please see the example `input` and `output` below.
[input]
[2, 34, 12, 29, 38, 1, 12, 8, 8, 9, 29, 38, 8, 9, 2, 3, 7, 10, 12, 8, 34, 7]
[output]
9
14
8
"""
number_list = [2, 34, 12, 29, 38, 1, 12, 8, 8, 9, 29, 38, 8, 9, 2, 3, 7, 10, 12, 8, 34, 7]
def iteration_three(arg):
# Sort list in place
arg.sort()
# Median number is at index location: total index / 2
print(arg[len(arg)//2])
# Average is array total / array length
print(sum(arg)//len(arg))
# Iterate over list values
max_counts = 0
max_value = None
for i in arg:
# If the count of item in list is > max_counts, max_value is item
if arg.count(i) > max_counts:
max_counts = arg.count(i)
max_value = i
# TODO max_value = map(lamda x: arg.count(x) > max_counts, arg)
print(max_value)
if __name__ == "__main__":
iteration_three(number_list)
|
70d7800f351b7adebb372c24e4e945c8a91fa901 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/njrmic001/question3.py | 446 | 4.375 | 4 | #question3.py
#A program to calculate the value of PI, compute and display the area of a circle with radius entered by the user
#Author: Michelle Njoroge
from math import*
a=2
b=sqrt(2)
pi=2*(a/b)
while b<2:
b=sqrt(2+b)
pi=pi*(a/b)
print("Approximation of pi:",round(pi,3))
y=eval(input("Enter the radius:\n"))
Area=round((pi*y**2),3)
print("Area:",round((pi*y**2),3))
|
adacb18a6c3bdbd4632a1482cd0055bf3a60a0f3 | NourAlaaeldin/Python-projects | /Tuples.py | 190 | 3.53125 | 4 | #creating a tupple
#we can't modify a tupple
coordinates = (2,3)
print(coordinates)
print(coordinates[0])
#we can create a list of tupples
#ex of using tupples : sorting data
|
46e2c1cbebadda10f4ed300a6a5848699f5a89ff | Prerna983/260567_PythonPractiseLTTS | /comments.py | 525 | 4.53125 | 5 | # This program evaluates the hypotenuse c.
# a and b are the lengths of the legs.
a = 3.0
b = 4.0
c = (a ** 2 + b ** 2) ** 0.5 # We use ** instead of square root.
print("c =", c)
# This is a test program.
x = 1
y = 2
# y = y + x
print(x + y)
print("I've also learnt multi-line comments")
# to make a multi line
# comment
# select all the
# lines you want to
# comment
# and then press
# ctrl+/
# same goes for de-comment
#Making a doc-string
"""
This serves same purpose
as a multi-line
comment without actual comment
""" |
f4039b0f8b7162f024cc28c67db69244924c0d31 | Igor-Ferraz7/CursoEmVideo-Python | /Curso/Mundo 1/Desafio035.py | 427 | 3.5 | 4 | am = '\033[33m'
vd = '\033[4;32m'
vm = '\033[4;31m'
az = '\033[34m'
r = '\033[35m'
ci = '\033[36m'
des = '\033[m'
a = int(input(f'{ci}Primeira reta{des}:'))
b = int(input(f'{ci}Segunda reta{des}:'))
c = int(input(f'{ci}Terceira reta{des}:'))
if a < b + c and b < a + c and c < a + b:
print(f'{vd}As retas acima podem formar um triângulo{des}.')
else:
print(f'{vm}As retas acima não podem formar um triângulo{des}.')
|
978af9e14b5f80257c47e9e6c784c66e3e1628e8 | rojan-rijal/internmate | /microservices/airbnb/app/apptconn.py | 1,580 | 3.640625 | 4 | #Module Name: Airbnb API Client for Python
#Date of the code: 4/19/20
#Programer(s) Name: Janeen Yamak, Brittany Kraemer, Rojan Rijal
#Brief description: This file is a client for the Airbnb api. A user shall input the city, state, and offset and it shall return a list of apartments located in the near area
#Data Structure: A list of Dictionaries
#Algorithm: Parsing through a json list
import airbnb
api = airbnb.Api(randomize = True)
def findApt(city,state):
apts = []
location = city+", "+state
#should return a json object of apartments in the given location
data = api.get_homes(location, offset = 1, items_per_grid = 10)
#parse through the json file and grab the data we need and insert that data into a dictionary
for k in data['explore_tabs'][0]['sections'][0]['listings']:
aptInfo= {}
aptInfo['name'] = k['listing']['name']
aptInfo['id'] = k['listing']['id']
aptInfo['urls'] = k['listing']['picture_urls']
aptInfo['guests']= k['listing']['guest_label'].split(' ')[0]
aptInfo['homeType']= k['listing']['bedroom_label']
aptInfo['numOfBaths'] = k['listing']['bathroom_label'].split(' ')[0]
numBedRooms = k['listing']['bed_label'].split(' ')[0]
aptInfo['numBedroom']= k['listing']['bed_label'].split(' ')[0]
aptInfo['rate']= k['pricing_quote']['rate_with_service_fee']['amount_formatted'].split('$')[1]
#append a dictionary to the list
apts.append(aptInfo)
#return a list of apartments to the api
return apts
|
e14ed769c82de0f6685808a25c4f8668aa2b7313 | IamWenboZhang/LeetCodePractice | /844BackspaceStringCompare.py | 631 | 3.625 | 4 | class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
s0 = []
t0 = []
for i in range(len(S)):
if S[i] == "#":
if len(s0) > 0:
s0.pop()
else:
s0.append(S[i])
for j in range(len(T)):
if T[j] == "#":
if len(t0) > 0:
t0.pop()
else:
t0.append(T[j])
return s0 == t0
S = "a##c"
T = "#a#c"
s = Solution()
r = s.backspaceCompare(S,T)
print(r) |
a7d68d48ecadf2b7a574d38737e845ddce62eb7d | chazkiker2/code-challenges | /misc/return_next_number/test_return_next_number.py | 434 | 3.796875 | 4 | import unittest
from return_next_number import *
class ReturnNextNumber(unittest.TestCase):
def test(self):
self.assertEqual(addition(2), 3, "2 plus 1 equals 3.")
self.assertEqual(addition(-9), -8, "-9 plus 1 equals -8.")
self.assertEqual(addition(999), 1000, "999 plus 1 equals 1000.")
self.assertEqual(addition(73), 74, "73 plus 1 equals 74.")
if __name__ == '__main__':
unittest.main()
|
e6f963291cc4c21d76b1e63a2da084c2a93f27eb | subezio-whitehat/CourseMcaPython | /c2python/c2p10.py | 183 | 4.28125 | 4 | #10. Accept the radius from user and find area of circle.
r=int(input("\nEnter the radius of circle:"))
area=3.14*r*r
print("\nThe area of the circle with radius %d is %f!" %(r,area)) |
df0e2428f220d4d2f1356b160295f04db583f163 | mateogolf/python | /list2dict.py | 567 | 4.0625 | 4 | def make_dict(arr1, arr2):
new_dict = {}
#Error Case: what is arrays are different length
if len(arr1) >= len(arr2):
keys = arr1
data = arr2
else:
keys = arr2
data = arr1
for i in range(0,len(keys)):
new_dict[keys[i]] = data[i]
print "{}: {}".format(keys[i],data[i])
return new_dict
# function input
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
print make_dict(name,favorite_animal) |
304ec11d2ef3dcda59568b86881751cc4faa8149 | wgay/allpyprj | /test.py | 455 | 3.9375 | 4 | #! /usr/bin/python3
counter = 100 #整型变量
miles = 1000.0 #浮点型变量
name = "runoob" #字符串
print(counter)
print(miles)
print(name)
#多个变量赋值
a = b = c = 1
a,b,c = 1,2,"runoob"
'''
python标准数据类型
Number(数字) 不可变
String(字符串)不可变
List(列表)可变
Tuple(元组)不可变
Set(集合)可变
Dictionary(字典)可变
'''
#Number Python3支持int,float,bool,complex(复数)
|
a2e5684a013575d7edc30331087915fd8e425970 | paosq/test-assignment | /task1.py | 338 | 4.3125 | 4 | def rectangle_area(a, b):
"""
Calculates the area of a rectangle given its side lengths
:param a: first side of the rectangle
:param b: second side of the rectangle
:return: area of the rectangle
:raises ValueError: if either number was negative
"""
if a<0 and b<0:
return "error"
return a*b
|
c7c76fe1b6c1153994ee6daf516fa42d5f39cb24 | revanthnamburu/Codes | /PilingCubesVertical.py | 725 | 4.15625 | 4 | #You are given a horizontal numbers each representing a cube side.
#You need to pile them vertically such a way that,upper cube is <= lower cube.
#Given you can take the horizontal cube side from either left most or from right most.
#If it can be piled up vertivally retirn 'YES' or else return 'NO'
#EX:3,2,1,1,5
#you first pick 5 and then palce 3 on it.
#next 2 is place on 3 and 1 is on 2 and so on,So possibel.Return 'YES'
def Piling(n,l):
temp=max(l)+1
length=n//2
if n%2==1:
length=n//2+1
for i in range(length):
if max(l[i],l[n-1-i])<=temp:
temp=min(l[i],l[n-1-i])
else:
return 'No'
return 'Yes'
print(Piling(6,[3,2,1,1,2,5])) |
39040c19312c025f6ae625cb71e50b414e6e0654 | jkz/python-www | /www/utils/functions.py | 186 | 3.59375 | 4 | def header_case(name):
splits = name.replace('-', '_').split('_')
if splits[0].upper() == 'HTTP':
splits = splits[1:]
return '-'.join(w.capitalize() for w in splits)
|
28f434d25df9d199c0a1d9377b71b7bad42e7c59 | Jiawei-Wang/LeetCode-Study | /819. Most Common Word.py | 430 | 3.796875 | 4 | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
"""
remove all punctuations
change to lowercase words
count for each word not in banned set
return the most common word
"""
ban = set(banned)
words = re.findall(r'\w+', paragraph.lower())
return collections.Counter(w for w in words if w not in ban).most_common(1)[0][0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.