blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2279bc1343d76245ef3ff63bf8dc9fc037119de6 | OrdenWills/100daysofpyhton | /trycode5.py | 480 | 3.984375 | 4 | print("mary had a little lamb")
print("it's fur was white as {}.".format("snow"))
print("and everywhere that mary went. ")
print("." * 10) #this looks strange tho
end1="c"
end2="h"
end3="e"
end4="e"
end5="s"
end6="e"
end7="b"
end8="u"
end9="r"
end10="g"
end11="e"
end12="r"
#we notice that end= ' ' at the end will remove it after first execution of code to see what happens
print(end1 + end2 + end3+ end4 + end5 + end6 ,end= '')
print(end7 + end8 + end9 + end10 + end11 + end12) |
efee696cf56fb7ba8a121eebc59c0daead0a9ea2 | Silversmithe/Jukebot_Hero | /research/Algorithm/Leveling.py | 17,189 | 3.78125 | 4 | #!/usr/bin/python
"""
FILE: Leveling.py
DESCRIPTION: Finding the average of a level of a graph while finding out
if a point should be incorporated into that level
"""
"""
What is a level?
- a level is a group of adjacent equidistant points from the origin
- a level represents an object or the lack of an object in front of a SENSOR
"""
import time
import math
from matplotlib import pyplot as plt
# lets test the idea of leveling a graph
VAR_SAMPLE = 50 # originally 50
VAR_SAMPLEx2 = 16 # originally 16
VAR_SAMPLEx5 = 4 # originally 4
VAR_SAMPLEx10 = 4 # originally 2
VAR_SAMPLEx30 = 1.5 # originally 2
# get graph information
# all samples with the box measurement
samplex30 = [13,13,13,14,14,14,14,23,42,43,43,41,41,41,41,41,41,40,41,41,41,40,40,40,39,40,40,39,39,39,39,40,38,38,39,38,38,39,38,39,38,38,39,38,38,39,38,39,39,38,39,38,38,38,39,38,39,39,38,38,38,38,39,39,38,39,38,38,39,38,39,39,39,39,39,40,39,40,40,39,42,42,41,40,41,40,41,41,41,41,41,41,41,15,13,12,12,12,12,11,12,12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,10,10,10,10,10,10,10,10,10,10,11,11,11,10,11]
samplex10 = [13,13,14,14,14,14,17,28,37,43,42,42,41,41,42,39,40,41,41,40,41,41,40,37,40,40,40,39,37,38,38,40,39,38,38,38,38,38,38,39,39,39,38,38,38,38,39,39,39,39,38,38,38,38,38,39,39,37,39,38,38,38,38,38,38,38,39,39,39,38,38,38,38,40,37,40,39,39,39,39,42,41,41,41,41,38,37,41,41,38,38,41,41,15,15,12,12,12,12,12,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10]
samplex5 = [13,13,14,13,14,14,14,15,37,37,43,42,39,42,42,36,41,41,41,41,35,39,40,40,40,40,39,40,35,40,35,38,39,37,39,36,39,34,39,36,39,37,38,39,36,39,36,39,37,39,37,39,36,38,38,38,39,37,39,37,39,36,39,37,38,37,37,37,38,39,37,39,36,39,36,38,37,38,41,41,40,42,40,41,41,37,41,41,41,40,41,35,41,24,13,12,12,12,11,12,12,12,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,11,11,10,11,10,11,11]
pop_samplex30 = [13,13,14,14,14,14,14,14,39,41,42,42,42,41,41,40,31,30,29,28,27,26,27,27,26,27,26,26,26,26,26,26,25,26,26,26,25,26,26,25,25,26,26,26,25,25,25,24,24,23,24,24,23,23,23,23,23,23,22,22,23,23,23,23,22,22,23,23,23,23,22,23,24,24,23,24,24,25,28,37,36,36,36,37,37,34,35,34,35,35,34,35,34,15,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,10,10,10,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,10,11,10,11]
pop_samplex5 = [13,13,14,14,13,14,14,20,31,42,42,36,42,37,42,42,29,32,29,28,27,26,26,27,27,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,24,24,24,23,23,23,24,24,24,23,23,22,22,23,23,23,21,23,23,22,23,23,21,23,23,23,23,24,24,24,25,27,34,37,35,37,34,35,35,33,35,33,35,35,33,35,35,17,12,12,11,12,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,11,11,11,11]
# populated room sample
pop_room_samplex10 = [187,170,172,189,172,127,57,56,60,60,60,59,59,54,57,59,54,57,58,55,54,58,57,55,57,55,57,53,56,57,53,56,53,57,53,56,57,54,57,53,57,58,55,57,57,59,54,57,59,55,57,59,52,57,59,60,86,60,200,175,196,200,206,195,201,202,202,201,199,205,193,201,201,201,195,211,195,206,200,201,195,206,192,209,190,156,209,147,98,100,103,112,106,101,111,108,113,109,102,106,111,103,112,109,102,111,107,109,117,112,123,151,103,102,112,261,131,112,243,243,273,247,249,294,199,259,271,227,154,139,153,142,153,142,152,143,152,144,152,143,139,152,136,152,142,152,143,152,144,151,145,151,144,151,144,151,144,151,144,152]
# just for one level on the graph
def levelGraph(graph, sample_variance):
"""
Find the different levels of the graph and display them
"""
level_low = level_high = 0
level_average = current_value = graph[0]
for i in range(1, len(graph)):
current_value = graph[i]
if ( -1*sample_variance <= (current_value - level_average) <= sample_variance):
level_average = (current_value + level_average)/2
else:
level_high = i;
break
if (level_high == level_low):
level_high = len(graph)-1
return [level_low, level_high, level_average]
# VERSION 1
# gets all levels in the graph
def mapLevelGraph(graph, sample_variance, debug=False):
"""
Find the different levels of the graph and display them
these level indexes are inclusive
"""
levels = [] # array that contains all of the levels
current_level_low = current_level_high = 0
current_level_average = current_value = graph[0]
for i in range(1, len(graph)):
current_value = graph[i]
if debug:
print(i)
if ( -1*sample_variance <= (current_value - current_level_average) <= sample_variance):
if debug:
print("Matches current level-> value:", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
current_level_average = math.ceil((current_value + current_level_average)/2)
else:
if debug:
print("** Outside current level", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
"""
I have some thoughts here:
Just because a point is outside of the average variance does not make it actually outside of the level
is there not a possibility that this point is an outlier?
it might be usefull look at the point after the current point (look at the trend of points after the current one)
to determine wether the current point should be apart of the current level or the next level
"""
current_level_high = i-1;
# store levels in levels array
levels.append([current_level_low, current_level_high, current_level_average])
current_level_low = current_level_high = i
current_level_average = graph[i]
# once its done, the highest limit is the last index
current_level_high = len(graph)-1
levels.append([current_level_low, current_level_high, current_level_average])
return levels
# VERSION 2
# gets all levels in the graph
def mapLevelGraphLookAhead(graph, sample_variance, debug=False):
"""
Find the different levels of the graph and display them
these level indexes are inclusive
"""
levels = [] # array that contains all of the levels
current_level_low = current_level_high = 0
current_level_average = current_value = graph[0]
for i in range(1, len(graph)):
current_value = graph[i]
if debug:
print(i)
if ( -1*sample_variance <= (current_value - current_level_average) <= sample_variance):
if debug:
print("Matches current level-> value:", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
current_level_average = math.ceil((current_value + current_level_average)/2)
# elif (i > 0) and (i < len(graph)-1) and ( -1*sample_variance <= (current_value - graph[i-1]) <= sample_variance):
# if debug:
# print("Matches current level-> value:", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
# current_level_average = math.ceil((current_value + current_level_average)/2)
else:
if debug:
print("** Outside current level", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
"""
I have some thoughts here:
Just because a point is outside of the average variance does not make it actually outside of the level
is there not a possibility that this point is an outlier?
it might be usefull look at the point after the current point (look at the trend of points after the current one)
to determine wether the current point should be apart of the current level or the next level
this is the most useful if your degree resolution is high! meaning you take more samples
"""
# LOOK AHEAD/ LOOK BEHIND
# check ahead if the next one is within the limit
if 0 < i < len(graph)-1:
# if the one behind you and the one in front of you are close to each other
# you should most likely be with them
behind_value = graph[i-1]
ahead_value = graph[i+1]
if (( -1*sample_variance <= (ahead_value - current_level_average) <= sample_variance)) and (( -1*sample_variance <= (ahead_value - current_level_average) <= sample_variance)):
# if not then actually end level
# its an outlier (that belongs) and should not be counted towards the average
#current_level_average = math.ceil((current_value + current_level_average)/2)
# REDEMPTION
pass
else:
# STILL NOT REDEEMED
current_level_high = i-1;
# store levels in levels array
levels.append([current_level_low, current_level_high, current_level_average])
current_level_low = current_level_high = i
current_level_average = graph[i]
else:
current_level_high = i-1;
# store levels in levels array
levels.append([current_level_low, current_level_high, current_level_average])
current_level_low = current_level_high = i
current_level_average = graph[i]
# once its done, the highest limit is the last index
current_level_high = len(graph)-1
levels.append([current_level_low, current_level_high, current_level_average])
return levels
# VERSION 3
# gets all levels in the graph
def mapGraphLevelEvening(graph, sample_variance, debug=False):
"""
Find the different levels of the graph and display them
these level indexes are inclusive
"""
levels = [] # array that contains all of the levels
current_level_low = current_level_high = 0
current_level_average = current_value = graph[0]
for i in range(1, len(graph)):
current_value = graph[i]
if debug:
print(i)
if ( -1*sample_variance <= (current_value - current_level_average) <= sample_variance):
if debug:
print("Matches current level-> value:", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
current_level_average = math.ceil((current_value + current_level_average)/2)
# elif (i > 0) and (i < len(graph)-1) and ( -1*sample_variance <= (current_value - graph[i-1]) <= sample_variance):
# if debug:
# print("Matches current level-> value:", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
# current_level_average = math.ceil((current_value + current_level_average)/2)
else:
if debug:
print("** Outside current level", current_value, ", ave: ", current_level_average, ", diff: ", (current_value - current_level_average))
"""
I have some thoughts here:
Just because a point is outside of the average variance does not make it actually outside of the level
is there not a possibility that this point is an outlier?
it might be usefull look at the point after the current point (look at the trend of points after the current one)
to determine wether the current point should be apart of the current level or the next level
this is the most useful if your degree resolution is high! meaning you take more samples
"""
# LOOK AHEAD/ LOOK BEHIND
# check ahead if the next one is within the limit
if 0 < i < len(graph)-1:
# if the one behind you and the one in front of you are close to each other
# you should most likely be with them
behind_value = graph[i-1]
ahead_value = graph[i+1]
if (( -1*sample_variance <= (ahead_value - current_level_average) <= sample_variance)) and (( -1*sample_variance <= (ahead_value - current_level_average) <= sample_variance)):
# if not then actually end level
# its an outlier (that belongs) and should not be counted towards the average
#current_level_average = math.ceil((current_value + current_level_average)/2)
# REDEMPTION
pass
else:
# STILL NOT REDEEMED
current_level_high = i-1;
# store levels in levels array
levels.append([current_level_low, current_level_high, current_level_average])
current_level_low = current_level_high = i
current_level_average = graph[i]
else:
current_level_high = i-1;
# store levels in levels array
levels.append([current_level_low, current_level_high, current_level_average])
current_level_low = current_level_high = i
current_level_average = graph[i]
# once its done, the highest limit is the last index
current_level_high = len(graph)-1
levels.append([current_level_low, current_level_high, current_level_average])
# LETS SEE WHAT THIS DOES
"""
now that we have all the levels in order, use the level averages to find out what levels seem off
Use the level averages and the level ranges, clean out the graph even further
only dealing with the levels with a level above and below, NOT a limit point
"""
levels_to_remove = []
for i in range(1, len(levels)-1):
# lets look only at the levels that are one point
# pull out the current level
level = levels[i]
level_behind = levels[i-1]
level_ahead = levels[i+1]
if level[1] - level[0] == 0:
# if the difference of the high limit & low limit are zero
# the high and low limit are the same
# if ( -1*sample_variance <= (ahead_value - current_level_average) <= sample_variance):
if level_behind[2] < level_ahead[2]:
level[2] = (level_ahead[2] + level_behind[2])/2
elif level_behind[2] > level_ahead[2]:
level[2] = (level_ahead[2] + level_behind[2])/2
elif level_behind[2] == level_ahead[2]:
level[2] = level_behind[2]
elif (-1*sample_variance <= (level_behind[2] - level_ahead[2]) <= sample_variance):
# so if the level in front and the level behind have similar averages
# and if the variance you are measuring is very small
if level[1] - level[0] < 10:
new_ave = (level_ahead[2] + level_behind[2])/2
level[2] = new_ave
level[0] = level_behind[0]
level[1] = level_ahead[1]
levels_to_remove.append(level_ahead)
levels_to_remove.append(level_behind)
# remove suggested levels
for level in levels_to_remove:
levels.remove(level)
return levels
def smooth(name, samples, sample_variance, debug=False):
"""
given the samples and the variance, find each level of the graph
while predicting each level average
"""
print(name)
level_output = mapGraphLevelEvening(samples, sample_variance)
print(level_output)
# create a graph using the level averages to show distinction
output_graph = []
for level in level_output:
# for each level
for i in range(level[0], level[1]+1):
# for each range fill in the correct average
output_graph.append(level[2])
plt.figure(name)
plt.subplot(211)
plt.plot(samples)
plt.subplot(212)
plt.plot(output_graph)
plt.show()
def run():
smooth("Sampling Rate 30",samplex30, VAR_SAMPLEx30)
print()
smooth("Sampling Rate 10", samplex10, VAR_SAMPLEx10)
print()
smooth("Sampling Rate 5", samplex5, VAR_SAMPLEx5)
print()
smooth("Populated Area, Sampling Rate 30", pop_samplex30, VAR_SAMPLEx30)
print()
smooth("Populated Area, Sampling Rate 5", pop_samplex5, VAR_SAMPLEx5)
print()
smooth("Populated Room, Sampling Rate 10", pop_room_samplex10, VAR_SAMPLEx10)
if __name__ == '__main__':
run()
|
a6c9a1eced3987dc4b38694101caaad44a9fdb5f | VProv/Poem2poem | /models/rhyme_testers.py | 8,035 | 3.546875 | 4 | import rupo.api
from enum import Enum
from typing import NamedTuple, Optional
def get_reversed(line):
return ''.join(reversed(line))
class LetterType(Enum):
NOT_LETTER = 0
VOWEL = 1
CONSONANT = 2
SIGN = 3
'''
Auxiliary class providing convenient functions for retrieving Russian letter type.
'''
class RuAlphabetInfo(object):
_ru_letters = set(''.join([chr(n) for n in range(ord('а'), ord('я') + 1)]) + 'ё')
assert len(_ru_letters) == 33
_ru_vowels = set('аеёийоуыэюя')
_ru_consonants = set('бвгджзклмнпрстфхцчшщ')
_ru_signs = set('ъь')
assert _ru_vowels & _ru_consonants == set()
assert _ru_vowels | _ru_consonants | _ru_signs == _ru_letters
@staticmethod
def get_ru_letter_type(ch: str) -> LetterType:
if ch in RuAlphabetInfo._ru_vowels:
return LetterType.VOWEL
elif ch in RuAlphabetInfo._ru_consonants:
return LetterType.CONSONANT
elif ch in RuAlphabetInfo._ru_signs:
return LetterType.SIGN
else:
return LetterType.NOT_LETTER
@staticmethod
def lower_and_strip_left_non_letters(line: str) -> str:
line = line.lower()
# Skip everything before first letter:
while len(line) > 0 and line[0] not in RuAlphabetInfo._ru_letters:
line = line[1:]
return line
#class RhymeInfo(NamedTuple):
# text: str
# finished: bool
# Old-style for Python 3.5:
RhymeInfo = NamedTuple('RhymeInfo',
[('text', str), # text that will be used for testing whether rhyme is present
('finished', bool) # is text complete
])
class IRhymeTester(object):
def extract_rhyme_info(self, line: str) -> RhymeInfo:
raise Exception('Not implemented')
def is_rhyme(self, info1: RhymeInfo, info2: RhymeInfo) -> Optional[bool]:
# Returns True - rhyme present, False - absent, None - don't know
raise Exception('Not implemented')
'''
Implements suffix-based rhyming.
'''
class RuReversedSuffixRhymeTester(IRhymeTester):
def extract_rhyme_info(self, line: str) -> RhymeInfo:
# input: line is REVERSED string
# We iterate all vowels from the beginning of line until first consonant
# Or all consonants until first vowel
# SIGNs are ignored but inserted to output
line = RuAlphabetInfo.lower_and_strip_left_non_letters(line)
finished = False
prefix_len = 0
prev_ch_type = None
for ch in line:
ch_type = RuAlphabetInfo.get_ru_letter_type(ch)
if ch_type == LetterType.NOT_LETTER:
finished = True
break
prefix_len += 1
if ch_type != LetterType.SIGN:
if prev_ch_type is None:
prev_ch_type = ch_type
elif prev_ch_type != ch_type:
finished = True
break
return RhymeInfo(text = line[:prefix_len],
finished = finished)
def is_rhyme(self, info1: RhymeInfo, info2: RhymeInfo) -> Optional[bool]:
if not info1.finished or not info2.finished:
l = min(len(info1.text), len(info2.text))
if info1.text[:l] != info2.text[:l]:
return False
return None
return info1.text == info2.text
def test_RuReversedSuffixRhymeTester():
tester = RuReversedSuffixRhymeTester()
for line, suffix, finished in [('пижама', 'ма', True),
('обученный', 'ный', True),
('Ихтиандр', 'андр', True),
('КНДР', 'кндр', False),
('махать', 'ать', True)]:
for l in (line, line + '!', ' ' + line + ', '):
info = tester.extract_rhyme_info(get_reversed(l))
assert info.text == get_reversed(suffix)
assert info.finished == (finished or l[0] == ' ')
assert tester.is_rhyme(info, info) == (True if info.finished else None)
#test_RuReversedSuffixRhymeTester()
'''
Implements word-based rhyming.
It uses 'rupo' library.
'''
class RuReversedWordRhymeTester(IRhymeTester):
_WORD_INTERNAL_CHARS = set('-.')
def __init__(self, rupo_engine = None):
if rupo_engine is None:
self._rupo_engine = rupo.api.Engine(language = 'ru')
self._rupo_engine.load(stress_model_path = RUPO_STRESS_MODEL_PATH,
zalyzniak_dict = RUPO_ZALYZNIAK_DICT_PATH)
else:
# Assume loaded engine:
assert rupo_engine.language == 'ru'
self._rupo_engine = rupo_engine
def extract_rhyme_info(self, line: str) -> RhymeInfo:
# line is REVERSED string
# Here we skip everything until first letter
# return: it TRIES to return complete word (returns part in case if line contains only part)
line = RuAlphabetInfo.lower_and_strip_left_non_letters(line)
is_internal_char = lambda ch: ch in RuReversedWordRhymeTester._WORD_INTERNAL_CHARS
finished = False
word_len = 0
for ch in line:
is_word_char = is_internal_char(ch) or \
RuAlphabetInfo.get_ru_letter_type(ch) != LetterType.NOT_LETTER
if not is_word_char:
finished = True
break
word_len += 1
while word_len > 0 and is_internal_char(line[word_len - 1]):
word_len -= 1
return RhymeInfo(text = get_reversed(line[:word_len]),
finished = finished)
def is_rhyme(self, info1: RhymeInfo, info2: RhymeInfo) -> Optional[bool]:
if not info1.finished or not info2.finished:
return None
return self._rupo_engine.is_rhyme(info1.text, info2.text)
def test_RuReversedWordRhymeTester(rupo_engine):
tester = RuReversedWordRhymeTester(rupo_engine)
augment_line = lambda l: (l, l + '!', ' ' + l + ', ', 'Мы и ' + l)
for line, word, finished in [('серая корова', 'корова', True),
('молока, много', 'много', True),
('Ихтиандр', 'ихтиандр', False),
('КНДР', 'кндр', False),
('аб-вг', 'аб-вг', False),
('.-аб.вг.-', 'аб.вг', False)]:
for l in augment_line(line):
info = tester.extract_rhyme_info(get_reversed(l))
assert info.text == word
assert info.finished == (finished or not l.startswith(line))
any_vowels = any([RuAlphabetInfo.get_ru_letter_type(ch) == LetterType.VOWEL for ch in word])
assert tester.is_rhyme(info, info) == (any_vowels if info.finished else None)
for line1, line2, is_rhyme in [('серая корова', 'не очень здорова', True),
('молока много', 'не мало', False),
('и играть', 'и скакать', False),
('и играть', 'не играть', True)]:
for l1 in augment_line(line1):
for l2 in augment_line(line2):
info1 = tester.extract_rhyme_info(get_reversed(l1))
info2 = tester.extract_rhyme_info(get_reversed(l2))
assert tester.is_rhyme(info1, info2) == is_rhyme
#test_RuReversedWordRhymeTester(global_rupo_engine)
|
ec0beb1594b2ba3cdfb95a29d342e99c12adcab8 | jbeen2/AlgorithmStudy | /programmers/부족한 금액 계산하기.py | 197 | 3.515625 | 4 | # Weekly Challenge 1
def solution(price, money, count):
answer = sum([i*price for i in range(count+1)]) - money
if answer >= 0 : return answer
else : return 0
print(solution(3, 20, 4)) |
d52e07ac8cecca24517fbf1e8db3ab9331fa5324 | james-721/chat_limpet | /common_functions.py | 236 | 3.671875 | 4 | import math
def distance_finder(loc1, loc2):
inside = ((loc1[0] - (loc2[0])) ** 2) + ((loc1[1] - (loc2[1])) ** 2) + ((loc1[2] - (loc2[2])) ** 2)
distance = math.sqrt(inside)
distance = round(distance, 2)
return distance |
6741dfd84673f751765d5b93a377a462b82da315 | BatuhanAktan/SchoolWork | /CS121/Assignment 4/sort_sim.py | 2,852 | 4.21875 | 4 | '''
Demonstration of time complexities using sorting algorithms.
Author: Dr. Burton Ma
Edited by: Batuhan Aktan
Student Number: 20229360
Date: April 2021
'''
import random
import time
import a4
def time_to_sort(sorter, t):
'''
Returns the times needed to sort lists of sizes sz = [1024, 2048, 4096, 8192]
The function sorts the slice t[0:sz] using the sorting function
specified by the caller and records the time required in seconds.
Because a slice is sorted instead of the list t, the list t is not modified by
this function. The list t should have at least 8192 elements.
The times are returned in a list of length 4 where the times in seconds
are formatted strings having 4 digits after the decimal point making it easier to
print the returned lists.
Parameters
----------
sorter : function
A sorting function from the module a4.
t : list of comparable type
A list of elements to slice and sort.
Returns
-------
list of str
The times to sort lists of lengths 1024, 2048, 4096, and 8192.
Raises
------
ValueError
If len(t) is less than 8192.
'''
if len(t) < 8192:
raise ValueError('not enough elements in t')
times = []
for sz in [1024, 2048, 4096, 8192]:
# slice t
u = t[0:sz]
# record the time needed to sort
tic = time.perf_counter()
sorter(u)
toc = time.perf_counter()
times.append(f'{toc - tic:0.4f}')
return times
list8192 = list(range(8192))
def sim_sorted():
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_partial():
a4.partial_shuffle(list8192)
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_reverse():
list8192.reverse()
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_shuffled():
random.shuffle(list8192)
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
sim_shuffled()
sim_reverse()
sim_partial()
sim_sorted()
|
517b2a70822e581424af41bfde09e41eb4ab179f | mukeshphulwani66/Competitive-coding-python | /recursion/combination.py | 326 | 3.71875 | 4 | def combination(mylist,r):
if r == 0:
return [[]]
L = []
for i in range(0,len(mylist)):
first = mylist[i]
rem = mylist[i+1:]
combList = combination(rem,r-1)
for x in combList:
L.append([first]+x)
return L
print(combination(["A","B","C","D"],3)) |
ced4a64606c36371142a4806783d48433e4d6147 | mukeshphulwani66/Competitive-coding-python | /dynamic programming/minnimum path sum.py | 997 | 3.859375 | 4 | '''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
'''
grid = [[1,2,3],
[4,5,6]]
m = len(grid) #row length 3
n = len(grid[0]) #column length 3
result = [[0 for x in range(n) ] for x in range(m) ]
#[
# [0,0,0]
# [0,0,0]
# [0,0,0]
# ]
result[0][0] = grid[0][0]
for j in range(1,n):#1,2
result[0][j] = grid[0][j] + result[0][j-1]
for i in range(1,m):#1,2
result[i][0] = grid[i][0] + result[i-1][0]
for i in range(1,m):
for j in range(1,n):
result[i][j] = grid[i][j] + min(result[i-1][j],result[i][j-1])
print(result)
print(result[m-1][n-1])
|
882106286eb7f66079a6fe3b822bb771b5ba13b3 | mukeshphulwani66/Competitive-coding-python | /Arithmetic problems/sexyprimes.py | 847 | 3.8125 | 4 | '''
Given a range of the form [L, R].The task is to print all the sexy prime pairs in the range.
Examples:
Input : L = 6, R = 59
Output : (7, 13) (11, 17) (13, 19)
(17, 23) (23, 29) (31, 37) (37, 43)
(41, 47) (47, 53) (53, 59)
Input : L = 1, R = 19
Output : (5, 11) (7, 13) (11, 17) (13, 19)
'''
from math import sqrt
def generatePrimes(n):
primes = [True] * (n+1)
primes[0] = False
primes[1] = False
for i in range(2,int(sqrt(n))+1):
if primes[i] == True:
for j in range(i*i,n+1,i):
primes[j] = False
return primes
L = int(input())
R = int(input())
myprimesnos = generatePrimes(R)
for i in range(L,len(myprimesnos)-6):
if myprimesnos[i] == True:
x = i
y = x + 6
if myprimesnos[y] == True:
print("({0},{1})".format(x,y))
|
bcdc37c7edad6deddcb5a14d5b23e4c35896ca8f | ngs90/RLBanana | /sumtree.py | 3,473 | 3.515625 | 4 | import numpy as np
# SUM Tree functions
class Node:
# The code is based on: https://adventuresinmachinelearning.com/sumtree-introduction-python/
def __init__(self, left, right, is_leaf: bool=False, idx=None, insertion_time=None):
self.left = left
self.right = right
self.is_leaf = is_leaf
if not self.is_leaf:
self.value = self.left.value + self.right.value
self.parent = None
self.idx = idx
self.insertion_time = insertion_time
if left is not None:
left.parent = self
if right is not None:
right.parent = self
#self.value = sum(n.value for n in (left, right) if n is not None)
@classmethod
def create_leaf(cls, value, idx, insertion_time):
leaf = cls(None, None, is_leaf=True, idx=idx, insertion_time=insertion_time)
leaf.value = value
return leaf
def create_tree(inp: list, insertion_times: list):
nodes = [Node.create_leaf(v,i,t) for i, (v, t) in enumerate(zip(inp, insertion_times))]
leaf_nodes = nodes
while len(nodes) > 1:
inodes = iter(nodes)
nodes = [Node(*pair) for pair in zip(inodes, inodes)]
return nodes[0], leaf_nodes
def retrieve(value: float, node: Node):
if node.is_leaf:
return node
if node.left.value >= value:
return retrieve(value, node.left)
else:
return retrieve(value - node.left.value, node.right)
def update(node: Node, new_value: float, new_insertion_time=None):
change = new_value - node.value
node.value = new_value
if new_insertion_time:
node.insertion_time = new_insertion_time
propagate_changes(change, node.parent)
def propagate_changes(change: float, node: Node):
node.value = node.value + change
if node.parent is not None:
propagate_changes(change, node.parent)
if __name__ == '__main__':
# #INPUT = [1,2,3,4,6,15,4,4]
INPUT = [1,4,2,3]
insertion_times = [0,1,2,3]
root_node, leaf_nodes = create_tree(INPUT, insertion_times)
def demonstrate_sampling(root_node: Node):
tree_total = root_node.value
iterations = 100000
selected_vals = []
selected_idxs = []
selected_insertion_times = []
for i in range(iterations):
rand_val = np.random.uniform(0, tree_total)
leaf_node = retrieve(rand_val, root_node)
selected_val = leaf_node.value
selected_idx = leaf_node.idx
selected_insertion_time = leaf_node.insertion_time
selected_vals.append(selected_val)
selected_idxs.append(selected_idx)
selected_insertion_times.append(selected_insertion_time)
return selected_vals, selected_idxs, selected_insertion_times
selected_vals, selected_idxs, selected_insertion_times = demonstrate_sampling(root_node)
#print(selected_vals[:100])
# the below print statement should output ~4
print(f"Should be ~4: {sum([1 for x in selected_vals if x == 4]) / sum([1 for y in selected_vals if y == 1])}")
# the below print statement should output ~1.5
print(f"Should be ~1.5: {sum([1 for x in selected_idxs if x == 3]) / sum([1 for y in selected_idxs if y == 2])}")
# the below print statement should output ~2
print(f"Should be ~2: {np.mean([t for x, t in zip(selected_idxs, selected_insertion_times) if x == 2])}")
|
c9b3636195f06863bfe65e779b5dcabdeb7313a4 | gab706/Hangman | /main.py | 2,734 | 3.65625 | 4 | import time
from functions import *
from game import *
ComplexNames = TextNames
clearScreen()
clickText(f"Mystery Man > Welcome traveler, you seem lost, allow me to introduce myself, I'm {ComplexNames.NARRATOR_ITSELF}")
clearScreen()
playerName = getPlayerName()
clearScreen()
clickText(f"{ComplexNames.NARRATOR} Hi {playerName}, welcome to the mystery realm, it seems you're trapped here.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} The only way to exit this realm is to participate in our ancient game of Hangman.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} Before we begin the ancient council has allowed you to pick the amount of chances you get")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} You should know though, the more chances you get, the harder the words will be")
clearScreen()
attempts = getAttemptsNumber()
clearScreen()
levelOne = Hangman(playerName, attempts)
levelOneResult = levelOne.play()
if not levelOneResult[0]:
clickText(f"{ComplexNames.NARRATOR} Ha, did you really fail after the first game, that is unfortunate.\n{getColour('BLUE')}Word: {getColour('RESET')}{levelOneResult[1]}")
clearScreen()
print(f"{getColour('RED')}YOU DIED")
exit()
clickText(f"{ComplexNames.NARRATOR} Well well well, it seems you're smarter than I anticipated.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} None the less, you still have two more games to win.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} Otherwise you'll be stuck here forever.")
clearScreen()
levelTwo = Hangman(playerName, attempts)
levelTwoResult = levelTwo.play()
if not levelTwoResult[0]:
clickText(f"{ComplexNames.NARRATOR} At least you managed to make it halfway through, none the less you failed.\n{getColour('BLUE')}Word: {getColour('RESET')}{levelTwoResult[1]}")
clearScreen()
print(f"{getColour('RED')}YOU DIED")
exit()
clickText(f"{ComplexNames.NARRATOR} I just can't seem to get you to lose.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} This is the last round, if you win you'll be let go, if not, well then.")
clearScreen()
levelThree = Hangman(playerName, attempts)
levelThreeResult = levelThree.play()
if not levelThreeResult[0]:
clickText(f"{ComplexNames.NARRATOR} Ohhhh so close, that's unlucky.\n{getColour('BLUE')}Word: {getColour('RESET')}{levelThreeResult[1]}")
clearScreen()
print(f"{getColour('RED')}YOU DIED")
exit()
clickText(f"{ComplexNames.NARRATOR} Bu-but, that's not possible.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} The games are rig- I mean too difficult for any human to win.")
clearScreen()
clickText(f"{ComplexNames.NARRATOR} I guess you're free to go, feel free to come back anytime.")
clearScreen()
exit() |
94cc9b875edca75c61ce7921a14a7c0d7e9f3bfc | sammhit/Learning-Coding | /HackerRankSolutions/electronicShop.py | 817 | 4.09375 | 4 | #!/bin/python3
import sys
#https://www.hackerrank.com/challenges/electronics-shop/problem
def getMoneySpent(keyboards, drives, s):
# Complete this function
sarr=[]
for keyboard in keyboards:
for drive in drives:
sarr.append(keyboard+drive)
sarr.sort(reverse=True)
for elem in range(len(sarr)):
if s>=sarr[elem]:
return sarr[elem]
if elem==(len(sarr)-1):
return -1
s,n,m = input().strip().split(' ')
s,n,m = [int(s),int(n),int(m)]
keyboards = list(map(int, input().strip().split(' ')))
drives = list(map(int, input().strip().split(' ')))
# The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
moneySpent = getMoneySpent(keyboards, drives, s)
print(moneySpent)
|
dfba925cf90c84910c32768a9a4f4b95a798006f | sammhit/Learning-Coding | /HackerRankSolutions/bestAndWorst.py | 695 | 3.984375 | 4 | #!/bin/python3
import sys
#https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
def breakingRecords(score):
hRecords = 0
lRecords = 0
highest = score[0]
lowest = score[0]
for each in score:
if each>highest:
hRecords+=1
highest=each
if each<lowest:
lRecords+=1
lowest=each
return hRecords, lRecords
# Complete this function
if __name__ == "__main__":
n = int(input().strip())
score = list(map(int, input().strip().split(' ')))
result = breakingRecords(score)
print (" ".join(map(str, result)))
|
a38ccc08bc8734389f11b1a6a9ac15eca5b7d53a | sammhit/Learning-Coding | /HackerRankSolutions/quickSortPartion.py | 521 | 4.1875 | 4 | #!/bin/python3
import sys
#https://www.hackerrank.com/challenges/quicksort1/problem
def quickSort(arr):
pivot = arr[0]
left = []
right = []
for i in arr:
if i>pivot:
right.append(i)
if i<pivot:
left.append(i)
left.append(pivot)
return left+right
# Complete this function
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = quickSort(arr)
print (" ".join(map(str, result)))
|
84204405dbc1c4a9e3d62cd6c268ec65e6304cf5 | quangvinh86/Python-HackerRank | /Python_domains/3-Strings-Challenges/Codes/Ex3_6.py | 550 | 3.890625 | 4 | #!/usr/bin/env python3
def validate_string(input_string):
# alphanumeric
print(any([sg_char.isalnum() for sg_char in input_string]))
# alphabetical
print(any([sg_char.isalpha() for sg_char in input_string]))
# Digits
print(any([sg_char.isdigit() for sg_char in input_string]))
# lowercase
print(any([sg_char.islower() for sg_char in input_string]))
#uppcase
print(any([sg_char.isupper() for sg_char in input_string]))
if __name__ == '__main__':
# s = input()
s = "1q2w3e4r@A"
validate_string(s)
|
d3d50cb016ef1554a59452a806d959796ef53b45 | quangvinh86/Python-HackerRank | /Python_domains/2-Basic-Data-Types-Challenges/Code/Ex2_4.py | 297 | 4.21875 | 4 | #!/usr/bin/env python3
def find_second_largest(integer_list):
return sorted(list(set(integer_list)))[-2]
if __name__ == '__main__':
# n = int(input())
# arr = map(int, input().split())
integer_list = map(int, "1 -4 0 -2 -4".split())
print(find_second_largest(integer_list))
|
9005000d28ac02469091f5f2dbe823715bdd693f | quangvinh86/Python-HackerRank | /Python_domains/1_Introduction_Challenges/Code/Ex1_5_Loops.py | 551 | 3.859375 | 4 | #!/usr/bin/env python3
'''
# [Ex5_Loops](https://www.hackerrank.com/challenges/python-loops/problem)
Nhận đầu vào là một số tự nhiên N ( 1<= N <= 20). i là các giá trị thỏa mãn 0 <= i < N.
In ra màn hình các số bình phương của i. Mỗi số trên 1 dòng.
'''
def solve(input_number):
'''
' params: number
' rtype: none
'''
for index in range(input_number):
print(index ** 2)
return None
def main():
input_number = 5
solve(input_number)
if __name__ == "__main__":
main()
|
96aa9d68c07f0e696bd72831b8876e02c24c56da | bswood9321/PHYS-3210 | /Exam2/Exam2_Q1_BSW.py | 2,757 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 23:54:26 2019
@author: Brandon
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10,10,100)
y = (5/4)*x -2
plt.plot(x,y)
plt.grid()
plt.title("A linear equation; Y=5/4X-2")
plt.show()
y1=x**3-4
plt.plot(x,y1)
plt.grid()
plt.title("A nonlinear equation; y=X^3-4")
plt.show()
print('--------------------------------------------')
print('A first order DE is an equation with first derivative and the variables, '
'for example, dy/dx +y=-x^2. These type of equations are fairly straight forward to solve, '
'but can still be solved, in Python, using Eulers method, or an RK2 method')
t_i=0
x1=1
X=[x1]
T=[t_i]
dt=.01
t=t_i
while t<=(t_i+10):
dxdt=4*np.sin(t)**2
x1=x1+dxdt*dt
t=t+dt
X.append(x1)
T.append(t)
plt.plot(T,X)
plt.grid()
plt.title("1st order DE")
plt.show()
print('-------------------------------------------')
print('A fourth order DE is one that calculates a value based on the fourth derivative of a function '
' such as the Euler Bernoulli Beam Theory equation, E*I*d^4x/dw^4 = q(x)')
print('-------------------------------------------')
print('A coupled 1st ODE is one where you have multiple derivatives, such as '
'dx/dt = q and dy/dt =p. We can use diffeq techniques to find x and y dependent upon t and solve similarly as any other.')
x2=1
y2=1
t_i1=0
X2=[x2]
Y2=[y2]
T2=[t_i1]
dt=.01
t2=t_i1
while t2<=(t_i1+10):
dxdt=.25*x2*np.sin(t2)**4
dydt=.25*y2*np.cos(t2)**4
x2=x2+dxdt*dt
y2=y2+dydt*dt
X2.append(x2)
Y2.append(y2)
T2.append(t2)
t2=t2+dt
plt.plot(T,X2)
plt.plot(T,Y2)
plt.show()
print('----------------------------------------')
print('Question 2: '
'The difference between the Euler method and an RK2 method is that the Euler '
'method uses a full step of dt to calculate the next value of x, where the RK2 '
'method uses a half step value of the derivative to calculate the next value of x. '
'In other words, the RK2 method is using the average value of the derivative between '
'x and x+dx, rather than just the value of the derivative at x. This decreases the area '
'of the "box" outside of the function that we would consider error when using the the value of the '
'derivative at either x or x+dx. Again, in other words, the Euler method does not take into account the '
'curvature of the function, where RK methods do. As we increase the value of the RK method, up to RK4 and beyond, '
'the accuracy improves. An RK4 method would be perfectly accurate for any function of an order of 4 or less, for '
'the same reason as above, it uses more steps inbetween evqaluating x values.')
|
78a204b4a7ddcc8d39cab0d2c92430d292ad204a | bswood9321/PHYS-3210 | /Week 03/Exercise_06_Q4_BSW.py | 1,653 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 19:50:39 2019
@author: Brandon
"""
import numpy as np
import numpy.random as rand
import matplotlib.pyplot as plt
def walk(N):
rand.seed()
x = [0.0]
y = [0.0]
for n in range(N):
x.append(x[-1] + (rand.random() - 0.5)*2.0)
y.append(y[-1] + (rand.random() - 0.5)*2.0)
return np.array(x), np.array(y)
M, N = 0, 1000 #Setting variables for later
Distance = list() #Creating an empty list to hold the distances we will record
Walker = list() #Creating an empty list of the number of steps each walker takes
while(M<=99):
walker1=walk(N) #Our walkers
Distance.append(np.sqrt((walker1[0][-1]**2)+(walker1[1][-1]**2))) #Appending the Distance list with the distances of each walker
Walker.append(N) # Appending the Walker list with the number of steps the walker has taken
M = M+1 #Increasing our M value to progress the while loop
N = N+45 #Increasing our N value to change our walker's number of steps
plt.plot(Walker, Distance, 'r+')
plt.xlabel("Number of steps")
plt.ylabel("Distance from the origin")
plt.show()
# By looking at the plot we receive, we can fairly well determine that the distance
# from the origin is fairly random, and does not necessarily increase, decrease, or
# stagnate as the N value of the walker changes.This is exactly as I imagined would happen.
# there is no reason why the distance should stay around any particular number. In fact,
# I believe if we plotted the average dsitance for several iterations of this code, we would find
# a similar plot of seemingly random values. |
fc76bed2804c3befa9f3534e79a126cb0a978445 | bswood9321/PHYS-3210 | /Week 02/Exercise05_BSW.py | 1,177 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import matplotlib.pyplot as plt
N = int(input("Pick a number: "))
n, a, sum1, m, b, sum2 = 1, 0, 0, N, 0, 0
while (n<=N):
a = 1/n
sum1+=a
n = n+1
while (m>=1):
b = 1/m
sum2+=b
m = m-1
error = (sum1 - sum2)/(np.absolute(sum1)+np.absolute(sum2))
print("For N = :",N,", the error is: ",error)
N1=1
Ns=[]
Errors=[]
while N1<=N:
n1, a1, sum11, m1, b1, sum21 = 1, 0, 0, N1, 0, 0
while (n1<=N1):
a1 = 1/n1
sum11+=a1
n1 = n1+1
while (m1>=1):
b1 = 1/m1
sum21+=b1
m1 = m1-1
Ns.append(N1)
error1 = (sum11 - sum21)/(np.absolute(sum11)+np.absolute(sum21))
Errors.append(error1)
N1=N1+1
plt.plot(Ns,Errors,'r-')
plt.xlabel("N")
plt.ylabel("Error(x10^-16)")
plt.title("N vs. Error")
plt.show()
print("The down summation is more precise because the error of the number is proportional to the number you are summing, therefore as the number decreases, there is less error, versus starting with a small number, and adding more error for every summation.")
|
ca36e5f0b93e976ee70b0873fecede0cbc5de6d2 | C74C3/probabilitysimulation | /probabilitysimulator.py | 2,641 | 3.9375 | 4 | """
Probabilty Simulation by Alex Funnell. Written in Python 3.7.2.
||| DESCRIPTION |||
Probabilty Simulation is a python program to calculate expirmental probability.
It can be configured heavily to your needs. You can change the values
in the "VARIABLES" section below, but the main calculations are not to be touched
in order to work successfully everytime. It will display a table at t
What each value does:
probabilitysimulation is updated for bugfixes and changes to the GitHub page here: https://github.com/C74C3/probabilitysimulation
Thank you for downloading. You can explore more at https://cyber.c7division.com
"""
import random
from timeit import default_timer as timer
# VARIABLES
coinFlip = "true"
diceRoll = "false"
mincount = 1
maxcount = 6
times = 100000
# NO TOUCHEY BELOW HERE :)
count = 0
oneCount = 0
twoCount = 0
threeCount = 0
fourCount = 0
fiveCount = 0
sixCount = 0
headsCount = 0
tailsCount = 0
flipTimes = times
if diceRoll == "true":
start = timer()
while count < times:
rollnum = random.randint(mincount, maxcount)
if rollnum == 1:
oneCount = oneCount + 1
elif rollnum == 2:
twoCount = twoCount + 1
elif rollnum == 3:
threeCount = threeCount + 1
elif rollnum == 4:
fourCount = fourCount + 1
elif rollnum == 5:
fiveCount = fiveCount + 1
elif rollnum == 6:
sixCount = sixCount + 1
count = count + 1
print(str(count) + "/" + str(times))
print("Number of 1s rolled: " + str(oneCount))
print("Number of 2s rolled: " + str(twoCount))
print("Number of 3s rolled: " + str(threeCount))
print("Number of 4s rolled: " + str(fourCount))
print("Number of 5s rolled: " + str(fiveCount))
print("Number of 6s rolled: " + str(sixCount))
end = timer()
elif coinFlip == "true":
start = timer()
while count < flipTimes:
flipnum = random.randint(1,2)
if flipnum == 1:
headsCount = headsCount + 1
elif flipnum == 2:
tailsCount = tailsCount + 1
count = count + 1
print(str(count) + "/" + str(flipTimes))
print("Number of heads: " + str(headsCount))
print("Number of tails: " + str(tailsCount))
end = timer()
total = headsCount + tailsCount
print("Total: " + str(total))
totalTime = end - start
totalTime = round(totalTime, 3)
print("Time elapsed: " + str(totalTime) + " seconds.")
|
343553df4497258e168a4ea2d17cf4508820ba0b | marcelogaray/SICARIOS | /src/admin_module/user_module/membership.py | 1,386 | 3.8125 | 4 | __author__ = 'Roy Ortiz'
import datetime
from datetime import datetime
class Membership(object):
def __init__(self, type, percent_of_discount, start_date):
"""
type is a string it stores the membership type
percent_of_discount is an int value it will store the percentage of discount from 0 to 100
start_date is a date value to indicate the membership start date
"""
self._type = type
self._percent_of_discount = percent_of_discount
self._start_date = start_date
def get_type(self):
"""
Returns the type of membership
:return: the type name
"""
return self._type
def get_discount(self):
"""
Returns the percentage of discount according the membership type
:return: the percentage from 0 to 100
"""
return self._percent_of_discount
def get_start_date(self):
"""
Returns the membership start date
:return: the suscription start date
"""
return self._start_date
def calculate_end_date(self, start_date):
"""
Returns the end date calculated from start date this by adding 6 months
:return: the membership end date
"""
end_date = start_date + datetime.timedelta(6*365/12)
return end_date
|
01c48f4a4eb9bf29fc8d4364dbd2d759ce265b0f | nii5/lesson03 | /tast05.py | 493 | 3.609375 | 4 |
my_sum = 0
while True:
str = input('Введите набор чисел через пробел')
my_list = str.split(' ')
stop = False
for i in my_list:
if i.isdigit():
my_sum = my_sum + int(i)
else:
print(my_sum)
stop = True
break
if stop:
break
else:
print(f'Текущая сумма чисел {my_sum}')
print (f'Текущая сумма чисел {my_sum}')
|
fed18b055337f8e88a9ed840e8e26afcdb56a4b6 | dunkle/python_Learn | /fanye_readfile.py | 589 | 3.53125 | 4 | #向上翻页
#读的时候,采用截取的方法读
#Page = 1 range[0,5) Page = 2 range[5,10) Page = n range(0,5)
# 向下翻页
file = open("gitlab_acess.log","r")
lines = file.readlines()
num = 1
while True:
control = input(">>>")
if control == "N":
print("++++-第%s页开始+++")
start = (num-1)*5
end = num*5
for line in lines[start:end]:
print(line)
print("++++-第%s页结束+++")
num += 1
elif control =="E":
break
elif control =="U":
num -= 1
print("++++-第%s页开始+++")
|
e04ecdf0de9152e925c6dbd00abfc236318a6398 | fenscsb08/INF6050GroupProject | /DemoInfo.py | 483 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 20:50:01 2018
@author: TenleySablatzky
"""
print("Let's start by getting to know you a little bit.")
Gender = input("Please select one: M/F or type N for nonbinary ")
str.capitalize("n", "m", "f")
Age = input("Enter your age numberically: ")
Weight = input("What is your current weight in pounds? ")
Height = input("Please enter your height in inches: ")
User = []
User = [Gender, Age, Weight, Height]
|
99eb4e757c3f6ebe5f1d77537288eb0623b90fd6 | adlerpriit/Codingame | /FantasticBits/FantaticBitsOOP.py | 17,421 | 3.65625 | 4 | import sys
import math
import random
# Grab Snaffles and try to throw them through the opponent's goal!
# Move towards a Snaffle and use your team id to determine where you need to throw it.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance2(self, p):
return (self.x - p.x) * (self.x - p.x) + (self.y - p.y) * (self.y - p.y)
def distance(self, p):
return math.sqrt(self.distance2(p))
def angle(self, p):
alpha = math.atan2(p.y - self.y, p.x - self.x)
return alpha
def closest(self, a, b):
da = b.y - a.y
db = a.x - b.y
c1 = da * a.x + db * a.y
c2 = -db * self.x + da * self.y
det = da * da + db * db
cx = 0
cy = 0
if det != 0:
cx = (da * c1 - db * c2) / det
cy = (da * c2 + db * c1) / det
else:
# the point is already on the line
cx = self.x
cy = self.y
return Point(cx, cy)
class Collision:
def __init__(self, a, b, t):
self.a = a
self.b = b
self.t = t
class Unit(Point):
def __init__(self, mid, vx, vy, x, y):
super().__init__(x, y)
self.mid = mid
self.vx = vx
self.vy = vy
def collision(self, u, time):
# # square of the distance
# dist = self.distance2(u)
# # sum of radii squared
# sr = (self.r + u.r) * (self.r + u.r)
# if (type(self) is Wizard and type(u) is Snaffle) or (type(u) is Wizard and type(self) is Snaffle):
# if type(self) is Wizard:
# sr = (self.r - 1 + self.r - 1) * (self.r - 1 + self.r - 1)
# else:
# sr = (u.r - 1 + u.r - 1) * (u.r - 1 + u.r - 1)
# if dist < sr:
# return Collision(self, u, 0.0)
# if self.vx == u.vx and self.vy == u.vy:
# return None
# # change reference. make u stationary
# x = self.x - u.x
# y = self.y - u.y
# myp = Point(x, y)
# vx = self.vx - u.vx
# vy = self.vy - u.vy
# up = Point(0, 0)
# p = up.closest(myp, Point(x + vx, y + vy))
# pdist = up.distance2(p)
# mypdist = myp.distance2(p)
# if pdist < sr:
# length = math.sqrt(vx * vx + vy * vy)
# # find point along the line where the collision occurs?
# backdist = math.sqrt(sr - pdist)
# p.x -= backdist * (vx / length)
# p.y -= backdist * (vy / length)
# # point now further, we're going in wrong way
# if myp.distance2(p) > mypdist:
# return None
# pdist = p.distance(myp)
# if pdist > length:
# return None
# t = pdist / length
# if time + t < 1.0:
# return Collision(self, u, t)
# return None
x2 = self.x - u.x
y2 = self.y - u.y
r2 = self.r + u.r
if type(self) is Snaffle and type(u) is Wizard:
r2 = u.r - 1
vx2 = self.vx - u.vx
vy2 = self.vy - u.vy
a = vx2*vx2 + vy2*vy2
if a < 0.0001:
return None
b = -2.0*(x2*vx2 + y2*vy2)
delta = b*b - 4.0*a*(x2*x2 + y2*y2 - r2*r2)
if delta < 0.0:
return None
t = (b - math.sqrt(delta))*(1.0/(2.0*a))
if t <= 0.0:
return None
if time + t > 1.0:
return None
return Collision(self, u, t)
def bounce(self, u):
#print(self.mid, [self.vx,self.vy], file=sys.stderr)
#print(u.mid, [u.vx,u.vy], file=sys.stderr)
m1 = self.m
m2 = u.m
mcoeff = (m1 + m2) / (m1 * m2)
nx = self.x - u.x
ny = self.y - u.y
# distance between units while colliding squared
dnxny2 = nx * nx + ny * ny
dvx = self.vx - u.vx
dvy = self.vy - u.vy
# impact factor
product = (nx * dvx + ny * dvy) / (dnxny2 * mcoeff)
fx = nx * product
fy = ny * product
# apply impact factor once
self.vx -= fx / m1
self.vy -= fy / m1
u.vx += fx / m2
u.vy += fy / m2
# if impulse is less than 100, normalise it to 100
impulse = math.sqrt(fx * fx + fy * fy)
if impulse < 100:
fx = fx * 100 / impulse
fy = fy * 100 / impulse
# apply impact factor once more
self.vx -= fx / m1
self.vy -= fy / m1
u.vx += fx / m2
u.vy += fy / m2
#print(self.mid, [self.vx, self.vy], file=sys.stderr)
#print(u.mid, [u.vx, u.vy], file=sys.stderr)
def move(self, t):
self.x += self.vx * t
self.y += self.vy * t
def boost(self, p, thrust):
ra = self.angle(p)
self.vx += math.cos(ra) * thrust/self.m
self.vy += math.sin(ra) * thrust/self.m
def end(self):
# def tround(float):
# if round(float + 1) - round(float) != 1:
# return round(float + abs(float) / float * 0.5)
# return round(float)
self.x = round(self.x)
self.y = round(self.y)
self.vx = round(self.vx * self.f)
self.vy = round(self.vy * self.f)
class Wizard(Unit):
m = 1
r = 400
f = 0.75
def __init__(self, tid, mid, vx, vy, x, y, state):
super().__init__(mid, vx, vy, x, y)
self.tid = tid
self.state = state
self.got = None
self.catchtimer = 0
def catch(self, u):
if not self.catchtimer and not self.state:
u.x = self.x
u.y = self.y
u.vx = self.vx
u.vy = self.vy
self.state = 1
self.got = u
u.caught = self
self.catchtimer = 3
return True
return False
def throw(self, p, thrust):
if not self.got:
return False
self.got.boost(p, thrust)
self.got.caught = None
self.got = None
self.state = 0
return True
def move(self,t):
super().move(t)
if self.got:
self.got.x = self.x
self.got.y = self.y
self.got.vx = self.vx
self.got.vy = self.vy
def end(self):
super().end()
if self.catchtimer == 2 and self.state:
self.got.caught = None
self.got = None
self.state = 0
if self.catchtimer:
self.catchtimer -= 1
class Snaffle(Unit):
m = 0.5
r = 150
f = 0.75
def __init__(self, mid, vx, vy, x, y):
super().__init__(mid, vx, vy, x, y)
self.caught = None
def move(self, t):
if not self.caught:
super().move(t)
def end(self):
if self.caught:
self.x = self.caught.x
self.y = self.caught.y
self.vx = self.caught.vx
self.vy = self.caught.vy
else:
super().end()
class Bludger(Unit):
m = 8
r = 200
f = 0.9
thrust = 1000
def __init__(self, mid, vx, vy, x, y):
super().__init__(mid, vx, vy, x, y)
self.last = None
class Pole(Unit):
r = 300
m = 99 ** 9
vx = 0
vy = 0
f = 0
def __init__(self, mid, vx, vy, x, y):
super().__init__(mid, vx, vy, x, y)
class Line():
def __init__(self, mid, a, b):
self.mid = mid
self.a = a
self.b = b
def collision(self,u,time):
r = u.r
if type(self) is Goal and type(u) is Snaffle:
r = -1
#vertical line
if self.a.x == self.b.x:
if (u.x + r > 16000 and u.vx > 0) or (u.x - r < 0 and u.vx < 0):
return Collision(self, u, 0.0)
elif u.x < self.a.x - r < u.x + u.vx or u.x > self.a.x + r > u.x + u.vx:
t = (abs(u.x - self.a.x) - r) / abs(u.vx)
y = u.y + t*u.vy
if self.a.y + u.r < y < self.b.y - u.r:
#print("Line collision",u.mid, self.mid,":",u.x,u.y,u.vx,u.vy,t,file=sys.stderr)
if time + t < 1.0:
return Collision(self, u, t)
else:
return None
else:
return None
#horisontal line
if self.a.y == self.b.y:
if (u.y + r > 7500 and u.vy > 0) or (u.y - r < 0 and u.vy < 0):
return Collision(self, u, 0.0)
elif u.y < self.a.y - r < u.y + u.vy or u.y > self.a.y + r > u.y + u.vy:
t = (abs(u.y - self.a.y) - r) / abs(u.vy)
x = u.x + t*u.vx
if self.a.x + u.r < x < self.b.x - u.r:
#print("Line collision",u.mid, self.mid,":",u.x,u.y,u.vx,u.vy,t,file=sys.stderr)
if time + t < 1.0:
return Collision(self, u, t)
else:
return None
else:
return None
def bounce(self, u):
# this is gross oversimplification here. as the lines are only vertical or hoisontal
# vertical line
# print(u.mid, u.x, u.y, u.vx, u.vy, file=sys.stderr, end="\t")
if self.a.x == self.b.x:
# if abs(u.x - self.a.x) != u.r:
# print("OFF",self.mid,u.mid,u.x,self.a.x,file=sys.stderr)
# else:
# print("ON:",self.mid,u.mid,u.x,self.a.x,file=sys.stderr)
u.vx = -u.vx
# horisontal line
if self.a.y == self.b.y:
# if abs(u.y - self.a.y) != u.r:
# print("OFF",self.mid,u.mid,u.y,self.a.y,file=sys.stderr)
# else:
# print("ON:",self.mid,u.mid,u.y,self.a.y,file=sys.stderr)
u.vy = -u.vy
#print(u.vx, u.vy, file=sys.stderr)
class Goal(Line):
def __init__(self, mid, a, b):
super().__init__(mid, a, b)
def bounce(self, u):
if type(u) is Snaffle:
u.mid = None
u.vx = 0
u.vy = 0
if self.mid == 'gw':
u.x = -1000
u.y = 3750
return 1
else:
u.x = 17000
u.y = 3750
return 0
else:
super().bounce(u)
class Arena:
el = (
Pole('nw', 0, 0, 0, 1750),
Pole('sw', 0, 0, 0, 5750),
Pole('ne', 0, 0, 16000, 1750),
Pole('se', 0, 0, 16000, 5750),
Line('n', Point(0, 0), Point(16000, 0)),
Line('s', Point(0, 7500), Point(16000, 7500)),
Line('nw', Point(0, 0), Point(0, 1450)),
Goal('gw', Point(0, 2050), Point(0, 5450)),
Line('sw', Point(0, 6050), Point(0, 7500)),
Line('ne', Point(16000, 0), Point(16000, 1450)),
Line('se', Point(16000, 6050), Point(16000, 7500)),
Goal('ge', Point(16000, 2050), Point(16000, 5450))
)
def delta_angle(alpha, beta):
phi = abs(beta - alpha) % (2 * math.pi)
return phi if phi < math.pi else 2 * math.pi - phi
def play(entities):
eID = range(len(entities))
# for eid in eID:
# S = entities[eid]
# print(eid, S.x, S.y, S.vx, S.vy, type(S), sep="\t", file=sys.stderr)
t = 0.0
n = 0
past_collision = {}
while t < 1.0:
if n > 100:
exit("INF LOOP")
first_collision = None
for i in range(len(eID)-1):
if not entities[eID[i]].mid:
continue
for el in Arena.el:
col = el.collision(entities[eID[i]], t)
if col and col.t <= 0.0001 and (col.b.mid, col.a.mid) in past_collision:
continue
if col and (not first_collision or col.t < first_collision.t):
first_collision = col
if col.t == 0.0:
break
for j in range(i + 1, len(eID)):
if not entities[eID[j]].mid:
continue
col = entities[eID[j]].collision(entities[eID[i]], t)
if col and col.t <= 0.0001 and (col.b.mid, col.a.mid) in past_collision:
continue
if col and (not first_collision or col.t < first_collision.t):
first_collision = col
if col.t == 0.0:
break
if not first_collision:
for eid in eID:
if not entities[eid].mid:
continue
entities[eid].move(1.0 - t)
t = 1.0
else:
if first_collision.t > 0.0:
for eid in eID:
if not entities[eid].mid:
continue
#u = entities[eid]
#print(u.mid, u.x, u.y, "-->", end=" ", file=sys.stderr)
entities[eid].move(first_collision.t)
#print(u.x, u.y, "[", first_collision.t, "]", file=sys.stderr)
t += first_collision.t
past_collision[first_collision.b.mid, first_collision.a.mid] = t
if type(first_collision.b) is Wizard and type(first_collision.a) is Snaffle:
print(first_collision.b.mid, "caught",first_collision.a.mid,file=sys.stderr)
first_collision.b.catch(first_collision.a)
else:
# print("bounce", first_collision.a.mid, first_collision.b.mid, first_collision.t, type(first_collision.a), type(first_collision.b), file=sys.stderr)
first_collision.a.bounce(first_collision.b)
if type(first_collision.a) is Bludger and type(first_collision.b) is Wizard:
first_collision.a.last = first_collision.b
# print("time in turn:", t, file=sys.stderr)
n+=1
for eid in eID:
if not entities[eid].mid:
continue
entities[eid].end()
# my_team_id = int(input()) # if 0 you need to score on the right of the map, if 1 you need to score on the left
#
# mteam = {}
# oteam = {}
# bludg = {}
# snaff = {}
# entities = {}
#
# # game loop
# while True:
# sTime = timer()
# entities = int(input()) # number of entities still in game
# for i in range(entities):
# # entity_id: entity identifier
# # entity_type: "WIZARD", "OPPONENT_WIZARD" or "SNAFFLE" (or "BLUDGER" after first league)
# # x: position
# # y: position
# # vx: velocity
# # vy: velocity
# # state: 1 if the wizard is holding a Snaffle, 0 otherwise
# entity_id, entity_type, x, y, vx, vy, state = input().split()
# entity_id = int(entity_id)
# x = int(x)
# y = int(y)
# vx = int(vx)
# vy = int(vy)
# state = int(state)
# if entity_type == 'WIZARD':
# mteam[entity_id] = Wizard(entity_id, vx, vy, x, y, state)
# entities[entity_id] = mteam[entity_id]
# if entity_type == 'OPPONENT_WIZARD':
# oteam[entity_id] = Wizard(entity_id, vx, vy, x, y, state)
# entities[entity_id] = oteam[entity_id]
# if entity_type == 'SNAFFLE':
# snaff[entity_id] = Snaffle(entity_id, vx, vy, x, y)
# entities[entity_id] = snaff[entity_id]
# if entity_type == 'BLUDGER':
# bludg[entity_id] = Bludger(entity_id, vx, vy, x, y)
# entities[entity_id] = bludg[entity_id]
#
# eID = sorted(entities)
# for eid in eID:
# S = entities[eid]
# print(eid, S.x, S.y, S.vx, S.vy, type(S), sep="\t", file=sys.stderr)
# t = 0.0
# pastCol = {}
# while t < 1.0:
# fcol = None
# for i in range(len(eID)):
# for j in range(i + 1, len(eID)):
# col = entities[eID[i]].collision(entities[eID[j]])
# if col and col.t < 0.1 and (col.a.mid, col.b.mid) in pastCol:
# continue
# if col and col.t + t < 1.0 and (not fcol or col.t < fcol.t):
# fcol = col
# if not fcol:
# for eid in eID:
# entities[eid].move(1.0 - t)
# t = 1.0
# else:
# print("collision", fcol.a.mid, fcol.b.mid, fcol.t, file=sys.stderr)
# for eid in eID:
# entities[eid].move(fcol.t - t)
# if type(fcol.a) is Wizard and type(fcol.b) is Snaffle:
# fcol.a.catch(fcol.b)
# elif type(fcol.a) is Snaffle and type(fcol.b) is Wizard:
# fcol.b.catch(fcol.a)
# else:
# fcol.a.bounce(fcol.b)
# t += fcol.t
# pastCol[fcol.a.mid, fcol.b.mid] = t
# print("time in turn:", t, file=sys.stderr)
# for eid in eID:
# entities[eid].end()
# for eid in sorted(entities):
# S = entities[eid]
# print(eid, S.x, S.y, S.vx, S.vy, sep="\t", file=sys.stderr)
#
# for i in range(2):
# # Write an action using print
# # To debug: print("Debug messages...", file=sys.stderr)
#
#
# # Edit this line to indicate the action for each wizard (0 <= thrust <= 150, 0 <= power <= 500)
# # i.e.: "MOVE x y thrust" or "THROW x y power"
# X = str(random.randint(0, 16000))
# Y = str(random.randint(0, 7500))
# print("MOVE", X, Y, "100")
# print("Timing:", round(timer() - sTime, 5), file=sys.stderr)
|
6df2e08197f766370b9ea1a4e9a33f9563d85c50 | olaudemy/litsp | /bracket_checker.py | 483 | 3.734375 | 4 | def balance_checker(data):
pocket = []
left_br = "{[("
right_br = "}])"
for i in data:
if i in left_br:
pocket.append(right_br[ left_br.index(i) ])
elif i in right_br:
if pocket and i == pocket[-1]:
pocket.pop(-1)
else:
print("No balance at check_it")
return
if pocket:
print("No balance at check_it")
else:
print("The world has balanced check_it")
|
bb3f951f4b11b64a18002ffa77bd6880bff60b37 | MesutCevik/AlexaSkillsNew | /Miscellaneous/decorators4learning/functions_returning_functions.py | 193 | 4.0625 | 4 | def f(x):
""" This function returns the function 'g' which is inside function. """
def g(y):
return y + x + 3
return g
nf1 = f(1)
nf2 = f(3)
print(nf1(1))
print(nf2(1))
|
48062dcd3b54044bc64c0c497a47da3f8640724c | MesutCevik/AlexaSkillsNew | /Miscellaneous/decorators4learning/functions_as_parameters_2.py | 247 | 3.625 | 4 | import math
def foo(func):
print("The function " + func.__name__ + " was passed to foo.")
result = 0
for x in [1, 2, 2.5]:
result += func(x)
print(result)
return result
print(foo(math.sin))
print(foo(math.cos))
|
aed0bc3fcbdc63e47a4cea6d15c0903db82760a8 | Ovsjah/gothonweb_py | /gothonweb/parser.py | 2,650 | 3.625 | 4 | class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, obj):
self.subject = subject[1]
self.verb = verb[1]
self.object = obj[1]
def edit(self):
return "%s %s %s" % (self.subject,
self.verb, self.object)
class Subject(object):
def parse_subject(self, data):
self.data = data
Stuff().skip(data, 'stop word')
Stuff().skip(data, 'error')
next_word = Stuff().peek(data)
if next_word == 'noun':
return Stuff().match(data, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
class Verb(object):
def parse_verb(self, data):
self.data = data
Stuff().skip(data, 'stop word')
Stuff().skip(data, 'error')
next_word = Stuff().peek(data)
if next_word == 'verb':
return Stuff().match(data, 'verb')
else:
raise ParserError("Expected a verb next.")
class Object(object):
def parse_object(self, data):
self.data = data
Stuff().skip(data, 'stop word')
Stuff().skip(data, 'error')
next_word = Stuff().peek(data)
if next_word == 'noun':
return Stuff().match(data, 'noun')
elif next_word == 'direction':
return Stuff().match(data, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
class Stuff(Subject, Verb, Object):
def __init__(self):
pass
def parse_sentence(self, data):
self.data = data
subj = Subject().parse_subject(data)
verb = Verb().parse_verb(data)
obj = Object().parse_object(data)
return Sentence(subj, verb, obj)
def peek(self, data):
self.data = data
if data:
word = data[0]
return word[0]
else:
return None
def match(self, data, exp):
self.data = data
self.exp = exp
if data:
word = data.pop(0)
if word[0] == exp:
return word
else:
return None
else:
return None
def skip(self, data, word_type):
self.data = data
self.word_type = word_type
while self.peek(data) == word_type:
self.match(data, word_type)
|
022095f6b832b23007e8b7c487a06037f849e9d5 | DARRIUS-LK/celcius-to-fahrenheit | /temp2.py | 123 | 3.953125 | 4 | celcius = input('please input celcius:' )
celcius = float(celcius)
fahrenheit = celcius * 9 / 5 + 32
print(fahrenheit, 'f') |
c3833a93466dbc82202bb5fc973e65bd6c552129 | DolanDark/Practice-Files | /prog03.py | 318 | 3.84375 | 4 | n = int(input())
if n == 0:
print("Time estimate is 0 minutes")
elif n in range(1, 2000):
print("Time estimate is 25 minutes")
elif n in range(2001,4000):
print("Time estimate is 35 minutes")
elif n in range(4001, 7000):
print("Time estimate is 45 minutes")
else:
print("invalid input") |
d61d34b7f14afa23557ae0f777b3307ed3bf56ff | DolanDark/Practice-Files | /hamletprog.py | 1,929 | 3.640625 | 4 | import collections
import matplotlib.pyplot as plt
hamlet = '''To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die—to sleep,
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to: 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep, perchance to dream—ay, there's the rub:
For in that sleep of death what dreams may come,
When we have shuffled off this mortal coil,
Must give us pause—there's the respect
That makes calamity of so long life.
For who would bear the whips and scorns of time,
Th'oppressor's wrong, the proud man's contumely,
The pangs of dispriz'd love, the law's delay,
The insolence of office, and the spurns
That patient merit of th'unworthy takes,
When he himself might his quietus make
With a bare bodkin? Who would fardels bear,
To grunt and sweat under a weary life,
But that the dread of something after death,
The undiscovere'd country, from whose bourn
No traveller returns, puzzles the will,
And makes us rather bear those ills we have
Than fly to others that we know not of?
Thus conscience doth make cowards of us all,
And thus the native hue of resolution
Is sicklied o'er with the pale cast of thought,
And enterprises of great pith and moment
With this regard their currents turn awry
And lose the name of action.'''
dic1 = {}
for i in hamlet:
if i in dic1:
dic1[i] = dic1[i] + 1
else:
dic1[i] = 1
print(dic1)
X,Y = zip(*dic1.items())
plt.bar(X, Y)
plt.show()
dic2 = {}
for j in hamlet:
dic2[j] = dic2.get(j, 0)+1
print(dic2)
plt.bar(dic2.keys(), dic2.values())
plt.show()
count = collections.Counter(hamlet)
print(count)
plt.bar(count.keys(), count.values())
plt.show()
|
16d8012778a0a4b005ff28bf8af8b0e669e3eba7 | DolanDark/Practice-Files | /prog05.py | 732 | 3.859375 | 4 | interior_wall = int(input())
exterior_wall = int(input())
if interior_wall: #checks for true value
in_wall = []
for i in range(interior_wall):
in_wall.append(float(input()))
if exterior_wall:
ex_wall = []
for i in range(exterior_wall):
ex_wall.append(float(input()))
if interior_wall < 0 or exterior_wall < 0:
print("Invalid Input")
exit()
if exterior_wall and interior_wall:
print(f" Total cost {sum(in_wall) * 18 + sum(ex_wall) * 12} INR")
else:
if exterior_wall:
print(f" Total cost {sum(ex_wall) * 12} INR")
elif interior_wall:
print(f" Total cost {sum(in_wall) * 18} INR")
else:
print("Total cost is zero") |
24b14caef5e04fe94d320e851c2d22c9e43102e5 | DolanDark/Practice-Files | /prog18.py | 339 | 3.875 | 4 | x = int(input())
y = int(input())
smallest = x if x < y else y
isCoprime = True
for i in range(smallest):
if i > 1:
if x % i == 0 and y % i == 0:
isCoprime = False
break
print(isCoprime)
# from math import gcd
#
# if gcd(x,y) == 1:
# print("True")
# else:
# print("False") |
70fe8fdf2f0d12b61f21f5d9bd825d2f0a0ec93f | LiuJLin/learn_python_basic | /ex32.py | 639 | 4.53125 | 5 | the_count = [1, 2, 3, 4, 5]
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d"% number)
#also we can go through mixed lists too
#notice we have use %r since we don't know what's in it
for i in change:
print("I got %r"% i)
#we can also build lists, first start with an empty one
elements = []
#the use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list."% i)
#append is a function that lists Understanding
elements.append(i)
for i in elements:
print("Elements was: %d"% i)
|
552b709ecd6407b5e22fbebcd3315281227ca631 | ichlasiana/project-euler | /scripts/p006.py | 782 | 3.59375 | 4 | # Sum square difference
# https://projecteuler.net/problem=6
# Problem 6
# The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
# 3025 - 385 = 2640
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def p006(n):
sum_of_squares = n * (n + 1) * (2 * n + 1) // 6 # Formula: [n(n + 1)(2n + 1)] / 6
square_of_sum = (n * (n + 1) // 2) ** 2 # Formula: [n(n + 1) // 2] ^ 2
return square_of_sum - sum_of_squares
p006(10) # Expected Output: 2640
|
1d9bdb0de6584f4f7aefd63da7a1638a3954a3c8 | nico-olivares22/CompuacionII-Practica | /GuiaPráctica-COMPUTACIONII/ejercicio13.py | 818 | 3.921875 | 4 | """Ejercicio 13 – Multiprocessing
Escribir un programa que genere tres procesos hijos (fork) cuyos nombres serán
“Hijo1”, “Hijo2” e “Hijo3”.
El proceso padre debe mostrar por pantalla el mensaje “Lanzando hijo NN” en la
medida que ejecuta cada uno de los procesos.
Cada hijo que se lance mostrará por pantalla su pid, el pid de su padre, esperará un
segundo, y luego terminará.
El padre debe esperar a la terminación de sus hijos."""
import os
import time
from multiprocessing import Process
#función reducida en 1
def childProcess(x, pid):
print("Process -", x, ", PID Hijo:", os.getpid(), ", PID Padre:", pid)
# Padre
if __name__ == '__main__':
pid = os.getpid()
for x in range(1, 4):
p = Process(target=childProcess, args=(x, pid))
p.start()
p.join()
|
ac4da547e6797940cd9c206f948a4e00454d3af5 | youngtux/python | /02_06_while문_list_sort.py | 257 | 3.59375 | 4 | # 5개의 값을 입력받아서 크기순으로 출력
# while문, list사용법
d_list = []
cnt = 1
while cnt<6 :
d = input(str(cnt)+"번째 값을 입력하세요.:")
d_list.append(d)
cnt = cnt + 1
d_list.sort()
print(d_list)
|
9d1cb5e2ec644a4efd28779d7f170161e132fd4b | Phongkaka/python | /TrinhTienPhong_92580_CH04/Exercise/page_114_exercise_03.py | 1,076 | 4.03125 | 4 | """
Author: Trịnh Tiến Phong
Date: 20/10/2021
Program: page_114_exercise_03.py
Problem:
3. Translate each of the following numbers to binary numbers:
a. 47(8)
b. 127(8)
c. 64(8)
* * * * * ============================================================================================= * * * * *
Solution:
Result:
a. 100111
b. 1010111
c. 110100
"""
def swapTen(decimal):
if decimal == 0:
print(0)
else:
bitString = ''
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
return bitString
def swapEight(decimal):
a = decimal
length = len(decimal)
decimal = int(decimal)
total = 0
for i in range(0, length):
index = decimal % 10
total += (index * pow(8, i))
decimal //= 10
print("The binary representation of", str(a), "is", swapTen(total))
# main
element = ['47', '127', '64']
swap = []
for decimal in element:
swap.append(swapEight(decimal))
|
a23918b8be59403c251423abdf493a3f5cd9106f | Phongkaka/python | /TrinhTienPhong_92580_CH03/Exercise/page_92_exercise_01.py | 594 | 3.96875 | 4 | """
Author: Trịnh Tiến Phong
Date: 05/10/2021
Program: page_92_exercise_01.py
Problem:
1. Translate the following for loops to equivalent while loops:
a. for count in range(100):
print(count)
b. for count in range(1, 101):
print(count)
c. for count in range(100, 0, -1):
print(count)
Solution:
"""
# a
countA = 0
while 0 <= countA < 100:
print(countA)
countA += 1
# b
countB = 1
while 0 < countB < 101:
print(countB)
countB += 1
# c
countC = 100
while 0 < countC <= 100:
print(countC)
countC -= 1
|
8b8945a9936304593b65b5648bcb882365ba5ad3 | Phongkaka/python | /TrinhTienPhong_92580_CH05/Exercise/page_145_exercise_06.py | 469 | 4.1875 | 4 | """
Author: Trịnh Tiến Phong
Date: 31/10/2021
Program: page_145_exercise_06.py
Problem:
6. Write a loop that replaces each number in a list named data with its absolute value
* * * * * ============================================================================================= * * * * *
Solution:
Display result:
[21, 12, 20, 5, 26, 11]
"""
data = [21, -12, 20, 0, -5, 26, -11]
for item in range(0, len(data)):
data[item] = abs(data[item])
print(data)
|
6e37562c7ffed2695bf99118657aabbc986aaa88 | Phongkaka/python | /TrinhTienPhong_92580_CH03/Exercise/page_70_exercise_05.py | 381 | 4.03125 | 4 | """
Author: Trịnh Tiến Phong
Date: 03/10/2021
Program: page_70_exercise_05.py
Problem:
5. Assume that the variable teststring refers to a string. Write a loop that prints
each character in this string, followed by its ASCII value.
Solution:
Display:
p = 112; h = 104; o = 111; n = 110; g = 103
"""
name = "phong"
for i in name:
print(i, "=", ord(i), end="; ")
|
8fcae316dc7717b1eeb735f53c49866940c63e27 | Phongkaka/python | /TrinhTienPhong_92580_CH02/Exercise/page_46_exercise_01.py | 457 | 3.984375 | 4 | """
Author: Trinh Tien Phong
Date: 25/09/2021
Program: page_46_exercise_01.py
Problem:
1. Let the variable x be "dog"and the variable y be "cat". Write the values returned
by the following operations:
a. x +y
b. "the " +x +" chases the " +y
c. x * 4
Solution:
Display:
a. dogcat
b. the dog chases the cat
c. dogdogdogdog
"""
x = "dog"
y = "cat"
print(x + y)
print("the " + x + " chases the " + y)
print(x * 4)
|
e70cff4332c025e17994eee544699d2cfd7f0c53 | Phongkaka/python | /TrinhTienPhong_92580_CH04/Exercise/test.py | 435 | 3.890625 | 4 | """
Author: Trịnh Tiến Phong
Date: 20/10/2021
Program: page_114_exercise_05.py
Problem:
5. Translate each of the following numbers to decimal numbers:
a. 47(16)
b. 127(16)
c. AA(16)
* * * * * ============================================================================================= * * * * *
Solution:
Result:
a. 71
b. 295
c. 170
"""
data = "hello uda!"
print(data.find("uda")) |
0de84e9a8943307e88a2ab6d48bb9c5b1b8be86b | larwon/python | /Pandas_pt(2).py | 398 | 3.78125 | 4 | import numpy as np
import pandas as pd
#여러 개의 값들을 딕셔너리 값으로 넣어보자
a = pd.DataFrame([{'A':2, 'B':4, 'D':3}, {'A':4, 'B':5, 'C':7}])
print(a)
#총 칼럼은 A, B, C, D
#값이 없는 부분은 NaN으로 처리 (누락값)
s = pd.DataFrame(np.random.rand(5, 5),
columns=['A', 'B', 'C', 'D', 'E'],
index=[1, 2, 3, 4, 5])
print(s) |
986f69b9c6625f12928e4c213269310528eac0b3 | larwon/python | /bool.py | 191 | 3.8125 | 4 | # 101.
print(3 == 5)
# 102.
x = 4
print(1 < x < 5)
# 103.
print((3 == 3) and (4 != 3))
# 104.
if 4 < 3:
print("Hello World")
else:
print("Hi, there.")
|
a45f4958e8059b9bfef7fefcb123dcd4907c394c | larwon/python | /baekjoon_pt_2.py.py | 883 | 3.8125 | 4 | 1.
a = int(input("첫번째 숫자를 입력해주세요."))
b = int(input("두번째 숫자를 입력해주세요."))
if a > b:
print(">")
elif a == b:
print("==")
else:
print("<")
2.
a = int(input("시험성적을 입력해주세요 : "))
if 90 <= a <= 100:
print("A")
elif 80 <= a <= 89:
print("B")
elif 70 <= a <= 79:
print("C")
elif 60 <= a <=69:
print("D")
else:
print("F")
3.
a = int(input("연도를 입력해주세요"))
if ((a % 4 == 0 and a % 100 != 0) or (a % 400 == 0)):
print(1)
else:
print(0)
4.
a = int(input("x축을 입력해주세요 : "))
b = int(input("y축을 입력해주세요 : "))
if (a > 0 and b > 0):
print("Quadrant 1")
elif (a < 0 and b > 0):
print("Quadrant 2")
elif (a < 0 and b < 0):
print("Quadrant 3")
else:
print("Quadrant 4")
|
7d0d49210ba96496330d1519b07ef4137c74f09e | mmqfilho/jogo_da_velha | /velha_oo.py | 3,903 | 3.96875 | 4 | """
Jogo da velha
campos do tabuleiro
1 | 2 | 3
-----------
4 | 5 | 6
-----------
7 | 8 | 9
"""
class JogoDaVelha:
def __init__(self):
# inicializa tabuleiro
self._inicializa_tabuleiro()
# sequencia de possibilidades para se ganhar o jogo
self.possibilidades = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]
# valores dos jogadores
self.jogador_x = 1
self.jogador_o = -1
# sempre vou começar com o jogador X
self.jogador_atual = self.jogador_x
# indica o numero de jogadas em andamento
self.jogadas = 0
"""
campos do tabuleiro iniciam com valor 0 (zero)
"""
def _inicializa_tabuleiro(self):
self.tabuleiro = {x + 1: 0 for x in range(9)}
"""
Marca a casa jogada
"""
def _executa_jogada(self, casa):
if casa > 9:
raise()
self.tabuleiro[casa] = self.jogador_atual
self.jogadas += 1
"""
Faz a alternancia dos jogadores
"""
def _troca_jogador(self):
if self.jogador_atual == self.jogador_x:
self.jogador_atual = self.jogador_o
else:
self.jogador_atual = self.jogador_x
"""
verifica se o jogador atual ganhou o jogo
"""
def _verifica_ganhador(self):
for i in self.possibilidades:
ganhou = 0
for n in i:
if self.tabuleiro[n] == self.jogador_atual:
ganhou += 1
if ganhou == 3:
return True
return False
"""
Verifica se houve empate
"""
def _verifica_empate(self):
if self.jogadas >= 9:
return True
else:
return False
"""
Indica qual jogador deve iniciar o jogo
Se o jogo já iniciou retorna False
"""
def set_jogador(self, jogador='X'):
if self.jogadas == 0:
if jogador.upper() == 'O':
self.jogador_atual = self.jogador_o
else:
self.jogador_atual = self.jogador_x
return True
else:
return False
"""
Retorna o rótulo do jogador
"""
def get_jogador(self):
if self.jogador_atual == self.jogador_x:
return 'X'
else:
return 'O'
"""
Exibe estado atual do tabuleiro
X ou O em casas já jogadas ou o numero da casa em casas vazias
"""
def exibe_tabuleiro(self):
t = {}
for k in self.tabuleiro.keys():
if self.tabuleiro[k] == self.jogador_x:
t[k] = 'X'
elif self.tabuleiro[k] == self.jogador_o:
t[k] = 'O'
else:
t[k] = k
print('''
{} | {} | {}
-----------
{} | {} | {}
-----------
{} | {} | {}
'''.format(t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9]))
"""
Logica principal do jogo
"""
def jogar(self):
while not self._verifica_ganhador() and not self._verifica_empate():
try:
self.exibe_tabuleiro()
casa = int(input(f'Jogador {self.get_jogador()}, selecione um campo: '))
self._executa_jogada(casa)
if not self._verifica_ganhador():
self._troca_jogador()
except Exception:
print('Jogada inválida, informe o numero de uma casa não jogada!')
# exibe informação de vitpria
if self._verifica_ganhador():
self.exibe_tabuleiro()
print(f'Jogador {self.get_jogador()} GANHOU o jogo')
# exibe informação de empate
if self._verifica_empate():
self.exibe_tabuleiro()
print('O jogo acabou EMPATADO')
v = JogoDaVelha()
v.jogar()
|
fc399182e128c75611add67a65ddfe18d180dc55 | gamershen/everything | /hangman.py | 1,151 | 4.25 | 4 |
import random
with open(r'C:\Users\User\Desktop\תכנות\python\wordlist.txt', 'r') as wordfile:
wordlist = [line[:-1] for line in wordfile] # creates a list of all the words in the file
word = random.choice(wordlist) # choose random word from the list
letterlist = [letter for letter in word] # the word converted into a list of letters
secretlist = ['_' for letter in word] # the secret word as ( _ _ _ )
print('start playing\n')
print(' '.join(secretlist) + '\n')
def start_playing():
guess = input('guess a letter: ')
while len(guess) > 1 or (not (guess >= 'a' and guess <= 'z')) and (not (guess >= 'A' and guess <= 'Z')):
guess = input('that aint a letter,guess a letter: ') # char validation
[secretlist.pop(i) and secretlist.insert(i, char) for i, char in enumerate(word) if guess == char] # if guess is correct show the letter
print('\n' + ' '.join(secretlist))
for i in range(15):
start_playing()
print('tries left: ' + str(14 - i))
if letterlist == secretlist:
print('you won!')
break
if not letterlist == secretlist:
print(f'you lost! the word was: {word}')
|
44d385d04ffed3c7ced324d1599b83a01cbecce8 | tirsott/lc-go | /problems/0206.reverse-linked-list/reverse-linked-list.py | 692 | 3.921875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
old_head = head
while head.next:
new_head = head.next
head.next = new_head.next
new_head.next = old_head
old_head = new_head
return new_head
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
l1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
l2 = Solution().reverseList(l1)
while l2:
print(l2.val)
l2 = l2.next |
f04e141c5c6b2ce197e530bcb1bfd1eeabaf9cfa | tirsott/lc-go | /problems/0127.word-ladder/word-ladder.py | 2,856 | 3.515625 | 4 | from typing import List
import time as tt
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
neighbor = [[] for _ in range(len(wordList))]
start = [i for i in range(len(wordList)) if self.word_diff(beginWord,
wordList[i])]
end = [i for i in range(len(wordList)) if self.word_diff(endWord,
wordList[i])]
d = {}
for i in range(len(wordList)):
for j in range(len(wordList[i])):
if wordList[i][:j] + '*' + wordList[i][j+1:] not in d:
d[wordList[i][:j] + '*' + wordList[i][j+1:]] = [i]
else:
d[wordList[i][:j] + '*' + wordList[i][j + 1:]].append(i)
for k, v in d.items():
for i in range(len(v)):
neighbor[v[i]] = list(set(neighbor[v[i]] + v[:i] + v[i+1:]))
time = 2
if wordList.index(endWord) in start:
return time
while 1:
if [x for x in start if x in end]:
return time + 1
for i in start:
if not neighbor[i]:
neighbor[i] = [x for x in range(len(wordList)) if
self.word_diff(
wordList[i], wordList[x])]
for i in end:
if not neighbor[i]:
neighbor[i] = [x for x in range(len(wordList)) if
self.word_diff(
wordList[i], wordList[x])]
temp_start = list(set([x for j in [neighbor[i] for i in start] for
x in j] + start))
temp_end = list(set([x for j in [neighbor[i] for i in end] for
x in j] + end))
if [x for x in temp_start if x in end] or [x for x in temp_end if
x in start]:
return time + 2
if [x for x in temp_start if x in temp_end]:
return time + 3
if temp_start == start and temp_end == end:
return 0
time += 2
start = temp_start
end = temp_end
def word_diff(self, a ,b):
count = 0
for i in range(len(a)):
if a[i] != b[i]:
count += 1
if count > 1:
return False
return count == 1
#beginWord = "hit",
# endWord = "cog",
# wordList = ["hot","dot","dog","lot","log","cog"]
t = tt.time()
print(Solution().ladderLength("hit",
"cog",
["hot","dot","dog","lot","log","cog"]))
print(tt.time()-t) |
67a7cc30af26b12944b6ca1cd537455c14e6b50a | tirsott/lc-go | /problems/0007.reverse-integer/reverse-integer.py | 384 | 3.65625 | 4 | class Solution:
def reverse(self, x: int) -> int:
if x < 0:
x = - x
flag = -1
else:
flag = 1
res = 0
while x:
res = res * 10 + x % 10
x = x // 10
return res * flag if res * flag in range(-2 ** 31, 2 ** 31 - 1) else 0
if __name__ == '__main__':
print(Solution().reverse(-123)) |
effef5664a2dfb8f36d29722cf74934b58b542fb | tirsott/lc-go | /problems/0244.shortest-word-distance-ii/shortest-word-distance-ii.py | 702 | 3.6875 | 4 | from typing import List
class WordDistance:
def __init__(self, words: List[str]):
self.position = self._get_position(words)
def _get_position(self, words):
position = {}
for i in range(len(words)):
if words[i] in position:
position[words[i]].append(i)
else:
position[words[i]] = [i]
return position
def shortest(self, word1: str, word2: str) -> int:
return min([abs(x - y) for x in self.position[word1] for y in
self.position[word2]])
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2) |
f7d93b0f5a01ee074720d58f497d7ff0e4e1b27c | tirsott/lc-go | /problems/0048.rotate-image/rotate-image.py | 631 | 3.84375 | 4 | from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
'''
123
456
789
'''
length = len(matrix[0])
for i in range(length):
for j in range(length//2):
matrix[i][j], matrix[i][length-j-1] = matrix[i][length-j-1], matrix[i][j]
for i in range(length):
for j in range(length-i-1):
matrix[i][j], matrix[length-j-1][length-i-1] = matrix[length-j-1][length-i-1], matrix[i][j]
return |
40c7045b476223a743db0bff8cd7860353b34924 | tirsott/lc-go | /problems/0014.longest-common-prefix/longest-common-prefix.py | 504 | 3.8125 | 4 | from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ''
if not strs:
return res
shortest_length = min([len(str) for str in strs])
for i in range(shortest_length):
for str in strs:
if str[i] != strs[0][i]:
return res
res += strs[0][i]
return res
if __name__ == '__main__':
print(Solution().longestCommonPrefix(["dog","racecar","car"])) |
719a154003be326e640c0e882cba3c3ca07d5034 | tirsott/lc-go | /problems/0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.py | 637 | 3.53125 | 4 | from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if nums[0] < nums[-1]:
return nums[0]
mid = (len(nums) + 1) // 2
if nums[mid-1] > nums[mid]:
return nums[mid]
else:
if nums[mid-1] < nums[-1]:
return self.findMin(nums[:mid])
else:
return self.findMin(nums[mid:])
# 输入: [4,5,6,7,0,1,2]
# 输出: 0
# 12345
# 23451
# 34512
# 45123
# 51234
import time
t = time.time()
print(Solution().findMin([2,2,2,0,1]))
print(time.time()-t)
|
ac356398b8b66a16bc346af15b5671cfe72c0c99 | tirsott/lc-go | /problems/0189.rotate-array/rotated-array.py | 957 | 3.671875 | 4 | from typing import List
import math
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums[:] = self.rotate_nums(nums, k)
def rotate_nums(self, nums, k):
if k == 0:
return nums
for i in range(math.ceil(len(nums)/k)-1):
for j in range(k):
if (i+1) * k + j < len(nums):
nums[j], nums[(i+1) * k + j] = nums[(i+1) * k + j], nums[j]
if len(nums)%k == 0:
return nums
else:
return self.rotate_nums(nums[:k], k-len(nums)%k) + nums[k:]
# 输入: [1,2,3,4,5,6,7] 和 k = 3
# 输出: [5,6,7,1,2,3,4]
# 解释:
# 向右旋转 1 步: [7,1,2,3,4,5,6]
# 向右旋转 2 步: [6,7,1,2,3,4,5]
# 向右旋转 3 步: [5,6,7,1,2,3,4]
# print(Solution().rotate_nums([1,2,3,4,5,6,7], 3))
n = [1,2,3,4,5,6,7]
Solution().rotate(n, 3)
print(n) |
bae7e2709c16062e4296992c94140dd2a7eb2aed | tirsott/lc-go | /problems/0056.merge-intervals/merge-intervals.py | 607 | 3.609375 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])
left = 0
while left < len(intervals):
if left == 0:
left += 1
continue
if intervals[left][0] <= intervals[left-1][1]:
intervals[left-1] = [intervals[left-1][0], max(intervals[left-1][1], intervals[left][1])]
intervals.pop(left)
else:
left += 1
return intervals
print(Solution().merge([[1,3],[2,6],[8,10],[15,18]])) |
f9903bbf4aef77ba0ab3d933e7fdd6ae6e5b7abf | tirsott/lc-go | /problems/0247.strobogrammatic-number-ii/strobogrammatic-number-ii.py | 650 | 3.59375 | 4 | from typing import List
class Solution:
def findStrobogrammatic(self, n: int) -> List[str]:
mapping = {'1': '1', '6': '9', '8': '8', '9': '6', '0': '0'}
dp = [[] for _ in range(max(3, (n+1)))]
dp[0] = []
dp[1] = ['1', '8', '0']
if n == 1:
return dp[1]
dp[2] = ['11', '69', '88', '96', '00']
for i in range(3, n+1):
for x in dp[i-2]:
for y in mapping.keys():
dp[i].append(y+x+mapping[y])
return [x for x in dp[n] if not x.startswith('0')]
print(Solution().findStrobogrammatic(3))
print(Solution().findStrobogrammatic(4)) |
55eb3b4f08361c1d4ce6b7d79285ee398db50759 | tirsott/lc-go | /problems/0087.scramble-string/scramble-string.py | 817 | 3.609375 | 4 | class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
print(s1, s2)
if s1 == s2:
return True
for i in range(1, len(s1)):
if self.str_has_same_char(s1[:i], s2[:i]):
if self.isScramble(s1[:i], s2[:i]) and self.isScramble(
s1[i:], s2[i:]):
return True
elif self.str_has_same_char(s1[:i], s2[len(s1)-i:]):
if self.isScramble(s1[:i], s2[len(s1)-i:]) and self.isScramble(
s1[i:], s2[:len(s1)-i]):
return True
return False
def str_has_same_char(self, s1, s2):
return sorted(s1) == sorted(s2)
print(Solution().isScramble('abcdbdacbdac', 'bdacabcdbdac'))
# "abcdbdacbdac"
# "bdacabcdbdac"
# great rgeat
# abcde caebd
|
88784247731251f6fbfc188c95d1aa879bbff520 | tirsott/lc-go | /problems/0284.peeking-iterator/peeking-iterator.py | 822 | 4.09375 | 4 | class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.temp = []
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if self.temp:
return self.temp[0]
self.temp.append(self.iterator.next())
return self.temp[-1]
def next(self):
"""
:rtype: int
"""
if self.temp:
return self.temp.pop(0)
else:
return self.iterator.next()
def hasNext(self):
"""
:rtype: bool
"""
if self.temp:
return True
return self.iterator.hasNext() |
0ac76313cf2722e7088a118c0956a0c6fa4dfbc5 | tirsott/lc-go | /problems/0186.reverse-words-in-a-string-ii/reverse-words-in-a-string-ii.py | 741 | 3.71875 | 4 | from typing import List
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
left, right = 0, 0
while right < len(s):
while right < len(s) and s[right] != ' ':
right += 1
for i in range((right-left)//2):
s[left+i], s[right-1-i] = s[right-1-i], s[left+i]
right += 1
left = right
# 输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
# 输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
#
s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Solution().reverseWords(s)
print(s) |
cbbabc2107a4db45b6191beb4340ef652811c83e | tirsott/lc-go | /problems/0023.merge-k-sorted-lists/merge-k-sorted-lists.py | 1,469 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from typing import List
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
if len(lists) == 1:
return lists[0]
while len(lists) > 1:
res = []
for i in range(((len(lists)+1) // 2)):
if 2 * i + 1 < len(lists):
res.append(self.mergeTwoLists(lists[2 * i], lists[2 * i + 1]))
else:
res.append(lists[2 * i])
lists = res
res = []
return lists[0]
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
dummy = head
while l1 and l2:
if l1.val < l2.val:
dummy.next = l1
dummy = dummy.next
l1 = l1.next
else:
dummy.next = l2
dummy = dummy.next
l2 = l2.next
if l1:
dummy.next = l1
if l2:
dummy.next = l2
return head.next
if __name__ == '__main__':
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
l3 = ListNode(2)
l3.next = ListNode(6)
print(Solution().mergeKLists([l1,l2,l3])) |
2cb99b1052bcbd14215b3ddfddd76114a1c30e31 | tirsott/lc-go | /problems/0179.largest-number/largest-number.py | 514 | 3.625 | 4 | from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
nums = [str(num) for num in nums]
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] > nums[j] + nums[i]:
nums[i], nums[j] = nums[j], nums[i]
if nums[0] == nums[-1] == '0':
nums = nums[:1]
return ''.join(nums[::-1])
# 输入: [3,30,34,5,9]
# 输出: 9534330
print(Solution().largestNumber([0, 0])) |
00257ca64d744f77e19e34b23ecabb362be0052a | tirsott/lc-go | /problems/0229.majority-element-ii/majority-element-ii.py | 347 | 3.859375 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
return [x for x in set(nums) if nums.count(x) > (len(nums)//3)]
# 示例 1:
#
# 输入:[3,2,3]
# 输出:[3]
#
# 示例 2:
#
# 输入:nums = [1]
# 输出:[1]
#
# 示例 3:
#
# 输入:[1,1,1,3,3,2,2,2]
# 输出:[1,2]
|
301af9471ac7bbbe454c0d558d3f796101d8c647 | tirsott/lc-go | /problems/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.py | 1,518 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.max_path(root)
return self.max_path_sum(root)
def max_path_sum(self, node):
if not node:
return 0
if not node.left and not node.right:
return node.val
if not node.left:
return max(node.val + max(node.right.maxval, 0),
self.max_path_sum(node.right))
if not node.right:
return max(node.val + max(node.left.maxval, 0),
self.max_path_sum(node.left))
return max(node.val + max(node.left.maxval, 0) + max(
node.right.maxval, 0), self.max_path_sum(node.left),
self.max_path_sum(node.right))
def max_path(self, node):
if not node:
return 0
if not node.left and not node.right:
node.maxval = node.val
return node.val
node.maxval = max(max(self.max_path(node.left), 0),
max(self.max_path(node.right), 0)) + node.val
return node.maxval
#[9,6,-3,null,null,-6,2,null,null,2,null,-6,-6,-6]
# -10
# / \
# 9 20
# / \
# 15 7
t = TreeNode(-10, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
t1 = TreeNode(-2, TreeNode(-1))
a = Solution().maxPathSum(t)
print(a)
print(t.left.maxval) |
cb8d2565899a06a9e0af4b79a92364c96eb97df8 | ib407ov/Labs---5 | /Завдання 2.py | 176 | 3.78125 | 4 | n = int(input('You can find the number of digits in the numer: '))
i = 0
while n != 0:
n = n // 10
i += 1
print(n)
print('You have {0} numbers'.format(i)) |
5b419bf68ec5db639c12aaee1b49461eac6fa61a | pankratdodo/dr_quine-42 | /python/Colleen.py | 352 | 3.53125 | 4 | # Comment outside
def another_func():
str = "# Comment outside{0}{0}def another_func():{0} str = {2}{1}{2}{0} print(str.format(chr(10), str, chr(34))){0}{0}if __name__ == '__main__':{0} # Comment inside{0} another_func()"
print(str.format(chr(10), str, chr(34)))
if __name__ == '__main__':
# Comment inside
another_func()
|
fd722b3d1dedacaab9996e5180e08c2f81491bc3 | mateenjameel/Python-Course-Mathematics-Department | /Week 5_GUI Development Tkinter Python/gui_12_FeedBack_FORM.py | 2,714 | 3.53125 | 4 | import tkinter
from tkinter import *
def save():
text=E1.get()+"\n"+E2.get()+"\n"+E3.get()+"\n"+E4.get()+"\n"+E5.get()+"\n"+E6.get()+"\n"+E7.get()+"\n"+E8.get()+"\n"+E9.get()
with open ("text.txt",'w')as f:
f.writelines(text)
nimrah=tkinter.Tk()
nimrah.title("nimrah ansari")
nimrah.geometry('675x590')
title=Label(nimrah,text="STUDENT INFORMATION",font=("areil 20 bold italic "),fg="lightblue").grid(row=0,column=2)
line1=Label(nimrah,text="STUDENT NAME:",font=("Arial 12 bold italic ")).grid(row=1, column=1, padx=20, sticky='w')
E1=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E1.grid(row=1,column=2,pady=10,padx=20,sticky="e")
line2=Label(nimrah,text="FATHER NAME:",font=("Arial 12 bold ")).grid(row=2, column=1, padx=20, sticky='w')
E2=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E2.grid(row=2,column=2,pady=10,padx=20,sticky="e")
line3=Label(nimrah,text="SEAT NUMBER:",font=("Arial 12 bold italic ")).grid(row=3, column=1, padx=20, sticky='w')
E3=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E3.grid(row=3,column=2,pady=10,padx=20,sticky="e")
line4=Label(nimrah,text="SECTION:",font=("Arial 12 bold italic ")).grid(row=4,column=1, padx=20, sticky='w')
E4=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E4.grid(row=4,column=2,pady=10,padx=20,sticky="e")
line5=Label(nimrah,text="DEPARTMENT:",font=("Arial 12 bold italic ")).grid(row=5, column=1, padx=20, sticky='w')
E5=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E5.grid(row=5,column=2,pady=10,padx=20,sticky="e")
line6=Label(nimrah,text="SUBJECT:",font=("Arial 12 bold italic ")).grid(row=6, column=1, padx=20, sticky='w')
E6=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E6.grid(row=6,column=2,pady=10,padx=20,sticky="e")
line7=Label(nimrah,text="DATE OF BIRTH:",font=("Arial 12 bold italic ")).grid(row=7, column=1, padx=20, sticky='w')
E7=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E7.grid(row=7,column=2,pady=10,padx=20,sticky="e")
line8=Label(nimrah,text="PHONE NUMBER:",font=("Arial 12 bold italic ")).grid(row=8, column=1, padx=20, sticky='w')
E8=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E8.grid(row=8,column=2,pady=10,padx=20,sticky="e")
line9=Label(nimrah,text="EMAIL ADDRESS:",font=("Arial 12 bold italic ")).grid(row=9, column=1, padx=20, sticky='w')
E9=Entry(nimrah,bd=5,relief=GROOVE,width=60)
E9.grid(row=9,column=2,pady=10,padx=20,sticky="e")
# to save enter data in txt file
button_quit=Button(nimrah,text="OK",command=save,width=12,height=2,bg="lightblue")
button_quit.grid(row=10,column=2, pady=10)
# to close window
button_quit_1=Button(nimrah,text="Cancel",command=nimrah.destroy,width=12,height=2,bg="lightblue")
button_quit_1.grid(row=12,column=2)
nimrah.mainloop()
|
270cd8531880d6a2ab9054ac5c1bf70f5abf27aa | mateenjameel/Python-Course-Mathematics-Department | /Week 3_Mastering the Loops Part # 2/nested_loop_one.py | 159 | 4 | 4 | side = int(input("Please Enter the side of the square: "))
for i in range(side):
for i in range(side):
print('9', end = ' ')
print()
|
3ac625a4ef5169a8583ca33edbd571c90ad6ee9a | mateenjameel/Python-Course-Mathematics-Department | /Object Oriented Programming/class_19.py | 456 | 3.765625 | 4 | class Vehicle: #parent class
"Parent Class"
def __init__(self, price):
self.price = price
def display(self):
print ('Price = $',self.price)
class Category(Vehicle): #derived class
"Child/Derived class"
def __init__(self, price, name):
Vehicle.__init__(self, price)
self.name = name
def disp_name(self):
print ('Vehicle = ',self.name)
obj = Category(1200, 'BMW')
obj.disp_name()
obj.display()
|
a14b405482d5e61cb494517635f43a28cc9e01bc | mateenjameel/Python-Course-Mathematics-Department | /Week 4_Mastering Functions in Python Programming/function_four.py | 241 | 3.75 | 4 | def Arith(a,n,d):
first_term = int(a)
number = int(n)
difference = int(d)
Answer = first_term + (number - 1)*difference
print("The result of Arithmetic Progression is: ", Answer)
return
Arith(2,10005,2) |
63da190f27e5252b9353562da697106d8e0c63d6 | mateenjameel/Python-Course-Mathematics-Department | /Week 3_Mastering the Loops Part # 2/nested_four.py | 127 | 3.640625 | 4 | for i in range(10):
for j in range(i):#RANGE_OF_J_LOOP_IS_THE_VALUE_OF_OUTER_I
print(i, end=" ")
print() |
dbc8639bf1702af883eec6a0581dabd0ac0fef65 | mateenjameel/Python-Course-Mathematics-Department | /Object Oriented Programming/class_26.py | 641 | 3.546875 | 4 | class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.email = first + '.' + 'last' +'@gmail.com'
self.pay = pay
def fullname(self):
return '{] {}'.format(self.first, self.last)
class Developer(Employee):
def __init__(self,first,last,pay, prog_lang):
super().__init__(first,last,pay)
#Employee.__init__(self,first,last,pay)
self.prog_lang = prog_lang
dev1 = Developer("Ahmed", "Usman", 50000, 'Python')
dev2 = Developer("Furqan", "Asad", 60000,'C++')
print(dev1.email)
print(dev1.prog_lang)
|
efead44c4d9c3ea1b6de8a1868cffc3030911343 | mateenjameel/Python-Course-Mathematics-Department | /Week 14_Integration with Plotting Responses/integration_six.py | 301 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1,3,1000)
def f(x):
return x**2
plt.plot(x,f(x))
plt.axhline(color='red')
plt.fill_between(x, f(x), where = [(x>0) and (x<2) for x in x], color='blue', alpha =0.3)
# alpha is for transparency
plt.show()
|
92d0db25839f0ff639bf6e782bb8733a2e39ccfb | LoganG-T/SpotifyDataAnalysis | /ArtistGrouping.py | 8,744 | 3.625 | 4 | #Group all artists in a playlist / list of playlists and display the results
#
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pandas
import matplotlib.pyplot as plt
#Spotify developer account details
CLIENT_ID = ''
CLIENT_SECRET = ''
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(CLIENT_ID, CLIENT_SECRET))
#Users spotify userID and the ID of the users playlist (Only public playlists available)
username = ''
playerlist = ''
def Top_Artists():
results = sp.user_playlist_tracks(username, playerlist)
tracks = results['items']
fields = ['items,total']
Data = {
'Artist' : [],
'Songs' : []
}
track_count = 0
#Adds all tracks from a chosen playlist into a data list
while track_count < results["total"]:
for t in tracks:
track_id = t['track']['id']
track_name = t['track']['name']
track_artist = t['track']['artists'][0]['name']
print(track_id + ' ' + track_name + ' ' + track_artist)
if track_artist in Data['Artist']:
a_index = Data['Artist'].index(track_artist)
Data['Songs'][a_index] += 1
else:
Data['Artist'] += [track_artist]
Data['Songs'] += [1]
track_count += 1
results = sp.user_playlist_tracks(username, playerlist, fields=fields, limit=100, offset=track_count)
tracks = results['items']
if track_count > 200:
break
DisplayData = {
'Artist' : [],
'Songs' : []
}
def Find_Top_Ten():
top_ten = [1 for i in range(10)]
for i in range(len(Data['Artist'])):
if Data['Songs'][i] > min(top_ten):
top_ten[top_ten.index(min(top_ten))] = Data['Songs'][i]
return min(top_ten)
for i in range(len(Data['Artist'])):
if Data['Songs'][i] >= Find_Top_Ten():
DisplayData['Artist'] += [Data['Artist'][i]]
DisplayData['Songs'] += [Data['Songs'][i]]
df = pandas.DataFrame(DisplayData,columns=['Artist','Songs'])
df.plot(x = 'Artist', y='Songs', kind='barh')
plt.show()
top_artist = ""
top_count = 0
for artist in range(len(Data['Artist'])):
if Data['Songs'][artist] > top_count:
top_artist = Data['Artist'][artist]
top_count = Data['Songs'][artist]
print(top_artist)
#https://developer.spotify.com/documentation/web-api/reference/albums/get-album/
#https://developer.spotify.com/documentation/web-api/reference/object-model/#album-object-simplified
def Group_Year():
results = sp.user_playlist_tracks(username, playerlist)
tracks = results['items']
fields = ['items,total']
Years = {
'Release Date': [],
'Song Count': []
}
total_count = 0
explicit_count = 0
while total_count < results["total"]:
for t in tracks:
track_name = t['track']['name']
track_artist = t['track']['artists'][0]['name']
track_date = t['track']['album']['release_date']
print(track_date)
if track_date is None:
continue
if int(track_date[:4]) in Years['Release Date']:
Years['Song Count'][Years['Release Date'].index(int(track_date[:4]))] += 1
else:
Years['Release Date'] += [int(track_date[:4])]
Years['Song Count'] += [1]
total_count += 1
results = sp.user_playlist_tracks(username, playerlist, fields=fields, limit=100, offset=total_count)
tracks = results['items']
total_count += 1
if total_count > 1500:
break
Years = Order_Years(Years)
df = pandas.DataFrame(Years, columns=['Release Date', 'Song Count'])
df.plot(x='Release Date', y='Song Count', kind='bar')
plt.show()
#Orders a given Dataset of release dates of songs in ascending order
def Order_Years(given_years):
years = given_years['Release Date']
s_count = given_years['Song Count']
n_years = sorted(years)
new_s_count = []
for i in range(len(years)):
new_s_count += [s_count[years.index(n_years[i])]]
new_years = {
'Release Date':n_years,
'Song Count':new_s_count
}
return new_years
#https://developer.spotify.com/documentation/web-api/reference/tracks/get-track/
def Explicit_Percent():
results = sp.user_playlist_tracks(username, playerlist)
tracks = results['items']
fields = ['items,total']
Explicit_Songs_Index = {
'Artist': [],
'Song': []
}
total_count = 0
explicit_count = 0
while total_count < results["total"]:
for t in tracks:
track_id = t['track']['id']
track_name = t['track']['name']
track_artist = t['track']['artists'][0]['name']
if t['track']['explicit']:
print(track_name)
if track_artist in Explicit_Songs_Index['Artist']:
a_index = Explicit_Songs_Index['Artist'].index(track_artist)
Explicit_Songs_Index['Song'][a_index] += [track_name]
else:
Explicit_Songs_Index['Artist'] += [track_artist]
Explicit_Songs_Index['Song'] += [[track_name]]
explicit_count += 1
total_count += 1
results = sp.user_playlist_tracks(username, playerlist, fields=fields, limit=100, offset=total_count)
tracks = results['items']
total_count += 1
if total_count > 1500:
break
graph_data = {
'Song type': ['Not explicit', 'Explicit'],
'Amount': [total_count - explicit_count, explicit_count]
}
df = pandas.DataFrame(graph_data, columns=['Song type', 'Amount'])
df.plot(x='Song type', y='Amount', kind='bar')
plt.show()
print(str(total_count) + ' ' + str(explicit_count))
#https://developer.spotify.com/documentation/web-api/reference/personalization/get-users-top-artists-and-tracks/
def User_Favourite_Tracks(given_user):
token = util.prompt_for_user_token(given_user, 'user-top-read', CLIENT_ID, CLIENT_SECRET,
'http://localhost:8080')
sp_a = spotipy.Spotify(auth=token)
track_results = sp_a.current_user_top_tracks()
for t in track_results['items']:
track_name = t['name']
track_artist = t['artists'][0]['name']
print(track_name + ' ' + track_artist)
def User_Favourite_Artists(given_user):
#limit-50, offset-50, time_range-(long_term, medium_term,short_term)
token = util.prompt_for_user_token(given_user, 'user-top-read', CLIENT_ID, CLIENT_SECRET,
'http://localhost:8080')
sp_a = spotipy.Spotify(auth=token)
artist_results = sp_a.current_user_top_artists(limit=10)
print(artist_results)
for t in artist_results['items']:
print(t)
follower_count = t['followers']['total']
genres = t['genres']
artist_name = t['name']
artist_popularity = t['popularity']
print(str(follower_count) + ' ' + str(genres) + ' ' + str(artist_name) + ' ' + str(artist_popularity))
#Explicit_Percent()
#Top_Artists()
#Group_Year()
#User_Favourite_Tracks(username)
#User_Favourite_Artists(username)
CLIENT_ID = input('Please enter the Spotify developer Client ID')
CLIENT_SECRET = input('Please enter the Spotify developer Client Secrect ID')
username = input('Please enter your Spotify username')
playerlist = input('Please enter the Spotify playlist to analyse. This must be a public playlist.')
user_input = ''
while user_input is not 'q' and user_input is not 'quit':
user_input = input('Enter one of the following commands or type q to quit.\n \'top\', \'year\',\'explicit\',\'personal\'\n')
if user_input == 'top':
Top_Artists()
elif user_input == 'year':
Group_Year()
elif user_input == 'explicit':
Explicit_Percent()
elif user_input == 'personal':
print('You will need to sign into your Spotify account to allow access to this app.\n To quit enter q to go back enter b.\n')
second_input = input('Enter a command.\n\'track\',\'artist\'\n')
if second_input == 'track':
User_Favourite_Tracks(username)
elif second_input == 'artist':
User_Favourite_Artists(username)
|
a8a49630d4e3fcf8ec20ae04af47626c282d6c2f | pannachow/cs50 | /fibonacci.py | 205 | 4 | 4 | def fibonacci(n):
if n==0:
return 0
if n==1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
for i in range(7):
# x = fibonacci(i)
# print(x)
print(fibonacci(i))
|
caa1be529eed780e4db83da6a6c8a13bc7fcfb61 | stainley/python-workshop | /lesson3/helper_currency.py | 329 | 3.515625 | 4 | def convert_currency(amount, rate, margin=0):
return amount * rate * (1 + margin)
def compute_usd_total(amount_in_aud=0, amount_in_gpb=0):
total = 0
total += convert_currency(amount_in_aud, 0.78)
total += convert_currency(amount_in_gpb, 1.29, 0.01)
return total
print(compute_usd_total(amount_in_gpb=10))
|
56ef70d8a5a9462ac5144cd5e04f01642d0d51f2 | timisaurus/workspace-python-Hello_world | /edx/edx_list_manipulation.py | 5,102 | 3.796875 | 4 | # This program accepts a integer between 1 to 9999 as parameter and returns
# the number as a string.
input_retry = True
n = 0
while input_retry:
input_retry = False
try:
n = int(input('please enter an integer between 1 and 9999: '))
assert n > 0 or n < 10000 == True
except (AssertionError, TypeError, ValueError):
print('Invalid input!')
input_retry = True
int_fuck_me_list = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 40, 50, 60, 70, 80, 90]
str_fuck_me_list = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty',
'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty',
'ninety', 'hundred', 'thousand']
comprehensive_double_digit_list = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety']
comprehensive_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
quadruple_output = ''
triple_output = ''
double_output = ''
single_output = ''
hundred_output = ''
thousand_output = ''
space_1 = ''
space_2 = ''
space_3 = ''
space_4 = ''
space_5 = ''
overcomplicated_not_space_5 = False
mass = 0
user_input = n
if user_input <= 9:
while mass <= 10:
if user_input == mass:
single_output = comprehensive_list[mass - 1]
break
else:
mass = mass + 1
elif user_input <= 99:
double_digit_mass = 100
while double_digit_mass >= 20:
if user_input >= double_digit_mass:
insert_double = int(double_digit_mass / 10 - 1)
insert_single = user_input - double_digit_mass - 1
double_output = comprehensive_double_digit_list[insert_double]
single_output = comprehensive_list[insert_single]
break
else:
double_digit_mass = double_digit_mass - 10
elif user_input <= 9999:
x = user_input
quadruple_digit_mass = 10000
while quadruple_digit_mass >= 1000:
if x >= quadruple_digit_mass:
insert_quadruple = int(quadruple_digit_mass / 1000 - 1)
quadruple_output = comprehensive_list[insert_quadruple]
thousand_output = 'thousand'
x = x - quadruple_digit_mass
else:
quadruple_digit_mass = quadruple_digit_mass - 1000
triple_digit_mass = 1000
while triple_digit_mass >= 100:
if x >= triple_digit_mass:
insert_triple = int(triple_digit_mass / 100 - 1)
triple_output = comprehensive_list[insert_triple]
hundred_output = 'hundred'
x = x - triple_digit_mass
else:
triple_digit_mass = triple_digit_mass - 100
if x == 0:
pass
elif x <= 9:
test = user_input - 1
if test < 10000:
if test < 1000:
space_4 = ''
space_5 = ' '
else:
space_2 = ''
space_3 = ''
space_4 = ''
space_5 = ' '
insert_single = x - 1
single_output = comprehensive_list[insert_single]
pass
elif x <= 99:
double_digit_mass = 100
while double_digit_mass >= 20:
if x >= double_digit_mass:
insert_double = int(double_digit_mass / 10 - 1)
insert_single = x - double_digit_mass - 1
double_output = comprehensive_double_digit_list[insert_double]
if insert_single == -1:
single_output = ''
else:
single_output = comprehensive_list[insert_single]
break
else:
double_digit_mass = double_digit_mass - 10
mass = 0
for int_elements in int_fuck_me_list:
if x == int_elements:
while mass <= 20:
if int_elements == int_fuck_me_list[mass]:
double_output = str_fuck_me_list[mass]
single_output = ''
overcomplicated_not_space_5 = True
break
else:
mass += 1
break
mass = 0
for int_elements in int_fuck_me_list:
if user_input == int_elements:
while mass <= 20:
if int_elements == int_fuck_me_list[mass]:
double_output = str_fuck_me_list[mass]
single_output = ''
overcomplicated_not_space_5 = True
break
else:
mass += 1
break
if quadruple_output != '':
space_1 = ' '
if triple_output != '':
space_2 = ' '
space_3 = ' '
if double_output != '':
space_4 = ' '
if not overcomplicated_not_space_5:
space_5 = ' '
if user_input < 1000:
space_2 = ''
if user_input < 100:
space_4 = ''
print(quadruple_output, space_1, thousand_output, space_2, triple_output, space_3,
hundred_output, space_4, double_output, space_5, single_output, sep='')
|
0ebaf72736ec6b8f1705ecd653a4353d0e2f7ff6 | timisaurus/workspace-python-Hello_world | /book/fermats_theorem.py | 2,986 | 3.90625 | 4 | # This program tries to disprove the fermates theorem
def it_worked():
print('Holy smokes, Fermat was wrong!')
user_input = int(input('type a positive integer again: '))
a = user_input
b = user_input
c = user_input
n = user_input
ticker(a, b, c, n)
def it_didnt_worke():
print('No, that doesnt work.')
user_input = int(input('type a positive integer again: '))
a = user_input
b = user_input
c = user_input
n = user_input
ticker(a, b, c, n)
def check_fermat(a, b, c, n):
sum_c = (a ** n) + (b ** n)
if (a ** n) + (b ** n) == (c ** n):
it_worked()
def ticker(a, b, c, n):
x = a
z = b
y = c
w = n
e = a
f = b
g = c
o = n
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
a = x
b = y
c = z
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
a = x
b = y
c = z
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
a = x
b = y
c = z
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
a = x
b = y
c = z
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
a = x
b = y
c = z
while c > 1:
c = c - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while a > 1:
a = a - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
while b > 1:
b = b - 1
check_fermat(a, b, c, n)
print(a, b, c, n)
if a == 1 and b == 1 and c == 1 and n == 2:
it_didnt_worke()
if a == 1 and b == 1 and c == 1:
n = n - 1
a = e
b = f
c = g
e = e - 1
f = f - 1
g = g - 1
o = o - 1
ticker(e, f, g, o)
user_input = int(input('type a positive integer: '))
a = user_input
b = user_input
c = user_input
n = user_input
ticker(a, b, c, n)
|
10b0f21e24f0c8b9295234fd7118093c951e3ab7 | timisaurus/workspace-python-Hello_world | /edx/edx_functions.py | 3,584 | 4.40625 | 4 | # This program calculates and prints loan information.
# This function lets the user input 3 times.
def input_user():
x = float(input('principal :'))
y = float(input('annual_interest_rate :'))
z = int(input('duration :'))
loan_information(x, y, z)
# This function calculates the main information.
def loan_information(principal, annual_interest_rate, duration):
total_monthly_payments = duration * 12
monthly_interest_rate = annual_interest_rate / 100 / 12
if annual_interest_rate == 0:
return principal / (duration * 12)
monthly_payment = principal * ((monthly_interest_rate * ((1 + monthly_interest_rate) **
total_monthly_payments)) / (
((1 + monthly_interest_rate) ** total_monthly_payments) - 1))
total_payment = monthly_payment * 12
total_payment_loop = total_payment
a = principal
b = annual_interest_rate
c = duration
d = monthly_payment
e = total_payment_loop
f = total_payment
output_loan_information(a, b, c, d, e, f)
# This function calculates the remaining balance.
def remaining_balance(a, b, c, d):
n = c * 12
r = b / 100 / 12
if b == 0:
return a - d * (a / n)
rn1 = (1 + r) ** n
rd1 = (1 + r) ** d
balance = a * ((rn1 - rd1) / (rn1 - 1))
return balance
# This function gives the output of the functions above.
def output_loan_information(principal, annual_interest_rate, duration, monthly_payment,
total_payment_loop, total_payment):
print('LOAN AMOUNT:', int(principal), 'INTEREST RATE (PERCENT):', int(annual_interest_rate))
print('DURATION (YEARS):', int(duration), 'MONTHLY PAYMENT:', int(monthly_payment))
for years in range(duration):
years = years + 1
print('YEAR:', int(years), 'BALANCE:', int(remaining_balance(principal, annual_interest_rate,
duration, years * 12)), 'TOTAL PAYMENT',
int(total_payment_loop))
total_payment_loop = total_payment_loop + total_payment
input_user()
'''
# This function returns the remaining loan balance.
def remaining_loan_balance(principal, annual_interest_rate, duration , number_of_payments):
principal = float(principal)
annual_interest_rate = float(annual_interest_rate)
duration = int(duration)
number_of_payments = int(number_of_payments)
monthly_interest_rate = annual_interest_rate/100/12
total_payments = duration*12
if annual_interest_rate == 0:
loan_balance = principle*(1-(number_of_payments/total_payments))
else:
rn1 = (1+monthly_interest_rate)**total_payments
rp1 = (1+monthly_interest_rate)**number_of_payments
loan_balance = principal*((rn1-rp1)/(rn1-1))
return loan_balance
print(remaining_loan_balance(1000.0,4.5,5,12))
def calculate_loan_payment(principal, annual_interest_rate, duration):
principal = float(principal)
annual_interest_rate = float(annual_interest_rate)
duration = int(duration)
total_monthly_payments = duration*12
if annual_interest_rate == 0:
return principal/(duration*12)
total_monthly_payments = duration*12
monthly_interest_rate = annual_interest_rate/100/12
monthly_payment = principal*((monthly_interest_rate*((1+monthly_interest_rate)**
total_monthly_payments))/(((1+monthly_interest_rate)**total_monthly_payments)-1))
return monthly_payment
calculate_loan_payment(1000.0,4.5,5)
'''
|
e0d6812a81d0a65fb8998b63ac1af09247fc803e | Nihilnia/June1-June9 | /thirdHour.py | 1,283 | 4.21875 | 4 | """ 7- Functions """
def sayHello():
print("Hello")
def sayHi(name = "Nihil"):
print("Hi", name)
sayHello()
sayHi()
def primeQ(number):
if number == 0 or number == 1:
print(number, "is not a Primer number.")
else:
divs = 0
for f in range(2, number):
if number % f == 0:
divs += 1
if divs == 0:
print(number, "is a Primer number.")
else:
print(number, "is not a Primer number.")
primeQ(13)
# return() Expression
def hitMe():
firstNumber = int(input("Give me a number: "))
secondNumber = int(input("Give me the second number: "))
return firstNumber + secondNumber
print("Result:", hitMe())
# Flexible parameters - we know it.
""" 8- Lambda Expressions """
#Short way to create a function
def Nihil1():
print("Gimme tha Power")
Nihil2 = lambda: print("Gimme tha Power x2")
Nihil1()
Nihil2()
#Another Example
divideNumbers = lambda a, b: float(a/b) #If we won't write anything, it means return
print(divideNumbers(12, 2))
#Last Example
""" Finding are of circle (A = pi * r**2) """
findCircle = lambda r: 3.14 * (r ** 2)
print(findCircle(r = 2.5)) |
9140dd7db00f4aab06b41ed49069ddd42d596b76 | infotraining-team/py-bs-2020-12-07 | /bank_account.py | 1,558 | 3.71875 | 4 | class BankAccount:
__interest_rate = 0.01
def __init__(self, owner, balance):
self.__balance = balance
self.__owner = owner
def info(self):
print("owner:", self.__owner, " - balance:", self.__balance)
def withdraw(self, amount):
if (self.__balance < amount):
amount = self.__balance
print("insufficent funds")
self.__balance -= amount
return amount
def deposit(self, amount):
self.__balance += amount
@staticmethod
def get_bank_info():
print("HtB bank")
@staticmethod
def add(a, b):
return a + b
@classmethod
def get_interest_rate(cls):
print(cls.__interest_rate)
## @staticmethod equals to:
## get_bank_info = staticmethod(get_bank_info)
#print(BankAccount.__name__)
person1acc = BankAccount(owner="Leszek", balance=100)
person2acc = BankAccount("Ola", 200)
bank_log = []
bank_log.append(person1acc)
bank_log.append(person2acc)
bank_log.append(BankAccount("Sonia", 300))
for account in bank_log:
account.info()
amount = account.withdraw(200)
print("asked for:", 200, "withdrawed:", amount)
#print(person1acc.__balance)
#person1acc.balance = -100
print("-"*20)
for account in bank_log:
account.info()
## print(person1acc._BankAccount__balance) <- you shouldn't do it
## This is my interface
person1acc.deposit(200)
person1acc.withdraw(100)
person1acc.info()
person1acc.get_bank_info()
BankAccount.get_bank_info()
BankAccount.get_interest_rate()
BankAccount.add(2, 4)
|
00d7e9e92bf0b708a8ba97c369cee34df3912217 | infotraining-team/py-bs-2020-12-07 | /inheritance.py | 451 | 3.75 | 4 | class Parent:
def __init__(self):
print("Parent constructor")
self.parent_attr = 123
def method(self):
print("parent method")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child constructor")
def method(self):
super().method()
print("child method")
p = Parent()
p.method()
print(p.parent_attr)
print("-------")
c = Child()
c.method()
print(c.parent_attr) |
e77f4ff186007985b1a38c2369f45e2920d98221 | tudou-man/Finite_element_method | /Finite_element_method_py/3.py | 495 | 3.625 | 4 | def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
if s == '':
return 0
longest_len = 1
curr = []
for x in s:
if x in curr:
index = curr.index(x)
curr = curr[index + 1:]
print (curr)
curr.append(x)
# print(curr)
if longest_len < len(curr):
longest_len = len(curr)
return longest_len
longest_len = lengthOfLongestSubstring("abaacbca")
print (longest_len) |
af4c141fc364f89f4d1ad14541b368c164f40b81 | stephenfreund/PLDI-2021-Mini-Conf | /scripts/json_to_csv.py | 1,116 | 4.15625 | 4 | # Python program to convert
# JSON file to CSV
import argparse
import csv
import json
def parse_arguments():
parser = argparse.ArgumentParser(description="MiniConf Portal Command Line")
parser.add_argument("input", default="data.json", help="paper file")
parser.add_argument("out", default="data.csv", help="embeddings file to shrink")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
# Opening JSON file and loading the data
# into the variable data
with open(args.input) as json_file:
data = json.load(json_file)
# now we will open a file for writing
data_file = open(args.out, "w")
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
|
f43c35a61455a975adc8087581a90b2938cbfc1d | LuzinDaniil/lab2 | /dict_algs.py | 714 | 3.65625 | 4 | def dict(arr):
res = []
for i in arr:
for child in i['children']:
if child['age'] > 18:
res.append(i['name'])
return res
if __name__ == "__main__":
ivan = {
"name": "ivan",
"age": 34,
"children": [{
"name": "vasja",
"age": 12,
}, {
"name": "petja",
"age": 10,
}],
}
darja = {
"name": "darja",
"age": 41,
"children": [{
"name": "kirill",
"age": 21,
}, {
"name": "pavel",
"age": 15,
}],
}
emps = [ivan, darja]
print(dict(emps))
|
aabe0fd787be306682edc976f2eb6fd2e72d347b | J2xMurphy/JointFrame | /lib/c8.py | 1,912 | 4 | 4 | import math
#---------------------------------------------------------------------------
# This is used to calculate the angle using atan
def calcAngle(pt1,pt2,cstats,v):
p1 = cstats[pt1]
p2 = cstats[pt2]
## Reminder that P1 and P2 are formatted in Y: X: D: when output
if v == 1:
print(str(p1)+","+str(p2))
## sx is the x distance, while sy is the y distance
sy = math.fabs(int(p2[0])-int(p1[0]))#---------------------------\
sx = math.fabs(int(p2[1])-int(p1[1]))# \
oy = int(p1[0])>int(p2[0])# \ Calculations for the ending tan
ox = int(p1[1])>int(p2[1])# /---------------------------------
#if v == 1:
# tpx0=int(p1[0])-int(p2[0])
# print(str(p1[0])+", "+str(p2[0])+", "+str(tpx0))
# tpx1=int(p1[1])-int(p2[1])
# print(str(p1[1])+", "+str(p2[1])+", "+str(tpx1))
sxy=round(float(sx/sy),2)# /
#----------------------------------------------------------------/
tsxy=math.atan(sxy)
final = round(math.degrees(tsxy),2)
verbose=0
#---------------------------------------------------------------------------
#Depending on the quadrant, the final angle needs to be adjusted by 90x.
if (oy==True and ox ==False):
verbose = math.fabs(90-final)
final = math.fabs(90-final)+90
if (oy==False and ox ==False):
verbose = final
final = final
if (oy==False and ox ==True):
verbose = math.fabs(90-final)
final = math.fabs(90-final)+270
if (oy==True and ox ==True):
verbose = final
final = final+180
if v == 1:
print("X:"+str(sx)+", Y:"+str(sy)+", tan("+str(sxy)+"), = "+str(tsxy)+", "+str(final)+", "+str(verbose))
print("oy:"+str(oy)+" ox:"+str(ox))
return final
#---------------------------------------------------------------------------
# |
3c2ed0f17a7e642936cecffe9788c511e16276f1 | SathriMamatha123/EDUYEAR-PYTHON---20 | /Day2.py | 438 | 3.953125 | 4 | Name='Stella'
Marks=90
Balance =30864.89
AccNo =13786431991
print("My name is {}, and I got {} Marks in ComputerScience".format(Name,Marks))
print("My Account Number {}, and my Balance is {}" .format(AccNo,Balance))
print("My name is",Name,"and I got" ,Marks, "Marks in ComputerScience")
print("my name is " + Name +"." )
print(f"my name is {Name}, and my AccountNumber is {AccNo}")
|
ae7922f1cd7be6def39e113f61390b4ceebcb016 | gngoncalves/cursoemvideo_python_pt1 | /desafio18.py | 510 | 4.1875 | 4 | from math import sin, cos, tan, radians
num = int(input('Insira um ângulo: '))
print('Valores em Rad:')
print('O seno de {}º é {:.2f}.'.format(num,sin(num)))
print('O cosseno de {}º é {:.2f}.'.format(num,cos(num)))
print('A tangente de {}º é {:.2f}.\n'.format(num,tan(num)))
print('Valores em Deg:')
print('O seno de {}º é {:.2f}.'.format(num,sin(radians(num))))
print('O cosseno de {}º é {:.2f}.'.format(num,cos(radians(num))))
print('A tangente de {}º é {:.2f}.'.format(num,tan(radians(num)))) |
f49b75b94eeceac8906b6f812c706f31439e8240 | gngoncalves/cursoemvideo_python_pt1 | /desafio09.py | 616 | 4.125 | 4 | num = int(input('Insira um número inteiro: '))
n1 = num*1
n2 = num*2
n3 = num*3
n4 = num*4
n5 = num*5
n6 = num*6
n7 = num*7
n8 = num*8
n9 = num*9
n10 = num*10
print('Tabuada de {0}:'.format(num))
print('-'*12)
print('{} x 1 = {:2}'.format(num,n1))
print('{} x 2 = {:2}'.format(num,n2))
print('{} x 3 = {:2}'.format(num,n3))
print('{} x 4 = {:2}'.format(num,n4))
print('{} x 5 = {:2}'.format(num,n5))
print('{} x 6 = {:2}'.format(num,n6))
print('{} x 7 = {:2}'.format(num,n7))
print('{} x 8 = {:2}'.format(num,n8))
print('{} x 9 = {:2}'.format(num,n9))
print('{} x 10 = {:2}'.format(num,n10))
print('-'*12) |
0a5ebbc78c07295677b0df7239dc5cd1f668e7de | gngoncalves/cursoemvideo_python_pt1 | /desafio54.py | 499 | 3.640625 | 4 | from datetime import date
atual = date.today().year
maior = 0
menor = 0
for i in range (1,8):
print('=' * 45)
nasc = int(input('Digite o de nascimento [Pessoa {}/7]: '.format(i)))
if atual - nasc >= 21:
maior += 1
else:
menor += 1
print('=' * 45)
print('Nos dados informados acima, temos \033[32m{}\033[m pessoas com idade acima de 21 anos.'.format(maior))
print('Nos dados informados acime, temos \033[36m{}\033[m pessoas com idade abaixo de 21 anos.'.format(menor)) |
902258a6ec97197a8840559bc4692514b6e4d1f4 | gngoncalves/cursoemvideo_python_pt1 | /desafio42.py | 690 | 3.921875 | 4 | l1 = float(input('Insira o primeiro lado do triângulo: '))
l2 = float(input('Insira o segundo lado do triângulo: '))
l3 = float(input('Insira o terceiro lado do triângulo: '))
c1 = l1 < (l2 + l3)
c2 = l2 < (l1 + l3)
c3 = l3 < (l1 + l2)
if c1 == True and c2 == True and c3 == True:
if l1 == l2 == l3:
print('Estes lados nos permitem formar um triângulo equilátero.')
elif l1 == l2 or l1 == l3 or l2 == l3:
print('Estes lados nos permitem formar um triângulo isósceles.')
elif l1 != l2 != l3 != l1:
print('Estes lados nos permitem formar um triângulo escaleno.')
else:
print('Estes lados não permitem formar um triângulo.')
print('Obrigado.') |
c64c542b57107c06de2ce0751075a81fcb195b61 | DmitriiIlin/Merge_Sort | /Merge_Sort.py | 1,028 | 4.25 | 4 | def Merge (left,right,merged):
#Ф-ция объединения и сравнения элементов массивов
left_cursor,right_cursor=0,0
while left_cursor<len(left) and right_cursor<len(right):
if left[left_cursor]<=right[right_cursor]:
merged[left_cursor+right_cursor]=left[left_cursor]
left_cursor+=1
else:
merged[left_cursor+right_cursor]=right[right_cursor]
right_cursor+=1
for left_cursor in range(left_cursor,len(left)):
merged[left_cursor+right_cursor]=left[left_cursor]
for right_cursor in range(right_cursor,len(right)):
merged[left_cursor+right_cursor]=right[right_cursor]
return merged
def MergeSort(array):
#Основная рекурсивная функция
if len(array)<=1:
return array
mid=len(array)//2
left,right=MergeSort(array[:mid]),MergeSort(array[mid:])
return Merge(left,right,array.copy())
"""
a=[2,45,1,4,66,34]
print(MergeSort(a))
print(a)
"""
|
d166529ddb87574ad1aac74e599e53f187f82b73 | hkilter/bullwhip_effect | /supplier_buyer_graph/diffusion_v0.2.0.py | 4,615 | 3.546875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Luke
#
# Created: 01/06/2013
# Copyright: (c) Luke 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import sys, os, csv
import networkx as net
import matplotlib.pyplot as plot
import matplotlib.colors as colors
from py2neo import neo4j
from py2neo import gremlin
import random as r
def main():
pass
#I've already defined a company network
#Go and get a company
#two phenomenon: diffusion through a population normally: r(0) rate
# difusion through a set of companies, non-normally : watching the other companies market cap
class Company(object):
def __init__(self, id):
#Start with a single initial preference
self.id=id
self.i = r.random()
self.a = self.i
#we value initial opinion and subsequent information equally
self.alpha=0.8
def __str__(self):
return(str(self.id))
def _roulette_choice(self,names,values, inverse=False):
"""
roulette method makes unequally weighted choices based on a set of values
Names and values should be lists of equal lengths
values are between 0 and 1
if inverse=False, names with higher values have a higher probability of choice;
if inverse=True, names with lower values have hight probability
"""
wheel=names
for i in range(len(names)):
if not inverse:
wheel.extend([names[i] for x in range(1+int(values[i]*10))])
else:
wheel.extend([names[i] for x in range(1+int((1-values[i])*10))])
return(r.choice(wheel))
def interact(self):
"""
instead of looking at all of the neighbors,
let's pick a random node and exchange information with him
this will create an edge and weigh it with their similarity.
Phase II -- make roulette choice instead of random choice
"""
neighbors=g[self].keys()
values=[v['weight'] for v in g[self].values()]
## roll dice and decide to communicate with
## similar (0.6), dissimilar(0.3) or random (0.1)
roll=r.random()
if r <= 0.1 or len(neighbors)==0:
partner=r.choice(g.nodes())
elif r<=0.4:
partner=self._roulette_choice(neighbors,values,inverse=True)
else:
partner=self._roulette_choice(neighbors,values,inverse=False)
w=0.5
s=self.a*w + partner.a*w
# update my beliefs = initial belief plus sum of all influences
self.a=(1-self.alpha)*self.i + self.alpha*s
g.add_edge(self,partner,weight=(1-self.a-partner.a))
density=0.9
g=net.Graph()
#create a network of Company objects. Also could be called the network of agents for diffusion model.
for i in range(10):
c=Company(i)
g.add_node(c)
def consensus(g):
"""
Calculcate consensus opinion of the graph
"""
aa=[n.a for n in g.nodes()]
return min(aa),max(aa),sum(aa)/len(aa)
def trim_edges(g, weight=1):
g2=net.Graph()
for f, to, edata in g.edges(data=True):
if edata != {}:
if edata['weight'] > weight:
g2.add_edge(f,to,edata)
return g2
density=0.05
decay_rate=0.01
network_size=100
runtime=200
g=net.Graph()
# create a network of Company objects
for i in range(network_size):
c=Company(i)
g.add_node(c)
##this will be a simple random graph, with random weights
for x in g.nodes():
for y in g.nodes():
if r.random()<=density: g.add_edge(x,y,weight=r.random())
col=[n.a for n in g.nodes()]
pos=net.spring_layout(g)
net.draw_networkx(g,pos=pos, node_color=col,cmap=plot.cm.Reds)
cons=[]
for i in range(runtime):
for node in g.nodes():
node.interact()
#degrade edge weights by a fixed rate
for f,t,data in g.edges(data=True):
data['weight']=data['weight']*(1-decay_rate)
if data['weight']<0.1: g.remove_edge(f,t)
col=[n.a for n in g.nodes()]
ew=[1000*edata['weight'] for f,to,edata in g.edges(data=True)]
plot.figure(2)
plot.plot(col)
cons.append(consensus(g))
plot.figure(i)
g2=trim_edges(g, weight=0.3)
col=[n.a for n in g2.nodes()]
net.draw_networkx(g2,node_color=col, cmap=plot.cm.Reds) #,edge_color=ew,edge_cmap=plot.cm.RdPu)
plot.figure(i+1)
plot.plot(cons)
plot.figure(i+2)
plot.hist([e['weight'] for f,t,e in g.edges(data=True)])
plot.show()
if __name__ == '__main__':
main()
|
9a8e8de1b5fd6d2b1acf4596227f60f3b46678ee | HRIDDHIMABANSAL/intro.py | /intro.py | 338 | 4 | 4 | introduction=input("write something about you")
characterCount=0
wordCount=1
print(introduction)
for i in introduction:
characterCount=characterCount+1
if(i==" "):
wordCount=wordCount+1
print("no. words in the string")
print(wordCount)
print("no. of characters in the paragraph")
print(characterCount)
|
546f13f754d939cdb1bda0f246087118fdc0df92 | AmaurX/automated_flappy_bird | /flappy_automation_code/scripts/controller.py | 2,452 | 3.609375 | 4 | #!/usr/bin/env python
import math
DESIRED_VELOCITY_NORM = 2.1
class Controller():
'''
This controller tracks target velocity values : Vx and Vy
They are computed from the current state, from the desired velocity norm, and from the desired direction angle given by the planner
The desired velocity norm is a constant. However, when flappy is closing on the obstacle but not yet commited to pass (e.g. in IS_PASSING mode),
we dampen the velocity target by a factor that grows the closer we get to the obstacle. This allows for better final approach when
the estimation of the gap height stabalizes a bit late.
The controler is a very simple P controller, with different gain for each part.
The Kpx controller is huge because thanks to the dynamics of the game, Flappy cannot go backwards.
This mean that there can be no oscillation and therefore a very high gain is gonna acheive the goal faster.
This also works because there is no uncertainty in the dynamics, the state is always known perfectly.
For Kpy, there can be oscillation, so this gain is of "normal" magnitude.
One could try implementing a PI or PID controller, but the game is simple enough that a simple P controller works well.
'''
def __init__(self, state, planner):
self.state = state
self.planner = planner
self.Kpx = 10000000
self.Kpy = 50
def giveAcceleration(self):
# Getting the target velocity and angle
desiredAngle = self.planner.approach_angle
desiredSpeed = DESIRED_VELOCITY_NORM
# When flappy is closing on the obstacle but not yet commited to pass (e.g. in IS_PASSING mode),
# we dampen the velocity target by a factor that grows the closer we get to the obstacle
if self.planner.mode != "IS_PASSING" and self.planner.obstacle.x.estimate - 0.1 >= 0.0:
desiredSpeed *= 1 - 0.4/(0.9+self.planner.obstacle.x.estimate)
# Computing the desired Vx annd Vy, that are actually tracked
desiredVx = math.cos(desiredAngle) * desiredSpeed
desiredVy = math.sin(desiredAngle) * desiredSpeed
# Computing the diff between desired velocity and current velocity
diffvy = desiredVy - self.state.vy
diffvx = desiredVx - self.state.vx
# The controler is a very simple P controller, with different gain for each part
return (self.Kpx * diffvx, self.Kpy * diffvy)
|
0f8a9e2bf060fa284a3d3aee09f87d446d6cf568 | betoxedon/CursoPython | /Programação_Funcional/closure.py | 302 | 3.734375 | 4 | #!/usr/bin/python3
def multiplicar(x):
def calcular(y):
return x*y
return calcular
if __name__ == '__main__':
dobro = multiplicar(2)
triple = multiplicar(3)
print(triple)
print(dobro)
print(f'O triplo de 3 é {triple(3)}')
print(f'O dobro de 7 é {dobro(7)}')
|
820ed5f7338202897dc05c8dd3e915214572152e | betoxedon/CursoPython | /Fundamentos/area_circulo_v2.py | 154 | 3.640625 | 4 | #!/usr/local/bin/python3
''' Cálculo da área de um círculo '''
PI = 3.1415
RAIO = 15.3
AREA = PI * RAIO ** 2
print(f'A Área do círculo é {AREA}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.