blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
2db607a082883f797dbb726ee982b15d6c35758d | prijindal/hackeearth | /problem/algorithm/rest-in-peace-21-1.py | 234 | 3.765625 | 4 | for i in xrange(input()):
N = input()
if N%21 == 0:
print("The streak is broken!")
elif str(N).find('21') >=0:
print("The streak is broken!")
else:
print("The streak lives still in our heart!")
|
7760e403dcb34f8f9bf4b736443ab69230bb9375 | hoodielive/modernpy | /2022/beazley/closures.py | 462 | 3.84375 | 4 | x = 10
y = 'hello, world'
items = [10, 20]
names = ['dave', 'Thomas', 'Lewis', 'paula']
names = names.sort(key=lambda name: name.upper())
print(names)
def greeting(name):
print("hello", name)
greeting('Guido')
print(greeting)
g = greeting
g('Guide')
items.append(greeting)
print(items[2])
print(items[2]('Osa Meji'))
import time
def after(seconds, func):
time.sleep(seconds)
func()
def hello():
print('Hello, Howdy')
after(5, hello)
|
c49836f2e56130e13c2dacd1c19ed24793523e5b | hirak0373/AI-Practices | /marksheet.py | 672 | 4.0625 | 4 | eng =input("Enter marks of English: ")
bio = input("Enter marks of Biology: ")
chem = input("Enter marks of Chemistry: ")
pak = input("Enter marks of Pakistan Sudies: ")
sin = input("Enter marks of Sindhi: " )
obtain =int(eng)+int(bio)+int(chem)+int(pak)+int(sin)
print (obtain)
per =int(obtain)/425
per1=per*100
print("your percentage is: "+str(per1))
if per1 >= 80 and per1 <= 100:
print("Grade: A+")
elif per1 >= 70 and per1 <=79.99:
print("Grade: A")
elif per1 >= 60 and per1 <=69.99:
print("Grade: B")
elif per1 >= 50 and per1 <=59.99:
print("Grade: C")
elif per1 >= 40 and per1 <=49.99:
print("Grade: D")
elif obtain <40:
print("Grade: fail") |
a1e36e9263692b0e4a178d57b6334878051b3aee | ppli2015/leetcode | /9 Palindrome Number.py | 410 | 3.515625 | 4 | # -*-coding:cp936-*-
__author__ = 'lpp'
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
x = str(x)
print x
for i in range(len(x) / 2):
if x[i] != x[0 - i - 1]:
return False
return True
test = Solution()
print test.isPalindrome(0)
|
0e66d86b3ac7f5322e1d0e940ceafa8e5d5228d4 | JeffHanna/Advent_of_Code_2018 | /day_09.py | 6,887 | 4.09375 | 4 | # -+- coding utf-8 -*-
"""
--- Day 9: Marble Mania ---
You talk to the Elves while you wait for your navigation system to initialize. To pass the time, they introduce you to their favorite marble game.
The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.
First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble.
Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble.
However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
For example, suppose there are 9 players. After the marble with value 0 is placed in the middle, each player (shown in square brackets) takes a turn. The result of each of those turns would produce circles of marbles like this, where clockwise is to the right and the resulting current marble is in parentheses:
[-] (0)
[1] 0 (1)
[2] 0 (2) 1
[3] 0 2 1 (3)
[4] 0 (4) 2 1 3
[5] 0 4 2 (5) 1 3
[6] 0 4 2 5 1 (6) 3
[7] 0 4 2 5 1 6 3 (7)
[8] 0 (8) 4 2 5 1 6 3 7
[9] 0 8 4 (9) 2 5 1 6 3 7
[1] 0 8 4 9 2(10) 5 1 6 3 7
[2] 0 8 4 9 2 10 5(11) 1 6 3 7
[3] 0 8 4 9 2 10 5 11 1(12) 6 3 7
[4] 0 8 4 9 2 10 5 11 1 12 6(13) 3 7
[5] 0 8 4 9 2 10 5 11 1 12 6 13 3(14) 7
[6] 0 8 4 9 2 10 5 11 1 12 6 13 3 14 7(15)
[7] 0(16) 8 4 9 2 10 5 11 1 12 6 13 3 14 7 15
[8] 0 16 8(17) 4 9 2 10 5 11 1 12 6 13 3 14 7 15
[9] 0 16 8 17 4(18) 9 2 10 5 11 1 12 6 13 3 14 7 15
[1] 0 16 8 17 4 18 9(19) 2 10 5 11 1 12 6 13 3 14 7 15
[2] 0 16 8 17 4 18 9 19 2(20)10 5 11 1 12 6 13 3 14 7 15
[3] 0 16 8 17 4 18 9 19 2 20 10(21) 5 11 1 12 6 13 3 14 7 15
[4] 0 16 8 17 4 18 9 19 2 20 10 21 5(22)11 1 12 6 13 3 14 7 15
# MOVE WITHOUT MODULUS 23 RULE
[5] 0 16 8 17 4 18 9 19 2 20 10 21 5 22 11(23) 1 12 6 13 3 14 7 15
However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
[5] 0 16 8 17 4 18(19) 2 20 10 21 5 22 11 1 12 6 13 3 14 7 15
[6] 0 16 8 17 4 18 19 2(24)20 10 21 5 22 11 1 12 6 13 3 14 7 15
[7] 0 16 8 17 4 18 19 2 24 20(25)10 21 5 22 11 1 12 6 13 3 14 7 15
Here are a few more examples:
10 players; last marble is worth 1618 points: high score is 8317
13 players; last marble is worth 7999 points: high score is 146373
17 players; last marble is worth 1104 points: high score is 2764
21 players; last marble is worth 6111 points: high score is 54718
30 players; last marble is worth 5807 points: high score is 37305
What is the winning Elf's score?
--- Part Two ---
Amused by the speed of your answer, the Elves are curious:
What would the new winning Elf's score be if the number of the last marble were 100 times larger?
"""
from collections import defaultdict, deque
from itertools import cycle
import re
def _parse( filepath: str ) -> tuple:
with open( filepath, 'r' ) as f:
line = f.readline( )
return tuple( [ int( x ) for x in re.findall( r'\d+', line ) ] )
class Game( ):
"""
Instance an Elf marble game. The provided player_count and final_marble_value are used to set the state of the game and establish
the end-game trigger. Once the game is simulated the winning elf and their score are presented.
"""
def __init__( self, player_count: int, final_marble_value: int, part_2_scale : bool = False ):
self._player_count = player_count
self._players = defaultdict( list )
self._final_marble_value = final_marble_value if not part_2_scale else final_marble_value * 100
self._current_marble_idx = 0
self._marble = 0
self._circle = deque( [ self._marble ] )
def _calculate_score( self ):
"""
Sums the totals of all of the elves' marbles. The winner is the elf with the highest score.
"""
high_score = 0
winning_player = 0
for player, marbles in self._players.items( ):
score = sum( marbles )
if score > high_score:
high_score = score
winning_player = player
print( 'The winning elf is: {0} with a score of: {1}'.format( winning_player, high_score ) )
def _turn( self, player: int ) -> bool:
"""
Simulates a game turn of the elf marble game. The turn rules can be found in the module docstring.
Arguments:
player {int} -- The current player
"""
self._marble += 1
if self._marble % 23 == 0:
extra_score_marble_idx = ( self._current_marble_idx - 7 ) % len( self._circle )
self._current_marble_idx = ( extra_score_marble_idx )
extra_score_marble = self._circle[ extra_score_marble_idx ]
self._circle.remove( self._circle[ extra_score_marble_idx ] )
self._players[ player ].extend( [ self._marble, extra_score_marble ] )
else:
insert_location = ( self._current_marble_idx + 1 ) % len( self._circle ) + 1
self._circle.insert( insert_location, self._marble )
self._current_marble_idx = insert_location
if self._marble == self._final_marble_value:
self._calculate_score( )
return True
return False
def play( self ):
"""
Public method to start the game once the initial state is established.
"""
game_over = False
while not game_over:
for p in cycle( range( 1, self._player_count + 1 ) ):
game_over = self._turn( p )
if game_over:
break
if __name__ == '__main__':
player_count, final_marble_value = _parse( r'day_09_input.txt' )
game_1 = Game( player_count, final_marble_value )
print( 'Playing Game 1...' )
game_1.play( )
game_2 = Game( player_count, final_marble_value, part_2_scale = True )
print( 'Playing Game 2...' )
game_2.play( )
|
9ed588d3366c2690f2368fb9de70e8746cf4b17d | Fengyongming0311/TANUKI | /Zero_Python/0-2章.Python的基本语法/python基本语法.py | 11,399 | 3.90625 | 4 | python内置函数
Python dir() 函数
https://www.cnblogs.com/mq0036/p/7205626.html
self.assertEqual('Action Bar', els[1].text)
self.assertEqual(a,b,msg=msg) #判断a与1.b是否一致,msg类似备注,可以为空
self.assertNotEqual(a,b,msg=msg) #判断a与b是否不一致
self.assertTrue(a,msg=none) #判断a是否为True
self.assertFalse(b,msg=none) #判断b是否为false
Python程序语言指定任何非0和非空(null)值为true,0或者null为 False,所以Python中的 1 代表 True,0代表 False
======================================================================
python 获得对象的所有属性和方法
描述
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
语法
dir 语法:
dir([object])
参数说明:
object -- 对象、变量、类型。
返回值
返回模块的属性列表。
实例
以下实例展示了 dir 的使用方法:
>>>dir() # 获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ]) # 查看列表的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
要判断对象是否有某个属性,可以用:
hasattr(Object, "name")
如:
hasattr(self,"diaplay_name")
如果有这个属性,会返回True
======================================================================
表示之后的为注释 #
'''
注释多行
'''
同一行书写多个语句
import sys; x = 'foo'; sys.stdout.write(x + '\n')
变量赋值
a = 13
b = 'python的变量赋值'
python数据类型
1、字符串
2、布尔类型
3、整数
4、浮点数
5、数字
6、列表
7、元组
8、字典
9、日期
1.字符串:
dondake='我是dondake'
print (dondake)
2.布尔类型:
dondake = False (dondake = 0)
dondake = True (dondake = 1)
3.整数:
bnt=20
print (bnt)
4.浮点数:
eloat = 2.4
print (eloat)
5.数字:
包括整数和浮点数(包括数字类型转换和数学函数)
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
6.列表:
list=['physics', 'chemistry', 1997, 2000]
nums=[1, 3, 5, 7, 8, 13, 20]
访问列表的值:
nums[0] #为1
num[2:5] #为 [5, 7, 8] 从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素
nums[1:] # [3, 5, 7, 8, 13, 20] 从下标为1切割到最后一个元素
nums[:-3] #为 [1, 3, 5, 7] 从最开始的元素一直切割到倒数第3个元素,但不包含倒数第三个元素'''
nums[:] # [1, 3, 5, 7, 8, 13, 20] 返回所有元素
更新列表:
nums = [0,3,5,7,8,9,15]
nums[0] = "fym"
print (nums)
输出为:['fym', 3, 5, 7, 8, 9, 15]
删除列表元素
del nums[0];
print "nums[:]:", nums[:];
输出为:nums[:]: [3, 5, 7, 8, 13, 20]
列表脚本操作
print len([1, 2, 3]); #3
print [1, 2, 3] + [4, 5, 6]; #[1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4; #['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3] #True
for x in [1, 2, 3]: print x, #1 2 3
列表截取
L=['spam', 'Spam', 'SPAM!'];
print L[2]; #'SPAM!'
print L[-2]; #'Spam'
print L[1:]; #['Spam', 'SPAM!']
列表排序函数
list = [1,5,8,2,77,3,2,86,123,41,22]
don = sorted(list)
做了一个复制并排序
print (don)
7.元组(tuple)
Python的元组与列表类似,不同之处在于元组的元素不能修改;元组使用小括号(),列表使用方括号[];元组创建很简单,只需要在括号中添加元素,并使用逗号(,)隔开即可。
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
元组中只有一个元素时,需要在元素后面添加逗号,例如:tup1 = (50,)
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,例如:
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
tup3 = tup1 + tup 2
print (tup3)
输出:(12, 34.56, 'abc', 'xyz')
删除元组
元组中的元素值是不允许删除的,可以使用del语句来删除整个元组,例如:
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
元组索引&截取
L = ('one', 'two', 'three!');
print (L[2]) #three!
print (L[-2]) #two 因为three是-3
print (L[1:]) #('two', 'three!')
元组内置函数
len(tuple) 计算元组元素个数。
max(tuple) 返回元组中元素最大值。
min(tuple) 返回元组中元素最小值。
tup1 = (1,2,3)
tup2 = (5,6,7)
print(len(tup1)) 输出3
print (max(tup2)) 输出7
print (min(tup1)) 输出1
8、字典
字典(dictionary)是除列表之外python中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典由键和对应的值组成。字典也被称作关联数组或哈希表。基本语法如下:
zidian = {'xingming': 'fengyongming', 'shengri': int(1989), 'phoneNO': 13466738904}
print (zidian )
输出:{'xingming': 'fengyongming', 'shengri': 1989, 'phoneNO': 13466738904}
字典中一个KEY对应多个值:
zidian = {'xingming': ['fengyongming',13466738904],'shengri': int(1989), 'phoneNO': 13466738904}
print (zidian['xingming'])
访问字典里的值
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
print (dict['name'])
print (dict['age'])
输出:Zara
7
修改字典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
dict["age"] = 27 #修改已有键的值
dict["school"] ="wutong" #增加新的键/值对
print (dict['age'])
print (dict['school'])
####################################################
输出 27
wutong
删除字典
del dict['name'] # 删除键是'name'的条目
dict.clear() # 清空词典所有条目
del dict # 删除词典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
del dict['name']
print (dict)
#########################################################
条件循环语句
if else
score = 66
if score<60:
print ("不及格")
else:
print ("及格")
if elif else
score = 60
if score<60:
print ("D")
elif score<80:
print ("C")
elif score<90:
print ("B")
else:
print ("A")
for循环
world=['China','England','America']
for i in world:
print (i)
range内建函数 ==
num = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(num)):
print (i)
for语句也可以else语句块中止,可可以和break和continue一块使用
for target in object:
# statementSuite1
if boolenExpression1:
break
if boolenExpression2:
continue
else:
statementSuite2
for循环正常退出后,执行else块
break语句提供了for循环的异常退出,跳过else子句
continue语句终止目前的循环异常,继续循环余下的部分
while循环
count = 0
while (count < 9):
print ('The index is:', count)
count += 1
无限循环
while True:
print ("无限循环")
while+ else
count=5
while count>0:
print ('i love python')
count=count-1
else:
print ('over')
break语句
count = 0
while (count < 9):
print ('The index is:', count)
count += 1
if count == 4:
break
pass 语句
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
异常处理
def into_jinjianshenqing():
try:
time.sleep(1)
driver.switch_to_frame('mainFrame')
time.sleep(1)
driver.switch_to_frame('leftFrame')
WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath("/html/body/div/ul[2]/li[1]/a")) #wait
driver.find_element_by_xpath("/html/body/div/ul[2]/li[1]/a").click()
driver.switch_to_default_content() #退出框架
except Exception as e:
print ("转入进件申请BUG==============:",e)
finally:
pass
函数
def plus(_num1,_num2):
return (_num1+_num2)
a = 1
b = 2
c = plus(a,b)
print (c)
匿名函数 lambda
匿名 就是 不需要以标准的方式来声明,
WebDriverWait(driver, 10).until(lambda x: x.find_element_by_css_selector("select[id=\"loan_time\"][class=\"select_styleN1\"]"))
driver.find_element_by_css_selector("select[id=\"loan_time\"][class=\"select_styleN1\"]").find_element_by_xpath("/html/body/div[2]/div/form/ul[2]/li[4]/div/div[1]/select/option[3]").click()
引用各种模块
import var 引用
var.tim(a,b)
from module import var
tim(a,b)
from module import * (不是良好的变成风格)
区别
面向对象编程
什么是json:
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。
==========================
查看XX端口是否被占用
netstat -ano | findstr 5037
==========================
with open('/path/to/file', 'r') as f:
print(f.read())
等同于
这和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f.close()方法。
调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。
如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
========================== |
91788e186c882685265ea2ac9eedb4728f14621a | saghevli/conway_life | /conway_life.py | 2,952 | 4.21875 | 4 | # conway's game of life
# rules:
# any live cell with fewer than two live neighbors dies
# a live cell with two or three live neighbors lives
# a live cell with four or more live neighbors dies
# a dead cell with > 3 live neighbors
import time
BOARD_SIZE = 41
generation = 0
def main():
interval = .5
board = [[0 for i in range(BOARD_SIZE)] for i in range(BOARD_SIZE)]
# get input coordinates
print "input comma separated inital state coordinates with \"end\" on the last line"
input = raw_input()
while input != "end" :
coordinates = [int(i) for i in input.split(',')]
print coordinates
print str(coordinates[0]) + "|" + str(coordinates[1])
board[coordinates[0]][coordinates[1]] = 1
input = raw_input()
user_interval = raw_input("generation interval in seconds? default is .5, enter 'n' for default: ")
if user_interval != "n":
interval = float(user_interval)
animate(board, interval)
def animate(board, interval):
while True:
printBoard(board)
board = update(board)
time.sleep(interval)
def update(board):
global generation
generation += 1
newBoard = [[0 for i in range(BOARD_SIZE)] for i in range(BOARD_SIZE)]
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
liveNeighbors = numberLiveNeighbors(board, i, j)
# if alive and 2 or 3 live neighbors, stay alive
if board[i][j] and (liveNeighbors == 2 or liveNeighbors == 3) :
newBoard[i][j] = 1
# if dead and 3 live neighbors, come to life
if ~board[i][j] and liveNeighbors == 3 :
newBoard[i][j] = 1
return newBoard
def numberLiveNeighbors(board, i, j):
if i >= BOARD_SIZE or j >= BOARD_SIZE or i < 0 or j < 0:
return -1;
numLiveNeighbors = 0;
numLiveNeighbors += isLive(board, i - 1, j - 1); # up, left
numLiveNeighbors += isLive(board, i - 1, j); # up
numLiveNeighbors += isLive(board, i - 1, j + 1); # up, right
numLiveNeighbors += isLive(board, i, j - 1); # left
numLiveNeighbors += isLive(board, i, j + 1); # right
numLiveNeighbors += isLive(board, i + 1, j - 1); # down, left
numLiveNeighbors += isLive(board, i + 1, j); # down
numLiveNeighbors += isLive(board, i + 1, j + 1); # down, right
return numLiveNeighbors
# if out of bounds, not alive. if in bounds, check. 1 indicates alive, 0 dead
def isLive(board, i, j):
if i >= BOARD_SIZE or j >= BOARD_SIZE or i < 0 or j < 0:
return 0
return board[i][j]
def printBoard(board):
print "************************* Generation " + str(generation) + " *************************"
for i in range(BOARD_SIZE):
line = ""
for j in range(BOARD_SIZE):
if board[i][j] :
line += "& "
else :
line += "_ "
print line
if __name__ == "__main__":
main()
|
08b524796160ba0b12a7b580d5197e66b0f73a1e | russellgao/algorithm | /dailyQuestion/2020/2020-04/04-27/python/py1.py | 1,099 | 3.890625 | 4 | # 方法一
# 顺序合并
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def mergeKLists(lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
def mergeTwo(list1, list2) :
head = ListNode()
pre_head = head
current_1 = list1
current_2 = list2
while current_1 and current_2 :
if current_1.val < current_2.val :
pre_head.next = current_1
current_1 = current_1.next
else :
pre_head.next = current_2
current_2 = current_2.next
pre_head = pre_head.next
if current_1 :
pre_head.next = current_1
elif current_2 :
pre_head.next = current_2
return head.next
result = None
for item in lists :
result = mergeTwo(result,item)
return result
# 时间复杂度:O(k^2*n)
# 空间复杂度:没有用到与 kk 和 nn 规模相关的辅助空间,故渐进空间复杂度为 O(1)O(1)。 |
2f3eeeaf13c553dc35eaf4ec5e5acf8ebf040e2e | AndreasHae/tictactoe-py | /model/test_game.py | 823 | 3.6875 | 4 | import unittest
from model.game import Game
class GameTest(unittest.TestCase):
def setUp(self):
self.game = Game()
def test_next_player(self):
first_player = self.game.next_player
self.game.turn(0, 0)
second_player = self.game.next_player
self.game.turn(1, 0)
self.assertEqual(first_player, self.game.next_player)
self.game.turn(0, 1)
self.assertEqual(second_player, self.game.next_player)
def test_turn_input_checked(self):
with self.assertRaises(AssertionError):
self.game.turn(-1, -1)
with self.assertRaises(AssertionError):
self.game.turn(3, 3)
def test_turn_cell_occupied(self):
self.game.turn(0, 0)
with self.assertRaises(AssertionError):
self.game.turn(0, 0)
|
a35bffa98fef5c129aefcb1a776f97f5d4c26ed0 | Dylan-Barclay/fundamentals | /functions_basic_ii/functions_basic_ii.py | 707 | 3.75 | 4 | # 1.
def countDown(max):
for x in range(max,-1,-1):
print(x)
countDown(10)
print('')
#2.
def printReturn(first, second):
print(first)
return(second)
print(printReturn(1,2))
print('')
#3.
x = [1,2,3,4,5,6,7,8,9]
def firstPlusLength(x):
print(x[0] + len(x))
firstPlusLength(x)
print('')
#4.
def valuesGreaterThanSecond(arr):
new_arr = []
if len(arr) < 2:
return False
else:
print(arr[2])
for x in arr:
if x >= arr[2]:
new_arr.append(x)
return new_arr
print(valuesGreaterThanSecond([1,10,3,5,8]))
# 5
def thisLengthThatValue(length, value):
return(f'{value},' * length)
print(thisLengthThatValue(4,7))
|
d745b37537b120f5ba8789f87c1c7940ddda64f6 | fzingithub/SwordRefers2Offer | /3_Offer2nd-HandWriting/3_Queue&Stack/2_队列和栈_队列中的最大值.py | 848 | 3.9375 | 4 | class MaxQueue:
def __init__(self):
self.queue = []
self.IO2Queue = [] # 维护一张单调非减的双端队列 [5,3,3,1_最短回文串.py]
def max_value(self):
if not self.queue:
return -1
else:
return self.IO2Queue[0]
def push_back(self, value):
while self.IO2Queue and self.IO2Queue[-1] < value:
self.IO2Queue.pop()
self.IO2Queue.append(value)
self.queue.append(value)
def pop_front(self):
if not self.queue:
return -1
value = self.queue.pop(0)
if value == self.IO2Queue[0]:
self.IO2Queue.pop(0)
return value
# Your MaxQueue object will be instantiated and called as such:
# obj = MaxQueue()
# param_1 = obj.max_value()
# obj.push_back(value)
# param_3 = obj.pop_front() |
27225a0aa68a2ff5d62182850c1c8c9ccc8270d4 | IlyaNazaruk/python_courses | /HW/10/task_10_4.py | 804 | 3.65625 | 4 | # Имеются два текстовых файла с одинаковым числом строк.
# Выяснить, совпадают ли их строки.
# Если нет, то получить номер первой строки, в которой эти файлы отличаются друг от друга.
def compare_lines(lines_1, lines_2):
for number, line in enumerate(lines_1):
if line != lines_2[number]:
return number
return -1
first_file = open('task_10_4_1.txt')
second_file = open('task_10_4_2.txt')
lines_1 = first_file.readlines()
lines_2 = second_file.readlines()
first_file.close()
second_file.close()
result = compare_lines(lines_1, lines_2)
if result == -1:
print('files are the same')
else:
print('the bad line is', result)
|
b373b3fcbc02ad49b3582da332394ecaa60902c9 | brajesh-rit/hardcore-programmer | /Rough/fibonacci_memo.py | 201 | 3.625 | 4 | def fib (n, memo = {}):
if (n in memo):
return memo[n]
if (n <= 2):
return 1
memo[n] = fib(n-1 , memo ) + fib(n-2, memo)
return memo[n]
print(fib(6))
print(fib(7))
print(fib(8))
print(fib(50)) |
44767425956f3596d6a1eac5d9ceae408d4a2beb | qianhk/ToChildren | /main.py | 1,417 | 4.15625 | 4 | #!/usr/bin/env python3
# coding=utf-8
import time
def print_hi(name):
print(f'Hi, {name}')
def is_leap_year(year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print(f'{year}年是闰年')
# print(f'\033[0;32m{year}年是闰年\033[0m')
else:
print(f'{year}年不是闰年')
# print(f'\033[0;31m{year}年不是闰年\033[0m')
def pythagorean_triple():
total = 0
for_total = 0
# for a in range(1, 101):
# for b in range(1, 101):
# for c in range(1, 101):
# for_total += 1
# if a * a + b * b == c * c:
# total += 1
# print(f'勾股数: {a} {b} {c}')
for c in range(1, 101):
for b in range(1, c):
for a in range(1, b):
for_total += 1
# time.sleep(0.00000001)
if a * a + b * b == c * c:
total += 1
print(f'勾股数: {a} {b} {c}')
print(f'\n勾股数共 {total} 个, 总循环 {for_total} 次。')
if __name__ == '__main__':
print_hi('Hong Kai')
# is_leap_year(100)
# is_leap_year(400)
# is_leap_year(2021)
# is_leap_year(2020)
# is_leap_year(2000)
# is_leap_year(1900)
# while True:
# input_year = int(input('请输入年份:'))
# is_leap_year(input_year)
pythagorean_triple()
|
2fee5df6830ffb59ad18aac03f87731c209de0ac | reokashiwa/KyotoPythonDrill | /section2.py | 863 | 3.859375 | 4 | a = 1 + 2
# aの値を標準出力に出力します。
print(a)
# => a
# idはpythonのbuilt-in functionです。
# Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
# オブジェクトとしての固有値を出力してくれる、という理解でいいのかな。
print(id(a))
# => 4545919968
# 実行するごとに変化します。
# typeもpythonのbuilt-in functionで、
# With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
# だそうです。つまり、
print(type(a))
# => <class 'int'>
# は、
print(a.__class__)
# => <class 'int'>
# と同値になるということですね。
|
1b68a8e7dda9a6d812c4f6c2407797177ad9c621 | campbellmarianna/Code-Challenges | /python/spd_2_4/two_sum_solutions.py | 1,426 | 3.921875 | 4 | '''
Two Sum Problem:
Given an array a of n numbers and a target value t, find two numbers whose sum is t.
Example: a=[5, 3, 6, 8, 2, 4, 7], t=10 => [3, 7] or [6, 4] or [8, 2]
There are multiple ways to solve Two Sum.
What is described below:
- solution ideas
- code implementations
'''
# Solution Idea #1
# - create a set of all items, get number from set subtract from target and see if the complement is in the set if it is return those two numbers in a list as the result
def two_sum1(a, t):
'''Liability: does not haddle duplicates, only unique values''' # 4
result = []
seen = set(a) # {5, 3, 6, 8, 2, 4, 7}
for num in seen:
complement = t - num
if complement == num:
continue
if complement in seen:
result.append(num)
result.append(complement)
return result
# Solution Idea #2
# - sort w/2 pointers front and back and them together and see if they equal the target, if so add them to the result
def two_sum2(a, t):
result = []
a_sorted = sorted(a)
i = 0
j = -1
while i <= len(a_sorted)//2:
two_sum = a_sorted[i] + a_sorted[j]
if two_sum == t:
result.extend([a_sorted[i], a_sorted[j]])
return result
i += 1
j -= 1
if __name__ == '__main__':
a = [5, 3, 6, 8, 2, 4, 7]
t = 10
# print(two_sum1(a, t))
print(two_sum2(a, t))
|
9ad1d92dbe259f710b86505589c321e07b3365c5 | zhuliangnan/Python_Learning-journey | /untitled/Day3_function.py | 1,422 | 3.765625 | 4 | #函数的使用与定义
#abs(x) 绝对值
print(abs(-97.4))
#max(a,b,c,d...) 返回最大值
print(max(1.9,1.7,9.0,6))
l=[1,6,9,4,79]
print(max(l))#显然它也可以接受 list类型
#类型转换函数 int() str() bool()
print(int('657'))
#print(int('a')) 这个是不行的
print(str(234.8))
print(bool(-1),bool(4),bool('a'),bool(''),bool(0))#空字符串和0都是false
print('this is following is def function()\n')
#函数定义 def
def myfirst_fun(x):
if x>=18:
return 'adult'
else:
return 'child'
print(myfirst_fun(23))
#如果我们把myfirst_fun 保存在 abstest.py中 我们可以使用 from abstest import myfirst_fun 来导入,具体表现为
#from abstest import myfirst_fun
#myfirst_fun(23)
#如果要定义一个什么都不干空函数 用pass 其作用在于现在不知道想运行什么写什么代码 可以作为占位符使用 以后想起来了在写
def nop(x):
if x<=0:
pass
print(nop(-6))
#可以返回多个值 实际上是返回一个tuple
#这里值得关注的是angle=0为默认值 我们可以不给这个值 默认参数一定要指向不可变的值
import math
def move(x,y,step,angle=0):
nx=x+step*math.cos(angle)
ny=y-step*math.sin(angle)
return nx,ny
x,y=move(100,100,60,math.pi/6)
print(x,y)
print(move(100,100,60,math.pi/6))#这里我们可以发现其实返回的还是一个值 tuple
print(move(100,100,math.pi/6))#我们这里不给angle的值它默认就是0 |
6fcbd4940406ebaacdd52d2a1136e1bfc14797d8 | stephenchenxj/myLeetCode | /isomorphicString.py | 3,110 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 20:56:26 2019
@author: dev
205. Isomorphic Strings
Easy
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
Accepted
258,065
Submissions
663,196
"""
class Solution(object):
def __init__(self):
self.hashmapA = {}
self.hashmapB = {}
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
# if not s or not t:
# return True
dic = {}
dic2 = {}
count = 0
count2 = 0
for a,b in zip(s,t):
print(a)
print(b)
if not a in dic:
dic[a] = count
count += 1
if not b in dic2:
dic2[b] = count2
count2 +=1
for a,b in zip(s,t):
if not dic[a] == dic2[b]:
return False
return True
index = 0
for c in s:
if c not in self.hashmapA:
self.hashmapA[c] = [index]
else:
self.hashmapA[c].append(index)
index += 1
index = 0
for c in t:
if c not in self.hashmapB:
self.hashmapB[c] = [index]
else:
self.hashmapB[c].append(index)
index += 1
listA = []
for kA in self.hashmapA:
listA.append(self.hashmapA[kA])
listB = []
for kB in self.hashmapB:
listB.append(self.hashmapB[kB])
print (listA)
print (listB)
# if listA == listB:
# return True
# else:
# return False
for index in listA:
if index not in listB:
return False
return True
def main():
s = 'abcdefgh'
t = 'xyzstu'
u = '123456'
for a,b in zip(s,t):
print(a)
print(b)
for a,b,c in zip(s,t,u):
print(a)
print(b)
print(c)
import sys
ret = Solution().isIsomorphic('egg', 'add')
out = (ret)
print (out)
ret = Solution().isIsomorphic('ab', 'aa')
out = (ret)
print (out)
if __name__ == '__main__':
main() |
e66d56d490163e074f2903239510c82a6010c524 | jyoon1421/py202002 | /Ch3_2.py | 212 | 3.5625 | 4 |
test_size = int( input() )
for i in range (test_size):
num, text = input().split()
num = int(num)
text = str(text)
for j in range (len(text)):
print( num * text[j], end='' )
print()
|
5604e0759263490a051edeef94af96ac14e7a4de | billyxs/notes.md | /python/learning/code/student_manager/hs_student.py | 290 | 3.703125 | 4 | # Class inheritance
class HighSchoolStudent(Student):
school_name = "Springfield High"
def get_school_name(self):
return "This is a High School Student"
def get_name_capitalize(self):
orig_value = super().get_name_capitalize()
return orig_value + "HS"
|
ab0dfc3eb968dbb106aa79ac5a44ac30d75c3e12 | norwald/ThinkStats | /first.py | 2,199 | 3.921875 | 4 | #!/usr/bin/python
from resources import survey
class First:
"""
Calculates number of live birds
Args:
list of pregnancy records
Returns:
number of live birds
"""
def calc_live_births(self):
live_births = 0
for record in self.get_records():
if record.outcome == 1:
live_births += 1
return live_births
"""
Partitions live birds in first-time birds and other
Args:
list of pregnancy records
Returns:
tupple (records first-time babies, records other babies)
"""
def partition_live_birds(self):
first_births = []
other_births = []
for record in self.get_records():
if record.outcome == 1:
if record.birthord == 1:
first_births.append(record)
else:
other_births.append(record)
return first_births, other_births
"""
Calculate average birth length
Args:
list of pregnancy records
Returns:
average pregnancy length of list's elements
"""
def average_preg(self, records):
prg_sum = 0.0
for record in records:
prg_sum += record.prglength
return float(prg_sum/len(records))
def get_records(self):
return self.table.records
def __init__(self):
self.table = survey.Pregnancies()
self.table.ReadRecords()
def main():
first = First()
print 'Number of pregnancies: ', len(first.get_records())
print 'Number of live births: ', first.calc_live_births()
first_births, other_births = first.partition_live_birds()
print 'Number of first-time births', len(first_births)
print 'Number of not first-time births', len(other_births)
avg_first_births = first.average_preg(first_births)
avg_other_births = first.average_preg(other_births)
print 'Average duration of first-time pregnancies', avg_first_births
print 'Average duration of not first-time pregnancies', avg_other_births
print 'Pregnancy duration difference in days: ', (avg_first_births - avg_other_births) * 7
if __name__ == "__main__":
main()
|
6510ba9b132db8838f7243200ba22b73094cdaa8 | jordanchenml/leetcode_python | /0101_SymmetricTree.py | 825 | 4.3125 | 4 | '''
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.mirrorVisit(root.left, root.right)
def mirrorVisit(self, left, right):
if left is None and right is None:
return True
try:
if left.val == right.val:
if self.mirrorVisit(left.left, right.right) \
and self.mirrorVisit(left.right, right.left):
return True
return False
except:
return False
|
b7d8ecdd9c367717410adbddc131170569ea9bea | filipzivanovic/57-Exercises-for-Programmers | /3_Calculations/13_Determining_Compound_Interest.py | 1,003 | 3.9375 | 4 | import math
def inputNumber(what):
while True:
try:
userInput = float(input("Enter the %s: " % what))
if(userInput <= 0):
print("Not a positive number! Try again.")
continue
except ValueError:
print("Not a number! Try again.")
continue
else:
return userInput
break
P = inputNumber("principal")
r = inputNumber("interest")
t = inputNumber("number of years")
n = inputNumber("number of times the interest is compounded per year")
def calculateCompoundInterest(P, r, t, n):
A = P * pow((1 + r / 100 / n), n * t)
return A
A = calculateCompoundInterest(P, r, t, n)
print("$%.2f invested at at %.2f%% for %d years compounded %d times per year is $%.2f." % (P, r, t, n, A))
print("By years:")
for i in range(int(t)):
A = calculateCompoundInterest(P, r, i+1, n)
print("After %d. year at %.2f%%, the investment of $%.2f will be worth $%.2f." % (i+1, r, P, A)) |
bd7ce9e260eaf740b3e33badc6a39ac9bbda7a0e | Sabinu/6.00x | /2.03 Lecture 16 - Sampling & Monte Carlo Methods/01_rollDice.py | 1,005 | 3.5625 | 4 | import random
def rollDie():
return random.choice([1, 2, 3, 4, 5, 6])
def rollN(n):
result = ''
for i in range(n):
result += str(rollDie())
return result
print('5 random rolls of a Die:', rollN(5))
def getTarget(goal):
numTries = 0
numRolls = len(goal)
while True:
numTries += 1
result = rollN(numRolls)
if result == goal:
return numTries
def runSim(goal, numTrials):
total = 0
for i in range(numTrials):
total += getTarget(goal)
# print 'Average number of tries =', total / float(numTrials)
print('Probability =', 1 / (total / float(numTrials)))
print('Probability =', 0.0001286)
runSim('11111', 100)
runSim('54324', 100)
def atLeastOneOne(numRolls, numTrials):
numSuccess = 0
for i in range(numTrials):
rolls = rollN(numRolls)
if '1' in rolls:
numSuccess += 1
fracSuccess = numSuccess / float(numTrials)
print(fracSuccess)
atLeastOneOne(10, 1000) |
58d5badfaa74bc2e318ee4af1cc7822b56f8722e | rayhan60611/Python-A-2-Z | /8.Chapter-8/05_pr_01.py | 630 | 4.125 | 4 | def maximum(num1, num2, num3):
if (num1>num2):
if(num1>num3):
return num1
else:
return num3
else:
if(num2>num3):
return num2
else:
return num3
m = maximum(13, 55, 2)
print("The value of the maximum is " + str(m))
# different Solve Problem no 1 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
f1=0
f2=0
def maximum ( x , y , z):
if x>y:
f1=x
else:
f1=y
if y>z:
f2=y
else:
f2=z
if f1>f2:
return f1
else:
return f2
a=maximum(9, 15, 6)
print( f"The Maximum Number Is: {a}") |
a4eee347a9bf8c969cdb29cc2e8c3ca3c37d27f1 | BryanSWong/Python | /ex21/ex21sd4.py | 785 | 4.15625 | 4 | # for study drill part four make a simple formula and use the functions to make it.
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
added = add(5, 5)
subtracted = subtract(10, 5)
multiplied = multiply( 5, 5)
divided = divide(120, 2)
# The formula is divide the adding of mutiplication of a subtraction
# divie(divided, add(added, multiply(multiplied, subtract(subtracted, 3))))
simple = divide(divided, add(added, multiply(multiplied, subtract(subtracted, 3))))
print "The formula result is equal to: ", simple
print
|
f451fa6bde2aa192e23f8ffca14ba439465759b7 | spiderr7/cls-python | /Desktop/Program/Variable's/8.non_local.py | 193 | 3.65625 | 4 | a,b=1,2
print(a,b)
def outer():
a,b=10,20
print(a,b)
def swap():
nonlocal a,b
a,b=b,a
print(a,b)
print(a,b)
swap()
print(a,b)
outer()
print(a,b)
|
282b22b45fd627098c97c4cc1859a49424b29f8c | hanbyeol94628/demoHanbyeol | /src/main/webapp/WEB-INF/uploadFiles/5slvsVtpwJnD67y2I0DokN2UQKJ0a352.py | 825 | 3.921875 | 4 | """
print('\n\n')
print("태어난 년도를 입력하세요 : ", end="")
years = input()
print(int(years) >= 90)
print('\n\n')
print("파이썬 영어 철자를 입력하시오 : ", end="")
str = input()
print(str == 'python')
print('\n\n')
print('첫번째 수 입력 : ', end='')
num1 = input()
print('두번째 수 입력 : ', end='')
num2 = input()
print(int(num1) % int(num2) == 0)
print('\n\n')
print("12의 약수일까? : ", end="")
number = input()
print(12%int(number) == 0)
"""
print("\n\n")
print("정거장 수를 입력하세요 : ", end="")
stopP = int(input())
m = 2
if stopP > 10 :
m = 4
time = int(stopP) * m
hour = time//60
minute = time%60
if hour != 0 :
print("총 소요시간은 ", hour, "시간", minute,"분입니다.")
else :
print("총 소요시간은 ", minute,"분입니다.") |
e79181b0dcd9b59101eebba191777426fff80dc6 | vasantidatta/PythonProjectDemo | /Demo_1/String_demo1.py | 859 | 3.953125 | 4 | # String is immutable sequence of characters
a="The only truth is Death"
print(a)
print(a[6])
print(len(a))
print("only" in a)
print("love" not in a)
for x in "shreesh":
print(x)
y=0
while y<len("shreesh"):
print(y)
y=y+1
if "truth" in a:
print("yes, 'free' is present")
if "love" not in a:
print("no, 'love' is not present")
z='''1)Does god really exist?
why things work for some people and never for some people.
sometimes i feel life is not fair'''
print(z)
c="""2)Nothing works in front of your own karma,
we have to face the results of our own karma
no matter how much we stay good and devotional"""
print(c)
print(c+z)
# String slicing
print(a[4:8])
print(a[4:])
print(a[:6])
print(a[-2:-8])
print(a[-3:])
print(a[:-6])
|
0cac1acd6fad5bcf776f4048aaa3dd8403698ee0 | CodeGuardianAngel96/OOPS-I-Posted | /Automobile.py | 1,034 | 4.46875 | 4 | '''
Create a class Automobile with an attribute color with default value “black”.
It contains instance variables name,mileage,max_speed.
Class vehicle is inherited by both classes lorry and bus.
These classes doesn’t contain any properties of their own.
Color: White, Vehicle name: ashokleyland load, Speed: 180, Mileage: 12
Color: White, Vehicle name: scania AC, Speed: 240, Mileage: 18
'''
# This document is still in process
class Automobile:
def __init__(self, name, color = 'black', mileage, maxSpeed):
self.name = name
self.mileage = mileage
self.maxSpeed = maxSpeed
self.color = color
def display(self):
print(self.name)
print(self.mileage)
print(self.maxSpeed)
print(self.color)
class Lorry(Automobile):
def __init__(self):
super().__init__()
class Bus(Automobile):
super().__init__()
if __name__ == "__main__":
l = Lorry('Ashoka Leyland', 'White', 12, 240)
l.display()
|
5ee2e17802fd394d5fdc62081794a547b2698047 | TestACCOUNT2112/labpy02 | /TugasPraktikum2.py | 355 | 3.78125 | 4 | A = int(input("Masukkan bilangan A: "))
B = int(input("Masukkan bilangan B: "))
C = int(input("Masukkan bilangan C: "))
if A > B and A > C:
maks = A;
print("Bilangan Terbesar adalah: A.",maks);
elif B > C and B > A:
maks = B;
print("Bilangan Terbesar adalah: B.",maks);
else:
maks = C;
print("Bilangan Terbesar adalah: C.",maks);
|
c63c516d35764153c2f5fe17bb752621aeedb225 | udaycoder/Minance | /minance1.py | 1,850 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 19:43:07 2018
@author: udaycoder
"""
def isLeapYear(year):
if((year%400 == 0) or (year%100!=0 and year%4==0)):
return True
else:
return False
def findNumberOfExtraDays(year):
count = 0;
if(year>2000):
for i in range(2001,(year+1)):
if(isLeapYear(i)):
count+=2
else:
count+=1
elif(year<2000):
for i in range((year+1),2001):
if(isLeapYear(i)):
count+=2
else:
count+=1
return count
def dayOfExtraDay(year):
day = ["Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday","Monday"]
revDay = ["Tuesday","Monday","Sunday","Saturday","Friday","Thursday","Wednesday"]
currIn = 0;
if(year==2000):
return day[currIn]
elif(year>2000):
currIn = findNumberOfExtraDays(year) % 7
return day[currIn]
elif(year<2000):
currIn = findNumberOfExtraDays(year)%7
return revDay[currIn]
year = int(input("Input: "))
print("Output: ")
if(isLeapYear(year)):
print(dayOfExtraDay(year))
else:
print("This is not a leap year")
year1=year
while(True):
year1+=1
if(isLeapYear(year1)):
break
d1 = year1-year
year2=year
while(True):
year2-=1
if(isLeapYear(year2)):
break
d2 = year-year2
if(d1==d2):
print("There are two leap years equidistant from current leap year")
print(year1," ",dayOfExtraDay(year1))
print(year2," ",dayOfExtraDay(year2))
elif(d1<d2):
print("Closest leap year: ",year1)
print(dayOfExtraDay(year1))
elif(d1>d2):
print("Closest leap year: ",year2)
print(dayOfExtraDay(year2)) |
4e5cfb93e785ced4c3344709c46bf95dabec016b | lianglee123/leetcode | /101~200/151~160/151.reverse_words_in_a_string.py | 328 | 3.765625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
tokens = list(filter(lambda x: x, s.split()))
tokens.reverse()
return " ".join(tokens)
if __name__ == '__main__':
s = Solution().reverseWords
print(s("the sky is bule"))
print(s(" hello world! "))
print(s("a good example")) |
2a90fc1df38db0cb5e69c4ebe843e0d5d7bc6fd4 | mcintoshsg/soccer_league | /soccer_league.py | 3,437 | 4.25 | 4 | import csv
# create a list to hold the entire league
football_league = [[],[],[]]
# Manually create a single collection that contains all information for all 18 players.
# Each player should themselves be represented by their own collection.'''
def get_all_players():
# open the file and read intp a single dictonary
with open('soccer_players.csv', newline = '') as csvfile:
soccer_reader = csv.DictReader(csvfile, delimiter = ',')
players = list(soccer_reader)
# assign all the playesr to a team
create_teams(players)
# write the letters to the parents
write_letters(players)
# Create appropriate variables and logic to sort and store players into three
# teams: Sharks, Dragons and Raptors.
# Be sure that your logic results in all teams having the same number of
# experienced players on each.
# The collections will be named sharks, dragons, raptors, and league.'''
def create_teams(players):
# create a variable to count the number of yes's and the number of no's we
# have added to each team
yes_ctr = 0
no_ctr = 0
# step 1: with the len of the list / 3 - this will tell us how many
# players we have to add the 3 teams
team_count = len(players) / 3
# step 2: create the 3 teams
for player in players:
if player['Soccer Experience'].upper() == "YES":
football_league[yes_ctr].append(player)
yes_ctr += 1
else:
football_league[no_ctr].append(player)
no_ctr += 1
if yes_ctr == team_count / 2:
yes_ctr = 0
if no_ctr == team_count / 2:
no_ctr = 0
# check the average of player height +/- 1
def check_height(player):
pass
# Create a function named write_letter that takes a player and returns a
# string of the letter to their guardian(s).
# Be sure the string is formatted as a letter and starts with "Dear" and the
# guardian(s) name(s) and with the additional required information:
# player's name, team name, and date & time of first practice.'''
def write_letters(players):
for player in players:
if player in football_league[0]:
player['Team'] = 'Sharks'
player['Practice Time'] = 'March 17th at 3pm'
elif player in football_league[1]:
player['Team'] = 'Dragons'
player['Practice Time'] = 'March 17th at 1pm'
else:
player['Team'] = 'raptors'
player['Practice Time'] = 'March 18th at 1pm'
letter_string = """\n\nDear {Guardian Names}\n
This is to inform you that {Name} will be playing for {Team} and
the first team practice will begin on the {Practice Time}.\n
Please ensure {Name} is on time.
\n\nKind Regards,
\nStuart McIntosh """.format(**player)
save_letters(letter_string, player)
# Save all 18 letters to disk, giving each letter a filename of the player's
# name, in lowercase and with underscores and ending in .txt.
# For example, kenneth_love.txt.'''
def save_letters(letter, player):
file_name = player['Name'].replace(' ', '_') + '.txt'
letter_file = open(file_name, 'w')
letter_file.write(letter)
letter_file.close
# Ensure your script doesn't execute when imported; put all of your logic and
# function calls inside of an if __name__ == "__main__": block.
if __name__ == '__main__':
get_all_players()
|
a9e24e57fd591199cdc9317372bdacb119c18d96 | wangyendt/LeetCode | /Easy/557. Reverse Words in a String III/Reverse Words in a String III.py | 305 | 3.75 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# author: wang121ye
# datetime: 2019/7/16 19:38
# software: PyCharm
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join([l[::-1] for l in s.split(' ')])
so = Solution()
print(so.reverseWords('Let\'s take LeetCode contest'))
|
4abbe3bae03cdf75c815b208b553c01e63236889 | benwatson528/advent-of-code-20 | /main/day10/adapter_array.py | 789 | 3.5 | 4 | from collections import defaultdict
from typing import List
def solve_diffs(adapters: List[int]) -> (int, int):
sorted_adapters = sorted(adapters)
one_diffs = 0
three_diffs = 1
last_val = 0
for adapter in sorted_adapters:
diff = adapter - last_val
if diff == 1:
one_diffs += 1
if diff == 3:
three_diffs += 1
last_val = adapter
return one_diffs, three_diffs
def solve_combinations(adapters: List[int]) -> int:
sorted_adapters = sorted(adapters)
combinations = defaultdict(int)
combinations[0] = 1
for adapter in sorted_adapters:
combinations[adapter] = combinations[adapter - 1] + combinations[adapter - 2] + combinations[adapter - 3]
return combinations[sorted_adapters.pop()]
|
eaa9e5b6401ce2d03e083ed82b7d20434766207b | diegobraga92/Algorithms | /Algorithms/Fibonacci/fibonacci_partial_sum.py | 966 | 3.5625 | 4 | # Uses python3
# Gets the last digit of the sum between two fibonacci numbers.
# Since both have the same period size (60 for mod 10), adds in this range
def calc_fib_mod(n, to, m):
period = [0,1, 1 % m]
i = 2
while not (period[i] == 1 and period[i-1] == 0):
i = i+1
period.append((period[i - 1] + period[i - 2]) % m)
# Subtracts 1 from i to invert its initial value of 2
modIndexFrom = n % (i - 1)
modIndexTo = to % (i - 1)
# Used a while instead of a straight for because when modIndexTo < modIndexFrom it is expected to do the sum by increasing to 60 (i - 1) and resetting
sum = 0
i = modIndexFrom
if modIndexTo == 59:
modIndexTo = -1
while i != modIndexTo + 1:
sum = (sum + period[i]) % m
i = i + 1
if (i >= 60):
i = 0
return sum
if __name__ == '__main__':
from_, to = map(int, input().split())
print(calc_fib_mod(from_, to, 10)) |
ef6ebcfd8b24024545cb232fb75fc1351fe90924 | AMx12/Python | /Application.py | 1,207 | 4 | 4 | from random import randint
import re
cont = True
while cont == True:
g = input("Guess a number between 1 and 10: ")
while g == "":
g = input("Enter a number between 1 and 10: ")
# regex = re.search('[a-zA-Z]+',g)
# amt = regex.group()
#use = len(amt)
# while use > 0 :
# g = input("Please enter a number between 1 and 10: ")
guessedNum = int(g)
rnd = randint(1,10)
while guessedNum > 10:
guessedNum = int(input("Enter a number between 1 and 10: "))
while guessedNum < 0:
guessedNum = int(input("Enter a number between 1 and 10: "))
if guessedNum == rnd:
print("Congratulations you guessed the number")
else:
print("Better luck next time")
print("The number was %d" % rnd)
cond = input("Do you wish to try again? Y/N: ")
again = False
while not again :
if cond.upper() == "N":
cont = False
again = True
elif cond.upper() == "Y":
cont = True
again = True
else:
cond = input("Please input Y/N: ")
|
0e0d4e01a94355a15b22de3343d8937e4c123279 | trofik00777/EgeInformatics | /probn/05.04/14.py | 185 | 3.5625 | 4 | def f(a, to):
n = a
s = "0123456789"
answ = ""
while n > 0:
b = n % to
answ += s[b]
n //= to
return answ[::-1]
print(f(67, 3))
|
f4917affc7849e5cdfdb359cd467151d4b651cbf | kaisersamamoon/py-notes | /作业/任务3.py | 1,895 | 3.734375 | 4 | """
print ("圆的计算")
print ( '1 ("通过半径计算") 2 ("通过面积计算") 3 ("通过周长计算")' )
times = 1
while times < 1000:
flyme = int( input ( "请选择你的模式:" ) )
a ,b , c = 1, 2 , 3
if flyme == a:
banjin = input ( "请输入圆的半径r:" )
ban = float (banjin)
r = ban
s = 3.14*( r * r )
print ( "面积:" , s )
c = r * 3.14 * 2
print ( "周长:" , c )
if flyme == b:
mianji = input ( "请输入圆的面积s:" )
ban = float (mianji)
s = ban
r = ( s / 3.14 )** 0.5
print ( "半径:" , r )
c = (( s / 3.14 )** 0.5 )*3.14 * 2
print ("周长:" , c )
if flyme == d:
zhouchang = input ( "请输入圆的周长c:" )
ban = float (zhouchang)
c = ban
r = ( c / 2 / 3.14 )
print ( "半径:" , r )
s = ( c / 2 / 3.14 ) * 3.14
print ( "面积:" , s )
"""
print ("圆的计算")
times = 1
while times < 1000:
print ( '1 ("通过半径计算") 2 ("通过面积计算") 3 ("通过周长计算")' )
flyme = int( input ( "请选择你的模式:" ) )
a ,b , c = 1, 2 , 3
if flyme == a:
banjin = float (input ( "请输入圆的半径r:" ))
r = banjin
s = 3.14*( r * r )
print ( "面积:" , s )
c = r * 3.14 * 2
print ( "周长:" , c )
if flyme == b:
mianji = float (input ( "请输入圆的面积s:" ))
s = mianji
r = ( s / 3.14 )** 0.5
print ( "半径:" , r )
c = (( s / 3.14 )** 0.5 )*3.14 * 2
print ("周长:" , c )
if flyme == c:
zhouchang = float (input ( "请输入圆的周长c:" ))
c = zhouchang
r = ( c / 2 / 3.14 )
print ( "半径:" , r )
s = ( 3.14 * r**2 )
print ( "面积:" , s )
if flyme > 3 or flyme <1:
print ( "选择错误,请重新输入:" )
|
5267d6ee06c00a2d493a4b819744f78ae42f0209 | nayana09/assesment4.1 | /initfun.py | 814 | 4.0625 | 4 | class person:
#init method or constructor
'''here name and age are the 2 parameters'''
def __init__(self, name, age):
self.name = name
self.age = age
#sample method
def my_fun(self):
print("My name is " + self.name)
p1 = person ("Ram", 40)
p2 = person ("sham", 33)
p3 = person ("kamala", 50)
p1.my_fun()
p2.my_fun()
p3.my_fun()
class person:
TITLES = ('Dr', 'Mr', 'Mrs', 'Ms')
def __init__(self, title, name, surname):
if title not in self.TITLES:
raise ValueError("%s is not a valid title." % title)
self.title = title
self.name = name
self.surname = surname
person = person("Mrs", "Suray", "Prakash")
print(person.title)
print(person.name)
print(person.surname)
|
fff4e75c64dc51f2102ca33a7339ebbbbe88d129 | tenqaz/crazy_arithmetic | /leetcode/剑指offer/剑指 Offer 11. 旋转数组的最小数字.py | 745 | 3.75 | 4 | """
@author: zwf
@contact: [email protected]
@time: 2023/6/24 12:48
@desc:
https://leetcode.cn/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/?envType=study-plan-v2&envId=coding-interviews
"""
from typing import List
class Solution:
def minArray(self, numbers: List[int]) -> int:
"""
遍历
时间复杂度:O(n)
空间复杂度:O(1)
"""
last_num = numbers[0]
for num in numbers[1:]:
if num >= last_num:
last_num = num
else:
return num
return numbers[0]
if __name__ == '__main__':
s = Solution()
# numbers = [3, 4, 5, 1, 2]
numbers = [1, 3, 5]
ret = s.minArray(numbers)
print(ret)
|
d3503833fb51cfa36522167090ce838be67fc2f5 | pushparajkum/python | /13lecture_17feb/disjoint_lists.py | 461 | 4.03125 | 4 | def disjoint(list1, list2):
flag = True
for i in range(len(list1)):
if list1[i] in list2:
flag = False
return flag
def main():
list1 = eval(input("Enter list1 : "))
list2 = eval(input("Enter list2 : "))
res = disjoint(list1,list2)
if res:
print("The 2 lists are disjoint..")
else:
print("The 2 lists are not disjoint..")
if __name__ == '__main__':
main() |
01283815db276f99bccfda264239303108f8ae5d | kaushikacharya/cpp_practise | /online_judge/hackerrank/python/poisson_distribution_3.py | 1,111 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/poisson-distribution-3/problem
# Sept 12, 2018
from math import e
def compute_prob(lambda_val, k):
numer = pow(lambda_val, k) * pow(e, -1 * lambda_val)
denom = reduce(lambda x, y: x * y, range(1, k + 1) if k > 0 else [1])
prob = numer / denom
return prob
val_lambda = 3
# (a) Find the probability that no calls come in a given 1 minute period.
prob_no_call = compute_prob(lambda_val=val_lambda, k=0)
prob_a = prob_no_call
# (b) Assume that the number of calls arriving in two different minutes are independent.
# Find the probability that atleast two calls will arrive in a given two minute period.
# We will compute the probability of complement.
# (i) No calls in both minutes of two minute period.
# product because event in 1st minute is independent of 2nd minute in 2 minute period.
# (ii) No call in one minute but 1 call in another minute.
prob_single_call = compute_prob(lambda_val=val_lambda, k=1)
prob_b = 1 - prob_no_call*prob_no_call - 2*prob_no_call*prob_single_call
print "{0:.3f}".format(prob_a)
print "{0:.3f}".format(prob_b)
|
b10bbbaed265f274e81b8dc589673bd1e2e177f0 | EPlatonenkova/beginner_python | /lesson_1/2.py | 254 | 3.515625 | 4 | a = None
while a != 0:
a = int(input('Введите время в секундах: '))
h = a // (60 * 60)
ost = a - h * 60 * 60
m = ost // 60
s = ost - m * 60
print(f'{str(h).zfill(2)}:{str(m).zfill(2)}:{str(s).zfill(2)}')
|
63a9d247ec9769bb84e5d100b53541cecc72ca38 | issarakoat/problems_with_py3 | /dynamic-programming/fibonacci.py | 343 | 3.78125 | 4 |
def fibonacci(n):
if(n == 0):
return 0
a = 0
b = 1
for i in range(2, n):
c = a + b
a = b
b = c
return a + b
assert(fibonacci(1) == 1)
assert(fibonacci(2) == 1)
assert(fibonacci(3) == 2)
assert(fibonacci(4) == 3)
assert(fibonacci(5) == 5)
assert(fibonacci(6) == 8)
assert(fibonacci(7) == 13) |
d9e79b4d8bf245d7eafcd6e89bdf1ed30798b2a4 | mattssonj/potential-couscous | /main/python_server.py | 1,833 | 3.65625 | 4 | '''
Server class that sends the data to its listeners
'''
import socket
import threading
HOST = '' #this will be device ip
PORT = 8888
def clientthread(conn, listener): # shadow-naming s becomes conn from here on.
# Sending message to connected client
print('Someone connected to server...')
# infinite loop so that function do not terminate and thread do not end.
while True:
# Receiving from client
byteData = conn.recv(1024) # equals java read-func, nums specify maximum byte-size of what could be recv.
# print(('Server received ' + byteData))
data = byteData.decode('utf-8')
data = str(data)
if not (len(data) < 1):
listener(data)
# came out of loop
conn.close()
def listen_for_connections(socket, listener):
while 1:
# wait to accept a connection - blocking call (blocking call means it waits until data is transferd from conn).
conn, addr = socket.accept()
print(('Connected with ' + addr[0] + ':' + str(addr[1])))
# start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the fun
threading.Thread(target=clientthread, args=(conn, listener)).start()
def start_server(listener):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print(('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]))
print('Socket bind complete')
# Start listening on socket
s.listen(10) # the number specifies nums of allowed failed connections before termination
print('Socket now listening')
threading.Thread(target=listen_for_connections, args=(s, listener)).start()
|
d7c2f9d4f3d2b739b882367a8cae5838bd3b3d00 | mgbo/My_Exercise | /2018_2019/_Simple_analogClock/analog_clock.py | 1,871 | 4.375 | 4 |
# Simple Analog Clock in python3
# by @TokyoEdTech
# Part 1: Getting Started
import turtle
import time
wn = turtle.Screen()
wn.bgcolor('black')
wn.setup(width=600, height=600)
wn.title("Simple Analog Clock by @TokyoEdTech")
wn.tracer(0)
# create our drawing pen
pen = turtle.Turtle()
pen.hideturtle() # Не показывать черепаху
pen.speed(0)
pen.pensize(3)
t = turtle.Turtle()
t.penup()
t.goto(0,250)
t.pendown()
t.hideturtle()
t.color('blue')
t.write("This is my first clock", align='center', font=('Arial', 20, 'normal'))
def draw_clock(h, m, s, pen):
# draw clock face
pen.up() # НЕ рисовать когда движется turtle.penup()/ turtle.pu()
pen.goto(0,210)
pen.setheading(180) # повернуть черепаху на n градусов
pen.color("green")
pen.pendown()
pen.circle(210)
# Draw the lines for the hours
pen.penup()
#pen.showturtle()
pen.goto(0,0)
pen.pendown()
pen.setheading(90)
for _ in range(12):
pen.up()
pen.fd(180)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0,0)
pen.rt(30)
# Draw the hour hand
pen.penup()
pen.goto(0,0)
pen.color('white')
pen.setheading(90)
angle = (h/12) * 360
pen.rt(angle)
pen.pendown()
#pen.shape('arrow')
pen.fd(100)
# Draw the minutes hand
pen.penup()
pen.goto(0,0)
pen.color('red')
pen.setheading(90)
angle = (m/60) * 360
pen.rt(angle)
pen.pendown()
pen.fd(120)
# Draw the seconds hand
pen.penup()
pen.goto(0,0)
pen.color('blue')
pen.setheading(90)
angle = (s/60) * 360
pen.rt(angle)
pen.pendown()
pen.fd(180)
while True:
h = int(time.strftime("%I"))
m = int(time.strftime("%M"))
s = int(time.strftime("%S"))
draw_clock(h, m, s, pen)
wn.update()
#time.sleep(1)
pen.clear()
# draw_clock(6, 15, 45, pen)
wn.mainloop() # Конец работы черепахи. Окно не закрывать.
|
c6c309756ebc2bb0f7e53a5056d22d4b5482b088 | ZX1209/gl-algorithm-practise | /leetcode-gl-python/leetcode-21-合并两个有序链表.py | 2,250 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
mergel = ListNode(0)
ans = mergel
while l1 != None or l2 != None:
if l1 == None:
mergel.next = l2
mergel = mergel.next
break
if l2 == None:
mergel.next = l1
mergel = mergel.next
break
if l2.val <= l1.val:
mergel.next = ListNode(l2.val)
mergel = mergel.next
l2 = l2.next
else:
mergel.next = ListNode(l1.val)
mergel = mergel.next
l1 = l1.next
return ans.next
# if __name__ == '__main__':
# ln1 = ListNode(1)
# l1 = ln1
# ln1.next = ListNode(2)
# ln1 = ln1.next
# ln1.next = ListNode(4)
# ln2 = ListNode(1)
# l2 = ln2
# ln2.next = ListNode(3)
# ln2 = ln2.next
# ln2.next = ListNode(4)
# ln2 = ln2.next
# test = Solution()
# test.mergeTwoLists(l1,l2)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution:
# def mergeTwoLists(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# if l2 == None:
# return l1
# if l1 == None:
# return l2
# result = ListNode(0)
# result1 = result
# while l1 and l2:
# if l1.val >= l2.val:
# result1.next = l2
# l2 = l2.next
# else:
# result1.next = l1
# l1 = l1.next
# result1 = result1.next
# while l1:
# result1.next = l1
# l1 = l1.next
# result1 = result1.next
# while l2:
# result1.next = l2
# l2 = l2.next
# result1 = result1.next
# return result.next |
99e93a3a865d98adb2fd06f4574b172165d8f111 | KiwiShow/PythonWeb | /data_structure_and_algorithm/binary_tree.py | 517 | 3.84375 | 4 | class Tree(object):
def __init__(self, element=None):
self.element = element
self.left = None
self.right = None
def traversal(self):
print(self.element)
if self.left is not None:
self.left.traversal()
if self.right is not None:
self.right.traversal()
def test():
t = Tree(0)
left = Tree(1)
right = Tree(2)
t.left = left
t.right = right
# 遍历
t.traversal()
if __name__ == '__main__':
test()
|
ff99819c2c7f7350d69c519015134f2f504cbbb0 | ryangillard/misc | /leetcode/885_spiral_matrix_III/885_spiral_matrix_III.py | 1,381 | 3.65625 | 4 | class Solution(object):
def spiralMatrixIII(self, R, C, r0, c0):
"""
:type R: int
:type C: int
:type r0: int
:type c0: int
:rtype: List[List[int]]
"""
spiral = []
spiral = self.everySquare(R, C, r0, c0, spiral)
return spiral
def everySquare(self, R, C, r0, c0, spiral):
row = r0
col = c0
direction = "right"
min_row = row
max_row = row + 1
min_col = col - 1
max_col = col + 1
while True:
if 0 <= row < R and 0 <= col < C:
spiral.append([row, col])
if len(spiral) == R * C:
return spiral
if direction == "right":
col += 1
if col == max_col:
direction = "down"
min_row -= 1
elif direction == "down":
row += 1
if row == max_row:
direction = "left"
max_col += 1
elif direction == "left":
col -= 1
if col == min_col:
direction = "up"
max_row += 1
elif direction == "up":
row -= 1
if row == min_row:
direction = "right"
min_col -= 1 |
b6deada4c47e1b12131a0b60a32988ed01a4b618 | epmoyer/cascade | /web/cascade/bomstrip.py | 974 | 3.6875 | 4 | """ Strip the UTF-8 Byte Order Mark (BOM) from a file (if it exists)
"""
import codecs
BOMLEN = len(codecs.BOM_UTF8)
def copy_and_strip_bom(infilename, outfilename):
"""Copy file into a new file, excluding the BOM (if it exists)
"""
buffer_size = 4096
with open(infilename, "r+b") as infile:
with open(outfilename, "wb") as outfile:
chunk = infile.read(buffer_size)
if chunk.startswith(codecs.BOM_UTF8):
chunk = chunk[BOMLEN:]
while chunk:
outfile.write(chunk)
chunk = infile.read(buffer_size)
def open_and_seek_past_bom(infilename):
"""Open file, seek past BOM (if it exists), and return the handle to the open file object
"""
infile = open(infilename, "r+b")
chunk = infile.read(BOMLEN * 2)
if chunk.startswith(codecs.BOM_UTF8):
infile.seek(BOMLEN)
else:
infile.seek(0)
return infile
|
8cbfee17ba8f5de9a11f4449c116314fe16fa11a | crazycharles/coding-interview-in-python | /69 扑克牌的顺子.py | 660 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 15:13:06 2019
@author: an
"""
class Solution(object):
def isContinuous(self, numbers):
"""
:type numbers: List[int]
:rtype: bool
"""
if len(numbers) == 0:
return False
zero_lst = []
orig_lst = []
for i in numbers:
if i == 0:
zero_lst.append(i)
else:
orig_lst.append(i)
orig_lst.sort()
if len(set(orig_lst)) != len(orig_lst):
return False
if orig_lst[-1] - orig_lst[0] <= 4:
return True
else:
return False |
ad0b906f7aba16c5d3068c4f61e3bc3fe81d3a7a | tusvhar01/python.project | /IF ELSE.py | 149 | 3.8125 | 4 | a=("harry","HARRY","Harry")
b=input("write your post: ")
if(b in a):
print("yes it is about harry ")
else:
print("no it is not about harry ") |
17e74d5191b3cad65a6573084b5cb9786a37aadc | Prabhat-Thapa45/flask-flower-bq | /src/check.py | 975 | 4.28125 | 4 | def check_flower_by_name(results: tuple, flower_name: str) -> bool:
"""Checks if the given flower_name is available in results if yes returns True else False
Args:
results (tuple): a tuple consisting of dict type as elements from rows of sql tables.
e.g: for table with one row ({'id': 1, 'flower_name': 'Rose', 'price': 6.5, 'quantity': 21},)
flower_name (str): name of a flower
returns:
boolean
"""
for items in results:
for key in list(items.items())[1]:
if items[key] == flower_name:
return True
else:
return False
def int_convertor(value: str) -> int:
"""Converts str type to int type
Args:
value (str): strings to be converted to int type
return:
int
raises:
ValueError: if value is str that cannot be converted into int
"""
try:
return int(value)
except ValueError:
return 0
|
34a9201993106c7b0a276c611d0fd2ee95d6d68e | morteza404/code_wars | /UniqueOrder.py | 670 | 4.15625 | 4 | """
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3]) == [1,2,3]
"""
def unique_in_order(input_iterable):
out = [input_iterable[0]]
for i in range(1,len(input_iterable)):
if input_iterable[i] != input_iterable[i-1]:
out.append(input_iterable[i])
return out
|
3fba912822b37b4673b582c7c0fbcb69969ff0f0 | nahida47/kaggle_competitions | /03_Zillow/kaggle_lib/Utils/KA_utils.py | 654 | 3.59375 | 4 | from __future__ import print_function, division
import time
class process_tracker:
'''
A simple process tracker and timer.
'''
def __init__(self, process_name, verbose=1):
self.process_name = process_name
self.verbose = verbose
def __enter__(self):
if self.verbose:
print(self.process_name + " begin ......")
self.begin_time = time.time()
def __exit__(self, type, value, traceback):
if self.verbose:
end_time = time.time()
print(self.process_name + " end ......")
print('time lapsing {0} s \n'.format(end_time - self.begin_time))
|
e111275e1bf03656392f94093a0f478a1352b4e8 | mariahmm/class-work | /5.2Answer.py | 731 | 4.15625 | 4 | count = 0
total = 0
while True:
test = input("Enter a number: ")
if test == "done" :
break
try:
num = float(test)
except:
print("Invalid input")
continue
count = count + 1
total = total + num
print("")
print("Sum is", total)
print("Count is", count)
print("Average is", total/count)
largest = None
smallest = None
while True:
test = input("Enter a number: ")
if test == "done" : break
try:
num = float(test)
except:
print("Invalid input")
continue
if smallest is None or num < smallest:
smallest = num
if largest is None or num > largest:
largest = num
print("Maximum is", largest)
print("Minimum is", smallest) |
edcf4806b76354b587f095afcca36e38d5920b4c | mveselov/CodeWars | /tests/kyu_8_tests/test_transportation_on_vacation.py | 450 | 3.625 | 4 | import unittest
from katas.kyu_8.transportation_on_vacation import rental_car_cost
class RentalCarCostTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(rental_car_cost(1), 40)
def test_equals_2(self):
self.assertEqual(rental_car_cost(4), 140)
def test_equals_3(self):
self.assertEqual(rental_car_cost(7), 230)
def test_equals_4(self):
self.assertEqual(rental_car_cost(8), 270)
|
3865156c177107ae3b55c85b18e45154693507ca | skyuniv/A-Kata-A-Day | /Python/Naughty_or_Nice.py | 1,102 | 4.0625 | 4 | # Naughty or Nice?
# Level: Beta
'''
In this kata, you will write a function that receives an array of string and returns a string that is
either 'naughty' or 'nice'. Strings that start with the letters b, f, or k are naughty. Strings that
start with the letters g, s, or n are nice. Other strings are neither naughty nor nice.
If there is an equal amount of bad and good actions, return 'naughty'
'''
def whatListAmIOn(actions):
# Your code
bad = 0
good = 0
for i in actions:
if i[0] in ['b', 'f', 'k']:
bad += 1
elif i[0] in ['g', 's', 'n']:
good += 1
if good > bad:
return 'nice'
else:
return 'naughty'
bad_actions = ['broke someone\'s window',
'fought over a toaster', 'killed a bug']
good_actions = ['got someone a new car',
'saved a man from drowning', 'never got into a fight']
actions = ['broke a vending machine',
'never got into a fight', 'tied someone\'s shoes']
print(whatListAmIOn(bad_actions))
print(whatListAmIOn(good_actions))
print(whatListAmIOn(actions))
|
e256f8fc2fc559028699e0b98b321ed86acd8108 | wayne-liberty/euler_python | /Digit cancelling fractions.py | 806 | 3.890625 | 4 | from fractions import Fraction
# help(fractions)
# print(fractions.Fraction(3, 6))
def judge(num, denom):
a_set = {int(num / 10), num % 10, int(denom / 10), denom % 10}
if len(a_set) != 3 or 0 in a_set:
return
num_list = [int(num / 10), num % 10]
denom_list = [int(denom / 10), denom % 10]
for i in set(str(num)) & set(str(denom)):
num_list.remove(int(i))
denom_list.remove(int(i))
if len(num_list) != 1:
return
if Fraction(num, denom) == Fraction(num_list[0], denom_list[0]):
print('{}/{}'.format(num, denom))
return True
f = Fraction(1, 1)
for denominator in range(10, 100):
for numerator in range(10, denominator):
if judge(numerator, denominator):
f *= Fraction(numerator,denominator)
print(f)
|
fb72de2180c9fd034e6e96f19a626d1a0337cf88 | fau-masters-collected-works-cgarbin/cot6405-analysis-of-algorithms | /longest-common-subsequence/alternatives/lcs_recursive.py | 1,347 | 3.703125 | 4 | '''LCS with recursion.
This is the simplest recursive solution, with memoization. It is not an
efficient implementation. It is here to illustrate conceptually how to solve
the problem.
Even with memoization, this solution hits the number of recursive calls in the
Python environment for input strings around 10,000 characters.
Based on http://wordaligned.org/articles/longest-common-subsequence.
According to it, this solution is based on the CLRS book.
'''
def memoize(fn):
'''Return a memoized version of the input function.
The returned function caches the results of previous calls.
Useful if a function call is expensive, and the function
is called repeatedly with the same arguments.
'''
cache = dict()
def wrapped(*v):
key = tuple(v) # tuples are hashable, and can be used as dict keys
if key not in cache:
cache[key] = fn(*v)
return cache[key]
return wrapped
@memoize
def lcs(xs, ys):
'''Returns the longest subsequence common to xs and ys.'''
@memoize
def lcs_(i, j):
if i and j:
xe, ye = xs[i-1], ys[j-1]
if xe == ye:
return lcs_(i-1, j-1) + [xe]
else:
return max(lcs_(i, j-1), lcs_(i-1, j), key=len)
else:
return []
return lcs_(len(xs), len(ys))
|
e2a22e7777f7ff884ce70664048bb07e352e6315 | cleysondiego/curso-de-python-dn | /semana_1/exercicios_aula_2/Exercicio13.py | 147 | 3.875 | 4 | numero = int(input('Digite um número: '))
def goiabada(numero):
return 'goiabada' if ((numero % 5) == 0) else numero
print(goiabada(numero)) |
e8e3fdd4556b24eb357aa7f669fb751dc08bbd40 | CescWang1991/LeetCode-Python | /python_solution/151_160/BinaryTreeUpsideDown.py | 1,176 | 4.0625 | 4 | # 156. Binary Tree Upside Down
# Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same
# parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left
# leaf nodes. Return the new root.
# Given a binary tree {1,2,3,4,5},
# return the root of the binary tree [4,5,2,#,#,3,1].
# 1 4(node)
# / \ / \
# 2 3 => 4(node) 1 => 5 2
# / \ / \ / \ / \
# 4 5 5 2(root)3 3 1(root)
class Solution:
# 把左子树继续颠倒,颠倒完后,原来的那个左孩子的左右孩子指针分别指向原来的根节点以及原来的右兄弟节点即可。
def upsideDownBinaryTree(self, root):
if not root or not root.left:
return root
node = self.upsideDownBinaryTree(root.left)
root.left.left = root.right # node.left
root.left.right = root # node.right
root.left = None
root.right = None
return node |
56a7259e9ec3ae779d563b045859615ac22c4fe3 | backmay/tisco_exam | /test_1.py | 438 | 3.609375 | 4 | input_a = '9876543'
input_b = [
'3467985',
'7865439',
'8743956',
'3456789',
]
def is_same_ditgit_in_same_index(input_a, input_b):
for index in range(len(input_a)):
if input_a[index] == input_b[index]:
print('{} : is Invalid'.format(input_b))
return
print('{} : is Valid'.format(input_b))
for index in range(len(input_b)):
is_same_ditgit_in_same_index(input_a, input_b[index])
|
da42e428c82ffb3049f97684837596991e7ba83d | sdemingo/algol | /acm-icpc/2011-PA-add-or-mul.py | 4,357 | 3.796875 | 4 | '''
Problem A
To Add or to Multiply
'''
import sys
# Clase para recoger todos las posibles soluciones. Cuando construyo un
# nodo puedo ejecutar su método build. Esto provocará que se construyana
# a su vez sus hijos de forma recursiva.
class Tree():
def __init__(self,config,output,op):
self.config=config
self.output=output
self.op=op
self.aChild=None
self.mChild=None
# Compruebo limites por exceso
def isValid(self):
if (self.output[1]>self.config['s']):
return False
return True
# Compruebo si es un nodo exitoso
def isSuccess(self):
if ( (self.output[0]>=self.config['r']) and (self.output[1]<=self.config['s'])):
return True
return False
# Construyo los arboles hijos siempre y cuando estos cumplan
# el requisito de validez
def build(self):
aout=[0,0]
mout=[0,0]
aout[0]=self.output[0]+self.config['a']
aout[1]=self.output[1]+self.config['a']
mout[0]=self.output[0]*self.config['m']
mout[1]=self.output[1]*self.config['m']
self.aChild=Tree(self.config,aout,"A")
self.mChild=Tree(self.config,mout,"M")
if (self.aChild.isValid()):
self.aChild.build()
if (self.mChild.isValid()):
self.mChild.build()
# Recorro el árbol buscando nodos exitosos. Para cada nodo que recorro
# apunto su codigo de instrucción en el programa, cuando vuelvo a el,
# acabada la exploración de sus hijos y retorno hacia el padre, quito
# ese codigo de operación.
#
# Cuando encuentro un caso de éxito clono el contenido del buffer
# programa en ese momento a la variable pcopy y la adjunto a la lista de
# programas exitosos.
def walkTree(succs,program,tree):
if (tree==None):
return
program.append(tree.op)
if (not tree.isSuccess()):
walkTree(succs,program,tree.mChild)
walkTree(succs,program,tree.aChild)
else:
pcopy=program[:]
succs.append(pcopy)
#print ("Econtrado nº"+str(len(succs))+": "+str(program)+ "output: "+str(tree.output))
program.pop()
# Comprime el programa en forma de lista de Aes y Mes en un string
# tal y como se indica en el enunciado
def compressProgram(program):
p=""
i=0
m=0
a=0
while (i<len(program)):
if (program[i]=="M"):
m+=1
if (a>0):
p=p+str(a)+"A "
a=0
if (program[i]=="A"):
a+=1
if (m>0):
p=p+str(m)+"M "
m=0
i+=1
if (a>0):
p=p+str(a)+"A"
a=0
if (m>0):
p=p+str(m)+"M"
m=0
return p
def main():
tests=[]
finput=open("2011-PA-add-or-mul.input")
for line in finput.readlines():
numbers=line.strip().split(" ")
numbers=list(map(int,numbers))
if max(numbers)==0:
break
config={}
config['a']=numbers[0]
config['m']=numbers[1]
config['p']=numbers[2]
config['q']=numbers[3]
config['r']=numbers[4]
config['s']=numbers[5]
tests.append(config)
# Una vez leidos todos los test empeizo a procesar
ntest=1
for config in tests:
output=[config['p'],config['q']]
program=[]
success=[]
tree=Tree(config,output,"")
tree.build()
walkTree(success,program,tree)
# Calculo la longitud mínima
minlen=sys.maxsize
for p in success:
if (len(p)<=minlen):
minlen=len(p)
# Solo me quedo con los que tienen esa longitu mínima
# y en caso de empate los ordeno lexicograficamente como si
# fueran strings
programs=[]
for p in success:
if len(p)==minlen:
programs.append("".join(p))
programs.sort()
#print (programs)
msg=""
if (len(programs)==0):
msg="impossible"
else:
best=compressProgram(programs[0])
if len(best)==0:
msg="empty"
else:
msg=best
print ("Case "+str(ntest)+": "+msg)
ntest+=1
if (__name__=='__main__'):
main()
|
b7a774bfc1f5960792250a0f585935a7d7ad0e7a | yaxche-io/dig-bioindex | /bioindex/lib/locus.py | 5,251 | 3.5625 | 4 | import abc
import itertools
import locale
import re
class Locus(abc.ABC):
"""
A location in the genome. Abstract. Must be either a SNPLocus or
a RegionLocus.
"""
LOCUS_STEP = 20000
def __init__(self, chromosome):
"""
Ensure a valid chromosome.
"""
self.chromosome = parse_chromosome(chromosome)
@abc.abstractmethod
def __str__(self):
pass
@abc.abstractmethod
def loci(self):
"""
A generator of record loci as tuples ('chromosome', position)
"""
pass
@abc.abstractmethod
def overlaps(self, chromosome, start, stop):
"""
True if this locus overlaps a region.
"""
pass
def stepped_pos(self, pos):
"""
Returns a position as a stepped position.
"""
return (pos // self.LOCUS_STEP) * self.LOCUS_STEP
class SNPLocus(Locus):
"""
Locus for a single SNP (base pair) at an exact position.
"""
def __init__(self, chromosome, position):
super().__init__(chromosome)
# ensure integer position
self.position = int(position)
def __str__(self):
"""
Return a string representation of the locus.
"""
return f'{self.chromosome}:{self.position}'
def loci(self):
"""
A generator of record loci. Reduce the total number of records by
dividing and placing them in buckets.
"""
yield self.chromosome, self.stepped_pos(self.position)
def overlaps(self, chromosome, start, stop):
"""
True if this locus is overlapped by the region.
"""
return self.chromosome == chromosome and start <= self.position < stop
class RegionLocus(Locus):
"""
Locus for a region on a chromosome.
"""
def __init__(self, chromosome, start, stop):
super().__init__(chromosome)
# ensure integer range
self.start = int(start)
self.stop = int(stop)
def __str__(self):
"""
Return a string representation of the locus.
"""
return f'{self.chromosome}:{self.start}-{self.stop}'
def loci(self):
"""
A generator of record loci.
"""
start = self.start // self.LOCUS_STEP
stop = self.stop // self.LOCUS_STEP
for position in range(start, stop + 1):
yield self.chromosome, position * self.LOCUS_STEP
def overlaps(self, chromosome, start, stop):
"""
True if this locus is overlapped by the region.
"""
return self.chromosome == chromosome and stop > self.start and start < self.stop
def chromosomes():
"""
Return an iterator of all chromosomes.
"""
return itertools.chain(range(1, 23), ['X', 'Y', 'XY', 'M', 'MT'])
def parse_chromosome(s):
"""
Parse and normalize a chromosome string, which may be prefixed with 'chr'.
"""
match = re.fullmatch(r'(?:chr)?([1-9]|1\d|2[0-2]|x|y|xy|m)', s, re.IGNORECASE)
if not match:
raise ValueError(f'Failed to match chromosome against {s}')
return match.group(1).upper()
def parse_columns(s):
"""
Parse a locus string and return the locus class, and column names
as a tuple. If not a valid locus string, returns None and a tuple
of all None.
"""
match = re.fullmatch(r'([^:]+):([^-]+)(?:-(.+))?', s)
if not match:
return None, (None, None, None)
cols = match.groups()
# return the class and columns parsed
return (RegionLocus if cols[2] else SNPLocus), cols
def parse_locus(s, gene_lookup_engine=False):
"""
Parse a locus string and return the chromosome, start, stop.
"""
match = re.fullmatch(r'(?:chr)?([1-9]|1\d|2[0-2]|x|y|xy|m):([\d,]+)(?:([+/-])([\d,]+))?', s, re.IGNORECASE)
if not match:
if not gene_lookup_engine:
raise ValueError(f'Failed to match locus against {s}')
return request_gene_locus(gene_lookup_engine, s)
chromosome, start, adjust, end = match.groups()
cur_locale = locale.getlocale()
try:
# parse thousands-separator commas
locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
# parse the start position
start = locale.atoi(start)
# if the adjustment is a + then end is a length, otherwise a position
if adjust == '+':
end = start + locale.atoi(end)
elif adjust == '/':
shift = locale.atoi(end)
start, end = start - shift, start + shift + 1
else:
end = locale.atoi(end) if end else start + 1
# stop position must be > start
if end <= start:
raise ValueError(f'Stop ({end}) must be > start ({start})')
return chromosome.upper(), start, end
finally:
# restore the original locale
locale.setlocale(locale.LC_ALL, cur_locale)
def request_gene_locus(engine, q):
"""
Use the __Genes table to lookup the region of a gene.
"""
sql = 'SELECT `chromosome`, `start`, `end` FROM `__Genes` WHERE `name` = %s'
gene = engine.execute(sql, q).fetchone()
if gene:
return gene[0], gene[1], gene[2]
raise ValueError(f'Invalid locus or gene name: {q}')
|
dcc9e6fddfb094520058056a468b4f134a7e4e48 | pweb6304/two-qubit-simulator | /two_qubit_simulator/initial_state.py | 471 | 3.796875 | 4 | def random_quantum_state():
"""
Returns a random qubit state.
The qubit will be a column vector with complex elements a+ib and c+id.
a,b,c and d are randomly chosen. The norm ensures the state is normalised.
"""
import numpy as np
import random
a = random.random()
b = random.random()
c = random.random()
d = random.random()
norm = np.sqrt (( a + 1j * b) * (a - 1j * b) + (c + 1j * d) * (c - 1j * d))
return np.array([[a + 1j * b] , [c + 1j * d] ]) / norm |
ec59d7fd195c031cd673fc6a075b057c4bbdc6fb | serbyshek/LB_4 | /individual3.py | 583 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#1. Дано слово.
#Удалить из него третью букву.
#Удалить из него k-ю букву
if __name__ == '__main__':
s = str(input('Введите слово'))
k = int(input('Введите порядковый номер буквы, которую желаете удалить'))
с = k + 1
v = s[:k] + s[с:]
j = s[:3] + s[4:]
print(f'В слове {s} удалена третья буква {j}. В слове {s} удалена {k}-я буква {v}') |
b7f08d79214db29607c830c06eee7f1ee294f785 | ahsueh1996/NomBot | /archive/v3/physics_model.py | 2,751 | 3.609375 | 4 | import math
import numpy as np
from scipy.optimize import fsolve
'''
2017 Aug 26
Albert Hsueh
Describes a model for predicting tragetories.
'''
G = 9.8
g = G
CABINET_PORPORTION = 0.3 # measured form screen the ratio the cabinets take up on the game screen
def adjust_gravity(play_field_height):
'''
The play field height might be scaled on different screen sizes
so here we adjust the gravitational accel based on the factor
parametraized by the play field height.
'''
global g
g = G * play_field_height * CABINET_PORPORTION # take the cabinet to be approx 1m and use as conversion to pixels
return
def projectile_model(v, si, ti , tf=-1, sf=(-1,-1)):
'''
This is a grade 12 phy model for projectiles. Given velocity, initial displacement
initial time, and either of the final time or final displacement, get a lambda func
in the x and y directions with the other optional info as the variable.
v: tuple, vx and vy
si: tuple, xi and yi
ti: float
ft: float
sf: tuple, xf and yf
Note the space coords:
0,0 ---------> x,0
|
|
v
0,y x,y
so g should be (+); going downwards
'''
global g
# these two functions are in the 0 = f(x) - x form
fx = lambda xt: si[0] + v[0] * (xt[1]-ti) - xt[0]
fy = lambda yt: si[1] + v[1] * (yt[1]-ti) + 0.5 * g * (yt[1]-ti)**2 - yt[0]
if tf>=0:
return (lambda xf: fx((xf,tf)), lambda yf: fy((yf,tf)))
elif sf[0]>=0 or sf[1]>=0:
return (lambda tf: fx((sf[0],tf)), lambda tf: fy((sf[1],tf)))
def eval_trajectory(obj, t=-1, pos=(-1,-1)):
'''
Solves the trajectory given the final displacement or the time.
Input -1 for any piece of information that is uneeded.
ie. t = -1 pos=(-1,20)
'''
v = obj.get_vel()
si = obj.get_dis()
ti = obj.get_time()
x_guess = None
y_guess = None
delta = 5
if t>=0:
''' solve for the POSITION GIVEN t'''
fx, fy = projectile_model(v, si, ti, tf=t)
x_guess = v[0] + delta
y_guess = v[1] + delta
elif pos[0]>=0 or pos[1]>=0:
''' solve for t GIVEN position'''
fx, fy = projectile_model(v, si, ti, sf=pos)
if pos[0] > -1:
x_guess = ti + delta
if pos[1] > -1:
y_guess = ti + delta
# solve
if x_guess != None:
x_sol = fsolve(fx, x_guess)[0]
if y_guess != None:
y_sol = fsolve(fy, y_guess)[0]
if t>=0:
return (x_sol, y_sol)
elif pos[0]>=0 and pos[1]>=0:
return x_sol if x_sol==y_sol else None
elif pos[0]>=0 or pos[1]>=0:
return x_sol if y_guess==None else y_sol
return -1
|
71b886890fe0339993f7b5ef6e1d7e27d5bd97a3 | rulidor/Python-Course | /assign.9/untitled1.py | 265 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 21:10:13 2019
@author: Lidor
"""
import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5])
y=np.array([50,20,30,90,100])
#plt.plot(x,y)
#plt.show(x)
print(x.mean())
print(x.min())
print(x.max()) |
62bf9474640f68d26ad231a243ab1a6fa5705cfd | erlengra/mqttSUB-httpPOST | /config.py | 3,326 | 3.609375 | 4 | import sys
import getopt
'''
Config class used to hold all options available from runtime. The options are placed in a directory and loaded
to the initialization of the application.
-configure_init() initializes the object
-config_input() returns a directory of options by using the sys class. options are set in the command terminal
'''
class Config(object):
options = dict() # create the options dictionary
options["user"] = "er"
options["broker"] = "test.mosquitto.org"
options["port"] = 1883
options["topic"] = [("sensors/lyse-test-01", 0)]
options["post_to_url"] = ""
options["threshold"] = 0
def configure_init(self, configure):
self.configure = configure
def config_input(self, options={}):
valid_options = " --help <help> \
-u <User>\
-h or -b <broker>\
-p <port>\
-t <topic>\
-n Client ID or Name\
-v <threshold>\
-a <URL> "
try:
opts, args = getopt.getopt(sys.argv[1:], "--help:u:h:p:t:n:v:a:") # code borrowed from youtube.com
except getopt.GetoptError: #
print(sys.argv[0], valid_options) #
sys.exit(2) #
qos = 0 #
for opt, arg in opts:
if opt == '-h':
options["broker"] = str(arg)
elif opt == '--help':
print(valid_options)
elif opt == "-b":
options["broker"] = str(arg)
elif opt == "-p":
options["port"] = int(arg)
elif opt == "-t":
options["topic"] = str(arg)
elif opt == "-u":
options["user"] = str(arg)
elif opt == "-a":
options["post_to_url"] = str(arg)
elif opt == "-v":
options["threshold"] = int(arg)
print("User: " + options["user"]) # very simple user feedback
print("Broker: " + options["broker"])
print("Port: " + str(options["port"]))
print("Topic: " + str(options["topic"]))
print("post_to_url: " + str(options["post_to_url"]))
print("Threshold: " + str(options["threshold"]))
print("\n")
print("Configuration complete")
print("\n")
return options
#END OF CLASS: CONFIG
'''
The Counter class holds necessary functions and variables for the counter used in the eval_data function.
Notify is a flag to determine if a post request has been sent.
Threshold_exceeded is a flag to determine if the sensor value has surpassed the user specific threshold value.
value holds the current counter value
-Init() initializes the instance
-Increment() increases the value by 1
-Reset() resets the value to 0
'''
class Counter:
NOTIFY = False
THRESHOLD_EXCEEDED = False
value = 0
def counter_init(self, counter):
self.counter = counter
def increment(self):
self.value += 1
def reset(self):
self.value = 0
#END OF CLASS: COUNTER
|
d6c3159ba85bb32167d57ea0d5f543d5d01ba39c | artbohr/codewars-algorithms-in-python | /7-kyu/age-in-days.py | 639 | 4.4375 | 4 | from datetime import date
def ageInDays(year, month, day):
return 'You are {} days old'.format((date.today() - date(year, month, day)).days)
'''
Did you ever want to know how many days you are old? Write a function ageInDays
which returns your age in days.
For example if today is 30 November 2015 then
ageInDays(2015, 11, 1) returns "You are 29 days old"
The birthday is entered as integers in the following order
ageInDays(year, month, day)
For example if you are born 27 November 2007 then call ageInDays(2007, 11, 27).
Your birthday is expected to be in the past.
Suggestions on how to improve the kata are welcome!
'''
|
67bac2d3c77270406360272da5999ef25321f328 | zhanglongqi/python-study | /myTimer.py | 2,233 | 3.828125 | 4 | __author__ = 'longqi'
'''
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# This is saying "while we have not reached 20 minutes running"
while mins != 20:
print ">>>>>>>>>>>>>>>>>>>>>", mins
# Sleep for a minute
time.sleep(60)
# Increment the minute total
mins += 1
# Bring up the dialog box here
'''
'''
import sched
import time
s = sched.scheduler(time.time, time.sleep)
def print_time():
print "From print_time", time.time()
def print_some_times():
print time.time()
s.enter(5, 1, print_time, ())
s.enter(10, 1, print_time, ())
s.run()
print time.time()
print_some_times()
'''
'''
import sched
import time
def hello(name):
print 'hello world, i am %s, Current Time:%s' % (name, time.time())
run(name)
def run(name):
s = sched.scheduler(time.time, time.sleep)
s.enter(3, 2, hello, (name,))
s.run()
s = sched.scheduler(time.time, time.sleep)
s.enter(3, 2, hello, ('guo',))
s.run()
'''
'''
from threading import Event, Thread
import time
class RepeatTimer(Thread):
def __init__(self, interval, function, iterations=0, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.iterations = iterations
self.args = args
self.kwargs = kwargs
self.finished = Event()
def run(self):
count = 0
while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
count += 1
def cancel(self):
self.finished.set()
def hello():
print 'hello world, Current Time:%s' % (time.time())
r = RepeatTimer(5.0, hello)
r.start()
'''
'''
from threading import Timer
def hello():
print "hello, world"
t.run()
t = Timer(1.0, hello)
t.start() # after 1 seconds, "hello, world" will be printed
'''
import threading;
i = 0
def work():
global i
threading.Timer(0.01, work).start()
print("stackoverflow ", i, end='\r')
i += 1
work();
|
b6b6b5120805c2bf4fe08d88b36cd460c31735c5 | amani021/100DaysOfPython | /Day_8.py | 1,685 | 4.3125 | 4 | # -------- DAY 8 "Generate Password" --------
# Goal: Learn about random library.
import random, string
from tkinter import *
root = Tk()
root.title('100 Days Of Python - Day 8')
root.configure(background='#E0E0E0')
# --------------- CREATE A FRAME ---------------
frame = LabelFrame(root, text=' GENERATE PASSWORD ', bg='#E0E0E0', fg='#00695C', font=5, padx=75, pady=75)
frame.pack(padx=20, pady=15)
infoLabel = Label(frame, text='Hi, this program for generate random password.\nYou can receive your own password from '
'here.\nJUST TRY IT!', bg='#E0E0E0', fg='#424242', font=('time', 16, 'bold'))
infoLabel.grid(row=0, column=0, columnspan=5, padx=4, pady=20)
askLabel = Label(frame, text='Length Of Password: ', bg='#E0E0E0', font=('time', 14, 'bold'))
askLabel.grid(row=1, column=0, padx=4, pady=20)
e_length = Entry(frame, width=25, font=7)
e_length.grid(row=1, column=1, padx=4, pady=20)
# --------------- FUNCTIONS ---------------
def generate_pass():
password = ''
for i in range(int(e_length.get())):\
password += random.choice(string.ascii_letters + string.punctuation + string.digits)
e_pass.config(text=password)
# --------------- BUTTONS & LABEL FOR PASSWORD ---------------
button = Button(frame, text='Generate', bg='#009688', fg='#fff', height=2, font=3, command=generate_pass)
button.grid(row=3, columnspan=2, sticky='snew', padx=4, pady=20)
passLabel = Label(frame, text='Your Password is: ', bg='#E0E0E0', font=('time', 14, 'bold'))
passLabel.grid(row=2, column=0, padx=4, pady=20)
e_pass = Label(frame, text='', width=25, bg='#fff', font=7)
e_pass.grid(row=2, column=1, padx=4, pady=20)
root.mainloop()
|
70cb21a2cfb8e5fcf8066e1fb887593352e79b87 | garderobin/Leetcode | /leetcode_python2/lc654_maximum_binary_tree.py | 905 | 3.921875 | 4 | # coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from abc import ABCMeta, abstractmethod
from data_structures.binary_tree import TreeNode
class MaximumBinaryTree(object):
__metaclass__ = ABCMeta
@abstractmethod
def construct_maximum_binary_tree(self, nums):
"""
看到区间极值就应该想到单调栈
:param nums:
:return:
"""
"""
:type nums: List[int]
:rtype: TreeNode
"""
stack = [] # monotonous desc
for num in nums:
node = TreeNode(num)
while stack and stack[-1].val < num:
node.left = stack.pop()
if stack:
stack[-1].right = node
stack.append(node)
return stack[0]
|
55f3fb61ee0d06fe52dbae821ca9b3a439724488 | kwantaing/CD_Python_Fundamentals | /functions_basic2.py | 782 | 3.8125 | 4 | def countdown(number):
newlist = []
for i in range(number,-1,-1):
newlist.append(i)
return newlist
# print(countdown(5))
def print_return(list):
print(list[0])
return(list[1])
# print(print_return([1,2]))
def first_plus_length(list):
return list[0]+len(list)
# print(first_plus_length([1,2,3,4,5]))
def vals_greater_than_second(list):
newlist = []
count=0
for i in list:
if(i>list[1]):
newlist.append(i)
count+=1
print(count)
if (len(newlist)<2):
return False
return newlist
# print(vals_greater_than_second([5,2,3,2,1,4]))
def this_l_that_val(size,value):
newlist=[]
for i in range(size):
newlist.append(value)
return newlist
# print(this_l_that_val(4,7))
|
61fa8f4cbbd7c51c1fe25b0d7bb7bce6fef53a92 | zopepy/leetcode | /flip_equivalent.py | 824 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flipEquiv(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
def compare(ltree, rtree):
if not ltree and not rtree:
return True
elif (not ltree and rtree) or (not rtree and ltree):
return False
if ltree.val == rtree.val:
c1=compare(ltree.left, rtree.left) and compare(ltree.right, rtree.right)
c2=compare(ltree.left, rtree.right) and compare(ltree.right, rtree.left)
return c1 or c2
return False
compare(root1, root2) |
ab3f5c76f3706b2fe46faa5ae3804e3081e2f746 | navazl/cursoemvideopy | /ex029.py | 385 | 3.828125 | 4 | vel = int(input('Qual a velocidade do carro? ')) # Lê a velocidade do carro.
if vel > 80: # Verifica se a velocidade do carro é maior que 80km/h.
multa = (vel - 80) * 7.00 # Descobre quantos Km/h ele está acima do limite e multiplica por R$7,00 (preço da multa).
print(f"Você foi multado e terá que pagar R${multa:.2f}")
print("Tenha um bom dia, dirija com segurança!")
|
095ff133bd0633b7f2554f9592a1b721bb21158e | jeremiedecock/snippets | /python/scipy/discrete_random_with_distribution.py | 1,160 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# see http://stackoverflow.com/questions/11373192/generating-discrete-random-variables-with-specified-weights-using-scipy-or-numpy
import numpy as np
from scipy.stats import rv_discrete
# IF VALUES ARE INTEGERS ########################
values = [1, 2, 3]
probabilities = [0.2, 0.5, 0.3]
num_samples = 1000
# A Scipy probability distribution
distrib = rv_discrete(values=(values, probabilities))
# One sample
value = distrib.rvs()
print("value =", value)
# Multiple samples
values = distrib.rvs(size=num_samples)
print(values)
print("Percentage of 1:", float(values.tolist().count(1)) / num_samples)
print("Percentage of 2:", float(values.tolist().count(2)) / num_samples)
print("Percentage of 3:", float(values.tolist().count(3)) / num_samples)
# IF VALUES ARE FLOATS ##########################
print()
values = np.array([1.1, 2.2, 3.3])
probabilities = [0.2, 0.5, 0.3]
# A Scipy probability distribution (values have to be integers)
distrib = rv_discrete(values=(range(len(values)), probabilities))
# Samples
indexes = distrib.rvs(size=100)
print(indexes)
print(values[indexes])
|
f932774e5c531a96cb257cbe82b39babe4e98b46 | delafrouzmir/Udemy-Data-Science | /Advanced Statistics/Section 34/l212.py | 866 | 3.71875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sbn
sbn.set()
from sklearn.linear_model import LinearRegression
data = pd.read_csv('real_estate_price_size.csv')
print (data.head())
x = data['size']
y = data['price']
x = x.values.reshape(-1,1)
print(x.shape)
reg = LinearRegression()
model = reg.fit(x,y)
# coefs:
print(model.coef_)
# intercept
print(model.intercept_)
# r-squares
print(model.score(x,y))
# plot
plt.scatter(x,y)
yhat = x*model.coef_[0] + model.intercept_
fig = plt.plot(x, yhat, lw=2, c='orange', label='Regression Line')
plt.xlabel('size of property')
plt.ylabel('price of property')
plt.show()
# prediction: price of a house of 750 sqft
pred_data = pd.DataFrame(data=[750], columns=['size'])
pred_data['predicted price'] = pd.DataFrame(reg.predict (pred_data), columns=['price'])
print(pred_data)
|
5150d0112a19ed1f6b9b1cdc4ab6f967d748e1c1 | pengzhefu/LeetCodePython | /hashtable/easy/q204.py | 2,449 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 11:39:47 2019
@author: pengz
"""
'''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
def countPrimes(n): ## written by my own, time limit exceeded
if n <= 2:
return 0
elif n == 3:
return 1
else:
pn = [2]
cnt = 1
for num in range(3,n):
prime = True
for i in pn:
if num % i ==0:
prime = False
break
if prime:
cnt+=1
pn.append(num)
else:
continue
return cnt
#a = countPrimes(49979)
print(round(7**0.5))
print(int(round(7**0.5)))
print(99//2+1)
def countPrimes1(n): ## 借鉴的别人的,超级巧妙的方法! 需要额外空间O(n), 时间复杂度为O(nlogn)?
if n <= 2:
return 0
res = [True] * n ## 如果大于2,提前生成一张列表,长度为n,index就带表小于n的非0数:0...n-1,假设都是prime(True)
res[0] = res[1] = False ## 0,1都不是,先人工变False
for i in range(2, n): ## 从2开始,一直到n-1
## 其实这里也还可以改进一下,就是可以不用到n-1,到根号n的向下取整就行了,也减少时间
if res[i] == True: ## 如果这个数是质数的话,那他的所有的倍数就都不是质数了
for j in range(2, (n-1)//i+1): ## 倍数从2开始,那最大到几倍呢,就应该是末尾的数(n-1)整除这个质数(i),
## 因为是range,所以要+1
## 其实这里j的范围还有一个可以改进加速的方法,就是把2改成i:range(i, (n-1)//i+1)
## 因为其实小于自己的质数倍的数字在之前已经被其他的变成False了,不是质数倍的也被小于自己的数字的倍数包含了
## 比如:如果是17,那么自己的2,3,5,7,11,13倍的都在之前这些质数的倍数包含了,
## 4,6,8,10,12,14,16倍被2包含,15被3包含
## 所以减少重复工作,可以从自己的本身倍数开始
res[i*j] = False ## 质数的倍数都不是质数,变False
return sum(res) ## 最后统计有多少个True就行了 |
8a5d81907a0eb9e43e0b4c5d034cf23860828dc4 | colinpollock/pong-ladder | /app/elo.py | 1,254 | 3.90625 | 4 | """Elo score computation.
See https://en.wikipedia.org/wiki/Elo_rating_system.
"""
from __future__ import division
def elo_update(winner_rating, loser_rating, to_11=True):
"""Compute the new rating for the winner and loser.
Args:
winner_rating - the winner's rating.
loser_rating - the loser's rating.
to_11 - whether the game was played to 11 (or 21). The k value is higher
when the game is played to 21.
Returns:
a pair (new rating for winner, new rating for loser).
"""
loser_ex = expectation(loser_rating, winner_rating)
k = compute_k_value(to_11)
new_winner_rating = int(winner_rating + (k * loser_ex))
new_loser_rating = int(loser_rating - new_winner_rating + winner_rating)
return (new_winner_rating, new_loser_rating)
def expectation(r1, r2):
"""Return the expected probability that a player with rating r1 will beat
a player rated r2.
"""
return 1 / (1 + 10 ** ((r2 - r1) / 400.0))
def compute_k_value(to_11):
"""
meow: document args etc
See https://en.wikipedia.org/wiki/Elo_rating_system#Most_accurate_K-factor.
"""
# TODO: read the k values from the config
if to_11:
return 10
else:
return 15
|
4a7cda727d0be4647b9aff5b6981f88acc03a859 | qilin-link/test | /test/ATMsystem/atm.py | 6,141 | 3.5625 | 4 | #!/usr/bin/env python
#_*_ coding:utf-8 _*_
from card import Card
from user import User
import random
class ATM(object):
def __init__(self,allUsers):
self.allUsers = allUsers #卡号-用户
#开户
def createUser(self):
#目标:向用户字典中添加一对键值对(卡号-用户)
name = raw_input("请输入您的姓名:")
idCard = raw_input('请输入您的身份证号码:')
phone = raw_input('请输入您的电话号码:')
prestoreMoney = int(raw_input('请输入预存款金额:'))
if prestoreMoney < 0:
print '预存款输入有误!!!开户失败......'
return -1
onePasswd = raw_input('请设置密码:')
#验证密码
if not self.checkPasswd(onePasswd):
print '密码输入错误!!开户失败......'
return -1
#所有需要的信息就全了
cardStr = self.randomCardId()
card = Card(cardStr, onePasswd, prestoreMoney)
user = User(name, idCard, phone, card)
#存到字典
self.allUsers[cardStr] = user
print '开户成功!!请牢记卡号%s......' % cardStr
#查询
def searchUserInfo(self):
cardNum = raw_input('请输入您的卡号:')
#验证是否存在该卡号
user = self.allUsers.get(cardNum)
if not user:
print '该卡号不存在!!查询失败......'
return -1
#判断是否锁定
if user.card.cardLock:
print '该卡已被锁定!!请解锁后再进行其他操作......'
return -1
#验证密码
if not self.checkPasswd(user.card.cardPasswd):
print '密码输入错误!!该卡已被锁定!!请解锁后再进行其他操作......'
user.card.cardLock = True
return -1
print '账号:%s 余额:%d' % (user.card.cardId, user.card.cardMoney)
#取款
def getMoney(self):
cardNum = raw_input('请输入您的卡号:')
#验证是否存在该卡号
user = self.allUsers.get(cardNum)
if not user:
print '该卡号不存在!!取款失败......'
return -1
#判断是否锁定
if user.card.cardLock:
print '该卡已被锁定!!请解锁后再进行其他操作......'
return -1
#验证密码
if not self.checkPasswd(user.card.cardPasswd):
print '密码输入错误!!该卡已被锁定!!请解锁后再进行其他操作......'
user.card.cardLock = True
return -1
#
money = int(raw_input('请输入取款金额:'))
if money > user.card.cardMoney:
print '余额不足!!取款失败......'
return -1
if money < 0:
print '输入错误!!取款失败......'
return -1
#取款
user.card.cardMoney -= money
print '取款成功!!余额:%d' % (user.card.cardMoney)
#存款
def saveMoney(self):
pass
#转账
def transferMoney(self):
pass
#改密
def changePasswd(self):
pass
#锁定
def lockUser(self):
cardNum = raw_input('请输入您的卡号:')
#验证是否存在该卡号
user = self.allUsers.get(cardNum)
if not user:
print '该卡号不存在!!锁定失败......'
return -1
if user.card.cardLock:
print '该卡已被锁定!!请解锁后再使用其他功能......'
return -1
#验证密码
if not self.checkPasswd(user.card.cardPasswd):
print '密码输入错误!!锁定失败......'
return -1
#验证身份证号
tempIdCard = raw_input('请输入您的身份证号码:')
if tempIdCard != user.idCard:
print '身份证号码输入错误!!锁定失败......'
return -1
#锁卡
user.card.cardLock = True
print '锁定成功......'
#解锁
def unlockUser(self):
cardNum = raw_input('请输入您的卡号:')
#验证是否存在该卡号
user = self.allUsers.get(cardNum)
if not user:
print '该卡号不存在!!解锁失败......'
return -1
if not user.card.cardLock:
print '该卡没有锁定!!无需解锁......'
return -1
#验证密码
if not self.checkPasswd(user.card.cardPasswd):
print '密码输入错误!!解锁失败......'
return -1
#验证身份证号
tempIdCard = raw_input('请输入您的身份证号码:')
if tempIdCard != user.idCard:
print '身份证号码输入错误!!解锁失败......'
return -1
#解锁
user.card.cardLock = False
print '解锁成功......'
#补卡
def newCard(self):
pass
#销户
def killUser(self):
pass
#验证密码
def checkPasswd(self, realPasswd):
for i in range(3):
tempPasswd = raw_input('请输入密码:')
if tempPasswd == realPasswd:
return True
return False
#生成卡号
def randomCardId(self):
while True:
str = ''
for i in range(6):
#随机生成一个数字
ch = chr(random.randrange(ord('0'),ord('9') + 1))
str += ch
#判断卡号是否重复
if not self.allUsers.get(str):
return str |
35bbec33ae4deedb1619952c9be42a18908cd4fd | lujiaxuan0520/Python-exercise | /python课后习题/3.7.py | 267 | 3.765625 | 4 | #3.7
#!/usr/bin/python
#encoding=utf-8
def method1():
sum=0
for i in range(1,100,2):
sum+=i
print(sum)
def method2():
sum=0
for i in range(100):
if(i%2==1):
sum+=i
print(sum)
if __name__=='__main__':
method1() |
9ab2c582bf6a5d4127c1deb486b2a3133bcff260 | renruru/homework | /sum(while).py | 496 | 3.59375 | 4 | # i=0
# sum = 0
# while i<=1000:
# sum=sum+i
# i=i+1
# print(sum)
#1+2+。。。+1000的值
# i=0
# while i<=100:
# i+=i
# print("hello,打印次数:",i)
# range表示,从0数到1001,参数可以放字符串,等等
# s=0
# for i in range(1001):
# s=s+i
# print(s)
# str = "hello my name is hanmeimei"
# for s1 in str:
# print(s1)
classmates = ['Michael', 'Bob', 'Tracy']
classmates.append('Adam')
classmates.insert(1, 'Jack')
classmates.pop()
print(classmates)
|
031a10782319255ada7207ab33b49d989a0e582d | avinashreddy21/Data-Mining | /1.Correlation/Pearson_Corr_Coeff.py | 769 | 3.515625 | 4 | import pandas as pd
from statistics import mean
import math
data = pd.read_csv('overdoses.csv')
data.Population = data.Population.str.replace(",", "")
data.Deaths = data.Deaths.str.replace(",", "")
a = list(data.Population)
b = list(data.Deaths)
float_a = [float(i) for i in a]
float_b = [float(j) for j in b]
mean_a = mean(float_a)
mean_b = mean(float_b)
assert len(float_a) == len(float_b)
length = len(float_a)
abproduct = 0
a_sqdiff = 0
b_sqdiff = 0
for k in range(length):
a_diff = float_a[k] - mean_a
b_diff = float_b[k] - mean_b
abproduct += (a_diff * b_diff)
a_sqdiff += (a_diff * a_diff)
b_sqdiff += (b_diff * b_diff)
print("Pearson correlation coefficient between population and deaths: ", abproduct/math.sqrt(a_sqdiff * b_sqdiff))
|
296fa51b74a2ef70861972c2f45233b6af229ca4 | fport/feyzli-python | /26.0 fonk2.py | 742 | 3.8125 | 4 | """def fonksiyon(belirle):
try:
liste = [x for x in range(100) if x % belirle ==0]
print(liste)
except TypeError:
print("Fonksiyona Gönderilen deger hatali")
fonksiyon("mert")
"""
"""
def fonksiyon(p1,p2,p3):
return p1+p2+p3
print(fonksiyon(1,2,3))"""
#arg yerine baska bişeydene koyabılırsın
def fonksiyon(*args):
toplam =0
for i in args:
toplam+=i
return print(toplam)
fonksiyon(1,2,3,4,5,6,7,8)
def yazdir(*kelime):
for i in kelime:
print(i,end=" ")
yazdir("yegen","sude")
def daireAlan(r,PI =3.1415):
return print(PI*(r**2))
daireAlan(5)# piyi kendi alıyor
daireAlan(5,3)#piyi biz degiştiriyoruz
daireAlan(5, PI=3)
|
06eacfd81166cca9ac0354b6dc00b6490489d78c | barathviknesh/GUVI | /Frls.py | 134 | 4 | 4 | n=int(input("Enter the number to print:"))
l=n
l=l%10
while(n>=10):
n=n//10
f=n
print("first digit:",f,"last digit",l)
|
0c2e36a6f4e8c464a9b415f972be96c5b4a6787f | wajishagul/wajiba | /Task7.py | 1,208 | 4.28125 | 4 | print("********Task 7 Functions********")
print("1. Create a function getting two integer inputs from user.& print the following:\nAddition of two numbers is +value\nSubtraction of two numbers is +value\nDivision of two numbers is +value\nMultiplication of two numbers is +value")
a=int(input("Enter the first number : "))
b=int(input("Enter the second number : "))
symbol=input("Enter '+' for addition,'-' for subtraction,'*' for multiplication,'/ for division': ")
def math_function(a,b,sign):
if sign== '+':
print("Addition of a and b is ",str(a+b))
elif sign== '-':
print("Subraction of a and b is ",str(a-b))
elif sign == '*':
print("Multiplication of a and b is ",str(a*b))
elif sign == '/':
print("Division of a and b is ",str(a/b))
math_function(a,b,symbol)
print("\n2.Create a function covid( ) & it should accept patient name, and body temperature, by default the body temperature should be 98 degree")
def covid(name,temp):
print("Enter the name : ",name)
if temp=='':
print("Temp is : 98")
else:
print("Temp is : ",temp)
name = input("Enter name : ")
temp=input("Enter temp : ")
covid(name,temp)
print("\n------------Task 7 Completed-----------") |
dc5bf9e6b2b9e5061dc028b3f16f4fd30a843777 | patriciaslessa/pythonclass | /Decision_2.py | 322 | 3.859375 | 4 |
def lista_2_ex_2():
"""
Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
"""
a = int(input("digite um número: "))
if float(a) >= 0:
print ("O número digitado é positivo" )
else:
print ("O número digitado é negativo")
lista_2_ex_2()
|
fb42bb06734d0de92faa15c47bf387d350ae9cd6 | 13jonerik/SimpleDFArunner | /DFA.py | 1,450 | 3.921875 | 4 | __author__ = 'jonerik13'
import string as s
mapping = {}
def runDFA():
#total number of states in the DFA
states = raw_input("How many states are in this DFA?: ")
#designate accepting states
aStates = str(raw_input("Which of these states are accepting states? Enter in 01234 format: "))
#used set() to make sure user did not duplicate
acceptStates = list(set(aStates))
#take the alphabet into a list, use to make a mock transition graph
sigma = str(raw_input("List the digits in the alphabet for your DFA. Enter in abc123&^$ format: "))
alphabet = list(set(sigma))
newDict = {}
numDict = {}
for i in alphabet:
mapA = {}
count = 0
letter = int(states)
for x in range(0, int(states)):
temp = raw_input("At stage " + str(count) + " if you see a (" + str(i) + ") what stage will the DFA transition to?: ")
count+=1
mapA[x] = int(temp)
mapping[str(i)] =mapA
path = []
stringTest = raw_input("Enter a string to test: " )
stringT = list(stringTest)
current = 0
for e in stringT:
letter = (mapping[str(e)])[current]
path.append(int(letter))
current = int(letter)
finalStage = str(path[-1])
print '*****'
if finalStage in acceptStates:
print "String Accepted!"
else:
print "String Rejected"
runDFA() |
57d3a6e7648ac75758cde5dc610f2d69ed2e4f9b | kcoppola88/Python | /password_generator.py | 1,402 | 3.890625 | 4 | import sys
import secrets
import string
def gen_pass():
while True:
try:
pass_length = int(input('Please enter an integer between 8 and 12: '))
if pass_length < 8:
print ("Not long enough. Please try again. \n")
pass
elif pass_length > 12:
print ("Too long. Please try again. \n")
pass
else:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*();'<>?"
password = ''.join(secrets.choice(alphabet) for i in range(pass_length))
print (password + "\a")
print ("\n")
input('Please copy your password then press enter to exit. ')
print ("\n")
sys.exit()
except ValueError:
print("That was not an integer. Please try again. \n")
def main():
while True:
print ("\n")
option = input('Welcome. Would you like to generate a password? Y/N: ').lower()
if option == "n":
print ("\n")
sys.exit()
elif option == "y":
gen_pass()
else:
print ("You did not enter a correct option. Please try again. \n")
pass
if __name__ == "__main__":
main() |
dad394612600ecca3f9fbb6265c58d0ee1077d5c | JustSage/electricity_bill_calculator | /src/console/menu.py | 831 | 3.609375 | 4 | from utils.utils import clean_function_name, list_previous_bills
from bills.elec_bill import calculate_my_electric_bill
def menu():
commands = { 1 : calculate_my_electric_bill, 2 : list_previous_bills}
print("_______ WELCOME _______")
print("Function Menu: ")
while True:
for key, val in commands.items():
name = clean_function_name(val)
print(str(key) + ") " + name)
print("Enter Q to quit")
try:
user_input = input("Enter menu option: ")
if user_input in ['Q','q']:
print("Have a good day!")
exit()
if int(user_input) in commands.keys():
print()
cmd = commands[int(user_input)]
cmd()
except ValueError:
print("Invalid Input")
|
c5ee470d812b23f80c947e31bec9ba818b5ce407 | oilmcut2019/final-assign | /jupyter-u07157113/Quiz_Python_20190309.git/Quiz_6.py | 117 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
a=int(input())
b=3
while a>b:
print(b)
b+=3
# In[ ]:
|
94d793f08f54080b6b2ff63134aecf73e4d4e7e9 | MacBook-Pro-gala/supinfo.python | /自学项目/pygamemods.py | 318 | 3.609375 | 4 | def pygamefrom(x, y, x1, y1, w):
aa = x1
bb = y1
for a in range(y + 1):
pygame.draw.line(screen, (0, 0, 0), (x1, y1), (x1, x * w + y1))
x1 = x1 + w
x1 = aa
y1 = bb
for b in range(x + 1):
pygame.draw.line(screen, (0, 0, 0), (x1, y1), (x1 + y * w, y1))
y1 = y1 + w |
e083844725017db22cb839e7e44ee0ffd6a12729 | LouiseCerqueira/python3-exercicios-cursoemvideo | /python3_exercicios_feitos/Desafio048.py | 352 | 3.796875 | 4 | #Faça um programa que calcula a soma entre todos os numeros ímpares que são múltiplos de três e que se encontram no intervalo de 1 até 500.
cont=0
cont2 = 0
for i in range(1,501, 2):
if i%3==0:
cont+=i
cont2 += 1 #Para saber quanto números foram somados
print(f'O somatório dos {cont2} múltiplos de 3, ímpares, é {cont}') |
08bdf748d33ca292b05fec5895bc1361d2ade7ff | epicmichael3257/RockPaperScissors | /game.py | 2,257 | 3.875 | 4 |
import random as r
name = input("Enter your name:")
print("Hello,",name)
newName = False
d = {}
with open("rating.txt",'rt') as f: #create dictionary from list values
for line in f:
a = line.split()
key,values = a[0],int(a[1])
d[key] = values
f.close()
if name not in d: #initalize them if they don't already exist --add them to file at the end
d[name] = 0
newName = True
player = ""
while player != "!exit": #yes ik the code could've been condensed using arrays and in the in operator
player = input()
player = player.lower()
if player == "scissors" or player == "paper" or player == "rock":
computer_responses = ["scissors", "paper", "rock"]
computer_response = r.randint(0, 3)
if player == "scissors":
if computer_response == 0:
print("There is a draw (scissors)")
d[name] += 50
elif computer_response == 1:
print("Well done. The computer chose paper and failed")
d[name] += 100
else: print("Sorry, but the computer chose rock")
elif player == "paper":
if computer_response == 0:print("Sorry, but the computer chose scissors")
elif computer_response == 1:
print("There is a draw (paper)")
d[name] += 50
else:
print("Well done. The computer chose rock and failed")
d[name] += 100
elif player == "rock":
if computer_response == 0:
print("Well done. The computer chose scissors and failed")
d[name] += 100
elif computer_response == 1:print("Sorry, but the computer chose paper")
else:
print("There is a draw (rock)")
d[name] += 50
elif player != "!exit" and player != "!rating":
print("Invalid input")
elif player == "!rating":
print("Your rating",d[name])
if newName:
with open('rating.txt','a') as f:
f.write(name+" "+str(d[name])+"\n")
f.close()
else:
with open('rating.txt','wt') as new:
for key in d:
new.write(key+" "+str(d[key])+"\n")
print("Bye!")
|
27e841de7f3b15fd5f76b0294cb3e4ff1c90b90e | jayaimzzz/Numseq-Package | /numseq/fib.py | 702 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Returns the nth Fibonacci number
"""
__author__ = "jayaimzzz"
import sys
import argparse
def fib(n):
if n == 0:
return 0
if n == 1:
return 1
if n > 1:
return fib(n - 1) + fib(n - 2)
else:
return "error"
def create_parser():
parser = argparse.ArgumentParser()
parser.add_argument('number', help='nth Fibonacci number')
return parser
def main():
"""Main function is declared as standalone, for testability"""
parser = create_parser()
args = parser.parse_args()
n = int(args.number)
return fib(n)
if __name__ == '__main__':
"""Docstring goes here"""
main()
|
df2f141450aa5520805dc70bc7df5541d8bc4587 | MakeSchool-17/sorting-algorithms-python-kazoo-kmt | /sort.py | 1,678 | 3.9375 | 4 | import time
import unittest
def timed_sort(list, key, algorithm='insertion'):
sort_func = globals()[algorithm]
start_time = time.time()
sorted_list = sort_func(list, key=key)
end_time = time.time()
elapsed_time = end_time - start_time
return (sorted_list, elapsed_time)
# ---
# Define your search algorithm functions here!
def insertion(list, key=lambda item: item):
size = len(list)
for i in range(1, size):
for j in range(i, 0, -1):
compare = list[j - 1]
current = list[j]
if key(current) < key(compare):
list[j] = compare
list[j - 1] = current
return list
def bucket(list):
"""assuming it contains [0, 10]"""
result = []
# list comprehension: [] for X in X
buckets = [[] for number in range(0, 11)]
# assign list items to each bucket
for number in list:
buckets[number].append(number)
for bucket in buckets:
# for number in bucket:
# result.append(number)
# result += bucket #this is worst because it includes copy and assign
result.extend(bucket)
return result
# You can also implement by dictionary (we've done in histogram)
class TestSorting(unittest.TestCase):
def test_bucket_sort(self):
list = [1, 5, 4, 7, 6, 8, 4, 2, 9, 1, 5, 4, 6, 8]
expected_result = sorted(list)
bucket_sorted = bucket(list)
self.assertEqual(bucket_sorted, expected_result)
print('original list:', list)
print('sorted list:', bucket_sorted)
# print(expected_result == bucket_sorted)
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.