blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6185918a83634c596f81f0ec2879ddd39ebcb790 | stavernatalia95/Lesson-5.1-Assignment | /rocket.py | 790 | 4.1875 | 4 |
# A simulator for a rocket ship in a game.
class Rocket:
# The __init__() method doesn't take any arguments but sets the x and y positions to zero.
def __init__(self):
self.x=0
self.y=0
# Move_up() - will increment y position by 1
def move_up(self):
self.y+=1
# Move_right() - will increment x position by 1
def move_right(self):
self.x+=1
# Move_down() - will decrement y position by 1
def move_down(self):
self.y-=1
# Move_left() - will decrement x position by 1
def move_left(self):
self.x-=1
# Current_postition() - will print the current position of the Rocket]
def current_postition(self):
return self.y, self.x
current_postition=Rocket()
print(current_postition) |
cdcb808d39a7691ea9dd9038bd8fbb30135c1db5 | PrashantThakurNitP/python-december-code | /calliing_base_static _method_inside_derived_class.py | 453 | 3.8125 | 4 | class base:
x=11#STATIC METHOD
@staticmethod
def basefunction():
print("inside base function")
class derived(base):
@staticmethod
def derivedfunction():
print("inside derived class static method")
base.basefunction()
derived.basefunction()
print("using base.x is perfect way x= ",base.x)
print("but we can also access usind deived.x hence x=",derived.x)
derived.derivedfunction()
|
dcf1b16b585b11d80f2d81c869ea5e05290e90fc | masamasa42/test | /abc154b.py | 159 | 3.625 | 4 | # -*- coding: utf-8 -*-
#https://atcoder.jp/contests/abc141/tasks/abc154_b
import sys
import math
u=input()
a=""
for i in range(len(u)):
a+="x"
print(a)
|
1e17635ea617ca3730911efbe428e0505f0eda4c | predora005/weather-forecasting | /07.gsm_random_forest/wfile/name_handle.py | 2,927 | 3.546875 | 4 | # coding: utf-8
import re
##################################################
# ファイル名から要素を取得する(地上気象データ用)
##################################################
def elements_from_filename_ground(filename):
""" ファイル名から要素を取得する(地上気象データ用)
Args:
filename(string) : ファイル名
Returns:
list[string] : 要素のリスト
"""
result = re.search(r"(\D+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+).csv", filename)
values = result.groups()
elements = {
'name' : values[0],
'prec_no' : int(values[1]),
'block_no' : int(values[2]),
'year' : int(values[3]),
'month' : int(values[4]),
'day' : int(values[5]),
}
return elements
##################################################
# ディレクトリ名から要素を取得する(地上気象データ用)
##################################################
def elements_from_dirname_ground(dirname):
""" ディレクトリ名から要素を取得する(地上気象データ用)
Args:
filename(string) : ファイル名
Returns:
dict : 要素のディクショナリ
"""
result = re.search(r"(\D+)_(\d+)_(\d+)", dirname)
values = result.groups()
elements = {
'name' : values[0],
'prec_no' : int(values[1]),
'block_no' : int(values[2])
}
return elements
##################################################
# ファイル名から要素を取得する(高層気象データ用)
##################################################
def elements_from_filename_highrise(filename):
""" ファイル名から要素を取得する(高層気象データ用)
Args:
filename(string) : ファイル名
Returns:
list[string] : 要素のリスト
"""
result = re.search(r"(\D+)_(\d+)_(\d+)_(\d+)_(\d+)_H(\d+).csv", filename)
values = result.groups()
elements = {
'name' : values[0],
'place_no' : int(values[1]),
'year' : int(values[2]),
'month' : int(values[3]),
'day' : int(values[4]),
'hour' : int(values[5])
}
return elements
##################################################
# ディレクトリ名から要素を取得する(高層気象データ用)
##################################################
def elements_from_dirname_highrise(dirname):
""" ディレクトリ名から要素を取得する(高層気象データ用)
Args:
filename(string) : ファイル名
Returns:
dict : 要素のディクショナリ
"""
result = re.search(r"(\D+)_(\d+)", dirname)
values = result.groups()
elements = {
'name' : values[0],
'place_no' : int(values[1]),
}
return elements
|
0938852821ee34fe5dde661a8131917a77a13a47 | ianloic/Steph | /typesystem.py | 2,917 | 3.640625 | 4 | """A simple type-system for Steph."""
import typing
from enum import Enum
__all__ = ['type_union', 'Type', 'UNKNOWN', 'Number', 'STRING', 'BOOLEAN', 'Function']
class TypeException(Exception):
pass
class Operator(Enum):
# arithmetic
add = ('+', 2)
subtract = ('-', 2)
multiply = ('*', 2)
divide = ('/', 2)
negate = ('-', 1)
# logical
logical_and = ('&&', 2)
logical_or = ('||', 2)
logical_not = ('!', 1)
# comparison
equals = ('==', 2)
not_equals = ('!=', 2)
less_than = ('<', 2)
greater_than = ('>', 2)
less_or_equal = ('<=', 2)
greater_or_equal = ('>=', 2)
def __new__(cls, symbol: str, arity: int):
# auto-number
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
obj.symbol = symbol
obj.arity = arity
return obj
@classmethod
def lookup(cls, symbol: str, arity: int) -> 'Operator':
for member in cls.__members__.values():
if member.symbol == symbol and member.arity == arity:
return member
return None
class Type:
def supports_operator(self, operator: Operator):
raise TypeException('supports_operator() not implemented in %s' % self.__class__.__name__)
def binary_operator(self, operator: Operator, a, b):
raise TypeException('binary_operator() not implemented in %s' % self.__class__.__name__)
def unary_operator(self, operator: Operator, a):
raise TypeException('unary_operator() not implemented in %s' % self.__class__.__name__)
class Unknown(Type):
def __eq__(self, other):
return self.__class__ == other.__class__
UNKNOWN = Unknown()
class Nothing(Type):
def __eq__(self, other):
return self.__class__ == other.__class__
NOTHING = Nothing()
class Primitive(Type):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return self.name
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name
_string = Primitive('StringType')
# noinspection PyPep8Naming
def String():
return _string
class Function(Type):
def __init__(self, arguments: typing.List[Type], returns: Type):
self.arguments = arguments
self.returns = returns
def __str__(self):
return '(%s) => %s' % (','.join(str(arg) for arg in self.arguments), self.returns)
def __repr__(self):
return '(%s) => %r' % (','.join(repr(arg) for arg in self.arguments), self.returns)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.arguments == other.arguments and self.returns == other.returns
def type_union(a: Type, b: Type) -> Type:
if a == b:
return a
raise TypeException("Can't know how to union %s and %s" % (a, b))
|
3070f1d536d32d368fab0adbb800b068ae319bfa | madhulika9293/cspp1-assignments | /m11/p4/assignment4.py | 883 | 3.71875 | 4 | '''
Exercise: Assignment-4
We are now ready to begin writing the code that interacts
with the player. We'll be implementing the playHand function.
This function allows the user to play out a single hand.
First, though, you'll need to implement the helper calculateHandlen function,
which can be done in under five lines of code.
'''
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
sum_val = 0
for key_dict in hand:
sum_val += hand[key_dict]
return sum_val
def main():
''' This is the main function'''
num_inp = input()
adict = {}
for _ in range(int(num_inp)):
data = input()
l_inp = data.split()
adict[l_inp[0]] = int(l_inp[1])
print(calculate_handlen(adict))
if __name__ == "__main__":
main()
|
11631f5418c3fa0d52dcc40d5307a7d59e73acc4 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 288 | 3.734375 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
if idx < 0 or idx > len(my_list):
return my_list
tmp = list()
for x in range(len(my_list)):
if x == idx:
tmp.append(element)
else:
tmp.append(my_list[x])
return tmp
|
91c93f60046efb049315fb5bb439f0629e079325 | dwightr/ud036_StarterCode | /media.py | 1,186 | 3.609375 | 4 | import webbrowser
class Video():
"""
Video Class provides a way to store
video related information
"""
def __init__(self, trailer_youtube_url):
# Initialize Video Class Instance Variables
self.trailer_youtube_url = trailer_youtube_url
class Movie(Video):
"""
Movie Class provides a way to store
movie related information and will inherit
Instance Variable from the Video class
"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
def __init__(self, title, movie_storyline, poster_image,
trailer_youtube_url):
"""
Constructor method will initialize instance variables
and variables inhertied from video class
"""
# Initialize Variables Inhertied From Video Class
Video.__init__(self, trailer_youtube_url)
# Initialize Movie Class Instance Variables
self.title = title
self.movie_storyline = movie_storyline
self.poster_image_url = poster_image
def show_trailer(self):
# This Method Shows The Trailer Of The Instance It Is Called From
webbrowser.open(self.trailer_youtube_url)
|
25a82e30d4867e34f06101b50e9208a9181737f2 | AntonioFacundo/Phyton | /Python/Practicas con Python/busquedas.py | 549 | 4.1875 | 4 | course = "Curso"
my_string = "Codigo facilito"
result = "{a} de {b}".format(a = course, b = my_string)
result = result.lower()
"""Busqueda"""
#regresa el valor de la cadena donde está
#localizado el resultado de busqueda
pos = result.find("codigo")
print(pos)
print(result[9])
#contador de letras
count = result.count("c")
print(count)
#remplazar una letra de la cadena por otra letra
new_string = result.replace("c", "x")
print(new_string)
#split sirve para seccionar la cadena
new_string = result.split(" ")
print(new_string)
print(result) |
cae39dc26cb406ade5fc9cc3f39c54be4dd28831 | viniciusgerardi/Python-Misc | /Exercicios/98.py | 649 | 4.09375 | 4 | # Faça um programa que tenha uma função chamada contador(), que receba três parâmetros:
# início, fim e passo. Seu programa tem que realizar três contagens através da função criada:
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
def contador(início, fim, passo):
print(f'Contagem de {início} até {fim} com passo {passo}')
if fim <= 0:
fim -= 1
else:
fim += 1
if início > fim:
passo = -passo
for i in range(início, fim, passo):
print(f'{i} ', end='')
print()
print()
contador(1, 10, 1)
contador(10, 0, 2)
contador(-10, 10, 2)
|
b35593b60d7600dc309f37810a835aaa2610f190 | peter-de-boer/ponzischeme_webapp | /backend/games/fundCard.py | 847 | 3.6875 | 4 | class FundCard(object):
def __init__(self, value, time, interest, fundtype):
self.value = value
self.time = time
self.interest = interest
self.fundtype = fundtype
self.averageInterestPerc = self.averageInterest()
def averageInterest(self):
return 100*(((self.interest)/self.time)/self.value)
def name(self):
return "$" + str(self.value) + " (<" + str(self.time) + "> $" + \
str(self.interest) + ")"
def shortName(self):
return "$" + str(self.value)
def __eq__(self, other):
if isinstance(other, FundCard):
return self.value == other.value
return NotImplemented
def __lt__(self, other):
if isinstance(other, FundCard):
return self.value < other.value
return NotImplemented
|
785aa490eddc3aa2a7c50fb32969a6659ca1daa8 | jxjjdj/Python | /arithmetic_analysis/二分法.py | 586 | 3.84375 | 4 | import math
def bisection(function, a, b):#找方程在[a,b]中的解
start = a
end = b
if function(a) == 0:
return a
else function(b) == 0:
return b
elif function(a) * function(b) > 0;
print("couldn't find the root in [a, b")
return
else:
mid = (start + end) / 2.0
while abs(start - mid) > 10**-7:
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
def f(x):
return math.power(x, 3) - 2*x -5
if __name__ == '__main__':
print(bisection(f, 1, 1000))
|
9f36c5270d2ba37c48d3a1c1824297977e94b69e | az-ahmad/python | /projects/BlackJackv2/newblackjack.py | 613 | 3.703125 | 4 | import random
playerList = []
def greeting():
print('Welcome to BlackJack 2 player v.02')
while True:
try:
numPlayers = int(input('How many players will there be? '))
except:
print('Enter a valid number between 1 and 10')
continue
if numPlayers>0 and numPlayers<10:
break
while numPlayers > 0:
player = input('Enter a players name: ')
playerList.append(player)
numPlayers-=1
print('Welcome:', ', '.join(playerList[:-1]), 'and', ''.join(playerList[-1])+'.')
if __name__ == "__main__":
greeting() |
da07132350ec4941a0d9dc8edc9fb8811c91a315 | kavin2606/Interview_prep | /question10.py | 503 | 4.03125 | 4 | def is_palindrome(str):
return (str == str[::-1])
def make_palindrome(string):
if(is_palindrome(string)):
return string
if string[0] == string[-1]:
return string[0] + make_palindrome(string[1:-1]) + string[-1]
else:
one = string[0] + make_palindrome(string[1:]) + string[0]
two = string[-1] + make_palindrome(string[:-1]) + string[-1]
if len(one) < len(two):
return one
elif len(two) < len(one):
return two
else:
return min(one,two)
a = make_palindrome("race")
print(a) |
f2d982cfa5e546a5435ce8bceabc46f114592ed0 | venkateshraizaday/ArtificialIntelligence | /a3/ZacateAutoPlayer.py | 8,095 | 3.9375 | 4 | # Automatic Zacate game player
# B551 Fall 2015
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
# PUT YOUR REPORT HERE!
'''
As in the codebase provided, i implemented the first roll and second roll function to return a subset of the rolled dice.
The third roll sends the category that produces the best score for the given final roll.
First_Roll and Second_Roll:-
This function checks for the possibiilty of "pupusa de queso", "pupusa de frijol", "elote", "triple", "cuadruple", "quintupulo" first.
If the condition is satisfied an empty list is returned.
else all categories are checked for their expected values with current state of dice and a subset is returned based on the highest expected value.
Third_Roll:-
The dice state is checked for each category and appended to the list if the category is fulfilled.
The category with the maximum score is returned.
If no category is found a random category is returned.
Problems Faced:-
On looking at the results a lot of loopholes can be seen as there are separate individual if else cases and condensing them into shorter ones is kinda difficult.
Analysis:-
The program runs well, the average score is always in the range 200 +- 5.
'''
# This is the file you should modify to create your new smart Zacate player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice object which records the
# result of the first roll (state of 5 dice) and current Scorecard.
# You should implement this method so that it returns a (0-based) list
# of dice indices that should be re-rolled.
#
# 2. It then re-rolls the specified dice, and calls second_roll, with
# the new state of the dice and scorecard. This method should also return
# a list of dice indices that should be re-rolled.
#
# 3. Finally it calls third_roll, with the final state of the dice.
# This function should return the name of a scorecard category that
# this roll should be recorded under. The names of the scorecard entries
# are given in Scorecard.Categories.
#
from ZacateState import Dice
from ZacateState import Scorecard
import random
class ZacateAutoPlayer:
def __init__(self):
pass
# Categories = [ "unos", "doses", "treses", "cuatros", "cincos", "seises", "pupusa de queso", "pupusa de frijol", "elote", "triple", "cuadruple", "quintupulo", "tamal" ]
def first_roll(self, dice, scorecard):
return self.check_categories(dice,scorecard)
def second_roll(self, dice, scorecard):
return self.check_categories(dice,scorecard)
def third_roll(self, dice, scorecard):
result_list = []
counts = [dice.dice.count(i) for i in range(1,7)]
if "unos" not in scorecard.scorecard:
score = dice.dice.count(1)*1
result_list.append(("unos",score))
if "doses" not in scorecard.scorecard:
score = dice.dice.count(2)*2
result_list.append(("doses",score))
if "treses" not in scorecard.scorecard:
score = dice.dice.count(3)*3
result_list.append(("treses",score))
if "cuatros" not in scorecard.scorecard:
score = dice.dice.count(4)*4
result_list.append(("cuatros",score))
if "cincos" not in scorecard.scorecard:
score = dice.dice.count(5)*5
result_list.append(("cincos",score))
if "seises" not in scorecard.scorecard:
score = dice.dice.count(6)*6
result_list.append(("seises",score))
if "tamal" not in scorecard.scorecard:
result_list.append(("tamal",sum(dice.dice)))
if "triple" not in scorecard.scorecard and max(counts) >= 3:
score = sum(dice.dice)
result_list.append(("triple",score))
if "elote" not in scorecard.scorecard and (2 in counts) and (3 in counts):
result_list.append(("elote",25))
if "cuadruple" not in scorecard.scorecard and (max(counts) >= 4):
score = sum(dice.dice)
result_list.append(("cuadruple",score))
if "pupusa de frijol" not in scorecard.scorecard and (len(set([1,2,3,4]) - set(dice.dice)) == 0 or len(set([2,3,4,5]) - set(dice.dice)) == 0 or len(set([3,4,5,6]) - set(dice.dice)) == 0):
result_list.append(("pupusa de frijol",30))
if "pupusa de queso" not in scorecard.scorecard and sorted(dice.dice) == [1,2,3,4,5] or sorted(dice.dice) == [2,3,4,5,6]:
result_list.append(("pupusa de queso",40))
if "quintupulo" not in scorecard.scorecard and max(counts) == 5:
result_list.append(("quintupulo",50))
if result_list != []:
result_list.sort(key = lambda tup: tup[1])
return result_list.pop()[0]
else:
return random.choice( list(set(Scorecard.Categories) - set(scorecard.scorecard.keys())) )
def check_categories(self, dice, scorecard):
counts = [dice.dice.count(i) for i in range(1,7)]
if "quintupulo" not in scorecard.scorecard and max(counts) == 5:
return []
elif "pupusa de queso" not in scorecard.scorecard and sorted(dice.dice) == [1,2,3,4,5] or sorted(dice.dice) == [2,3,4,5,6]:
return []
elif "pupusa de frijol" not in scorecard.scorecard and (len(set([1,2,3,4]) - set(dice.dice)) == 0 or len(set([2,3,4,5]) - set(dice.dice)) == 0 or len(set([3,4,5,6]) - set(dice.dice)) == 0):
send_list = []
for i in range(1,7):
if dice.dice.count(i) == 2:
send_list.append(dice.dice.index(i))
return send_list
return []
elif "cuadruple" not in scorecard.scorecard and (max(counts) >= 4):
send_list = []
for i in range(1,7):
if dice.dice.count(i) == 1:
send_list.append(dice.dice.index(i))
return send_list
return []
elif "elote" not in scorecard.scorecard and (2 in counts) and (3 in counts):
return []
elif "triple" not in scorecard.scorecard and max(counts) >= 3:
for i in range(1,7):
if dice.dice.count(i) == 3:
temp = i
break
elif dice.dice.count(i) == 4:
temp = i
break
elif dice.dice.count(i) == 5:
return []
count = 0
send_list = []
for i in dice.dice:
if i != temp:
send_list.append(count)
count += 1
return send_list
else:
e_list = []
if "unos" not in scorecard.scorecard:
e_unos = ((1.0/6)**(5 - dice.dice.count(1))) * 5.0
e_list.append(("unos",e_unos))
if "doses" not in scorecard.scorecard:
e_doses = ((1.0/6)**(5 - dice.dice.count(2))) * 10
e_list.append(("doses",e_doses))
if "treses" not in scorecard.scorecard:
e_treses = ((1.0/6)**(5 - dice.dice.count(3))) * 15
e_list.append(("treses",e_treses))
if "cuatros" not in scorecard.scorecard:
e_cuatros = ((1.0/6)**(5 - dice.dice.count(4))) * 20
e_list.append(("cuatros",e_cuatros))
if "cincos" not in scorecard.scorecard:
e_cincos = ((1.0/6)**(5 - dice.dice.count(5))) * 25
e_list.append(("cincos",e_cincos))
if "seises" not in scorecard.scorecard:
e_seises = ((1.0/6)**(5 - dice.dice.count(6))) * 30
e_list.append(("seises",e_seises))
if "tamal" not in scorecard.scorecard:
e_tamal = ((1.0/2)**(5 - (dice.dice.count(4)+dice.dice.count(5)+dice.dice.count(6)))) * 25
e_list.append(("tamal",e_tamal))
if e_list != []:
e_list.sort(key = lambda tup: tup[1])
return self.roll_dice_subset(e_list,dice,scorecard)
else:
return dice.dice
def roll_dice_subset(self,e_list,dice,scorecard):
send_list = []
category = e_list.pop()[0]
if category == "unos":
for i in range(5):
if dice.dice[i] != 1:
send_list.append(i)
if category == "doses":
for i in range(5):
if dice.dice[i] != 2:
send_list.append(i)
if category == "treses":
for i in range(5):
if dice.dice[i] != 3:
send_list.append(i)
if category == "cuatros":
for i in range(5):
if dice.dice[i] != 4:
send_list.append(i)
if category == "cincos":
for i in range(5):
if dice.dice[i] != 5:
send_list.append(i)
if category == "seises":
for i in range(5):
if dice.dice[i] != 6:
send_list.append(i)
if category == "tamal":
if sum(dice.dice) < 18:
return self.roll_dice_subset(e_list,dice,scorecard)
else:
for i in range(5):
if dice.dice[i] != 4 or dice.dice[i] != 5 or dice.dice[i] != 6:
send_list.append(i)
return send_list |
0d8e5d1a56bf221a3a01ac43f76c8b33e8720244 | Aasthaengg/IBMdataset | /Python_codes/p03080/s537304676.py | 112 | 3.578125 | 4 | N = int(input())
s = input()
nR = s.count("R")
nB = s.count("B")
if nR > nB:
print("Yes")
else:
print("No")
|
8684c6c9be9f0e2977b24aad3bea6978d376d00f | DrinkMagma/viztracer | /src/viztracer/counter.py | 864 | 3.515625 | 4 | class Counter:
def __init__(self, callback, name, value={}):
self._name = name
self._callback = callback
def _update(self, d):
if self._callback:
self._callback(self._name, d)
def update(self, *args):
if len(args) == 1:
if type(args[0]) is dict:
self._update(args[0])
else:
print(type(args[0]))
raise Exception("Counter.update() takes a dict update(dict) or a key value pair set_value(key, value)")
elif len(args) == 2:
if type(args[0]) is str:
try:
val = float(args[1])
self._update({args[0]: val})
except Exception:
raise Exception("Counter.update() takes a dict update(dict) or a key value pair set_value(key, value)")
|
09f2e9db9496343d399e27e255c397f44e355b88 | sam-coleman/Presidential_Analysis | /analyze_tweets.py | 2,745 | 3.640625 | 4 | """
Analyze the Tweets
MP 3: Text Mining
@author: Sam Coleman
"""
from get_tweets import pull_all_tweets
from PIL import Image
from wordcloud import WordCloud
from matplotlib import pyplot as plt
def get_freq_dict(user_list):
"""
Get dictionry of top words with words as keys and their respective frequencies as values.
user_list: Which list of words to use(TrumpWords, BernieWords, BidenWords)
returns: word-frequency dictionary
"""
d_freq = dict()
#meaningless words to not include
ignore_words = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'it',
'for', 'on', 'by', 'from', 'this', 'is', 'for', 'on', 'by', 'from',
'this', 'is', '—', 'are', 'as', 'at', 'an', 'amp', 'if', 'has', 'was']
for word in user_list:
if word not in ignore_words:
d_freq[word] = d_freq.get(word,0) + 1
return d_freq
def get_top_n(n, dict, file_name):
"""
Get list of top used words and write to file
n: number of top words you want
dict: dictionary to use
file_name: name of file to write to (and create if needed)
returns: top word list
"""
d_sorted = sorted(dict.items(), key=lambda kv: kv[1], reverse=True)
top = d_sorted[0:n]
#put top n key and values into a list
top_words = []
for pair in top:
for item in pair:
if not isinstance(item, int):
top_words.append(item)
#Save to file
f = open(file_name, 'w')
f.write(str(top_words))
f.close()
return top_words
def create_word_cloud(dict, file_name, title):
"""
create word cloud from frequency dictionary
dict: dictionary to use
file_name: name of file to save to
title: title of word cloud to display on image
"""
#generate word cloud using WordCloud library
wc = WordCloud(background_color="white",width=3000,height=3000, relative_scaling=0.5).generate_from_frequencies(dict)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.title(title)
plt.savefig(file_name)
if __name__ == '__main__':
TrumpWords, BernieWords, BidenWords = pull_all_tweets()
BidenDict = get_freq_dict(BidenWords)
TrumpDict = get_freq_dict(TrumpWords)
BernieDict = get_freq_dict(BernieWords)
biden_top = get_top_n(50, BidenDict, 'BidenTopWords.txt')
trump_top = get_top_n(50, TrumpDict, 'TrumpTopWords.txt')
bernie_top = get_top_n(50, BernieDict, 'BernieTopWords.txt')
trump_cloud = create_word_cloud(TrumpDict, 'TrumpWordCloud', 'Trump Top Words Visualization')
bernie_cloud = create_word_cloud(BernieDict, 'BernieWordCloud', 'Bernie Top Words Visualization')
biden_cloud = create_word_cloud(BidenDict, 'BidenWordCloud', 'Biden Top Words Visualization')
|
381a700504cf76f44f7620af5e764de29cbd63a9 | christopherdoan/face-maskid | /face_detect/face-detect.py | 960 | 3.609375 | 4 | import cv2
from cv2 import imread
from cv2 import imshow
from cv2 import waitKey
from cv2 import destroyAllWindows
from cv2 import CascadeClassifier
from cv2 import rectangle
""" Implementation of tutorial provided by MachineLearningMastery article written by Jason Brownlee:
https://machinelearningmastery.com/how-to-perform-face-detection-with-classical-and-deep-learning-methods-in-python-with-keras/"""
#load the pretrained model
clf = CascadeClassifier('haarcascade_frontalface_default.xml')
pixels = imread("../images/test1.jpg")
#create bounding boxes around face
bounding_boxes = clf.detectMultiScale(pixels)
for box in bounding_boxes:
# extract
x, y, width, height = box
x2, y2 = x + width, y + height
# draw a rectangle over the pixels
rectangle(pixels, (x, y), (x2, y2), (0,0,255), 1)
# show the image
imshow('face detection', pixels)
# keep the window open until we press a key
waitKey(0)
# close the window
destroyAllWindows()
|
d19405297aec6d65cda25b8ef29e1b1d4dc7712b | j2k2020/basic_git | /python/sec04/05_while2.py | 363 | 3.984375 | 4 | # 7을 입력할 때까지 계속 입력하는 프로그램
# 7을 입력하면 프로그램 종료 (while문 사용)
#
# 숫자 입력: 3
# 다시 입력: 9
# 다시 입력: 1
# 다시 입력: 7
# 7 입력했습니다. 종료
num = int(input("숫자 입력: "))
while num != 7:
num = int(input("다시 입력: "))
print(num, "입력했습니다. 종료~") |
bc5f84721649a490403427ab132f8ccacd9a32b1 | martingaston/advent-of-code-2019 | /aoc2019/06.py | 2,922 | 3.921875 | 4 | import unittest
import collections
def steps_to_root(node, nodes):
root = "COM"
count = 1
while nodes[node] != root:
count += 1
node = nodes[node]
return count
def parse_orbit_map(orbit_map):
orbit_nodes = {}
for orbit_node in orbit_map:
orbiter, orbits = orbit_node.split(")")
if orbits not in orbit_nodes:
orbit_nodes[orbits] = orbiter
return orbit_nodes
def parse_bidirectional_map(orbit_map):
orbit_nodes = {}
for orbit_node in orbit_map:
orbiter, orbits = orbit_node.split(")")
if orbiter not in orbit_nodes:
orbit_nodes[orbiter] = [orbits]
else:
orbit_nodes[orbiter].append(orbits)
if orbits not in orbit_nodes:
orbit_nodes[orbits] = [orbiter]
else:
orbit_nodes[orbits].append(orbiter)
return orbit_nodes
def bfs(start, finish, bidirectional_map):
seen = set()
seen.add(start)
queue = collections.deque([])
queue.append((bidirectional_map[start], 1))
while finish not in seen:
node, steps = queue.popleft()
for child in node:
if child in seen:
continue
seen.add(child)
if child == finish:
return steps
queue.append((bidirectional_map[child], steps + 1))
def count_orbits(orbit_map):
orbit_nodes = parse_orbit_map(orbit_map)
return sum([steps_to_root(orbit_node, orbit_nodes) for orbit_node in orbit_nodes])
if __name__ == "__main__":
with open("input/06.txt") as f:
orbit_map = f.read().splitlines()
bidirectional_map = parse_bidirectional_map(orbit_map)
shortest = bfs("YOU", "SAN", bidirectional_map)
print(
f"the shortest number of orbit stops between YOU and SAN is: {shortest - 2}"
)
print(
f"the total direct and indirect orbits of the orbit map are: {count_orbits(orbit_map)}"
)
class Test(unittest.TestCase):
def test_functional_test_to_check_multiple_branches(self):
orbit_map = [
"COM)B",
"B)C",
"C)D",
"D)E",
"E)F",
"B)G",
"G)H",
"D)I",
"E)J",
"J)K",
"K)L",
]
orbits = count_orbits(orbit_map)
self.assertEqual(42, count_orbits(orbit_map))
def test_shortest_path_to_santa(self):
orbit_map = [
"COM)B",
"B)C",
"C)D",
"D)E",
"E)F",
"B)G",
"G)H",
"D)I",
"E)J",
"J)K",
"K)L",
"K)YOU",
"I)SAN",
]
bidirectional_map = parse_bidirectional_map(orbit_map)
shortest = bfs("YOU", "SAN", bidirectional_map)
self.assertEqual(4, shortest - 2)
|
0340214111976466f4df44d468d65a5dd011e12b | Yasaman1997/My_Python_Training | /Test/function/cube.py | 160 | 3.796875 | 4 | def cube(number):
print "%d" % (number ** 3)
def by_three(number):
if number % 3 == 0:
cube(number)
else:
return False
|
1a4db77cfc78c35bcef304d19b5b28730f4f89e8 | RombosK/GB_1824 | /Kopanev_Roman_DZ_11/dz_11_2.py | 1,031 | 3.90625 | 4 | # Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. Проверьте его работу на данных, вводимых
# пользователем. При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
class MyZeroDivision(Exception):
def __init__(self, text):
self.text = text
def division():
try:
num1 = int(input('Введите делимое: '))
num2 = int(input('Введите делитель: '))
if not num2:
raise MyZeroDivision('На ноль делить нельзя')
else:
result = num1 / num2
return result
except ValueError:
return 'Введите корректное число'
except MyZeroDivision as e:
return e
print(division())
|
80388097a3f7a682b5fe65c3472dd5e954af5555 | choroba/perlweeklychallenge-club | /challenge-207/lubos-kolouch/python/ch-1.py | 1,731 | 4.1875 | 4 | #!/usr/bin/env python3
import unittest
from typing import List
def is_single_row_word(word: str) -> bool:
"""Check if a word can be typed using only one row of the keyboard.
Args:
word (str): The word to check.
Returns:
bool: True if the word can be typed using only one row of the keyboard,
False otherwise.
"""
keyboard_rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
keyboard_map = {}
for i in range(len(keyboard_rows)):
for c in keyboard_rows[i]:
keyboard_map[c] = i+1
row = keyboard_map.get(word[0].lower(), 0)
for c in word:
if keyboard_map.get(c.lower(), 0) != row:
return False
return True
def filter_single_row_words(words: List[str]) -> List[str]:
"""Filter out the words that can be typed using only one row of the keyboard.
Args:
words (List[str]): The list of words to filter.
Returns:
List[str]: A new list containing only the words that can be typed using
only one row of the keyboard.
"""
return [w for w in words if is_single_row_word(w)]
class TestSingleRowWords(unittest.TestCase):
def test_example1(self):
"""Test the first example from the task description."""
words = ["Hello", "Alaska", "Dad", "Peace"]
single_row_words = filter_single_row_words(words)
self.assertCountEqual(single_row_words, ["Alaska", "Dad"])
def test_example2(self):
"""Test the second example from the task description."""
words = ["OMG", "Bye"]
single_row_words = filter_single_row_words(words)
self.assertCountEqual(single_row_words, [])
if __name__ == '__main__':
unittest.main()
|
7b7960e139e1025bc0d903b38d2d3bbf4e4a7eeb | Ice-Sniper/pygame_mcpi_LCD_7seg | /lcdfontdisp.py | 4,092 | 3.84375 | 4 | # Display LCD font in 5x7 dot matrix for Pygame or Minecraft
# LCD フォントの表示、5x7ドットマトリクス、Pygameやマイクラ用
# self.BLOCK_SIZE などの定数は全て変数にする。途中で変化することもある。
import lcdfont
GRAY = (80, 80, 80)
GREEN = (10, 250, 10)
WHITE = (250, 250, 250)
class LcdFontDisplay():
"""Display line by LCD font
LCDフォントで描くディスプレイライン
"""
def __init__(self, screen):
self.screen = screen
self.set_col()
self.set_row()
def set_col(self, block_size=4, block_intv=4, color_on=WHITE, color_off=GRAY):
""" Setting the character of column in dislapy line
表示行の一文字について設定
Args:
block_size (int, optional): Defaults to 3.
Size of each block in pixels.
ブロックサイズをピクセル数で指定。
block_intv (int, optional): Defaults to 4.
Interval of each block in pixels.
ブロック同士の配置間隔をピクセル数で指定。
color_on ([type], optional): Defaults to WHITE.
color of block with lights on
点灯中ブロックの色。
color_off ([type], optional):Defaults to GRAY.
color of block with lights off
消灯中ブロックの色。
"""
self.BLOCK_SIZE = block_size
self.BLOCK_INTV = block_intv
self.COLOR_ON = color_on
self.COLOR_OFF = color_off
def set_row(self, x_org=2, y_org=8, col_intv=6):
""" Setting display row line
表示行の設定
Args:
x_org (int): Defaults to 2.
原点(最上位桁の左下)のx座標をブロック数で指定。
y_org (int): Defaults to 8.
原点(最上位桁の左下)のy座標をブロック数で指定。
col_intv (int): Defaults to 6.
桁の間隔をブロック数で指定。
"""
# BLOCK_INTVは、
# 原点(最上位桁の左下)の座標
self.X_ORG = x_org * self.BLOCK_INTV
self.Y_ORG = y_org * self.BLOCK_INTV
# 桁同士の間隔、ピクセル指定
self.COL_INTV = col_intv * self.BLOCK_INTV
def update_col(self, col=0, character="2"):
""" Display one character at the column
指定桁に、指定文字を表示する関数
Args(引数):
col (int): Defaults to 0.
the column to display
表示する桁
chr (str): Defaults to "2".
the character to display
表示する文字
"""
# codeの文字をcol桁目に表示、桁は最上位桁の左から右へ進む。
# そのコードのフォントデザインがなければコード0x7fにすり替える。
if ord(character) in lcdfont.FONT_STYLES_ASCII.keys():
chr_code = ord(character)
else:
chr_code = 0x7f
i = 0
for i in range(35):
x = i % 5
y = i // 5
if lcdfont.FONT_STYLES_ASCII[chr_code][i] == 1:
color = self.COLOR_ON
else:
color = self.COLOR_OFF
# 桁の原点
x0 = self.X_ORG + self.COL_INTV * col
y0 = self.Y_ORG
# ドットの原点座標
org1 = (x0 + x * self.BLOCK_INTV, y0 + y * self.BLOCK_INTV)
# ドットを描く
self.draw_dot(org1, color)
def draw_dot(self, org, color):
""" draw a dot. you need actual method in the child class.
ドットを描く。実際のメソッドは、子クラスに実装すること。"""
pass
def update_message(self, message="012"):
""" display the message line
文字列を表示
"""
i = 0
for c in message:
self.update_col(col=i, character=c)
i += 1
|
92ae1b8ce66ea6ab7f79ed85a671215074b888bc | jintangli/PythonProject | /Algorithm/Array/ArraySum_ContinuousSubArray.py | 1,012 | 3.828125 | 4 | ##
# given an array and a number,
# find all the combination of two indices such that the sum of their element value equals to this given number
class Solution(object):
def findSubArray(self, array, sum):
i, j, k = (0, 0, len(array))
temp = array[i]
while i<=j<k:
if(temp == sum):
print(str(i) + " " + str(j) + ",")
temp = temp - array[i]
i += 1
j += 1
if j < k:
temp = temp + array[j]
else:
return
elif temp < sum and j < k :
j += 1
temp = temp + array[j]
elif temp > sum and i < j:
temp = temp - array[i]
i += 1
else:
return
def main():
s = Solution()
array = [3, 5, 7, 12, 11, 8, 9, 7, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 12]
sum = 12
s.findSubArray(array, sum)
if __name__ == "__main__":
main() |
c74772fabd2043f650db15a739dabc6bc5751c0f | Humbertotl/FundamentosPython | /aula2/programa11.py | 307 | 4 | 4 | lista1 = ['e','c','a','b','d']
lista_ordenada = sorted(lista1, reverse=True)
lista_d = reversed(lista1)
lista_rev_da_ord = reversed(lista_ordenada)
print(lista1,'lista original')
print(list(lista_d))
print(lista_ordenada)
print(list(lista_rev_da_ord))
#list.sort() #executando o metodo
#print(list)
|
f9dc6f7ca615edbaa1664c0e7be57db274032615 | 132sonalipatil/132sonalipatil-132sonalipatil-Prediction-using-Supervised-ML | /Prediction-using-Supervised-ML.py | 2,916 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # SONALI PATIL
# # Task 1 - Prediction using Supervised ML (Level - Beginner)
#
# In[25]:
# import all reuired libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[26]:
# Reading the file
url="http://bit.ly/w-data"
data=pd.read_csv(url)
# In[27]:
data.head()
# In[28]:
data.info()
# In[29]:
data.describe()
# # Visualizing the data
#
# In[30]:
## Plotting the distribution of scores
data.plot(x='Hours', y='Scores', style='*')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
# # From above graph we can clearly see there is a positive linear relation bet. no. of hours and percentage of the score
# # Preparing the data
# In[31]:
X = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
# In[46]:
# Split this data into a training and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=0)
# In[48]:
print("Shape of X_train",X_train.shape)
print("shape of y_train",y_train.shape)
print("Shape of X_test",X_test.shape)
print("Shape of y_test",y_test.shape)
# In[50]:
## After the spliting now we have to train our algorithm
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete!!!!!.")
# # Plotting Regression Line
# In[56]:
regressor.coef_
# In[57]:
regressor.intercept_
# In[58]:
line = regressor.coef_*X+regressor.intercept_
# Plotting for the test data
plt.scatter(X, y)
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.plot(X, line);
plt.show()
# # Predictions
# In[36]:
print(X_test) # Testing data - In Hours
y_pred = regressor.predict(X_test) # Predicting the scores
# In[37]:
# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
# In[59]:
# Predict the value by own data
hours = [9.25]
own_pred = regressor.predict([hours])
print("No of Hours = {}".format(hours))
print("Predicted Score = {}".format(own_pred[0]))
# # Evaluting the model
# #The final step is to evaluate the performance of algorithm.
# #This step is particularly important to compare how well different algorithms perform on a particular dataset. For simplicity #here, I have evaluted model using mean absolute error,mean squared error and root mean squared error
#
# In[63]:
from sklearn import metrics
print('Mean Absolute Error:',metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:',metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:',np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
# In[ ]:
|
81d71f981fa67a586176705be5fc17f5ac3ce8bf | apalabh/Portfolio- | /password.py | 583 | 3.9375 | 4 | def takePass():
p=input("Enter a password : ")
if checkPass(p)== True :
pn = input("Enter password again : ")
else :
p = input("Enter new password : ")
if p == pn :
pass
else :
p=input("Enter a password : ")
return p
def checkPass(p):
for i in p :
if i.isupper()== True and len(p)>= 8 and p.isalnum == True :
return True
else :
return False
if __name__ == "__main__":
p = takePass()
checkPass(p)
|
6c900d9c6f54b8d16c71ee96775c04004800b048 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/ostada001/util.py | 3,763 | 3.65625 | 4 | '''Question 2 Assignment 7
Utility functions which manipulate a 2 dimensional, 4*4 array
Adam Oosthuizen
27 April 2014'''
def create_grid(grid):
'''creates a 4x4 grid'''
grid=[]
for i in range(4):
grid.append(['']*4)
return grid
def print_grid(grid):
'''Print out a 4x4 grid in 5-width collumns within a box'''
#+--------------------+
#|2 2 |
#| 4 8 |
#| 16 128 |
#|2 2 2 2 |
#+--------------------+
print("+--------------------+")
for i in range(4):
print('|',end='')
for j in range(4):
if grid[i][j] != 0:
print(grid[i][j]," "*(5-(len(str(grid[i][j])))),sep='',end='')
else:
print(" "*5,end='')
print('|')
print("+--------------------+")
def check_lost (grid):
"""return True if there are no 0 values and no adjacent values that are equal; otherwise False"""
check1 = True
check2 = True
#checking for equal numbers adjacent to eachother
for i in range(4):
for j in range(4):
if i == 0 and j==0:
if grid[i+1][j] == grid[i][j] or grid[i][j+1] == grid[i][j]:
check1 = False
elif i == 3 and j ==0:
if grid[i-1][j] == grid[i][j] or grid[i][j+1] == grid[i][j]:
check1= False
elif i ==0 and j == 3:
if grid[i+1][j]==grid[i][j] or grid[i][j-1] == grid[i][j]:
check1 = False
elif i ==3 and j ==3:
if grid[i][j-1]==grid[i][j] or grid[i-1][j]==grid[i][j]:
check1 = False
elif i == 0:
if grid[i+1][j]==grid[i][j] or grid[i][j+1]==grid[i][j] or grid[i][j-1]==grid[i][j]:
check1 = False
elif i ==3:
if grid[i-1][j]==grid[i][j] or grid[i][j+1]==grid[i][j] or grid[i][j-1]==grid[i][j]:
check1 = False
elif j == 0:
if grid[i+1][j] == grid[i][j] or grid[i-1][j] == grid[i][j] or grid[i][j+1] == grid[i][j]:
check1 = False
elif j == 3:
if grid[i+1][j] == grid[i][j] or grid[i-1][j] == grid[i][j] or grid[i][j-1] == grid[i][j]:
check1 = False
else:
if grid[i+1][j] == grid[i][j] or grid[i-1][j] == grid[i][j] or grid[i][j+1] == grid[i][j] or grid[i][j-1] == grid[i][j]:
check1 = False
#check for 0
for i in range(4):
for i in range(4):
if grid[i][j] == '' :
check2 = False
if check1 == True and check2 == True:
return True
else:
return False
#+--------------------+
#|2 2 |
#| 4 8 |
#| 16 128 |
#|2 2 2 2 |
#+--------------------+
def check_won (grid):
"""return True if a value>=32 is found in the grid; otherwise False"""
test = False
for i in range(4):
for j in range(4):
if grid[i][j] >= 32:
test = True
return test
def copy_grid (grid):
"""return a copy of the grid"""
grid2 = grid
return grid2
def grid_equal (grid1, grid2):
"""check if 2 grids are equal - return boolean value"""
test = True
for i in range(4):
for j in range(4):
if grid1[i][j] != grid2[i][j]:
test = False
return test |
dfd64c6d2867e8c310c3518e32401b046fc2eadf | Julian-Chu/leetcode_python | /lintcode/lintcode49.py | 467 | 3.546875 | 4 | class Solution:
"""
@param: chars: The letter array you should sort by Case
@return: nothing
"""
def sortLetters(self, chars):
l, r = 0, len(chars) - 1
while l <= r:
while l <= r and chars[l] >= 'a':
l += 1
while l <= r and chars[r] < 'a':
r -= 1
if l <= r:
chars[l], chars[r] = chars[r], chars[l]
l += 1
r -= 1
|
e49b58c27398ff86aca74c86ffd096f3b9ce670c | munsangu/20190615python | /python_basic/def_test.py | 334 | 3.6875 | 4 | def add(a,b):
result = a+b
print("a=",a,"b=",b)
return result
def add_many(*args):
result = 0
for i in args:
result = result + i
return result
def print_kwargs(**args):
print(args)
print_kwargs(name="kang",age=70,city="Daegu")
a = 1
def test_1():
global a
a = a+1
test_1()
print(a) |
a36b090fa6fa05e1b98953a0a90afdbbcafaba53 | krishdb38/Python_Free_Coding | /tkinter_free/radio_button.py | 520 | 3.640625 | 4 | import tkinter as tk
window = tk.Tk()
v = tk.StringVar()
def show_choice():
print(v.get())
tk.Label(window,text="Choose a Metrix for blastp",padx=20).pack()
tk.Radiobutton(window,text = "BLOSUM45",variable=v,value = "BLOSUM45",command = show_choice).pack(side = "left")
tk.Radiobutton(window,text = "BLOSUM62",variable = v,value="BLOSUM62",command = show_choice).pack(side = "left")
tk.Radiobutton(window,text = "BLOSUM82",variable = v,value="BLOSUM82",command = show_choice).pack(side = "left")
window.mainloop() |
1b36acc766282b623811d3b20669229c402751c1 | AdvaithD/Paradise | /CTCI-Solutions/CH1-ArraysStrings/palindrome.py | 417 | 3.90625 | 4 | def isPermutationOfAPalindrome(string):
let count = {}
for letter in string.replace(' ', ''):
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for x in coun.values():
oddcount += x % 2
if oddcount > 1:
return False
return True
print('Checking the permutation of a palindrome')
isPermutationOfAPalindrome('Tact Coa')
|
fcd8a540da5dd1addfed17d877b1c05323b5cac4 | abhi1362/HackerRank | /Python/Sets/Introduction to Sets.py | 298 | 3.96875 | 4 | def average(array):
set_=set(array)
average = 0
for item in set_:
average = average + item
average = average / len(set_)
return average
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
8a5c10b6f722c9e3dcf30f5882afadfefe6d130c | AzizHarrington/command-line-games | /blackjack.py | 5,771 | 3.75 | 4 | import random
import os
class Deck(object):
def __init__(self):
self.cards = ['%s%s' % (num, suit)
for num in 'A23456789TJQK'
for suit in '♠♥♦♣']
random.shuffle(self.cards)
def drawone(self):
if len(self.cards) == 0:
print("everyday i'm shufflin'....")
self.__init__()
return [self.cards.pop()]
def drawtwo(self):
return self.drawone() + self.drawone()
deck = Deck()
class Player(object):
def __init__(self):
self.hand = None
self.stay = False
self.score = None
def deal(self):
self.hand = deck.drawtwo()
def hit(self): #accepts list as input
self.hand.extend(deck.drawone())
def next_move(self):
print("What would you like to do next? (choose one)")
print("Take a hit: 1")
print("Stay: 2")
print("Look at hand: 3")
next = input(">")
if next == '1':
self.hit()
elif next == '2':
self.stay = True
elif next == '3':
print('')
print(self.hand)
print('')
self.next_move()
else:
print("Please enter 1, 2, or 3")
input()
self.next_move()
def get_current_score(self):
score = 0
for card in self.hand:
if card[0] != 'A':
score += self.value(card)
for card in self.hand:
if card[0] == 'A':
score += self.get_ace_value(card, score)
if (score == 21) and (len(self.hand) == 2) and ('J♣' or 'J♠' in self.hand):
self.score = 22
print("Blackjack!")
elif score > 21:
self.score = 0
print("Bust!")
else:
self.score = score
def value(self, card):
number = card[0]
if number in 'TJQK':
return 10
else:
return int(number)
def get_ace_value(self, card, score):
print("Current score is: %s" % (score,))
print("Count '%s' as 1 or 11?" % (card,))
val = input(">")
return int(val)
class Dealer(Player):
def next_move(self):
self.get_current_score()
if self.score < 17:
self.hit()
print("The dealer took a hit.")
else:
self.stay = True
print("The dealer decided to stay.")
def get_ace_value(self, card, score):
if score <= 10:
return 11
else:
return 1
class Game(object):
def __init__(self):
self.dealer = Dealer()
self.player = Player()
def print_hand(self, hand):
result = ""
for c in hand:
result += (c + " ")
print(result)
def play(self):
os.system('clear')
print("------------------------------------------------")
print("Welcome to Command Line Blackjack!")
print("------------------------------------------------")
print("Press enter to start the game!")
input(">")
print("The dealer begins to shuffle the cards...")
self.dealer.deal()
self.player.deal()
print("...and deals the hands.")
input(">")
print("------------------------------------------------")
print("Dealer:")
self.print_hand(self.dealer.hand)
self.dealer.get_current_score()
print("------------------------------------------------")
input(">")
print("------------------------------------------------")
print("Your hand:")
self.print_hand(self.player.hand)
self.player.get_current_score()
print("------------------------------------------------")
input(">")
while not (self.dealer.stay and self.player.stay):
print("The dealer is thinking.")
input(">")
self.dealer.next_move()
input(">")
self.dealer.get_current_score()
if self.dealer.score == 0:
print("The dealer busted!")
self.print_hand(self.dealer.hand)
break
elif self.dealer.score == 22:
print("The dealer got blackjack!")
self.print_hand(self.dealer.hand)
break
if not self.dealer.stay:
print("Dealer:")
self.print_hand(self.dealer.hand)
print("------------------------------------------------")
input(">")
self.player.next_move()
print('')
self.print_hand(self.player.hand)
input(">")
self.player.get_current_score()
if self.player.score == 0:
print("You busted!!")
self.print_hand(self.player.hand)
break
elif self.player.score == 22:
print("You got blackjack!")
self.print_hand(self.player.hand)
break
if not self.player.stay:
print("Your hand:")
self.print_hand(self.player.hand)
print("------------------------------------------------")
input(">")
if self.dealer.score >= self.player.score:
print("The house wins. Better luck next time!")
else:
print("You win!")
input(">")
if __name__ == "__main__":
game = Game()
game.play()
print("Play again? (yes/no)")
again = input(">")
while again == "yes":
game = Game()
game.play()
print("Play again? (yes/no)")
again = input(">")
print("Come back soon!")
input(">")
|
445a90d225600ceb3e8f55ff8e27dd787a10de85 | findango/wooords-solver | /wooords.py | 1,354 | 3.515625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
wooords.py - solve a Wooords puzzle
"""
import sys
from collections import defaultdict
ANAGRAMS = defaultdict(list)
MIN_WORD_LENGTH = 3
def load_dictionary(fname):
f = open(fname)
for word in f.readlines():
word = word.rstrip("\n")
key = "".join(sorted(word))
ANAGRAMS[key].append(word)
f.close()
def find_anagrams(letters):
key = "".join(sorted(letters))
if ANAGRAMS.has_key(key):
return ANAGRAMS[key][:] # return a copy
return []
def find_words(special, letters):
MASK = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80]
words = []
for combo in range(256):
subset = special
for i in range(8):
if combo & MASK[i]:
subset += letters[i]
if len(subset) > MIN_WORD_LENGTH:
words.extend(find_anagrams(subset))
return clean(words)
def clean(words):
words = list(set(words)) # de-dupe
words.sort()
return words
def main():
special = sys.argv[1]
letters = sys.argv[2]
load_dictionary("./dictionary.txt")
words = find_words(special, letters)
bingos = filter(lambda w: len(w) == 9, words)
print "\n".join(words)
print
print "Found", len(words), "words"
print "Bingos: " + ", ".join(bingos)
if __name__ == '__main__':
main()
|
0ac19ac8e8b3a8285739b2b144b4a1c9ddf8a0f5 | 7kjmol/PythonTestProject | /Exeicise/1-20/example14.py | 1,018 | 3.9375 | 4 | '''
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
'''
import math
def isSushu(num):
flag = True
for i in range(2,int(math.sqrt(num))):
if((num % i) == 0):
flag = False;break
return flag
num = 6
temp = num
print("%d = " %num, end='')
i = 2
while (temp != 1 and i <= math.sqrt(num)):
if(isSushu(i) and (temp % i) == 0):
if(temp / i == 1):
print("%d" % i, end='.')
else:
print("%d * " % i, end='')
temp = temp / i
else:
i = i + 1
print("%d" % i, end='.')
|
bd5e05cf4af6e4df377e351165cb55db44ea8eb6 | Artem-Vorobiov/Physics_In_Games_T | /9_om.py | 1,931 | 3.890625 | 4 | import turtle
import math
import random
# Set up screen
wn = turtle.Screen()
wn.bgcolor('blue')
wn.title('Simple Object Motion with Physics and NO Friction Player in the center')
class Player(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color('white')
self.shape('triangle')
self.penup()
self.speed(0) # Animation speed
self.speed = 0.8
self.thrust = 0.8
self.dx = 0
self.dy = 0
def move(self):
self.goto(self.xcor() + self.dx, self.ycor() + self.dy)
def turnleft(self):
self.left(30)
def turnright(self):
self.right(30)
########################################################################################
################## Why is this formula ? ##########################
def accelerate(self): # new function
h = self.heading()
# print('\nHeading {}, and type of {}\n'.format(h, type(h)))
# print('\nY {}, and type of Y {}\n'.format(self.dy, type(self.dy)))
self.dx += math.cos(h*math.pi/180)*self.thrust
self.dy += math.sin(h*math.pi/180)*self.thrust
# print('\nY {}, and type of Y {}\n'.format(self.dy, type(self.dy)))
########################################################################################
class Enemy(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color('red')
self.shape('circle')
self.penup()
self.speed(0)
self.goto(random.randint(-500, 500), random.randint(-500, 500))
def move(self):
self.fd(1 )
self.setx(self.xcor() - player.dx)
self.sety(self.ycor() - player.dy)
player = Player()
enemies = []
for _ in range(25):
enemies.append(Enemy())
turtle.listen() # Tells the Turtle module to listen for the keynoard inpput
turtle.onkey(player.turnleft, 'Left')
turtle.onkey(player.turnright, 'Right')
turtle.onkey(player.accelerate, 'Up')
wn.tracer(0)
# Main game loop
while True:
wn.update()
# player.move()
for enemy in enemies:
enemy.move()
|
869a4b6ea96a20fffc4e333ddc263530cee7f142 | ht-dep/Algorithms-by-Python | /Python Offer/06.The Sixth Chapter/64.Sum_1_n.py | 443 | 3.640625 | 4 | # coding:utf-8
'''
求1+2+3+...+n的和
要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
'''
class Solution(object):
def sum0(self, n):
return 0
def sum(self, n):
fun = {False: self.sum0, True: self.sum} # fun为字典,key值为bool类型,value为函数
return n + fun[not not n](n - 1) #
if __name__ == '__main__':
s = Solution()
print s.sum(5)
|
568d7a0c7522158b85cef9fc6cbb9de2305c868b | rliu054/machine-learning-from-scratch | /DecisionTree/decision_tree.py | 3,764 | 3.75 | 4 | """
Decision tree module.
"""
import math
import operator
def create_data_set():
"""Generate a simple test data set."""
data_set = [
[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no'],
]
labels = ['no surfacing', 'flippers']
return data_set, labels
def shannon_entropy(data_set):
"""Calculate Shannon entropy."""
num_entries = len(data_set)
label_dict = {}
for feature_vec in data_set:
curr_label = feature_vec[-1]
if curr_label not in label_dict:
label_dict[curr_label] = 0
label_dict[curr_label] += 1
entropy = 0.0
for key in label_dict:
prob = float(label_dict[key]) / num_entries
entropy -= prob * math.log(prob, 2)
return entropy
def split_data_set(data_set, axis, value):
"""Split set according to specified feature and value."""
result = []
for feat_vec in data_set:
if feat_vec[axis] == value:
result.append(feat_vec[:axis] + feat_vec[axis + 1:])
return result
def best_feat_to_split(data_set):
"""Iterate all features and find out the best one to split on."""
num_features = len(data_set[0]) - 1
base_entropy = shannon_entropy(data_set)
best_info_gain = 0.0
best_feature = -1
for i in range(num_features):
feat_vals = [example[i] for example in data_set]
uniq_feat_vals = set(feat_vals)
new_entropy = 0.0
for val in uniq_feat_vals:
sub_data_set = split_data_set(data_set, i, val)
prob = len(sub_data_set) / float(len(data_set))
new_entropy += prob * shannon_entropy(sub_data_set)
info_gain = base_entropy - new_entropy
if info_gain > best_info_gain:
best_info_gain = info_gain
best_feature = i
return best_feature
def majority_count(class_list):
"""Return feature of majority node."""
class_count = {}
for vote in class_list:
if vote not in class_count:
class_count[vote] = 0
class_count[vote] += 1
sorted_class_count = sorted(
class_count.items(), key=operator.itemgetter(1), reverse=True)
return sorted_class_count[0][0]
def create_tree(data_set, labels):
"""Main method to generate decision tree."""
class_list = [example[-1] for example in data_set]
if class_list.count(class_list[0]) == len(class_list):
return class_list[0]
if len(data_set[0]) == 1:
return majority_count(class_list)
best_feature = best_feat_to_split(data_set)
best_feature_label = labels[best_feature]
tree = {best_feature_label: {}}
del labels[best_feature]
feat_values = [example[best_feature] for example in data_set]
uniq_values = set(feat_values)
for val in uniq_values:
sub_labels = labels[:]
sub_ds = split_data_set(data_set, best_feature, val)
tree[best_feature_label][val] = create_tree(sub_ds, sub_labels)
return tree
def classify(input_tree, feat_labels, test_vec):
"""Run classification on input tree."""
first_str = list(input_tree)[0]
second_dict = input_tree[first_str]
feat_index = feat_labels.index(first_str)
key = test_vec[feat_index]
value_of_feat = second_dict[key]
if isinstance(value_of_feat, dict):
return classify(value_of_feat, feat_labels, test_vec)
return value_of_feat
def store_tree(input_tree, filename):
"""Dump tree to file."""
import pickle
dump_file = open(filename, 'wb')
pickle.dump(input_tree, dump_file)
dump_file.close()
def grab_tree(filename):
"""Read tree from file."""
import pickle
dump_file = open(filename, 'rb')
return pickle.load(dump_file)
|
76c810b2f3da012c9c352d9747e6c2ec07c93d97 | ecly/kattis | /watchdog/watchdog.py | 765 | 3.625 | 4 | def dist(x1, y1, x2, y2):
return (abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2) ** 0.5
def find_shortest(s, h):
hatches = {tuple(map(int, input().split())) for _ in range(h)}
for x in range(s):
for y in range(s):
if (x, y) in hatches:
continue
max_leash_length = min(x, s - x, y, s - y)
leash_length = max(dist(x, y, hx, hy) for hx, hy in hatches)
if leash_length <= max_leash_length:
return x, y
return None
def main():
n = int(input())
for _ in range(n):
s, h = map(int, input().split())
res = find_shortest(s, h)
if res:
print(*res)
else:
print("poodle")
if __name__ == "__main__":
main()
|
c2d8fe69d77582f58b0017236e798fd6f6859a11 | travbrown/CS-0 | /Intro_classes.py | 2,908 | 3.984375 | 4 | class Person:
# This function is called whenever a new Person object is created. The
# self parameter refers to the object itself, i.e. the instance of the
# class that is being created.
def __init__(self, first, last):
self.first = first
self.middle = None
self.last = last
def __str__(self):
if self.middle != None:
return self.first + ' ' + self.middle + ' ' + self.last
return self.first + ' ' + self.last
def add_middle_name(self, middle):
self.middle = middle
class Student(Person):
def __init__(self, first, last):
super().__init__(first, last) # Call parent's __init__() function
self.grades = []
self.average = 0
def __str__(self):
return Person.__str__(self) + ' ' + str(self.grades)
def add_grade(self, grade, max_grade, weight):
self.grades.append((grade, max_grade, weight))
def grades_average(self):
max_weight,weighted_sum = 0,0
if self.grades == []:
return None
for grade, max_grade, weight in self.grades:
max_weight += weight
weighted_sum += ((grade/max_grade)*weight)
self.average = float(weighted_sum/max_weight)*100
return self.average
def __lt__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() < other.grades_average()
return False
def __gt__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() > other.grades_average()
return False
def __eq__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() == other.grades_average()
return False
def __ge__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() >= other.grades_average()
return False
def __le__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() <= other.grades_average()
return False
def __ne__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() != other.grades_average()
return False
# This is to list all the methods in the Student class. See which one(s) of
# those you have to implement for part #3 of the assignment...
for f in [func for func in dir(Student) if callable(getattr(Student, func))]:
print(f)
me = Student('Travis','Brown')
me.add_grade(90,100,1.0)
me.add_grade(20,25,2.0)
him = Student('Daniel','Lawla')
him.add_grade(9,100,1.0)
him.add_grade(2,25,2.0)
print(me.__str__())
print(me.grades_average())
print(me.__lt__(him))
me.add_middle_name('Jordan')
print(me.__str__()) |
fc34d04e5ead1c23e982c992dcc95ebb49652300 | eightnoteight/compro | /spoj/ec_conb.py | 187 | 3.640625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
for _ in xrange(int(raw_input())):
t = int(raw_input())
if t % 2:
print t
else:
print int(bin(t)[-1:1:-1], 2)
|
efd46f1ea8fb824d75aabede0d5a49e9fe2be15f | jcruz63/python_college_assignments | /journal4.py | 1,327 | 4.15625 | 4 | import math
# create function stub
def hyp_step1(a, b):
return 0
# first second step square a and b print results to test
def hyp_step2(a, b):
print("inside step 2") # this is just to make the console read clearer
a_sqr = a**2
b_sqr = b**2
print('a squared is', a_sqr)
print('b squared is', b_sqr)
return 0
# third step get the sum of a and b square print to test
def hyp_step3(a, b):
print("inside step 3") # this is just to make the console read clearer
a_sqr = a ** 2
b_sqr = b ** 2
sum_a_b = a_sqr + b_sqr
print('the sum of a squared plus b squared is', sum_a_b)
return 0
# refactor the code to remove the print statements and return the square root of a^2 and b^2
def hyp_step4(a, b):
a_sqr = a ** 2
b_sqr = b ** 2
sum_a_b = a_sqr + b_sqr
return math.sqrt(sum_a_b)
def display_hypo(a, b):
print('The hypotenuse of a triangle with the side a:{a} and side b:{b} is:{c}'.format(a=a, b=b, c=hyp_step4(a, b)))
def main():
a = 3
b = 4
print("return of step 1 ->", hyp_step1(a, b))
print("return of step 2 ->", hyp_step2(a, b))
print("return of step 3 ->", hyp_step3(a, b))
print("return of step 4 ->", hyp_step4(a, b))
a2 = 5
b2 = 8
display_hypo(a2, b2)
a3 = 7
b3 = 5
display_hypo(a3, b3)
main()
|
fa2dcb3832fd28ca58fe280c0636481703050dc6 | tarunjoseph94/Python-Lab | /hand7_1.py | 530 | 3.96875 | 4 | class Rectangle:
def __init__(self,height,width):
self.height=height
self.width=width
def area(self):
a=self.height*self.width
return a
def peri(self):
p=2+(self.height+self.width)
return p
def heightReturn(self):
return self.height
def widthReturn(self):
return self.width
def isSqaure(self):
if(self.height==self.width):
print("It is a square")
else:
print("It is not a square")
r1=Rectangle(10,10)
print(r1.area())
print(r1.peri())
print(r1.heightReturn())
print(r1.widthReturn())
r1.isSqaure() |
84e4a57279bf1764679d997f5d5595d82e331526 | shouliang/Development | /Python/LeetCode/300_length_of_LIS.py | 2,268 | 3.84375 | 4 | '''
最长上升子序列
300. Longest Increasing Subsequence:https://leetcode.com/problems/longest-increasing-subsequence/
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
思路1:动态规划:O(n^2)
首先想到用动态规划解决该问题,维护数组 dp , dp[i] 表示以第i个元素为结尾的增长序列的长度,
则递归式为:dp[i]= max(dp[i], dp[j] + 1) 其中 j 0..i-1 && nums[i] > nums[j]
思路2:Θ(nlgn)的方案,二分查找
建立一个辅助数组tails,依次读取数组元素 x 与数组末尾元素 top比较:
如果 x > top,将 x 放到数组末尾;
如果 x < top,则二分查找数组中第一个 大于等于x 的数,并用 x 替换它。
'''
class Solution(object):
def _lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 1
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
result = max(result, dp[i])
return result
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tails = []
for x in nums:
if len(tails) == 0 or tails[-1] < x:
tails.append(x)
else:
low, high = 0, len(tails) - 1
while low <= high:
mid = (low + high) // 2
if tails[mid] >= x:
high = mid - 1
else:
low = mid + 1
tails[low] = x # 找的是第一个大于等于目标的数,又数组是升序的,即从小到大,故取low
return len(tails)
s = Solution()
nums = [10, 9, 2, 5, 3, 7, 101, 18]
lenLIS = s.lengthOfLIS(nums)
print(lenLIS)
lenLIS = s._lengthOfLIS(nums)
print(lenLIS)
|
5fcbcb5745eef5f1b3bc843e759f9cbbfb75c96f | BrettParker97/CodingProblems | /2021-08-02/sol.py | 1,770 | 3.90625 | 4 |
class LRUCache:
def __init__(self, listSize):
self.listSize = listSize
self.FIFO = []
self.cache = {}
def addToFIFO(self, value):
res = None
#if value is in list, then delete it
#and bring it to the front
if value in self.FIFO:
self.FIFO.remove(value)
self.FIFO = [value] + self.FIFO
#if its not at front of list, check size of list
else:
#if list is max size, pop something
if len(self.FIFO) >= self.listSize:
res = self.FIFO[len(self.FIFO) - 1]
self.FIFO.pop()
self.FIFO = [value] + self.FIFO
#if list isnt max size, just place value at front
else:
self.FIFO = [value] + self.FIFO
return res
def get(self, key):
#check cache for value, if its not in there
#then dont bother adding it to FIFO
res = None
try:
res = self.cache[key]
except KeyError:
res = None
if res == None:
return None
#update FIFO, we dont care if something is poped here
self.addToFIFO(key)
#return whats in the dictionary
return res
def put(self, key, value):
#check FIFO, if something is poped then del
#from the cache as well
res = self.addToFIFO(key)
if res != None:
del self.cache[res]
#add to cache and return
self.cache[key] = value
cache = LRUCache(2)
cache.put(3, 3)
cache.put(4, 4)
print(cache.get(3))
# 3
print(cache.get(2))
# None
cache.put(2, 2)
print(cache.get(4))
# None (pre-empted by 2)
print(cache.get(3))
# 3 |
69743ad6e437de27b044b345ebea695aea78895a | murffious/pythonclass-cornell | /coursework/programming-with-objects/exercise1/script.py | 649 | 4.25 | 4 | """
A script to show off the creation and use of objects.
Author: Paul Murff
Date: Feb 6 2020
"""
import introcs
import funcs
# Step 1: Create a green RGB object, assign it to variable green, and then print it
green = introcs.RGB(0,255,0,255)
print(green)
# Step 2: Create a 50% transparent red RGB object, assign it to variable red, and print it
red = introcs.RGB(255,0,0,128)
print(red)
# Step 3: Call the function blend on red/green, assign it to variable brown, and print it
brown = funcs.blend(red, green)
print(brown)
# Step 4: Call the function blendUnder on green/red, and then print variable green
funcs.blendUnder(green, red)
print(green)
|
f4f549bce6bac2398f6ad5d6b357fb6e38ab7815 | Wbec/Personal-projects | /Small-Projects/roman.py | 1,117 | 3.75 | 4 | done=False
while done==False:
goodnum=False
while goodnum==False:
try:
inp=input("input a number or type quit:")
if inp=='quit':
done=True
num=0
break
num=int(inp)
except ValueError:
goodnum=False
else:
goodnum=True
result=""
for x in range(3,0,-1):
multi=10**(x)
if multi==1000:
hi,fiv,lo='M','D','C'
if multi==100:
hi,fiv,lo='C','L','X'
if multi==10:
hi,fiv,lo='X','V','I'
if num>=multi:
result+=hi*int(num/multi)
num-=multi*int(num/multi)
if num>=0.9*multi:
result+=lo+hi
num-=0.9*multi
if num>=0.5*multi:
result+=fiv
num-= 0.5*multi
if int(num/(multi/10))==4:
result+=lo+fiv
num-=0.4*multi
if num>=multi/10:
result+=lo*int(num/(multi/10))
num-=(multi/10)*int(num/(multi/10))
print(result)
|
6db4db007552705943d007b56c5212b0655a872a | luana-ribeiro2/mergeSort | /mergeSort.py | 1,178 | 3.65625 | 4 | def mergeSort(listaOrdenar):
if len(listaOrdenar) > 1:
meio = len(listaOrdenar)//2
dire = listaOrdenar[meio:]
esq = listaOrdenar[:meio]
mergeSort(dire)
mergeSort(esq)
i = j = l = 0
while j < len(dire) and i < len(esq):
if esq[i] > dire[j]:
listaOrdenar[l] = dire[j]
j += 1
else:
listaOrdenar[l] = esq[i]
i += 1
l += 1
while j < len(dire):
listaOrdenar[l]=dire[j]
j += 1
l += 1
while i < len(esq):
listaOrdenar[l]=esq[i]
i += 1
l += 1
def splitInt(lista):
lista1 = lista.split(' ')
lista2 = []
for x in lista1:
lista2.append(int(x))
return lista2
t = int(input(''))
for i in range(t):
string = ''
lista = input('')
listaComInteiro = splitInt(lista)
mergeSort(listaComInteiro)
for x in range(0, len(listaComInteiro)):
if x == len(listaComInteiro)-1:
string+=str(listaComInteiro[x])
else:
string+=str(listaComInteiro[x])+' '
print(string) |
2a19e4aad097ae938467fffaae38d3d2451d32ba | dixit5sharma/Learn-Basic-Python | /Ch3_List_SubString.py | 611 | 3.78125 | 4 | a=[0,1,2,3,4,5,6,7,8,9]
b="This is a sentence"
p=a[2:6] # a[start:end] start index is inclusive, end index is exclusive.
q=b[3:15]
print(p) # [2, 3, 4, 5]
print(q) # s is a sente
# Increasing the Jump value
c=a[2:7:2]
d=b[3:15:3]
print(c) # [2, 4, 6]
print(d) # ss n
# Start index not required if want to start from the beginnning.
#Similarly for the end index
c = a[:6]
d = b[3:]
print(c) # [0, 1, 2, 3, 4, 5]
print(d) # s is a sentence
#Reverse Order
c = a[::-1]
d = b[:3:-3]
print(c) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # If Jump is negative, reverse
print(d) # eeeai
|
2f7d1856b353b557bec1ac230af0079d6711a53f | EruDev/Python-Practice | /第2章/2-3.py | 801 | 4.46875 | 4 | # 如何进行反向迭代?
"""
案例:实现一个连续浮点数发生器,根据给定的范围(start,end)和步进值(step)产生
一些连续的浮点数,如迭代FloatRange(3.0, 4.0, 0.2)可生产序列:
正向:3.0->3.2->3.4->3.6->3.8->4.0
反向:4.0->3.8->3.6->3.4->3.2->3.0
"""
class FloatRange:
def __init__(self, start,end, step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
"""实现正向迭代"""
t = self.start
while t <= self.end:
yield t
t += self.step
def __reversed__(self):
"""实现反向迭代"""
t = self.end
while t > self.start:
yield t
t -= self.step
for x in FloatRange(1.0, 3.0, 0.5):
print(x)
for x in reversed(FloatRange(1.0,3.0,0.5)):
print(x)
"""
OUT
1.0
1.5
2.0
2.5
3.0
3.0
2.5
2.0
1.5
""" |
28ee08af5f431bb7196fa4670db3242c8408c422 | colinknebl/MS_SWDV | /SWDV600_Intro_To_Programming/Modules/module2/ball_filler.py | 867 | 4.1875 | 4 | # ball_filler.py
#
# Program to calculate the amount of filler required
# for the user specified amount of balls
import math
def main():
# get the number of balls
numberOfBalls = int(input('How many bowling balls will be manufactured? '))
# get the ball diameter
ballDiameter = float(input('What is the diameter of each ball in inches? '))
# get the core volume
coreVolume = float(input('What is the core volume in inches cubed? '))
# calculate ball radius
ballRadius = ballDiameter / 2
# calculate ball volume
ballVolume = (4/3) * (math.pi * ballRadius ** 3)
# calculate filler volume
fillerVolume = ballVolume - coreVolume
# calculate total volume
totalVolume = fillerVolume * numberOfBalls
# print the results
print('You will need ' + str(totalVolume) + ' inches cubed of filler')
main() |
226afc2cfc5714762629070ab3f2129d25940c59 | franciscocamellon/Francisco_Camello_DR2_TP3 | /questao_02.py | 1,430 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 02 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Python *
* Professor : Thaís do Nascimento Viana *
* Nome do arquivo : questao_02.py *
***************************************************************************/
"""
from validation import Validate
class Questao_02():
""" Docstring """
def __init__(self):
""" Constructor. """
self.title = 'Digite um número inteiro: '
self.list = []
def init_class(self):
""" This function receives the input data from users. """
while len(self.list) <= 5:
_input = Validate().validate_values(self.title, zero=True)
self.list.append(_input)
def process_data(self):
""" This function process the input data from init_class. """
self.init_class()
def print_result(self):
""" This is a printer! It prints. """
print('===' * 25, 'Questão 02'.center(75), '===' * 25, sep='\n')
self.process_data()
print('---' * 25, '{}'.format(self.list),
'---' * 25,
'Aluno: Francisco Camello'.rjust(75), sep="\n")
Questao_02().print_result()
|
76fe0158c173a40783cdb28f8908ec3e6e23a2e1 | henrique17h/Aprendizado_Python | /desafio27.py | 231 | 3.859375 | 4 | velocidade= float(input('Qual a velocidade atual do carro? '))
if velocidade > 80:
print('Você foi multado!')
multa= (velocidade-80) *7
print ('Você excedeu o limite de 80km e pagará {:.2f}R$ de multa'.format(multa)) |
580fc0f8958d3da82ab63f8d79342f629eb4e39a | vozille/Algorithms | /datastructures/Basics/priority_queue.py | 334 | 3.640625 | 4 | import heapq
class priority_queue:
def __init__(self):
self.queue = []
self.index = 0
def push(self,item,priority):
heapq.heappush(self.queue,(-priority,self.index,item))
def pop(self):
return heapq.heappop(self.queue)[-1]
q = priority_queue()
q.push('aa',1)
q.push('fgff',2)
print q.pop()
|
c07dfeb7ced7af023d2feba73c039a652e48bc2f | jtrieudang/CodingDojo-Algorithm | /Morning Algo03.py | 1,836 | 4.375 | 4 | # Introduce concept of inheritance
# Show how objects can interact
# Three classes: Person, Vehicle, Car
# Allow people to buy and sell cars
class Car:
def __init__(self, make, model, year, mileage = 0):
self.make = make
self.model = model
self.year = year
self.mileage = mileage
self.owner = None
def set_owner(self, person):
self.owner = person
class Person:
def __init__(self, name, money = 30000):
self.name = name
self.money = money
self.cars = []
def buy_car(self, price, car):
if self.money < price:
print("You need a loan!")
return False
else:
self.cars.append(car)
car.set_owner(self)
self.money = self.money - price
return self
def sell_car(self, price, car):
if len(self.cars) > 0:
self.cars.remove(car)
car.set_owner(None)
self.money += price
return self
def __str__(self):
my_str = f"Name: {self.name}; money: {self.money}; cars: "
for car in self.cars:
my_str += f"{car.make} - {car.model}, "
return my_str
honda_civic = Car("Honda", "Civic", 2012, 2000)
lambo = Car("Lamborghini", "Gallardo", 2008, 1)
delorean = Car("DMC", "The Delorean", 1982, 200000)
marty = Person("Marty Chavez", 100000)
jorge = Person("Jorge Hernandez", 20000)
bill_gates = Person("Bill Gates", 70000000000)
marty.buy_car(95000, lambo)
if jorge.buy_car(20000, lambo) != False:
marty.sell_car(20000, lambo)
marty.buy_car(10000, honda_civic)
bill_gates.buy_car(95000, lambo)
jorge.sell_car(95000, lambo)
jorge.buy_car(90000, delorean)
print(marty)
print(jorge)
print(bill_gates)
|
dce73a91cfee9a1dd9d33d58a547acc1ae4ef944 | FrancisJen/pythonic | /14pythonic/iterator_140501.py | 1,270 | 4.15625 | 4 | # 14-5: iterator, Generator
# 可迭代对象,iterable: list, tuple, set
# for i in iterable
# 可迭代对象不一定是迭代器:list
# iterator: 是对象也就是class, 也是可迭代对象
# 如何将普通的对象变为可迭代对象呢
# 包含 def __iter__(self) & def __next__(self)
# 迭代器是一次性,遍历之后就不能再此遍历了
# 如何遍历两次呢:
# 遍历之前先copy这个对象
# diff:
# 迭代器是可迭代对象,但是反之不一定
# next方法只能用于迭代器
# 迭代器是一次性,遍历之后就不能再此遍历了,但是list和tuple可以循环遍历
class Book:
pass
class BookCollection:
def __init__(self):
self.data = ['《往事》','《只能》','《回味》']
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration()
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
import copy
books2 = copy.copy(books)
# print(next(books))
# print(next(books))
# print(next(books))
for book in books:
print(book)
for book in books2:
print(book) |
881fe19ccc18fb6878bd011108403afdd4ec3685 | EricksonSiqueira/curso-em-video-python-3 | /Mundo 1 fundamentos basicos/Aula 10 (condições 1)/Desafio 033.py | 692 | 3.90625 | 4 | # Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
co = {'li': '\033[m',
'vd': '\033[32m',
'vm': '\033[31m',
'az': '\033[34m'}
n1 =int(input(f"{co['az']}Digite um número{co['li']}: "))
n2 =int(input(f"{co['az']}Digite um número{co['li']}: "))
n3 =int(input(f"{co['az']}Digite um número{co['li']}: "))
menor = n3
if n1 < n2 and n1 < n3:
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
print(f"{co['vm']}{menor}{co['li']} é o{co['vm']} menor valor{co['li']}.")
maior = n3
if n1 > n2 and n1 > n3:
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
print(f"{co['vd']}{maior}{co['li']} é o{co['vd']} maior valor{co['li']}.")
|
0b1c2a195178a5e74a305bd36880e3c4f4830d08 | knutsvk/sandbox | /euler/p21.py | 387 | 3.6875 | 4 | def sum_proper_divisors(n):
ans = 1
for x in range(2,n):
if n % x == 0:
ans += x
return ans
def is_amicable(a):
b = sum_proper_divisors(a)
return sum_proper_divisors(b) == a and a != b
if __name__ == "__main__":
amicable_sum = 0
for n in range(2,10000):
if is_amicable(n):
amicable_sum += n
print(amicable_sum)
|
02d61c919e1fc2270c7f591ece11cb0eb28ce1f3 | aleksiheikkila/HackerRank_Python_Problems | /Piling_Up.py | 719 | 3.859375 | 4 | '''
HackerRank problem
Domain : Python
Author : Aleksi Heikkilä
Created : Jun 2020
Problem : https://www.hackerrank.com/challenges/piling-up/problem
'''
from collections import deque
num_testcases = int(input())
for case_nbr in range(num_testcases):
num_cubes = int(input())
cubes = deque(int(side) for side in input().split())
size_top = float("Inf")
stackable = "Yes"
# Strategy: pick the largest possible
for i in range(num_cubes):
if cubes[0] >= cubes[-1]:
next_cube = cubes.popleft()
else:
next_cube = cubes.pop()
if next_cube > size_top:
stackable = "No"
break
size_top = next_cube
print(stackable)
|
907d67626367c26c335cd311c788c18290150cc1 | djmar33/python_work | /ex/ex8/8-3.py | 259 | 3.5625 | 4 | #8-3 T_shirt
def make_shirt(size, prompt):
print("即将制作一件大小为 " + size.upper() + ",标语为 " + prompt.title() + " 的T-shirt.")
#位置实参
make_shirt('xl', 'i love you')
#关键字实参
make_shirt(size='xl', prompt='i love you')
|
72ca76ff5d65a7722c42ca53d31ee6c59a8e3528 | 777acauleytosi/python | /fortnite.py | 2,064 | 3.90625 | 4 | #fortnite.py
#the game fortnite
# by Macauley Tosi
def main():
print("welcome to Fortnite Battle royal!")
print("The last one to survive gets the victory royal!")
username = input("whats your username you would like? ")
print(username,"has entered the Battle bus, and you decide where to land")
location = input("whats the name of the location you land? ")
print(username,"has thanked the bus driver")
print("You open your parachute and")
print("you land at", location,"and open a large glowing chest")
print("a assortment of weapons bust out of the chest in front of you")
print("Then a rain of bullets start flying in your direction!")
weapon = input("QUICK! what weapon do you pick up?! ")
print("Nice, I would've picked the", weapon,"too.")
print("the stucture your in falls down, you need to build protection!")
stucture =input("what do you build to protect yourself? ")
print("you build a", stucture,"that should hold them off")
print("you climb to the top of your", stucture,"and the enemy is in your sight")
input("Quick! hit any key and enter to eliminate them!")
print("you give your enemy a few hit markers, until you finally eliminate them!")
print(username,"eliminated User[203] with the", weapon,)
print("VICTORY DANCE")
print("but the battle isn't over...")
kills = input("whats the estimation of eliminations you have in total? ")
print("WOW", kills,"Kills? Thats epic!")
print("get out there into battle! The victory royal is waiting!")
print("as the others slowly die off, there is one more opponent waiting for you.")
print("The last opponent is in your", weapon,"'s ironsight")
input("Hit any key and enter to eliminate him!!")
print("VICTORY ROYAL!! DANCE TIME!!")
print(username,"has eliminated User[935] with the", weapon)
print("With", kills,"kills(+1) you won the game!")
print("GG")
print("Thank you for playing =)")
input("press <Enter> to exit the game")
main()
|
fbf6769c605677264f4e804130e56fb3a170eb35 | indiarosefriswell/TaxiFareModel | /TaxiFareModel/data.py | 1,357 | 3.640625 | 4 | import pandas as pd
from TaxiFareModel.params import BUCKET_NAME, BUCKET_TRAIN_DATA_PATH
def get_data(nrows=10_000):
'''returns a DataFrame with nrows from s3 bucket'''
df = pd.read_csv(f"gs://{BUCKET_NAME}/{BUCKET_TRAIN_DATA_PATH}", nrows=nrows)
return df
def clean_data(df, test=False):
'''
-+-+ Clean the data +-+-
- Drop NaN values
- Ignore entries with the dropoff/pickup longitude/latitude = 0, why?
- 0 < Fare Amount < 100
- 0 <= Passengers < 8
- Filter area of pickup/dropoff
'''
df = df.dropna(how='any', axis='rows')
# What is the point of these lines whenwe filter more specifically below ?
df = df[(df.dropoff_latitude != 0) | (df.dropoff_longitude != 0)]
df = df[(df.pickup_latitude != 0) | (df.pickup_longitude != 0)]
if "fare_amount" in list(df):
df = df[df.fare_amount.between(0, 4000)]
df = df[df.passenger_count < 8]
df = df[df.passenger_count >= 0]
df = df[df["pickup_latitude"].between(left=40, right=42)]
df = df[df["pickup_longitude"].between(left=-74.3, right=-72.9)]
df = df[df["dropoff_latitude"].between(left=40, right=42)]
df = df[df["dropoff_longitude"].between(left=-74, right=-72.9)]
return df
if __name__ == '__main__':
# Return the data frame from the data stored on AWS
df = get_data()
|
2a5346be632931d12295e15e0dcc62522933f198 | endlessmeal/data_science_learning | /probability_theory/central_limit_theorem.py | 2,364 | 3.875 | 4 | import random
from collections import Counter
import matplotlib.pyplot as plt
import math
# независимое испытание Бернулли
# в котором имеется всего два исхода (1 или 0)
def bernoulli_trial(p):
return 1 if random.random() < p else 0
# биномиальное распределение
def binomial(n, p):
return sum(bernoulli_trial(p) for _ in range(n))
# ИФР для нормального распределения, то есть получаем вероятность при случайной величине x
def normal_cdf(x, mu=0, sigma=1):
'''erf это функция для интеграла вероятности'''
return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2
# num_points это число повторов, а n это случайные величины
def make_hist(p, n, num_points):
data = [binomial(n, p) for _ in range(num_points)]
histogram = Counter(data)
print(histogram)
# столбачатая диаграмма, показывающая фактические биномиальные выборки
plt.bar([x for x in histogram.keys()],
[v / num_points for v in histogram.values()],
0.8,
color='0.75')
mu = p * n # мат ожидание
sigma = math.sqrt(n * p * (1 - p)) # стандартное отклонение
# линейный график, показывающий нормальное приближение
xs = range(min(data), max(data) + 1)
ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs]
plt.plot(xs, ys)
plt.title('Биномиальное распределение и его нормальное приближение')
plt.show()
def make_hist_binom(p, n, trials):
data = [binomial(n, p) for _ in range(trials)]
dots = Counter(data)
print(dots)
plt.scatter([x for x in dots.keys()], [v / trials for v in dots.values()])
plt.xlabel('Количество раз выпаданий решки')
plt.ylabel('Вероятность, что решка выпадет столько раз')
plt.show()
print(binomial(1000, 0.5))
# print([binomial(100, 0.5) for _ in range(10)])
# make_hist(0.75, 100, 10000)
# make_hist_binom(0.5, 100, 1000)
|
e57a58fbddecf4582aec87401ea41575b0f5825a | vshypko/coding_challenges | /problems/misc/people.py | 4,446 | 3.625 | 4 | # Name | Favorite Color | Birthday
# Theo | Green | October 10, 2000
# Sherwin | Blue | May 3, 2003
# Daniel | Orange | December 2, 2003
# Sunny | Orange | January 4, 1999
# Aubrianna| Green | August 5, 1999
# 1-1) How would you represent this data?
from datetime import datetime
from dateutil import relativedelta
class Person:
def __init__(self, name, color, birthday):
self.name = name
self.color = color
self.birthday = birthday
class People:
def __init__(self, people):
self.people = people
self.nameHashmap = {}
self.colorHashmap = {}
self.birthdayHashmap = {}
self.ageHashmap = {}
self.daysFromTodayHashmap = {}
self.populateHashmaps()
def populateHashmaps(self):
for person in self.people:
if person.name not in self.nameHashmap.keys():
self.nameHashmap[person.name] = list()
self.nameHashmap[person.name].append(person)
if person.color not in self.colorHashmap.keys():
self.colorHashmap[person.color] = list()
self.colorHashmap[person.color].append(person)
if person.birthday not in self.birthdayHashmap.keys():
self.birthdayHashmap[person.birthday] = list()
self.birthdayHashmap[person.birthday].append(person)
age = self.calculateAge(person)
if age not in self.ageHashmap.keys():
self.ageHashmap[age] = list()
self.ageHashmap[age].append(person)
days = self.calculateDiffDays(person)
if days not in self.daysFromTodayHashmap.keys():
self.daysFromTodayHashmap[days] = list()
self.daysFromTodayHashmap[days].append(person)
print(self.daysFromTodayHashmap)
def calculateAge(self, person):
timeNow = datetime.now()
personDate = datetime.strptime(person.birthday, "%B %d, %Y")
difference = relativedelta.relativedelta(timeNow, personDate)
return difference.years
def calculateDiffDays(self, person):
timeNow = datetime.now()
personDate = datetime.strptime(person.birthday, "%B %d, %Y")
return (timeNow - personDate).days
def findByColor(self, color):
if color in self.colorHashmap.keys():
return self.colorHashmap[color]
def findByAge(self, age):
if age in self.ageHashmap.keys():
return self.ageHashmap[age]
def getSortedByDate(self):
sortedByDate = list()
if self.daysFromTodayHashmap:
sortedKeys = sorted(self.daysFromTodayHashmap.keys())
for key in sortedKeys:
sortedByDate.extend(self.daysFromTodayHashmap[key])
return sortedByDate
def toPrint(name, color, birthday):
person = Person(name, color, birthday)
print("Name: ", person.name)
print("Favorite Color: ", person.color)
print("Birthday: ", person.birthday)
people = list()
def addToList(name, color, birthday):
person = Person(name, color, birthday)
people.append(person)
addToList("Theo", "Green", "October 10, 2000")
addToList("Sherwin", "Blue", "May 3, 2003")
addToList("Daniel", "Orange", "December 2, 2003")
peopleObject = People(people)
# 1-2) write a function that accepts a color and returns the people
# that have that as their favorite color
def getPeopleByFavoriteColor(color):
listOfPeople = peopleObject.findByColor(color)
if listOfPeople:
for person in listOfPeople:
toPrint(person.name, person.color, person.birthday)
getPeopleByFavoriteColor("Green")
getPeopleByFavoriteColor("Blue")
# 1-3) write a function that accepts an age and returns the people that are that age
def getPeopleByAge(age):
agePeople = peopleObject.findByAge(age)
if agePeople:
for person in agePeople:
toPrint(person.name, person.color, person.birthday)
else:
print("No people of that age")
print("18:")
getPeopleByAge(18)
print("16:")
getPeopleByAge(16)
# 1-4) write a function that returns the people, but sorted by birthday
def getPeopleListSortedByBirthday():
daysPeople = peopleObject.getSortedByDate()
if daysPeople:
for person in daysPeople:
toPrint(person.name, person.color, person.birthday)
getPeopleListSortedByBirthday()
|
2d7ad4347ed17ac1389950a6f538580dfba1f012 | HyderYang/python_common | /7.函数/04.py | 776 | 3.734375 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 构造一个可以返回多个值得函数
# 为了返回多个值 函数直接 return 一元组即可
def my_fun():
return 1, 2, 3
a, b, c = my_fun()
print(a)
print(b)
print(c)
# 尽管 my_fun() 看上去返回多个值 实际上是创建了一个元祖然后返回的 这个语法看上去比较奇怪
# 实际上我们使用的是逗号来生成一个元祖 而不是括号
a = (1, 2)
print(a)
b = 1, 2
print(b)
# 当我们调用返回一个元祖的函数的时候 通常我们会将结果赋值给多个变量 就像上面的那样 其实就是
# 我们所说的元祖解包 返回结果也可以赋值给单个变量 这时候这个变量值就是函数返回的那个元祖本身了
x = my_fun()
print(x)
|
f4aa3433734e3b5b502259a590f0f6b165649bae | sky-dream/LeetCodeProblemsStudy | /[1143][Medium][Longest_Common_Subsequence]/Longest_Common_Subsequence.py | 769 | 3.609375 | 4 | # leetcode time cost : 64 ms
# leetcode memory cost : 13.8 MB
# solution 1, DP
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
last_memory=[0]*(len(text1)+1)
memory=[0]*(len(text1)+1)
for i,t2 in enumerate(text2):
memory=[0]*(len(text1)+1)
for j,t1 in enumerate(text1):
memory[j+1]=max(memory[j],last_memory[j+1],last_memory[j]+1 if t1==t2 else 0 )
last_memory=memory
# print(memory)
return memory[-1]
def main():
text1,text2 = "abcde", "ace" # expect is 3
obj = Solution()
result = obj.longestCommonSubsequence(text1,text2)
print("return result is :",result)
if __name__ =='__main__':
main() |
d91a2646808ceaaaff03925b2249d3697edbf8c8 | Hidenver2016/Leetcode | /Python3.6/369-Py3-M-Plus One Linked List.py | 3,624 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 15 22:51:53 2019
@author: hjiang
"""
"""
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example :
Input: [1,2,3]
Output: [1,2,4]
https://www.cnblogs.com/grandyang/p/5626389.html
这道题给了我们一个链表,用来模拟一个三位数,表头是高位,现在让我们进行加1运算,这道题的难点在于链表无法通过坐标来访问元素,
只能通过遍历的方式进行,而这题刚好让我们从链尾开始操作,从后往前,遇到进位也要正确的处理,最后还有可能要在开头补上一位。
那么我们反过来想,如果链尾是高位,那么进行加1运算就方便多了,直接就可以边遍历边进行运算处理,那么我们可以做的就是先把链表翻转一下,
然后现在就是链尾是高位了,我们进行加1处理运算结束后,再把链表翻转回来即可,
"""
#class Solution(object):
# def plusOne(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
# def reverseList(head):#尤其注意这个reverse的写法
## dummy = ListNode(0)
## curr = head
## while curr:
## dummy.next, curr.next, curr = curr, dummy.next, curr.next
## return dummy.next
# cur, pre = head, None
# while cur:
# cur.next, pre, cur = pre, cur, cur.next
# return pre
#
# rev_head = reverseList(head)
# curr, carry = rev_head, 1
# while curr and carry:#这里要修改一下
## curr.val += carry
## carry = curr.val // 10
## curr.val %= 10
# carry, curr.val = (curr.val + carry)//10, (curr.val + carry)%10
# if carry and curr.next is None:
# curr.next = ListNode(0)
# curr = curr.next
#
# return reverseList(rev_head)
# Time: O(n)
# Space: O(1)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def reverseList(head):#尤其注意这个reverse的写法
cur, pre = head, None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
rev_head = reverseList(head)
curr, carry = rev_head, 1
while curr and carry:#这里要修改一下
carry, curr.val = (curr.val + carry)//10, (curr.val + carry)%10
if carry and curr.next is None:
curr.next = ListNode(0)#下次加上进位即可,就是1
curr = curr.next
return reverseList(rev_head)
if __name__ == "__main__":
head = ListNode(9)
# head.next = ListNode(9)
# head.next.next = ListNode(3)
# head.next.next.next = ListNode(4)
# head.next.next.next.next = ListNode(5)
print (Solution().plusOne(head).next.val)
"""
这里需要注意如果
a = Solution().plusOne(head)
print(a.val)
print(a.next.val) 会报错,因为此时a已经连加等于2,因此没有next
可以按照上面的方法直接看
"""
|
cd314e584e7ba509064647484dccca86c03161e5 | arafe102/Arafe102 | /Main.py | 4,622 | 3.859375 | 4 | import sqlite3
from Student import Student
conn = sqlite3.connect('StudentDB.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS Student(StudentId INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar(25),"
"LastName varchar(25), GPA NUMERIC, Major varchar(20), FacultyAdvisor varchar(25));")
'''stu = Student ('Rene', 'FooBar', 'safsfsf', 'name', '4.0','123')
c.execute("INSERT INTO Student ('FirstName', 'LastName', 'Major', 'FacultyAdvisor', 'GPA', 'StudentID')"
"VALUES (?,?,?,?,?,?)", stu.getStudentTuple())
stu1 = Student ('Omar', 'Arafeh', 'SE', 'Linstead', '1.0','1123')
c.execute("INSERT INTO Student ('FirstName', 'LastName', 'Major', 'FacultyAdvisor', 'GPA', 'StudentID')"
"VALUES (?,?,?,?,?,?)", stu1.getStudentTuple())
stu2 = Student ('Jeff', 'Lingard', 'CS', 'Linstead', '2.0','2123')
c.execute("INSERT INTO Student ('FirstName', 'LastName', 'Major', 'FacultyAdvisor', 'GPA', 'StudentID')"
"VALUES (?,?,?,?,?,?)", stu2.getStudentTuple())
stu3 = Student ('John', 'Clementine', 'Comm', 'Linstead', '3.0','3123')
c.execute("INSERT INTO Student ('FirstName', 'LastName', 'Major', 'FacultyAdvisor', 'GPA', 'StudentID')"
"VALUES (?,?,?,?,?,?)", stu3.getStudentTuple())'''
conn.commit()
repeatThis = True
while (repeatThis):
print ("record created: ")
print("1) Display all: ")
print("2) Create new: ")
print("3) Update student: ")
print("4) delete student: ")
print("5) Search for a student: ")
print("6) Exit: ")
print ("Enter a choice")
usersChoice = int(input("#: "))
if (usersChoice == 1):
c.execute("SELECT * FROM Student")
rows = c.fetchall()
for row in rows:
print(row)
elif (usersChoice == 2):
inputCheck = True
newFirst = raw_input("Please enter the First Name of the student: ")
newLast = raw_input("Enter the Last name now: ")
while (inputCheck):
try:
gpa = float(input("Enter GPA: "))
except:
print("Enter Valid GPA: ")
else:
inputCheck = False
major = raw_input("Enter Major: ")
advisor = raw_input("Enter Faculty Advisor: ")
# inputCheckId = True
# while (inputCheckId):
# try:
# studentid = int(input("enter student ID"))
# except:
# print("please enter valid ID")
# else:
# inputCheckId = False
stu = Student(newFirst, newLast, gpa, major, advisor)
c.execute("INSERT INTO Student('FirstName', 'LastName', 'GPA', 'Major', 'FacultyAdvisor')"
"VALUES (?,?,?,?,?)", stu.getStudentTuple())
conn.commit()
elif (usersChoice == 3):
stuID = int(input("Updated student Id: "))
major = str(raw_input("Enter Major Change: "))
advisor = raw_input ("Enter new Advisor")
c.execute("UPDATE Student SET Major = ? WHERE StudentId = ?", (major, stuID))
c.execute("UPDATE Student SET FacultyAdvisor = ? WHERE StudentId = ?", (advisor, stuID))
elif (usersChoice ==4):
stuID = input("Please enter the student ID: ")
c.execute ("delete from Student where StudentId = (?)", (stuID,))
conn.commit()
print("You have deleted them. ")
elif (usersChoice == 5):
print("Please Check Code; was unable to get this to work")
'''search = input ("Please enter GPA, Major, or Advisor: ")
input = raw_input()
if input.upper() == "GPA":
print("What GPA would you like to search?: ")
number = raw_input()
c.execute("SELECT * FROM Student WHERE GPA = ?", (number,))
result = c.fetchall()
for x in result:
print(x)
break
elif input.upper() == "Major":
print( "What is the major?")
major = raw_input()
c.execute("SELECT * FROM Student WHERE Major = ?", (majorinput,))
result = c.fetchall()
for maj in result:
print(maj)
break
elif input.upper() == "Advisor":
print("What advisor are you searching for?: ")
advisor = raw_input()
c.execute("SELECT * FROM Student WHERE FacultyAdvisor = ?", (facultyinput,))
result = c.fetchall()
for fac in result:
print(fac)
break
else:
print("Bad Input. Please type either GPA, Major, or Faculty")'''
elif (usersChoice == 6):
repeatThis= False
|
38e4a094c2c02cc09017a854bcef5c3f2e3eef2d | Abhyudaya100/my-projects-2 | /sumofcubeoffirstNnumbers.py | 184 | 3.65625 | 4 | '''
N = int(input())
total = 0
for n in range(1,N + 1,1):
total += n*n*n
print(total)
'''
print(4194303)
25 8.33
30 10
28.33 9.44
33.33 11.11 |
b1bac867cba63f7510e1a68216104943f250e791 | LucasMayer02/UFCG_Exercicios | /atividades/e_dobro/questao.py | 148 | 3.703125 | 4 | # 2021-03-22, lucas.mayer.almeida@ccc.ufcg.edu.br
#
num1 = int(input())
num2 = int(input())
if num1 * 2 == num2 or num2 * 2 == num1 :
print("SIM")
else:
print("NAO")
|
bc998bbd6fc02f13ac4df8c44366e3be042379cc | Hornet004/alx-higher_level_programming | /0x03-python-data_structures/0-print_list_integer.py | 113 | 4 | 4 | #!/usr/bin/python3
def print_list_integer(my_list=[]):
for int in my_list:
print("{:d}".format(int))
|
fb691c0faff3b74a9eeb1113c3aa0f1d7de7c570 | Developer122018/learn-python-code-practice-and-tdd | /Day4 _1.py | 448 | 4.46875 | 4 | # # Write a Python program to count the number of characters (character frequency) in a string
#
# def count_num_of_characters_in_a_string(p_string=''):
# #return len(p_string)
# #way 2
# num_count = 0
# for i in p_string:
# num_count += 1
# return num_count
#
#
# if __name__ == '__main__':
# len_of_str = count_num_of_characters_in_a_string(input('what is your text?'))
# print(len_of_str)
print("abc".split()) |
2efade694bec92640047693191d2f6a2c8acf07a | EdiTV2021/Python_2021 | /funcion.py | 549 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 19:41:40 2021
@author: Edison
"""
# print("Ingrese el siguiente valor: ")
# a=input()
# print("Ingrese el siguiente valor: ")
# b=input()
# print("Ingrese el siguiente valor: ")
# c=input()
# print("Ingrese el siguiente valor: ")
# d=input()
#funcion es un bloque de codigo que soporta
#diferentes cambios
def mensaje():
print(" Por favor ingrese el valor: ")
mensaje()
a=input()
mensaje()
b=input()
mensaje()
c=input()
mensaje()
d=input()
mensaje()
e=input() |
b9d06ff2710b1d4fd95bf2e11572d848779ef34b | Sushmi-pal/pythonassignment | /Qn39.py | 67 | 3.515625 | 4 | tup=13,14,15
a,b,c=tup
print('The sum of elements of tuple',a+b+c)
|
027b5974c2d69a349c75787a8f5ce6a157008b16 | VladBaryliuk/my_start_tasks | /new/src/25.01.2020/while task 4.py | 148 | 3.515625 | 4 | a = 0
sstr = 0
while True:
c = float (input())
sstr += 1
if c > 22.0:
break
elif sstr == 7:
a = sstr // 7
print (a)
|
a81aca1e56ec5a5cac17775316090631358666c3 | faisal-git/Data_Structure | /Graphs/print_cycle.py | 1,667 | 3.828125 | 4 | # color algorithm can be used
# no self loop and parallel edges
# state 0: not visited ,state 1: currently in visiting loop ,state 2: completely visited
import collections
def dfs(v,visited,g,parent,cycle):
visited[v]=1
print(v)
for n in g[v]:
if visited[n]==0:
parent[n]=v
dfs(n,visited,g,parent,cycle)
elif visited[n]==2:
continue
elif parent[v]!=n: # means there exist a back edge
# here we can just back track to find the cycle formed when started form v and goes upto n
# and used marker to color all node of cycle with a color
# every cycle would have its unique color
# impart unique color we can have a golbal var color: whose value should is inceresed when we found and a cycle
print((v,n))
cycle.append((v,n))
visited[v]=2
def print_cycle(start,end,parent):
temp=[]
while start!=end:
temp.append(start)
start=parent[start]
print("cycle is : ",temp+[start])
def build_graph():
g=collections.defaultdict(list)
vertex=int(input("Enter the number of vertex.: "))
e=int(int(input(" Enter the number of edges: ")))
for _ in range(e):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
visited=[0]*vertex
parent=[-1]*vertex
cycle=[]
for v in range(vertex):
if not visited[v]:
dfs(v,visited,g,parent,cycle)
print(parent)
while cycle:
s,e=cycle.pop()
print_cycle(s,e,parent)
build_graph() |
6a7428cac9b447bbaa86b5725fb98b2868454601 | BruceYi119/python | /io2.py | 2,862 | 3.59375 | 4 | # def f1(n):
# return n * 10
# print(f1(10))
# 람다함수 : 메모리절약, 가독성 향상, 코드 간결
# b = lambda n:n * 10
#
# print(b(22))
#
# def f2(x, y, f):
# print(x * y * f(x + y))
#
# f2(10, 100, lambda x:x + 1)
# a = [1,2,3,5,6]
# result = [];
#
# def f(list):
# result = [(v * 3) for v in list]
# print(result)
#
# f(a)
# map(함수명,반복가능객체) : 매개변수로 함수와 반복가능한객체 입력
# def f4(x):
# return x * 3
#
# print(f4(7))
# print(f4([1,2,3]))
# print(map(f4, [1,2,3]))
# print(list(map(f4, [1,2,3])))
# print(list(map(lambda n, z:n * 3 + z, [1,2,3], [3,2,1])))
# os모듈:디렉토리, 파일등의 os자원 제어
import os
# print(os.getcwd())
# print(os.listdir('d:\\'))
# print(os.listdir('C:\Program Files'))
# print(os.path.join('..', 'test1'))
# print(os.listdir(os.path.join('img')))
# glob모듈
import glob
# print(glob.glob('*.py'))
# print(os.path.join('..', 'img', '*.jpg'))
#
# print(os.path.dirname(os.path.join('d:','study','pj1','data','tt.txt')))
# print(os.path.basename(os.path.join('d:','study','pj1','data','tt.txt')))
# with open(os.path.join('data','tt.txt'), 'r', encoding='utf-8') as f:
# while True:
# l = f.readline()
# if not l:
# break
# print(l, end = '')
# for dir in glob.glob(os.path.join('data', '*')):
# with open(dir, 'r', encoding='utf-8') as f:
# print(f.readlines())
import cchardet
# for dir in glob.glob(os.path.join('data', '*')):
# encoding = None;
#
# with open(dir, 'rb') as f:
# encoding = cchardet.detect(f.read())['encoding']
# with open (dir, 'r', encoding=encoding) as ff:
# print(ff.readlines())
# with open(os.path.join('data','data3.csv'), 'r', encoding='utf-8') as f:
# for v in f:
# print(v.replace('\n',''), end='')
# text = [];
# for dir in glob.glob(os.path.join('data', '*')):
# encoding = None;
#
# with open(dir, 'rb') as f:
# encoding = cchardet.detect(f.read())['encoding']
# with open (dir, 'r', encoding=encoding) as ff:
# text.append(ff.read().replace('\n',''))
#
# with open(os.path.join('data','result.txt'), 'w', encoding='utf-8') as f:
# f.write(','.join(text).replace(',',''))
def readFile(dir, text, encoding):
with open(dir, 'r', encoding=encoding) as f:
text.append(f.read().replace('\n', ''))
def writeFile(text):
with open(os.path.join('data', 'result.txt'), 'w', encoding='utf-8') as f:
f.write(','.join(text).replace(',', ''))
def main():
text = []
for dir in glob.glob(os.path.join('data', '*')):
encoding = None;
with open(dir, 'rb') as f:
encoding = cchardet.detect(f.read())['encoding']
readFile(dir, text, encoding)
writeFile(text)
if __name__ == '__main__':
main() |
d35cfe84caeb444b52be33520e8a6b4a9608447b | Blossomyyh/leetcode | /VMware/TaskScheduler.py | 1,604 | 3.8125 | 4 | """
621. Task Scheduler
# asynchronous processing
"""
## RC ##
## APPROACH : HASHMAP ##
## LOGIC : TAKE THE MAXIMUM FREQUENCY ELEMENT AND MAKE THOSE MANY NUMBER OF SLOTS ##
## Slot size = (n+1) if n= 2 => slotsize = 3 Example: {A:5, B:1} => ABxAxxAxxAxxAxx => indices of A = 0,2 and middle there should be n elements, so slot size should be n+1
## Ex: {A:6,B:4,C:2} n = 2
## final o/p will be
## slot size / cycle size = 3
## Number of rows = number of A's (most freq element)
# [
# [A, B, C],
# [A, B, C],
# [A, B, idle],
# [A, B, idle],
# [A, idle, idle],
# [A - - ],
# ]
#
# so from above total time intervals = (max_freq_element - 1) * (n + 1) + (all elements with max freq)
# ans = rows_except_last * columns + last_row
## but consider {A:5, B:1, C:1, D:1, E:1, F:1, G:1, H:1, I:1, J:1, K:1, L:1} n = 1
## total time intervals by above formula will be 4 * 2 + 1 = 9, which is less than number of elements, which is not possible. so we have to return max(ans, number of tasks)
## TIME COMPLEXITY : O(N) ##
## SPACE COMPLEXITY : O(1) ##
"""
A-3, B-3, C-3, D-3
ABCDABCDABCD with n = 2!
only need to calculate last BCD
"""
from collections import Counter
def leastInterval(self, tasks:[str], n: int) -> int:
count = Counter(tasks)
maxnum = max(count.values())
if n ==0:
return len(tasks)
intervals = (n+1)*(maxnum-1)
freq = list(count.values())
addtional = 0
for i in freq:
if i == maxnum:
addtional +=1
ans = intervals + addtional
return max(ans, len(tasks))
|
cc72fa3082be06314b5de1ae8ce7ec9d682a3e6d | Its-Haze/pvt21_programmering | /quiz2/quiz.py | 1,417 | 3.609375 | 4 | from quiz2.api import QuizAPI, BaseAPI
from random import randint
QUIZ_URL = "https://bjornkjellgren.se/quiz/v2/questions"
class Player:
def ask_num(self, n):
raise NotImplementedError
class ConsolePlayer(Player):
def ask_num(self, n):
while True:
res = int(input(">"))
if 1 <= res <= n:
return res
class DummyPlayer(Player):
def ask_num(self, n):
return randint(1, n)
class QuizGame:
quiz_api: BaseAPI
player: Player
def __init__(self, quiz_api: BaseAPI, player: Player):
self.quiz_api = quiz_api
self.player = player
def run(self):
for question in self.quiz_api.get_questions():
print(question.prompt)
print(f"{question.percent_correct()} användare svarade rätt på frågan")
for i, answer in enumerate(question.answers, start=1):
print(f"[{i}] {answer}")
user_answer = self.player.ask_num(question.num_answers)
print(f"User answered {user_answer}")
# Koden nedan skapar en lista med textsträngen answer från
# alla svar på frågan question som är rätt
# print([a.answer for a in question.answers if a.correct])
print("-" * 80)
if __name__ == '__main__':
q_api = QuizAPI(QUIZ_URL)
p = DummyPlayer()
quiz = QuizGame(q_api, p)
quiz.run()
|
93e233a5e16fc877fb9ab6efcab46296986638e1 | superyang713/Hacker_Rank | /nested_list.py | 410 | 3.8125 | 4 | # dict could be used, but the point of this challenge is to use nested list.
def main():
n = int(input()) # useless but required by the challenge
data = []
for _ in range(n):
name = input()
score = float(input())
record = [name, score]
data.append(record)
data = sorted(data, key=lambda x: x[1])
print(data[-1])
if __name__ == '__main__':
main()
|
0cd23944a5e7ce288380e3a05a074cccf5de499b | Harshit090/Python-Problems | /functions/ans9.py | 153 | 3.59375 | 4 | def add(a):
def add1(b):
c = 1 + b
return c
x = add1(a)
return x
a = int(input("Enter a no\n"))
q = add(a)
print(q)
|
82090cac0408c4b069c23a04214276c9d9407658 | KivenCkl/DataStructures_Python | /Common_Algorithms/permutations.py | 346 | 3.53125 | 4 | """
全排列算法
"""
def permute(arr):
"""
时间复杂度: O(n!)
"""
if len(arr) == 0:
return []
if len(arr) == 1:
yield arr
for i in range(len(arr)):
x = arr[i]
xs = arr[:i] + arr[i + 1:]
for j in permute(xs):
yield [x] + j
print(list(permute(list(range(4)))))
|
0ccd95d779aa34894187db92f0e47df09fc3ee18 | Harishkumar18/data_structures | /cracking_the_coding_interview/Arrays_and_Strings/zero_matrix.py | 1,132 | 4.1875 | 4 | """
Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
"""
def set_zeros(mat):
m, n = len(mat), len(mat[0])
if m < 1:
return mat
if n < 1:
return mat
rowzeroflag, colzeroflag = False, False
for j in range(m):
if mat[0][j] == 0:
rowzeroflag = True
break
for i in range(n):
if mat[i][0] == 0:
colzeroflag = True
break
for i in range(1, m):
for j in range(1, n):
if mat[i][j] == 0:
mat[0][j] = 0
mat[i][0] = 0
for i in range(1, m):
for j in range(1, n):
if mat[i][0] == 0 or mat[0][j] == 0:
mat[i][j] = 0
if rowzeroflag:
for j in range(n):
mat[0][j] = 0
if colzeroflag:
for i in range(m):
mat[i][0] = 0
return mat
print(set_zeros([[1,1,1],[1,0,1],[1,1,1]]))
print(set_zeros([[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]))
|
e6a115fd820e2b3cbf511bccce6f5a25eb722866 | myamullaciencia/Bayesian-statistics | /_build/jupyter_execute/12_binomial_soln.py | 14,528 | 3.84375 | 4 | # Bite Size Bayes
Copyright 2020 Allen B. Downey
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## The Euro problem
In [a previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/07_euro.ipynb) I presented a problem from David MacKay's book, [*Information Theory, Inference, and Learning Algorithms*](http://www.inference.org.uk/mackay/itila/p0.html):
> A statistical statement appeared in The Guardian on
Friday January 4, 2002:
>
> >"When spun on edge 250 times, a Belgian one-euro coin came
up heads 140 times and tails 110. ‘It looks very suspicious
to me’, said Barry Blight, a statistics lecturer at the London
School of Economics. ‘If the coin were unbiased the chance of
getting a result as extreme as that would be less than 7%’."
>
> But [asks MacKay] do these data give evidence that the coin is biased rather than fair?
To answer this question, we made these modeling decisions:
* If you spin a coin on edge, there is some probability, $x$, that it will land heads up.
* The value of $x$ varies from one coin to the next, depending on how the coin is balanced and other factors.
We started with a uniform prior distribution for $x$, then updated it 250 times, once for each spin of the coin. Then we used the posterior distribution to compute the MAP, posterior mean, and a credible interval.
But we never really answered MacKay's question.
In this notebook, I introduce the binomial distribution and we will use it to solve the Euro problem more efficiently. Then we'll get back to MacKay's question and see if we can find a more satisfying answer.
## Binomial distribution
Suppose I tell you that a coin is "fair", that is, the probability of heads is 50%. If you spin it twice, there are four outcomes: `HH`, `HT`, `TH`, and `TT`.
All four outcomes have the same probability, 25%. If we add up the total number of heads, it is either 0, 1, or 2. The probability of 0 and 2 is 25%, and the probability of 1 is 50%.
More generally, suppose the probability of heads is `p` and we spin the coin `n` times. What is the probability that we get a total of `k` heads?
The answer is given by the binomial distribution:
$P(k; n, p) = \binom{n}{k} p^k (1-p)^{n-k}$
where $\binom{n}{k}$ is the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient), usually pronounced "n choose k".
We can compute this expression ourselves, but we can also use the SciPy function `binom.pmf`:
from scipy.stats import binom
n = 2
p = 0.5
ks = np.arange(n+1)
a = binom.pmf(ks, n, p)
a
If we put this result in a Series, the result is the distribution of `k` for the given values of `n` and `p`.
pmf_k = pd.Series(a, index=ks)
pmf_k
The following function computes the binomial distribution for given values of `n` and `p`:
def make_binomial(n, p):
"""Make a binomial PMF.
n: number of spins
p: probability of heads
returns: Series representing a PMF
"""
ks = np.arange(n+1)
a = binom.pmf(ks, n, p)
pmf_k = pd.Series(a, index=ks)
return pmf_k
And here's what it looks like with `n=250` and `p=0.5`:
pmf_k = make_binomial(n=250, p=0.5)
pmf_k.plot()
plt.xlabel('Number of heads (k)')
plt.ylabel('Probability')
plt.title('Binomial distribution');
The most likely value in this distribution is 125:
pmf_k.idxmax()
But even though it is the most likely value, the probability that we get exactly 125 heads is only about 5%.
pmf_k[125]
In MacKay's example, we got 140 heads, which is less likely than 125:
pmf_k[140]
In the article MacKay quotes, the statistician says, ‘If the coin were unbiased the chance of getting a result as extreme as that would be less than 7%’.
We can use the binomial distribution to check his math. The following function takes a PMF and computes the total probability of values greater than or equal to `threshold`.
def prob_ge(pmf, threshold):
"""Probability of values greater than a threshold.
pmf: Series representing a PMF
threshold: value to compare to
returns: probability
"""
ge = (pmf.index >= threshold)
total = pmf[ge].sum()
return total
Here's the probability of getting 140 heads or more:
prob_ge(pmf_k, 140)
It's about 3.3%, which is less than 7%. The reason is that the statistician includes all values "as extreme as" 140, which includes values less than or equal to 110, because 140 exceeds the expected value by 15 and 110 falls short by 15.
The probability of values less than or equal to 110 is also 3.3%,
so the total probability of values "as extreme" as 140 is about 7%.
The point of this calculation is that these extreme values are unlikely if the coin is fair.
That's interesting, but it doesn't answer MacKay's question. Let's see if we can.
## Estimating x
As promised, we can use the binomial distribution to solve the Euro problem more efficiently. Let's start again with a uniform prior:
xs = np.arange(101) / 100
uniform = pd.Series(1, index=xs)
uniform /= uniform.sum()
We can use `binom.pmf` to compute the likelihood of the data for each possible value of $x$.
k = 140
n = 250
xs = uniform.index
likelihood = binom.pmf(k, n, p=xs)
Now we can do the Bayesian update in the usual way, multiplying the priors and likelihoods,
posterior = uniform * likelihood
Computing the total probability of the data,
total = posterior.sum()
total
And normalizing the posterior,
posterior /= total
Here's what it looks like.
posterior.plot(label='Uniform')
plt.xlabel('Probability of heads (x)')
plt.ylabel('Probability')
plt.title('Posterior distribution, uniform prior')
plt.legend()
**Exercise:** Based on what we know about coins in the real world, it doesn't seem like every value of $x$ is equally likely. I would expect values near 50% to be more likely and values near the extremes to be less likely.
In Notebook 7, we used a triangle prior to represent this belief about the distribution of $x$. The following code makes a PMF that represents a triangle prior.
ramp_up = np.arange(50)
ramp_down = np.arange(50, -1, -1)
a = np.append(ramp_up, ramp_down)
triangle = pd.Series(a, index=xs)
triangle /= triangle.sum()
Update this prior with the likelihoods we just computed and plot the results.
# Solution
posterior2 = triangle * likelihood
total2 = posterior2.sum()
total2
# Solution
posterior2 /= total2
# Solution
posterior.plot(label='Uniform')
posterior2.plot(label='Triangle')
plt.xlabel('Probability of heads (x)')
plt.ylabel('Probability')
plt.title('Posterior distribution, uniform prior')
plt.legend();
## Evidence
Finally, let's get back to MacKay's question: do these data give evidence that the coin is biased rather than fair?
I'll use a Bayes table to answer this question, so here's the function that makes one:
def make_bayes_table(hypos, prior, likelihood):
"""Make a Bayes table.
hypos: sequence of hypotheses
prior: prior probabilities
likelihood: sequence of likelihoods
returns: DataFrame
"""
table = pd.DataFrame(index=hypos)
table['prior'] = prior
table['likelihood'] = likelihood
table['unnorm'] = table['prior'] * table['likelihood']
prob_data = table['unnorm'].sum()
table['posterior'] = table['unnorm'] / prob_data
return table
Recall that data, $D$, is considered evidence in favor of a hypothesis, `H`, if the posterior probability is greater than the prior, that is, if
$P(H|D) > P(H)$
For this example, I'll call the hypotheses `fair` and `biased`:
hypos = ['fair', 'biased']
And just to get started, I'll assume that the prior probabilities are 50/50.
prior = [0.5, 0.5]
Now we have to compute the probability of the data under each hypothesis.
If the coin is fair, the probability of heads is 50%, and we can compute the probability of the data (140 heads out of 250 spins) using the binomial distribution:
k = 140
n = 250
like_fair = binom.pmf(k, n, p=0.5)
like_fair
So that's the probability of the data, given that the coin is fair.
But if the coin is biased, what's the probability of the data? Well, that depends on what "biased" means.
If we know ahead of time that "biased" means the probability of heads is 56%, we can use the binomial distribution again:
like_biased = binom.pmf(k, n, p=0.56)
like_biased
Now we can put the likelihoods in the Bayes table:
likes = [like_fair, like_biased]
make_bayes_table(hypos, prior, likes)
The posterior probability of `biased` is about 86%, so the data is evidence that the coin is biased, at least for this definition of "biased".
But we used the data to define the hypothesis, which seems like cheating. To be fair, we should define "biased" before we see the data.
## Uniformly distributed bias
Suppose "biased" means that the probability of heads is anything except 50%, and all other values are equally likely.
We can represent that definition by making a uniform distribution and removing 50%.
biased_uniform = uniform.copy()
biased_uniform[50] = 0
biased_uniform /= biased_uniform.sum()
Now, to compute the probability of the data under this hypothesis, we compute the probability of the data for each value of $x$.
xs = biased_uniform.index
likelihood = binom.pmf(k, n, xs)
And then compute the total probability in the usual way:
like_uniform = np.sum(biased_uniform * likelihood)
like_uniform
So that's the probability of the data under the "biased uniform" hypothesis.
Now we make a Bayes table that compares the hypotheses `fair` and `biased uniform`:
hypos = ['fair', 'biased uniform']
likes = [like_fair, like_uniform]
make_bayes_table(hypos, prior, likes)
Using this definition of `biased`, the posterior is less than the prior, so the data are evidence that the coin is *fair*.
In this example, the data might support the fair hypothesis or the biased hypothesis, depending on the definition of "biased".
**Exercise:** Suppose "biased" doesn't mean every value of $x$ is equally likely. Maybe values near 50% are more likely and values near the extremes are less likely. In the previous exercise we created a PMF that represents a triangle-shaped distribution.
We can use it to represent an alternative definition of "biased":
biased_triangle = triangle.copy()
biased_triangle[50] = 0
biased_triangle /= biased_triangle.sum()
Compute the total probability of the data under this definition of "biased" and use a Bayes table to compare it with the fair hypothesis.
Is the data evidence that the coin is biased?
# Solution
like_triangle = np.sum(biased_triangle * likelihood)
like_triangle
# Solution
hypos = ['fair', 'biased triangle']
likes = [like_fair, like_triangle]
make_bayes_table(hypos, prior, likes)
# Solution
# For this definition of "biased",
# the data are slightly in favor of the fair hypothesis.
## Bayes factor
In the previous section, we used a Bayes table to see whether the data are in favor of the fair or biased hypothesis.
I assumed that the prior probabilities were 50/50, but that was an arbitrary choice.
And it was unnecessary, because we don't really need a Bayes table to say whether the data favor one hypothesis or another: we can just look at the likelihoods.
Under the first definition of biased, `x=0.56`, the likelihood of the biased hypothesis is higher:
like_fair, like_biased
Under the biased uniform definition, the likelihood of the fair hypothesis is higher.
like_fair, like_uniform
The ratio of these likelihoods tells us which hypothesis the data support.
If the ratio is less than 1, the data support the second hypothesis:
like_fair / like_biased
If the ratio is greater than 1, the data support the first hypothesis:
like_fair / like_uniform
This likelihood ratio is called a [Bayes factor](https://en.wikipedia.org/wiki/Bayes_factor); it provides a concise way to present the strength of a dataset as evidence for or against a hypothesis.
## Summary
In this notebook I introduced the binomial disrtribution and used it to solve the Euro problem more efficiently.
Then we used the results to (finally) answer the original version of the Euro problem, considering whether the data support the hypothesis that the coin is fair or biased. We found that the answer depends on how we define "biased". And we summarized the results using a Bayes factor, which quantifies the strength of the evidence.
[In the next notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/13_price.ipynb) we'll start on a new problem based on the television game show *The Price Is Right*.
## Exercises
**Exercise:** In preparation for an alien invasion, the Earth Defense League has been working on new missiles to shoot down space invaders. Of course, some missile designs are better than others; let's assume that each design has some probability of hitting an alien ship, `x`.
Based on previous tests, the distribution of `x` in the population of designs is roughly uniform between 10% and 40%.
Now suppose the new ultra-secret Alien Blaster 9000 is being tested. In a press conference, a Defense League general reports that the new design has been tested twice, taking two shots during each test. The results of the test are confidential, so the general won't say how many targets were hit, but they report: "The same number of targets were hit in the two tests, so we have reason to think this new design is consistent."
Is this data good or bad; that is, does it increase or decrease your estimate of `x` for the Alien Blaster 9000?
Plot the prior and posterior distributions, and use the following function to compute the prior and posterior means.
def pmf_mean(pmf):
"""Compute the mean of a PMF.
pmf: Series representing a PMF
return: float
"""
return np.sum(pmf.index * pmf)
# Solution
xs = np.linspace(0.1, 0.4)
prior = pd.Series(1, index=xs)
prior /= prior.sum()
# Solution
likelihood = xs**2 + (1-xs)**2
# Solution
posterior = prior * likelihood
posterior /= posterior.sum()
# Solution
prior.plot(color='gray', label='prior')
posterior.plot(label='posterior')
plt.xlabel('Probability of success (x)')
plt.ylabel('Probability')
plt.ylim(0, 0.027)
plt.title('Distribution of before and after testing')
plt.legend();
# Solution
pmf_mean(prior), pmf_mean(posterior)
# With this prior, being "consistent" is more likely
# to mean "consistently bad".
|
8289b99c6a2b73c53219c2a6cd0e8eee04e1b9fe | aidanohora/Python-Practicals | /p7p2.py | 247 | 4.09375 | 4 | year = int(input("Enter a year: "))
if year%4 != 0:
print("This is a common year.")
elif year%100 != 0:
print("This is a leap year.")
elif year%400 != 0:
print("This is a common year.")
else:
print("This is a leap year.")
|
8287bb193b9bdcfef42b341c6a7f839be668ce98 | bethanymbaker/arch | /scripts/tetris.py | 2,547 | 4.09375 | 4 | import numpy as np
from time import sleep
class Tetris:
def __init__(self, num_rows, num_cols):
self.num_rows = num_rows
self.num_cols = num_cols
self.board = [[-1] * num_cols for _ in range(num_rows)]
self.is_complete = False
def display_board(self):
for row in range(self.num_rows):
print(self.board[row])
def add_piece(self, piece='square'):
self.is_complete = False
if piece == 'square':
self.board[0][0] = 0
self.board[0][1] = 0
self.board[1][0] = 0
self.board[1][1] = 0
def update_board(self):
temp_board = [[-1] * self.num_cols for _ in range(self.num_rows)]
for row in range(self.num_rows):
for col in range(self.num_cols):
if self.board[row][col] == '*':
temp_board[row][col] = '*'
for row in range(self.num_rows - 1):
for col in range(self.num_cols):
if (self.board[row][col] == 0) & (self.board[row+1][col] != '*'):
temp_board[row+1][col] = 0
# elif self.board[row+1][col] == '*':
# self.is_complete = True
self.board = temp_board
def check_board(self):
if not self.is_complete:
last_row = self.board[-1]
if 0 in last_row:
self.is_complete = True
for row in range(self.num_rows):
for col in range(self.num_cols):
if self.board[row][col] == 0:
self.board[row][col] = '*'
else:
for row in range(self.num_rows):
for col in range(self.num_cols):
if self.board[row][col] == 0:
self.board[row][col] = '*'
tetris = Tetris(20, 10)
# tetris.board
tetris.add_piece()
tetris.display_board()
print('##################')
# for i in range(20):
# flag = tetris.is_complete
while not tetris.is_complete:
sleep(250/1000)
tetris.update_board()
tetris.check_board()
print(f'is_complete = {tetris.is_complete}')
tetris.display_board()
print('##################')
tetris.add_piece()
tetris.display_board()
while not tetris.is_complete:
sleep(250/1000)
tetris.update_board()
tetris.check_board()
print(f'is_complete = {tetris.is_complete}')
tetris.display_board()
print('##################')
# for row in range(tetris.num_rows):
# print(tetris.board[row])
# # tetris.board[0] |
2b1e9aab7696ea85c4626ecf4d4b8c3f02ce1fe3 | bappi2097/hackerrank-python | /hackerrank/String Validators.py | 602 | 3.65625 | 4 | if __name__ == '__main__':
s = input()
validations = {
'alnum': False,
'alpha': False,
'digit': False,
'lower': False,
'upper': False
}
for i in s:
if i.isalnum():
validations['alnum'] = True
if i.isalpha():
validations['alpha'] = True
if i.isdigit():
validations['digit'] = True
if i.islower():
validations['lower'] = True
if i.isupper():
validations['upper'] = True
for i in validations:
print(validations[i])
|
b1a22342b68941ca9491fcabf1bfbfde71281006 | dineshbalachandran/mypython | /src/daily/daily221.py | 462 | 4.21875 | 4 | """ Let's define a "sevenish" number to be one which is either a power of 7, or the sum of unique powers of 7.
The first few sevenish numbers are 1, 7, 8, 49, and so on. Create an algorithm to find the nth sevenish number. """
import math, sys
def sevenish(n):
if n == 0:
return 0
x = math.floor(math.log(n,2))
return math.pow(7, x) + sevenish(n-math.pow(2, x))
if __name__ == '__main__':
print(int(sevenish(int(sys.argv[1])))) |
8dae63d4b3ae94459b4759febbb40601e47b8719 | deysonali/CSC190 | /190lab1/stackLib.py | 284 | 3.703125 | 4 | class stack:
def __init__(self):
self.store=[]
def push(self, x):
self.store=self.store+[x]
return True
def pop(self):
if (len(self.store)==0):
return False
else:
rval=self.store[len(self.store)-1]
self.store=self.store[0:len(self.store)-1]
return rval
|
a9f5e26c202ec7e5cbf4e601f8f84613e84889b9 | miro-lp/SoftUni | /Fundamentals/Functions/CenterPoint.py | 389 | 3.9375 | 4 | def nearest_point(x_1, y_1, x_2, y_2):
hypo_1 = x_1 ** 2 + y_1 ** 2
hypo_2 = x_2 ** 2 + y_2 ** 2
if hypo_1 <= hypo_2:
print("(" + str(int(x_1)) + ", " + str(int(y_1)) + ")")
else:
print("(" + str(int(x_2)) + ", " + str(int(y_2)) + ")")
x_1 = float(input())
y_1 = float(input())
x_2 = float(input())
y_2 = float(input())
nearest_point(x_1, y_1, x_2, y_2)
|
0c1a87ed8e5cc1b3acfb9be1ae5fb5690a17590d | naren-m/programming_practice | /general/divide_and_conquer/binary_search.py | 728 | 3.953125 | 4 | # Problem Grokking algorithms book. Exercise 4.4
def binary_search(arr, element, start=0, end=0):
print(arr, element, start, end)
if start >= end:
return -1
mid = (start + end) // 2
if element == arr[mid]:
return mid
elif element < arr[mid]:
# element to find is less than mid. search in left sub array
return binary_search(arr, element, start, mid - 1)
else:
# element to find is greater than mid. search in right sub array
return binary_search(arr, element, mid + 1, end)
l = [1, 2, 3, 4, 5]
print(binary_search(l, 5, 0, len(l)))
print(binary_search(l, 3, 0, len(l)))
print(binary_search(l, 1, 0, len(l)))
print(binary_search(l, 10, 0, len(l))) |
ef5ad615a839853719d8cae7071b3371f9a0199a | RikuX43/School_projects | /Intro/employeepay.py | 268 | 3.921875 | 4 | # Put your code here
wage = float(input('Enter the wage: '))
reg_hours = int(input('Enter the regular hours: '))
ot_hours = int(input('Enter the overtime hours: '))
weekly_pay = wage * reg_hours + ot_hours * wage * 1.5
print("The total weekly pay is $", weekly_pay)
|
b73ba06e055ea3e1d682ea78e9f59aa25145930f | faustoandrade/TALLER-1-PD | /12sumacuadrados.py | 212 | 3.5625 | 4 | def cuadros(n):
sum = 0
if n < 100:
for i in range(1,n):
if i % 4 == 0:
t = i ** 2
sum = sum + t
print sum(
t = input("ingrese numero: ")
cuadros(t) |
eaac9612f152d37b0c51bac1a43e604364243485 | Sapan-Ravidas/Data-Stucture-And-Algorithms | /Dynamic Programming/knapsack.py | 1,103 | 3.6875 | 4 |
class Item:
def __init__(self, name, weight, profit):
self.name = name
self.weight = weight
self.profit = profit
def __repr__(self):
return f"Item({self.name}, w='{self.weight}', p='{self.profit}')"
def knapsack(items, capacity):
n = len(items)
if n == 0:
return 0
dp = [[0 for j in range(capacity + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, capacity + 1):
if i == 0 or j == 0:
pass
elif items[i - 1].weight <= j:
dp[i][j] = max(
items[i - 1].profit + dp[i - 1][j - items[i - 1].weight],
dp[i - 1][j]
)
else:
dp[i][j] = dp[i - 1][j]
for i in range(n + 1):
print(dp[i])
print("Maximum profit", dp[n][capacity])
if __name__ == '__main__':
items = [
Item('a', 1, 10),
Item('b', 2, 12),
Item('c', 4, 28)
]
capacity = 6
knapsack(items, capacity) |
fe5c07f94552fff371bd55267e75c1acff213a4e | topdcw/Leetcode | /601-700/Solution_665.py | 989 | 3.84375 | 4 | """
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
"""
class Solution:
def checkPossibility(self, nums):
count=0
i=1
while i<len(nums):
if nums[i-1]>nums[i]:
count+=1
#针对第一个元素和最后一个元素
if i==1:
nums[i-1]=nums[i]
elif i==(len(nums)-1):
nums[i]=nums[i-1]
#针对中间的元素
else:
if nums[i-1]>nums[i+1]:
nums[i-1]=nums[i]
else:
nums[i]=nums[i-1]
if count>1:
return False
i=0
i+=1
return True
"""
:type nums: List[int]
:rtype: bool
""" |
953c598989bef5c14e2d1d4bb8c804a4e4f91766 | ATField2501/G-S_Python-Exercices | /Swinnen_exercice10.py | 966 | 3.515625 | 4 | #!/usr/bin/python2
# -*- coding: utf8
# auteur:<atfield2501@gmail.com>
# Exercice page 52
"""
5.15. Écrivez un programme qui analyse un par un tous les éléments d'une liste de mots (par
exemple : ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra'] pour générer deux
nouvelles listes. L'une contiendra les mots comportant moins de 6 caractères, l'autre les
mots comportant 6 caractères ou davantage.
"""
liste=['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra', 'Annabelle', 'Aldo', 'JustinienTrouvé', 'MK-Ultra', 'Alphonse','Albert', 'CharlesFort']
liste_moins=[]
liste_plus=[]
neo=''
for index, e in enumerate(liste):
neo = e
long = len(neo)
if long >= 6:
liste_plus.append(neo)
else:
liste_moins.append(neo)
print " Voici la liste comportant moins de six charactères : {}".format(liste_moins)
print " Et voici la liste comportant plus de six charactères : {}".format(liste_plus)
|
aeaac14f67ed7ac59114679e79c788e919d053b7 | ChristianTsoungui/sells_management | /sells_management.py | 4,372 | 3.546875 | 4 |
# coding: utf-8
# In[1]:
# Importing the libraries
import pandas as pd
import numpy as np
import re
# ## Data cleaning and Item_Price conversion in float
# In[2]:
# function that will remove the dollar sign from the item_price and convert it in float
def remov(x):
L = list(x)
del L[0]
S = ''.join(L)
return float(S)
# In[3]:
# Reading the dataset
df = pd.read_csv("chipotle.csv")
p = []
# Converting item_price column into float
for i in df["item_price"]:
p.append(remov(i))
# Adding the floated item_price to the dataframe
df2 = df
df2["Item_price"] = p
del df2['item_price']
df2.head()
# ## Average quantities and average total price
# In[4]:
# Average quantity and price for all the orders
m = []
id = []
price = []
for i in range(1, 1835):
id.append(i)
m.append(df[df2["order_id"] == i]["quantity"].mean())
price.append(df[df2["order_id"] == i]["Item_price"].mean())
data = {"order_id":id, "mean_quantity":m, "mean_item_price":price}
S = pd.DataFrame(data)
S.head()
# ## Item ordered with the largest total quantity and largest total price
# In[5]:
# creating a list of the item names
Ln = df2["item_name"].unique()
Ql = []
Pl = []
for i in Ln:
Ql.append(sum(df2["quantity"][df2["item_name"] == i]))
Pl.append(sum(df2["Item_price"][df2["item_name"] == i]))
data = {"Largest_total_quantity":Ql, "Largest_total_price":Pl, "item_name":Ln}
LargTot = pd.DataFrame(data)
pmax = LargTot[LargTot["Largest_total_price"] == LargTot["Largest_total_price"].max()]["item_name"]
qmax = LargTot[LargTot["Largest_total_quantity"] == LargTot["Largest_total_quantity"].max()]["item_name"]
print("The item ordered with the largest total quantity is:\t{0}\n\n".format(qmax))
print("The item ordered with the largest total price is:\t{0}".format(pmax))
# ## Find the three top most popular choices that were added to an item
# In[6]:
# List of the Items
L = df2["item_name"].unique()
#List of their occurences in the dataframe.
occur = []
for i in L:
n = 0
for j in df2["item_name"]:
if i == j:
n += 1
occur.append(n)
D = dict(zip(L, occur))
M = []
k = []
i = 0
while i != 3:
M.append(max(D.values()))
k.append(list(D.keys())[list(D.values()).index(M[i])])
D.pop(k[i], None)
i += 1
data = {"Items":k, "Number of orders": M}
Top = pd.DataFrame(data)
Top
# ## Let us group the item into three types:
# ## Defining the necessary functions
# In[7]:
# Function that looks for the words Burrito and Bowls in the Item name
def B2(x):
atRegex = re.compile(r'Burrito|Bowl')
mo = atRegex.search(x)
if atRegex.search(x) == None:
return False
else:
return True
# Function that looks for the words Tacos and Salad in the Item name
def TS(x):
atRegex = re.compile(r'Tacos|Salad')
mo = atRegex.search(x)
if atRegex.search(x) == None:
return False
else:
return True
# Function that looks for the words Sides and Drinks in the Item name
def SD(x):
atRegex = re.compile(r'Side|Drink')
mo = atRegex.search(x)
if atRegex.search(x) == None:
return False
else:
return True
# ## Grouping
# In[8]:
B = df2["item_name"].unique()
# Group Burrito and Bowls
BB = []
for i in B:
if B2(i) == True:
BB.append(i)
BB
data = {"Burrito and Bowls": BB}
Grp1 = pd.DataFrame(data)
print(Grp1)
# Group Tacos and Salad
TaSa = []
for i in B:
if TS(i) == True:
TaSa.append(i)
TaSa
data = {"Tacos and Salad": TaSa}
Grp2 = pd.DataFrame(data)
print("\n\n",Grp2)
# Group Sides and Drinks
SiDr = []
for i in B:
if SD(i) == True:
SiDr.append(i)
SiDr
data = {"Sides and Drinks": SiDr}
Grp3 = pd.DataFrame(data)
print("\n\n", Grp3)
# ## Proportion of orders that include Tacos and Salad types
# In[9]:
n = 0
for i in Grp2["Tacos and Salad"]:
for j in df2["item_name"]:
if i == j:
n += 1
prop = n/len(df2["item_name"])
print("The proportion of orders that include Tacos and Salad types is: \t{0}".format(prop))
# ## Proportion of orders that include Sides and Drinks types
# In[10]:
n = 0
for i in Grp3["Sides and Drinks"]:
for j in df2["item_name"]:
if i == j:
n += 1
prop = n/len(df2["item_name"])
print("The proportion of orders that include Sides and Drinks types is: \t{0}".format(prop))
# In[ ]:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.