blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
25d00cea5d15095e481f258fd98d1f14cebe8364 | Jean-Bi/100DaysOfCodePython | /Day 17/quiz-game-start/quiz_brain.py | 1,943 | 3.875 | 4 | class QuizBrain:
def __init__(self, question_list):
"""Constructs a new QuizBrain object."""
# The attribute question_number is initialized to 0
self.question_number = 0
# The attribute question_list is initialized with the value of the parameter question_list
self.question_list = question_list
# The attribute score is initialized to 0
self.score = 0
def next_question(self):
"""Displays the next question and asks for user answer."""
# Retrieves question matching the attribute question_number
question = self.question_list[self.question_number]
# Increments the attribute question_number by 1
self.question_number += 1
# Asks the user for its answer and stores it
user_answer = input(f"Q.{self.question_number}: {question.text} (True/False)?: ")
# Checks whether the user's answer is correct or not
self.check_answer(user_answer, question.answer)
def still_has_questions(self):
"""Checks whether the quiz still has questions"""
# Checks if the attribute question_number is less than the number of questions
return self.question_number < len(self.question_list)
def check_answer(self, user_answer, correct_answer):
"""Checks user's answer against the correct answer."""
# Checks if the user's answer equals the correct answer
if user_answer.lower() == correct_answer.lower():
# The user got the right answer
print("You got it right!")
# Increments user's score by 1
self.score += 1
else:
# The user got the wrong answer
print("That's wrong.")
# Prints the correct answer
print(f"The correct answer was: {correct_answer}.")
# Prints the user current score
print(f"Your current score is: {self.score}/{self.question_number}")
|
52906a1ae003271a1a440a30f80a69776d09f732 | hyejinHong0602/BOJ | /prac/WEEK1_교재실습.py | 1,870 | 3.96875 | 4 | #교재 실습
# print('세 정수의 최대값을 구합니다')
# a=int(input('정수 a값을 입력하세요:'))
# b=int(input('정수 b값을 입력하세요.'))
# c=int(input('정수 c값을 입력하세요.'))
#
# maximum=a
# if b>maximum : maximum=b
# if c>maximum : maximum=c
# print(maximum)
# def max3(a,b,c):
# maximum=a;
# if b>maximum:maximum=b
# if c>maximum:maximum=c
# return maximum
#
# print(f'최대값은?={max3(3,2,5)}')
#-----#
# name=input('이름을 입력하세요:')
# print(f'안녕하세요? {name} 님.')
#-----#
#중앙값 구하기
# def med3(a,b,c):
# if a>=b:
# if b>c:
# return b
# elif a<=c:
# return a
# else:
# return c
# elif a>c:
# return a
# elif b>c:
# return c
# else:
# return b
#
#
# print(f'중앙값: {med3(2,7,3)}')
# print(f'중앙값: {med3(7,2,3)}')
# print(f'중앙값: {med3(1,3,6)}')
#a부터 b까지의 합 구하기
# def sum2(a,b):
# if a>b:
# a,b=b,a
# sum=0
#
# for i in range(a, b+1):
# sum+=i
#
#
# print(f'합? {sum2(2,4)}')
# n=int(input('몇개를 출력?'))
#
# for i in range(1,n+1):
# if (i % 2 == 1):
# print(f'+', end='')
# else:
# print(f'-', end='')
# num=int(input('몇개출력?'))
# cut=int(input('몇개마다?'))
#
# for i in range(1, num + 1):
# print(f'*', end='')
# if i % cut == 0:
# print()
#
#for문 마다 if문을 수행하는건 효율적이지 않음.
# num=int(input('몇개출력?'))
# cut=int(input('몇개마다?'))
#
# n=num//cut
# nrest=num%cut
# for i in range(n):
# print('*'*cut,end='')
# print()
# for j in range(nrest):
# print('*',end='')
# s=int(input('넓이:'))
#
# for i in range(1,s):
# if i*i>s:break #중복제한
# if s%i==0:
# print(i,s//i)
|
f0a1f1826cdfbd4f5f044134facae8c5175cb6ee | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 2/ex041 - Classificando Atletas.py | 1,024 | 4.125 | 4 | """ A Confederação Nacional de Natação precisa de um program que leia o ano de nascimento
de um atleta e mostre sua categoria, de acordo com a idade:
-Até 9 anos: Mirim
-Até 14 anos: Infantil
-Até 19 anos: Junior
-Até 25 anos: Sênior
-Acima: Master
"""
from datetime import date
nasc = int(input("Qual ano de nascimento do atleta? "))
idade = date.today().year - nasc
if idade <= 9:
print("O atleta tem {} anos e se classica na categoria: {}Mirim{}".format(idade, "\033[1;34m", "\033[m"))
elif idade <= 14:
print("O atleta tem {} anos e se classifica na categoria: {}Infantil{}".format(idade, "\033[1;34m", "\033[m"))
elif idade <= 19:
print("O atleta tem {} anos e se classifica na categoria: {}Junior{}".format(idade, "\033[1;34m", "\033[m"))
elif idade <= 25:
print("O atleta tem {} anos e se classifica na categoria: {}Sênior{}".format(idade, "\033[1;34m", "\033[m"))
else:
print("A atleta tem {} anos e se classifica na categoria: {}Master{}".format(idade, "\033[1;34m", "\033[1;34m"))
|
d6e58b3c17d06c279908a0860004dc4fafc9e7fe | mradu97/python-programmes | /add_of_matrix.py | 823 | 3.765625 | 4 | l1=[[0,0],[0,0]]
l2=[[0,0],[0,0]]
l3=[[0,0],[0,0]]
i=0
while(i<=1):
j=0
while(j<=1):
l1[i][j] =int(input("Enter value"))
j = j + 1
i = i +1
i=0
while(i<=1):
j=0
while(j<=1):
l2[i][j] =int(input("Enter value"))
j = j + 1
i = i +1
i=0
while(i<=1):
j=0
while(j<=1):
print(l1[i][j],end=" ")
j = j + 1
print("")
i = i +1
k=0
while(k<=1):
m=0
while(m<=1):
print(l2[k][m],end=" ")
m = m + 1
print("")
k = k +1
i=0
while(i<=1):
j=0
while(j<=1):
k=0
while(k<=1):
l3[i][j]+=l1[i][k]*l2[k][j]
k=k+1
j=j+1
i=i+1
i=0
while(i<=1):
j=0
while(j<=1):
print(l3[i][j],end=" ")
j=j+1
print("")
i=i+1
|
8d13b5faae362f9ea4d2f461a97120447b7574ed | Rukeith/leetcode | /461. Hamming Distance/solution.py | 240 | 3.59375 | 4 | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
diff = x ^ y
result = 0
while diff != 0:
if diff % 2 != 0:
result += 1
diff >>= 1
return result
|
66bb8b561876c3824857297fa5e173f22ddf999e | haiyaoxliu/old | /workspace/cs/Missionaries and Cannibals..py | 897 | 3.640625 | 4 | moves = [ (2,0,1), (1,0,1), (1,1,1), (0,1,1), (0,2,1) ]
missionaries = 0
cannibals = 1
boat = 2
def solve(state, path):
if state == [0,0,-1]:
print 'solution:',path+[state]
return True
elif check(state,path):
for move in moves:
new = solve([state[missionaries] - state[boat] * move[missionaries],
state[cannibals] - state[boat] * move[cannibals],
-state[boat]],
path + [state] )
if new: return True
return False
def check(state,path):
if state in path: return False
elif state[cannibals] > state[missionaries] > 0 or 3 - state[cannibals] > 3 - state[missionaries] > 0: return False
elif state[cannibals] > 3 or state[cannibals] < 0 or state[missionaries] > 3 or state[missionaries] < 0: return False
else:
return True
solve([3,3,1],[]) |
cb34bd25a6d62adb12842ab175fcffe83600a9c4 | anonythrowaway/google-code-sample | /python/src/video_playlist.py | 1,198 | 4.1875 | 4 | """A video playlist class."""
class Playlist:
"""A class used to represent a Playlist."""
def __init__(self, name):
self._name = name
self._videos = list()
@property
def name(self):
return self._name
def add_video(self, video, playlist_name):
if video not in self._videos:
self._videos.append(video)
message = f'Added video to {playlist_name}: {video.title}'
else:
message = f'Cannot add video to {playlist_name}: Video already added'
print(message)
def show_playlist(self):
if len(self._videos) > 0:
for video in self._videos:
print(str(video))
else:
print('No videos here yet')
def remove_video(self, video, playlist_name):
try:
self._videos.remove(video)
print(f'Removed video from {playlist_name}: {video.title}')
except ValueError:
print(f'Cannot remove video from {playlist_name}: Video is not in playlist')
def clear_playlist(self, playlist_name):
self._videos.clear()
print(f'Successfully removed all videos from {playlist_name}')
|
947c08138c5c260b3b980689faa6c751f030b863 | ramyasutraye/Python-6 | /2.py | 115 | 4.03125 | 4 | a=int(input("enter no"))
if a%2==0:
print("even")
elif a<=0:
print("invalid")
else:
print("odd4") |
4ade9a5642b1da17f4fe980a1801fb86cb04a901 | ncaew/mytest1 | /guard/timer.py | 1,872 | 3.9375 | 4 | import threading
class Timer(object):
""" timer to count down, notify every step"""
def __init__(self, step, timeout):
self._step = step
self._step_action = None
self._step_action_args = None
self._timeout = timeout
self._timeout_action = None
self._tmargs = None
self._timer = threading.Timer(step, self._action)
self._count_down = 0
self.remain_second = 0
def start(self):
self._count_down = self._timeout / self._step
if self._timer.is_alive():
t = threading.Timer(self._step, self._action)
self._timer = t
self._timer.start()
def cancel(self):
self._timer.cancel()
def is_alive(self):
return self._timer.is_alive()
def set_step_action(self, action, args):
self._step_action = action
self._step_action_args = args
def set_timeout_action(self, action, args):
self._timeout_action = action
self._tmargs = args
def _action(self):
self._count_down -= 1
self.remain_second = self._count_down * self._step
if self._count_down == 0:
self._timer.cancel()
if self._step_action is not None:
self._step_action(self._step_action_args)
if self._timeout_action is not None:
self._timeout_action(self._tmargs)
else:
if self._step_action is not None:
self._step_action(self._step_action_args)
t = threading.Timer(self._step, self._action)
self._timer = t
self._timer.start()
if __name__ == '__main__':
def print1s(a):
print(a)
def printtimeout(a):
print(a)
t = Timer(10, 30)
t.set_step_action(print1s, "111111")
t.set_timeout_action(printtimeout, "timeout")
t.start()
|
73cee0ced6185306292e96f9ab04ff73888a1034 | Neeraj-kaushik/coding_ninja | /pattern14.py | 408 | 3.609375 | 4 | n= int(input())
n1=(n+1)/2
n2=n/2
i=1
while i<=n1:
space=1
while space<=i-1:
print(' ',end="")
space+=1
j=1
while j<=i:
print("*",' ',end="")
j=j+1
print()
i=i+1
i=1
while i<=n2:
space=1
while space<=n2-i:
print(' ',end="")
space+=1
j=1
while j<=n2-i+1:
print("*",' ',end="")
j=j+1
print()
i=i+1
|
882676658b32eb43e8e56162222b1ae7549f7627 | 09ubberboy90/PythonProjects | /graph/pack/__init__.py | 333 | 3.8125 | 4 | def test():
n = 2
x = 3
y = 4
n_increase = 0
x_increase = 0
y_increase = 0
while n_increase < n :
while x_increase < x :
while y_increase < y :
print("%d "% n)
y_increase +=1
x_increase += 1
n += 1
print(n)
test() |
be9b57cf253b8d0083fc79b487c274231f440523 | mofei952/leetcode_python | /dynamic_programming/198 House Robber.py | 1,266 | 3.9375 | 4 | """
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that
adjacent houses have security system connected and it will automatically
contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house,
determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
"""
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
prev = curr = 0
for num in nums:
prev, curr = curr, max(prev+num, curr)
return curr
if __name__ == "__main__":
print(Solution().rob([1, 2, 3, 1]))
print(Solution().rob([2, 7, 9, 3, 1]))
print(Solution().rob([]))
print(Solution().rob([0]))
|
631f1365a5674df691bf34fd22acc74989eaca32 | onclick360-blog/CS5590_PyDL | /Module1/In_Class_Exercise/ICE1/Source/reverse.py | 495 | 4.15625 | 4 | '''
author : ruthvic
created : 1/25/2019 9:00PM
'''
def string_reverse(tmp_str):
rev_str = ''
index = len(tmp_str) # get length of string
while index > 0:
# we do a rev traversal from last index
rev_str += tmp_str[ index - 1 ]
index = index - 1
return rev_str
# standard input to take first & last name
fName = input('Please enter first name: ')
lName = input('Please enter last name: ')
# print the reversed string
print(string_reverse(fName+" "+lName)) |
880f393e4a918b7f11d8ab72d8a19d237c85ca14 | zhangray758/python-final | /day02_final/str1.py | 235 | 3.515625 | 4 | # Author: ray.zhang
age=28
while True:
age=(input(">>>>:").strip())
if len(age) == 0:
continue
elif age.isdigit(): #注意:isdigit是str的方法。
print(age,type(age))
else:
break |
d9e2671dd906571f1f140bc8c1d554ebc08ffef4 | kenzzuli/hm_15 | /05_python高级/13_python提高-2/05_新式类中三种装饰器-练习.py | 845 | 3.859375 | 4 | # 实际开发中使用三种装饰器
class Goods:
def __init__(self, original_price, discount):
self.original_price = original_price
self.discount = discount
@property
def real_price(self):
return self.discount * self.original_price
@real_price.setter
def real_price(self, price):
self.original_price = price / self.discount
@real_price.deleter
def real_price(self):
del self.original_price
g = Goods(100, 0.8)
print(g.real_price) # 获取 商品实际价格 80.0
g.real_price = 200 # 修改 商品实际价格,顺带会根据折扣更改商品的原始价格
print(g.original_price) # 250.0
del g.real_price # 删除 商品实际价格,会删除商品的原始价格
# print(g.original_price) # AttributeError: 'Goods' object has no attribute 'original_price'
|
ef985f75da429348f7050dcbf07aa2adff3150c5 | fabiod905/Resolvendo-problemas-com-Python | /Desafios-com-Python/FIBONACCI.py | 377 | 3.859375 | 4 | n = int(input('Digite um número menor que 46:'))
while n >= 46:
n = int(input('Digite um número menor que 46:'))
lista = []
lista.append(0)
lista.append(1)
lista.append(1)
x = 2
while lista[x] < n:
num = lista[x] + lista[x-1]
lista.append(num)
num = 0
x += 1
lista.pop()
num_elementos = len(lista)
for i in range(0,num_elementos):
print(lista[i])
|
272823a64feb39ebc138882f6b7be77f48052ccc | R161559/NEERUGATTI-NAVEENA | /operatin on sine and cos.py | 790 | 3.609375 | 4 | # a program to generate sine , cosine fuctions and to do some of the operations on them
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,3*np.pi,0.1)
y=np.sin(x)
plt.subplot(5,1,1)
plt.plot(x,y,'r')
plt.title('sine')
plt.xlabel('amplitude')
plt.ylabel('time')
z=np.cos(x)
plt.subplot(5,1,2)
plt.plot(x,z,'b')
plt.title('cosine')
plt.xlabel('amplitude')
plt.ylabel('time')
k=y+z
plt.subplot(5,1,3)
plt.plot(x,k,'*')
plt.title('sum of sine and cosine')
plt.xlabel('amplitude')
plt.ylabel('time')
sub=y-z
plt.subplot(5,1,4)
plt.plot(x,sub,'g')
plt.title('subtraction of sine amd cos')
plt.xlabel('amplitude')
plt.ylabel('time')
mul=y*z
plt.subplot(5,1,5)
plt.plot(x,mul,'y')
plt.title('multiplication of two signals')
plt.xlabel('amplitude')
plt.ylabel('time')
plt.show()
|
75a4093feca39b2989327cb0a9b58060755a24a2 | CodingDojoDallas/python_oct_2017 | /Cooper_leibow/Python/fundamentals/fun_with_functions.py | 636 | 4.03125 | 4 | def oddEven(digit):
if digit % 2 == 0:
print "Number is", num, ". This is an even number"
else:
print "Number is", num, ". This is an odd number"
num = 45
oddEven(num)
def multiply(numbers, times):
for i in range(len(numbers)):
numbers[i] *= times
print numbers
return numbers
numbers = [2,4,6,10]
times = 5
multiply(numbers, times)
def layeredMultiples (numbers, times):
z = multiply(numbers, times)
print z
bigList = []
for i in range(len(z)):
bigList.append(z[i]*(1,))
print bigList
numbers = numbers = [2,4,6,10]
times = 3
layeredMultiples(numbers,times)
|
4c7809fa00fbb39753adf1535a53f616b41a10d6 | jonathan-ku/SPOJ | /SPOJ/ADDREV.py | 495 | 3.890625 | 4 | '''
Created on 2014-12-20
@author: Jonathan
'''
def add_reverse(x, y):
x = list(x)
y = list(y)
x.reverse()
y.reverse()
x_reverse = "".join(x)
y_reverse = "".join(y)
z = list(str(int(x_reverse) + int(y_reverse)))
z.reverse()
return int("".join(z))
if __name__ == '__main__':
N = int(raw_input())
out = []
for i in xrange(0,N):
num = raw_input().split()
out.append(add_reverse(num[0], num[1]))
for o in out:
print o |
c637b565dbaecc055c1a5768a594a2c9371f65b8 | ap3526/unitConversion | /unit_conversion.py | 1,928 | 4.25 | 4 | #Made by Akash Patel CS-171-A Lab Section 063
#Prints user interface according to homework insructions
print('Welcome to the Unit Conversion Wizard')
print('This program can convert between any of the following lengths:')
print('inches')
print('feet')
print('yards')
print('miles')
print('leagues')
print('centimeters')
print('decimeters')
print('meters')
print('hectometers')
print('kilometers\n')
#Dictionary / base unit is inches
key = {"inches": 1.0, "feet": 12.0, "yards": 36.0, "miles": 63360, 'leagues': 190080, 'centimeters': 0.393701, 'decimeters': 3.9370,'meters': 39.3701, 'decameters': 393.701, 'hectometers': 3937.01, 'kilometers':39370.1}
#Grabs necessary information for conversion
number = float(input('Enter value:\n'))
#based on user input, collect proper conversion value from dictionary
#newNumber represents the input converted to inches
unitFrom = input('Enter from units:\n')
if unitFrom == 'inches':
newNumber = number * key['inches']
elif unitFrom == 'feet':
newNumber = number * key['feet']
elif unitFrom == 'yards':
newNumber = number * key['yards']
elif unitFrom == 'miles':
newNumber = number * key['miles']
elif unitFrom == 'leagues':
newNumber = number * key['leagues']
elif unitFrom == 'centimeters':
newNumber = number * key['centimeters']
elif unitFrom == 'decimeters':
newNumber = number * key['decimeters']
elif unitFrom == 'meters':
newNumber = number * key['meters']
elif unitFrom == 'decameters':
newNumber = number * key['decameters']
elif unitFrom == 'hectometers':
newNumber = number * key['hectometers']
elif unitFrom == 'kilometers':
newNumber = number * key['kilometers']
#the unit that the user wants to convert to
unitTo = input('Enter to units:\n')
#print original value and its units then the new value and new units rounded to 4 decimal places
print(number, unitFrom, 'is', round(newNumber / key[unitTo], 4), unitTo)
|
e21700195ee52b4fd765a8e2f0c7f5b0de1f8cdb | darshanpatel44/DataStructure | /Q1.py | 237 | 3.625 | 4 | def CEF(L1,L2):
Output = []
for i in L1:
for j in L2:
if i != j:
continue
else:
Output.append(i)
return Output
L1=[1,2,3,5,8]
L2=[1,2,7,3,6]
print(CEF(L1,L2))
|
41b8732b002a69d3f22a3fde231feb73efc3291c | DaveKaretnyk/parsing-utils2 | /check-python33-manual/samples/miscellaneous/sample1.py | 2,461 | 3.75 | 4 |
def free_func_1(x=3):
return x+1
def free_func_2():
return 1
def free_func_3():
def my_local_func():
return 0
return my_local_func() + 1
def free_func_4():
def my_local_func():
def another_local_func():
return 1
return another_local_func() + 1
return my_local_func() + 1
class Silly1(object):
def __init__(self):
self._something = 'initial value'
def class_func_get1(self):
return self._something
def class_func_set1(self, new_value):
self._something = new_value
class Silly2(object):
def __init__(self):
self._something = 'initial value'
class InternalClass(object):
def __init__(self):
pass
class InternalClass2(object):
def __init__(self):
pass
def internal_class_method(self):
pass
def another_internal_method(self):
pass
def internal_class_method(self):
pass
def another_internal_method(self):
pass
def class_func_get2(self):
return self._something
def class_func_set2(self, new_value):
self._something = new_value
def class_func_another(self):
pass
def class_func_another2(self):
pass
class Silly3(object):
def __init__(self):
self._something = 'initial value'
def class_func_get1(self):
def class_func_internal():
pass
class_func_internal()
return self._something
def class_func_set1(self, new_value):
self._something = new_value
def _class_func_xxx(self):
def class_func_internal_xxx():
pass
class_func_internal_xxx()
self._something = self._something
if __name__ == "__main__":
print('Python 3.X print...') # Python 3 print...
# print 'Python 2.X print...' # Python 2 print...
free_func_1(2)
free_func_2()
free_func_3()
free_func_4()
silly1 = Silly1()
silly1.class_func_set1("blah")
get_current = silly1.class_func_get1()
# print 'silly1 returned: ', get_current
silly2 = Silly2()
silly2.class_func_set2("haha")
get_current = silly2.class_func_get2()
# print 'silly2 returned: ', get_current
silly3 = Silly3()
silly3.class_func_set1('hoho')
get_current = silly3.class_func_get1()
# print 'silly3 returned: ', get_current
|
632082b71cad67f6e84f13dfa6158b2d73f0eb60 | WillRonny/learn-python3 | /code/qua(函数练习).py | 217 | 3.53125 | 4 | import math #记得导入函数包math
def q(a,b,c):
d = b*b-4*a*c
if d >= 0:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
return x1,x2
else:
print("wujie")
print(q(1,5,3)) |
40f453831e668020571c0e7ac4230aced9d7eac5 | ersimon/2018-05-29-AMNH-CCA | /Day3Python/sample_workflow/read.py~ | 455 | 4.0625 | 4 | '''Here we store some sample ways to read in data and spit out the pieces that we want from the dataset let's assume all of the data we are using has a header and columns so we can read it in using pandas read_csv method
let's create a function to read in our kind of data set, then returns an x and y value that we care about '''
import pandas as pd
def read_my_csv(csvfile):
data = pd.read_csv(csvfile, sep =' ')
return data.xaxis, data.yaxis
|
2ea522a1e50336ae47b687230a3607f9c288ffc6 | EugeneStill/PythonCodeChallenges | /dijkstra.py | 2,214 | 4.15625 | 4 | import heapq
import unittest
# This class represents a directed graph using adjacency list representation
class Graph(object):
def __init__(self, V: int):
self.V = V
self.graph = [[] for _ in range(V)]
def addEdge(self, u: int, v: int, w: int):
self.graph[u].append((v, w))
self.graph[v].append((u, w))
def shortestPath(self, src: int):
# Create a priority queue to store vertices that are being preprocessed
pq = []
heapq.heappush(pq, (0, src))
# Create a vector for distances and initialize all distances as infinite (INF)
dist = [float('inf')] * self.V
dist[src] = 0
while pq:
# The first value in pair is the minimum distance from source to vertex at the time vertex was added to q
# vertex is second value in pair
d, current_vertex = heapq.heappop(pq)
# use i to get all adjacent vertices of a vertex
for neighbor, weight in self.graph[current_vertex]:
# update distance from source to neighbor if path to neighbor through current_vertex is shorter
if dist[neighbor] > dist[current_vertex] + weight:
# Updating distance of neighbor
dist[neighbor] = dist[current_vertex] + weight
heapq.heappush(pq, (dist[neighbor], neighbor))
print("RESULTS:")
for i in range(self.V):
print(f"{i} \t\t {dist[i]}")
return dist
class TestDijkstra(unittest.TestCase):
def test_dijkstra(self):
"""verify shortest path from start to each node in graph"""
# create the graph
V = 9
g = Graph(V)
g.addEdge(0, 1, 4)
g.addEdge(0, 7, 8)
g.addEdge(1, 2, 8)
g.addEdge(1, 7, 11)
g.addEdge(2, 3, 7)
g.addEdge(2, 8, 2)
g.addEdge(2, 5, 4)
g.addEdge(3, 4, 9)
g.addEdge(3, 5, 14)
g.addEdge(4, 5, 10)
g.addEdge(5, 6, 2)
g.addEdge(6, 7, 1)
g.addEdge(6, 8, 6)
g.addEdge(7, 8, 7)
expected_result = [0, 4, 12, 19, 21, 11, 9, 8, 14]
self.assertEqual(g.shortestPath(0), expected_result)
|
cadfb0d98ae61b621263a8d5e6a72745de8e93d2 | Balakumar5599/Assessment | /alternate_method_problem_1.py | 370 | 3.84375 | 4 | def color_pair(color_string):
count=[]
distinct_char=set(color_string)
for char in distinct_char:
count.append(color_string.count(char))
for item in count:
if item%2!=0:
return False
else:
return True
color_string=input("Enter the string: ")
print("Pair for all character:",color_pair(color_string))
|
421e3375214aba98254d2a38409075bd743cbcd8 | duongcao74/PythonHW | /hw9/covid-19.py | 4,886 | 3.953125 | 4 | # ----------------------------------------------------------------------
# Name: COVID19
# Purpose: Practice crawling web pages with beautiful soup, re, and
# urllib
#
# Author(s): Haitao Huang, Duong Cao
# ----------------------------------------------------------------------
"""
Implement a program that systematically compiles COVID-19 information
from multiple web pages and saves that information in a text file on the
user's computer.
"""
import urllib.request
import urllib.parse
import bs4
import re
def visit_url(url):
"""
Open the given url and return its visible content and the referenced
links
:param url:(string) - the address of the web page to be read
:return: BeautifulSoup object
"""
try:
with urllib.request.urlopen(url) as url_file:
bytes = url_file.read()
except urllib.error.URLError as url_err:
print(f'Error opening url: {url}\n{url_err}')
else:
soup = bs4.BeautifulSoup(bytes, 'html.parser')
return soup
def get_population(search):
"""
Finding the population numbers of searched countries.
:param search: (String) the search term
:return: (list of tuples) countries and population numbers
"""
URL = ('https://en.wikipedia.org/wiki'
+ '/List_of_countries_and_dependencies_by_population')
soup = visit_url(URL)
tables = soup.find_all('table')
table = tables[0]
result = []
regex = re.compile(search, re.IGNORECASE)
searched_countries = table.find_all('a', string=regex)
for each_country in searched_countries:
country = each_country.get_text()
population = each_country.find_next('td').get_text()
population = int(population.replace(',', ''))
result.append((country, population))
return result
def get_case(search):
"""
Finding the cases and deaths due to COVID-19 of the searched
countries
:param search: (String) the search term
:return: (list of tuple) countries and their number of COVID-19
cases, deaths, and the description
"""
URL = ('https://en.wikipedia.org/wiki/2019%E2%80%9320_coronavirus_'
+ 'pandemic_by_country_and_territory')
soup = visit_url(URL)
base_url = 'https://en.wikipedia.org/'
table = soup.find('table', {'id': "thetable"})
result = []
regex = re.compile(search, re.IGNORECASE)
non_empty_regex = re.compile(r'((/S )+(,|.))')
searched_countries = table.find_all('a', string=regex)
for each_country in searched_countries:
country = each_country.get_text()
next_td = each_country.find_next('td')
try:
cases = int(next_td.get_text().replace(',', ''))
except ValueError:
return result
else:
try:
deaths = int(next_td.find_next('td').get_text()
.replace(',', ''))
except ValueError:
return result
else:
country_url = each_country.get('href')
soup2 = visit_url(f'{base_url}{country_url}')
paragraph = soup2.find('p')
paragraph_text = paragraph.get_text()
while not paragraph_text.strip():
paragraph = paragraph.find_next('p')
paragraph_text = paragraph.get_text()
if ',' and '.' not in paragraph_text:
paragraph_text = ''
result.append((country, cases, deaths, paragraph.get_text()))
return result
def main():
search_term = input('Please enter a search term: ')
pop = dict(get_population(search_term))
cases = get_case(search_term)
# write output
with open(f'{search_term}summary.txt', 'w', encoding='utf-8') \
as output_file:
for i in range(len(pop)):
country = cases[i][0]
population = pop[country]
confirms = cases[i][1]
deaths = cases[i][2]
paragraph = cases[i][3]
cases_per_100k = f'{100000*confirms/population:,.1f}'
deaths_per_100k = f'{100000*deaths/population:,.1f}'
population = f'{population:,}'
confirms = f'{confirms:,}'
deaths = f'{deaths:,}'
output_file.write(f'Country: {country} \n')
output_file.write(f'Population: {population:>30} \n')
output_file.write(f'Total Confirmed Cases: {confirms:>19} \n')
output_file.write(f'Total Deaths: {deaths:>28} \n')
output_file.write(f'Cases per 100,000 people: '
f'{cases_per_100k:>18} \n')
output_file.write(f'Deaths per 100,000 people: '
f'{deaths_per_100k:>17} \n')
output_file.write(f'{paragraph} \n\n')
if __name__ == '__main__':
main() |
036b968c1101fbd5cfb0f51edc4334a682f41f39 | voiceteam1/voice | /linwanyan/homework2.3.py | 207 | 3.71875 | 4 | # -*- coding:utf-8 -*-
l1 = [[1,1,1],[2,2,2],[3,3,3]]
for i in l1:
print (i)
num = 0
for i in range(3):
for j in range(3):
a=l1[i]
b =a[j]
if i==j:
num+=b
print ('对角线之和为%d'%num)
|
08fc8afbab442d582fb0c46e8ec0712cc751f5cb | jpallavi23/Smart-Interviews | /06_SI_Basic-Hackerrank/08_Count Vowels and Consonants.py | 506 | 4.1875 | 4 | '''
Given a string, print count of vowels and consonants of the string.
Input Format
Input contains a string of upperscase and lowercase characters - S.
Constraints
1 <= len(S) <= 100
Output Format
Print count of vowels and consonants for the given string, separated by space.
Sample Input 0
abxbbiaaspw
Sample Output 0
4 7
'''
string = input().lower()
vowels = consonants = 0
for _ in string:
if _ in 'aeiou':
vowels += 1
else:
consonants += 1
print(f"{vowels} {consonants}") |
be07062a6fd3dcea21c334b71d05cf046000db07 | markomav/Wave-1 | /Compound Interest.py | 208 | 3.546875 | 4 | def interest(P):
I = 1.04
A1 = P * I**1
A2 = P * I**2
A3 = P * I**3
return('1st Year: $' + str(A1*100//1/100) + ', 2nd Year: $' + str(A2*100//1/100) + ', 3rd Year: $' + str(A3*100//1/100)) |
f2f785134ac8e6f6bfde21e8dcd160e75643b025 | kblicharski/ctci-solutions | /Chapter 2 | Linked Lists/ds/lists.py | 313 | 3.578125 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self) -> str:
return self.data
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def __len__(self) -> int:
return self.size
|
30941e1a16927e95e7e89bd27f4c759b32283b07 | CedArctic/VP-Tree | /utilities.py | 2,339 | 3.90625 | 4 | # Imports
import random, math
# Generates an array of random points on a two dimensional plane
def random_points(pointsNum):
a = []
for i in range(0, pointsNum):
a.append(Point(random.random(), random.random()))
return a
# Base class for a point
class Point:
def __init__(self, x, y):
self.X = x
self.Y = y
# Calculate distance between two points
def distance(self, otherPoint):
return math.sqrt(pow((self.X - otherPoint.X), 2)
+ pow((self.Y - otherPoint.Y), 2))
def print(self):
print("Point (X,Y): " + str(self.X) + ", " + str(self.Y) + "\n")
# Base class for a binary tree
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data),
if self.right:
self.right.PrintTree()
# Base class for a queu that will hold points and their distance to the query and be ordered by distance
class DQueue:
def __init__(self, maxLength):
self.data = []
self.maxLength = maxLength
# Returns number of elements currently in the DQueue
def length(self):
return len(self.data)
# Insert DQueue element ([point, distance]) based on distance
def insert(self, point, distance):
index = 0
if self.length() > 0:
while self.data[index][1] < distance:
index += 1
self.data.insert(index, [point, distance])
# Shave off excess elements
del self.data[self.maxLength:]
# Peek the distance of the last element - the one furthest away based on distance
def peek_distance(self):
return self.data[self.length()-1][1];
|
5c110754e347b12c53deb10ca61634da5ebd8ef0 | Jack-Flynn/01_lucky_unicorn | /pythonProject/01_rounds_and_payment.py | 516 | 3.859375 | 4 | # Show Rules
print("Costs: $1 per round, up to 10 rounds")
def num_check(question, low, high):
error = "Please enter a whole number between 1 and 10"
valid = False
while not valid:
try:
response = int(input(question))
if low < response <= high:
return response
else:
print(error)
except ValueError:
print(error)
# Ask for payment
how_much = num_check("How much would you like to play with?", 0, 10)
|
c14656db421f1b81becb41a3ae603e3c4ed07437 | zhuyul/ConnectFour-Game | /functions_for_both.py | 2,474 | 3.84375 | 4 | import connectfour
# Print Module
# The board should always be shown in a fixed format
# The game should repeatly remind the player of whose turn is next
def print_screen(game_state: connectfour.ConnectFourGameState) -> None:
''' Print the board in a fixed format, '.' represents no piece
'''
for i in range(1,connectfour.BOARD_COLUMNS+1):
print(i,end=' ')
print()
for row in range(connectfour.BOARD_ROWS):
for col in range(connectfour.BOARD_COLUMNS):
if game_state.board[col][row] == connectfour.NONE:
pixel = '.'
else:
pixel = game_state.board[col][row]
print(pixel,end=' ')
print()
return
def print_turn(game_state: connectfour.ConnectFourGameState) -> None:
'''The game should repeatly remind the player of whose turn is next
'''
print("{}'s turn is next".format(game_state.turn))
return
#input module
def collect_player_command()->str:
'''return the command of the player
'''
while True:
command=input('''\nEnter how you want to do with the piece ---
Enter examples:
DROP 1: To drop a piece at the first column
POP 5: To pop a piece at the fifth column
Your input is: ''').strip()
if command.split()[0]=='DROP' and type(eval(command[-1]))==int :
break
elif command.split()[0]=='POP' and type(eval(command[-1]))==int:
break
print('invalid input! please try again')
return command
# drop or pop
def game_each_move(command:str,column_number:int,game_state:connectfour.ConnectFourGameState)->connectfour.ConnectFourGameState:
'''each move for the game
'''
try:
if command=='D':
game_state=connectfour.drop_piece(game_state,column_number)
elif command=='P':
game_state=connectfour.pop_piece(game_state,column_number)
except connectfour.InvalidConnectFourMoveError:
print('Invalid move! Please try again')
except ValueError:
print('column_number must be int between 0 and {}'.format(connectfour.BOARD_COLUMNS))
return game_state
# winner
def check_for_winner(winner:str)->bool:
'''check if the game is over, and return True if the game is over
'''
if winner==connectfour.RED:
print('Red wins!')
return True
elif winner==connectfour.YELLOW:
print('Yellow wins!')
return True
return False
|
9bff042b80dcc39b9ff74dac81f6fab305093622 | Aiyane/aiyane-LeetCode | /101-150/单词拆分2.py | 1,677 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单词拆分2.py
"""
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]
"""
"""
思路:动态规划问题,注意 s 在 wordDict 中并不能直接返回,也可能被切分。
"""
__author__ = 'Aiyane'
class Solution:
def __init__(self):
self.map = {}
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
def wordBreakDB(s, lens, wordSet):
res = []
if s in self.map:
return self.map[s]
for wl in lens:
if s[:wl] in wordSet:
res.extend([s] if wl == len(s) else [s[:wl] + ' ' + kid for kid in wordBreakDB(s[wl:], lens, wordSet)])
self.map[s] = res
return res
return wordBreakDB(s, set(len(word) for word in wordDict), set(wordDict)) |
979c75911ce5f17aca87bdf4e8ff21df4d817922 | gitmengzh/100-Python-exercises | /100/q13.py | 485 | 3.734375 | 4 | '''
输入一个句子,然后计算字母和数字的个数
'''
input_string = input()
dict1 = {"DIGITS":0,"LETTERS":0}
for i in input_string:
if i.isdigit():
dict1["DIGITS"]+=1
if i.isalpha():
dict1["LETTERS"]+=1
else:
pass
print("DIGITS:",dict1["DIGITS"],"LETTERS:",dict1["LETTERS"],type(i))
'''
学习点: 对于字符串,可以遍历
对于字符串,可以判断其每个元素的类型 str.isdigit() str.isalpha()
''' |
47197139b18dac63a59ce14dbdcc1e0ef1cb7be5 | VinayHaryan/String | /q33.py | 1,871 | 4 | 4 | '''
REMOVE ALL CONSECUTIVE DUPLICATES FROM THE STRING
given a string s, remove all the consecutive duplicates.
note that this probleam is different from here we keep one
character and remove all subsequent same characters
Examples:
Input : aaaaabbbbbb
Output : ab
Input : geeksforgeeks
Output : geksforgeks
Input : aabccba
Output : abcba
'''
# Python3 program to remove consecutive
# duplicates from a given string.
# A iterative function that removes
# consecutive duplicates from string S
# def removeDuplicates(S):
# n = len(S)
# # We don't need to do anything for
# # empty or single character string.
# if (n < 2) :
# return
# # j is used to store index is result
# # string (or index of current distinct
# # character)
# j = 0
# # Traversing string
# for i in range(n):
# # If current character S[i]
# # is different from S[j]
# if (S[j] != S[i]):
# j += 1
# S[j] = S[i]
# # Putting string termination
# # character.
# j += 1
# S = S[:j]
# return S
# # Driver Code
# if __name__ == '__main__':
# S1 = "geeksforgeeks"
# S1 = list(S1.rstrip())
# S1 = removeDuplicates(S1)
# print(*S1, sep = "")
def removeduplicates(s):
n = len(s)
if n < 2:
return
j = 0
for i in range(n):
if (s[j] != s[i]):
j += 1
s[j] = s[i]
j += 1
s = s[:j]
return s
# driver code
if __name__ == '__main__':
s1 = 'geeksforgeeks'
s1 = list(s1.rstrip())
s1 = removeduplicates(s1)
print(*s1,sep='')
# Time Complexity : O(n)
# Auxiliary Space : O(1)
|
55eb302879eabb9f2ef70c14a4153b1cd26fece0 | ConnorYoto/COM701-Python-Data-Structures-and-Algorithms | /Merge Sort on a Linked List/MergeSort_LinkedList.py | 2,746 | 3.96875 | 4 | class Node:
def __init__(self, head = None, tail = None):
self.head = head
self.tail = tail
def setHead(self, head):
self.head = head
def setTail(self, node):
self.tail = node
def getHead(self):
return self.head
def getTail(self):
return self.tail
class MergeSortList:
def __init__(self):
self.head = None
def add(self, head):
tempNode = Node(head)
tempNode.setTail(self.head)
self.head = tempNode
del tempNode
def print(self):
current = self.head
if current is None:
print("Empty List!!!")
return False
while current:
print(str(current.getHead()), end=" ")
current = current.tail
if current:
print("-->", end=" ")
print()
def sortedMerge(self, a, b):
result = None
# Base Cases for the recursion
if a == None:
return b
if b == None:
return a
if a.head <= b.head:
result = a
result.tail = self.sortedMerge(a.tail, b)
else:
result = b
result.tail = self.sortedMerge(a, b.tail)
return result
def mergeSort(self, h):
# linkedlist <= 1 aka Base Case
if h == None or h.tail == None:
return h
# Find middle of lsit for split
midpoint = self.findMiddle(h)
midpointnext = midpoint.tail
# Break list in two
midpoint.tail = None
# Merge Sort Left Side of List
leftside = self.mergeSort(h)
# Merge Sort Right Side of List
rightside = self.mergeSort(midpointnext)
# Merge Left and Right Lists
sortedList = self.sortedMerge(leftside, rightside)
return sortedList
# Splitting the List down the middle for merge sort
def findMiddle(self, head):
if (head == None):
return head
slow = head
fast = head
while (fast.tail != None and fast.tail.tail != None):
slow = slow.tail
fast = fast.tail.tail
return slow
# Creating Object
myList = MergeSortList()
# Creating Elements
myList.add(77)
myList.add(56)
myList.add(49)
myList.add(62)
myList.add(69)
myList.head = myList.mergeSort(myList.head)
myList.print()
# I have chosen to implement Merge Sort because it is considered as
# one of the most efficient sorting algorithms with regards to Linked Lists
# The complexity of this algorithm is O(nlogn)
|
f43b66902a14a6fa61629fd9ccc18e677a494fb8 | KonstantinosVasilopoulos/MatchingGame | /main.py | 3,077 | 4.03125 | 4 | import random
import functions
# Welcome the player(s)
print('Welcome to the Matching Game')
# Get player count
player_count = functions.get_player_count()
# Get the difficulty level and set the board dimensions and cards
DIFFICULTY_LEVEL = functions.get_difficulty_level()
if DIFFICULTY_LEVEL == '1':
m = 4
n = 4
elif DIFFICULTY_LEVEL == '2':
m = 4
n = 10
else:
m = 4
n = 13
# Create cards and shuffle them
cards = functions.create_cards_list(DIFFICULTY_LEVEL)
random.seed()
random.shuffle(cards)
# Show board and hide all cards
functions.show_board(m, n, cards)
for card in cards:
card.hidden = True
# Dictionary containing player scores
player_scores = {}
for player in range(1, player_count + 1):
player_scores[player] = 0
# Main loop
while not functions.check_game_over(cards):
player = 1
while player <= player_count and not functions.check_game_over(cards):
# Let each player guess 2 cards
card1 = functions.guess_card(m, n, cards, 'Player ' + str(player) + ': Give row and column of the first card (eg 1 10): ')
functions.show_board(m, n, cards)
card2 = functions.guess_card(m, n, cards, 'Player ' + str(player) + ': Give row and column of the second card: ')
functions.show_board(m, n, cards)
# Compare the 2 cards
if functions.compare_cards(card1, card2):
functions.increase_score(card1, player, player_scores)
# Check for a K & Q combination
card3_success = False
if (card1.symbol == 'Q' and card2.symbol == 'K') or (card1.symbol == 'K' and card2.symbol == 'Q'):
# Let the player open a third card
card3 = functions.guess_card(m, n, cards, 'Player ' + str(player) + ': Give row and column of the third card: ')
functions.show_board(m, n, cards)
# Compare the 1st with the 3rd card
if functions.compare_cards(card1, card3):
functions.increase_score(card3, player, player_scores)
card2.hidden = True # Hide the 2nd card
card3_success = True
# Compare the 2nd with the 3rd card
elif functions.compare_cards(card2, card3):
functions.increase_score(card3, player, player_scores)
card1.hidden = True # Hide the 1st card
card3_success = True
else: # Hide all cards
card1.hidden = True
card2.hidden = True
card3.hidden = True
# Decide who the next player is
if not card3_success:
player = functions.choose_next_player(card1, card2, player, player_count)
else:
if functions.compare_cards(card1, card3):
player = functions.choose_next_player(card1, card3, player, player_count)
else:
player = functions.choose_next_player(card2, card3, player, player_count)
# Show results
print('Results')
for player in player_scores:
print('\tPlayer ' + str(player) + ': ' + str(player_scores[player]))
|
14cd6832ba8565b57a1248e17af7aad5691ee704 | zy15662UNUK/Homework | /camel_case.py | 757 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 3 22:39:25 2017
@author: James
"""
def camel_case(string):
"""
Write simple .camelcase method (camel_case function in PHP) for strings. All words must have their first letter capitalized without spaces.
For instance:
camelcase("hello case") => HelloCase
camelcase("camel case word") => CamelCaseWord
"""
if string == '':
return ''
string_list=string.split(' ')
out=''
head=''
for i in string_list:
if i == '':
string_list.remove(i)
for i in string_list:
head=i[0].upper()
out=out+head
for j in range(1,len(i)):
out=out+i[j]
return out
|
7a1a0ae6ab3856756efc5b431eacb2d1146e9315 | kiran-isaac/Voting-sytem | /vote.py | 3,345 | 3.71875 | 4 | import userInput
def voteFor(studentID):
cursor.execute(("SELECT votes FROM candidates WHERE studentID='{0}'").format(studentID))
voteCount = cursor.fetchone()["votes"]
cursor.execute(("UPDATE candidates "
"SET votes={0} "
"WHERE studentID={1}".format(voteCount+1 if voteCount else 1, studentID)))
def vote():
student, tutor = voterLogin()
if not student:
return
if student["voted"]:
print("You have already voted")
return
if student["abstained"]:
print("You have abstained")
return
if not userInput.yesno("Do you want to vote? : "):
stmt = ("UPDATE students "
"SET abstained=1, "
"voted=1 "
"WHERE studentID={}".format(student["studentID"]))
cursor.execute(stmt)
db.commit()
return
cursor.execute("SELECT * FROM candidates WHERE studentID IN (SELECT studentID FROM student_in_tutor WHERE tutorID='{0}')".format(tutor))
students = cursor.fetchall()
if students:
cursor.execute("SELECT * FROM students WHERE studentID<>{0} AND studentID IN {1}".format(student["studentID"], str(tuple([student["studentID"] for student in students])).replace(",)", ")")))
students = cursor.fetchall()
print("\n###{0} CANDIDATES###".format(tutor))
printCandidates(students)
print()
else:
print("There are no candidates for " + tutor)
return
while True:
studentIDs = [student["studentID"] for student in students]
vote = userInput.chooseFromList(int, "Please enter the ID of the candidate you want to vote for: ", studentIDs)
stmt = ("SELECT * FROM students "
"WHERE studentID={0}").format(vote)
cursor.execute(stmt)
student = cursor.fetchone()
print("You voted for", student["studentName"])
if userInput.yesno("Are you sure you want to vote for {0}"):
voteFor(vote)
stmt = ("UPDATE students "
"SET voted=1 "
"WHERE studentID={}".format(student["studentID"]))
cursor.execute(stmt)
db.commit()
def voterLogin():
nameRegex = "^[a-zA-Z ,.'-]+$"
run = True
while run:
cursor.execute("SELECT tutorID FROM tutor")
tutors = [x["tutorID"] for x in cursor.fetchall()]
tutor = userInput.chooseFromList(str, "What tutor are you in? ", tutors)
name = userInput.getStringInput("Please enter your full name: ", nameRegex).lower()
date = userInput.getDate("Please enter your date of birth (dd/mm/yyyy): ", "Invalid date")
date = datetime.datetime.strptime(date, '%d/%m/%Y').date().strftime("%Y-%m-%d")
cursor.execute("SELECT * FROM students WHERE studentName='{0}' AND dob='{1}' and studentID IN (SELECT studentID FROM student_in_tutor WHERE tutorID='{2}')".format(name, date, tutor))
student = cursor.fetchone()
if not student:
print("There is no registered voter with this name and date of birth")
run = userInput.yesno("Try again? ")
else:
cursor.execute("SELECT tutorID FROM student_in_tutor WHERE studentID={0}".format(student["studentID"]))
return student, cursor.fetchone()["tutorID"]
return False |
2a5087884164070bdb82aa13d12dab0863f8089c | zmayw/studious-waddle | /Application_python/algorithm_sorting/indexMaxHeap.py | 2,397 | 3.625 | 4 | #coding=utf-8
import random
class MaxHeap:
def __init__(self,capacity):
self.capacity = capacity
self.indexes = []
self.data = []
self.count = 0
def __shiftUp(self,k):
#当前节点与父节点进行大小比较,如果小于父节点,则调换位置
while(k > 0 and self.data[self.indexes[(k-1)/2]] < self.data[self.indexes[k]]):
self.indexes[(k-1)/2] ,self.indexes[k] = self.indexes[k],self.indexes[(k-1)/2]
k = (k-1)/2
def __shiftDown(self, k):
while((2*k+1) <= (self.count-1)):
j = 2*k+1 # data[k] 和data[j]进行交换,data[j]可能是左孩子,也可能是右孩子
if (j+1 <= self.count-1 and self.data[self.indexes[j+1]] > self.data[self.indexes[j]]):
j = j +1
if (self.data[self.indexes[k]] < self.data[self.indexes[j]]):
self.indexes[k],self.indexes[j] = self.indexes[j],self.indexes[k]
k = j
def isEmpty(self):
return self.count == 0
def insert(self, index, item):
if(index+1 < 1 or index + 1 > self.capacity):
return
self.data.append(item)
self.indexes.append(index)
self.count = self.count + 1
self.__shiftUp(index)
def extractMax(self):
if self.count < 0:
return
ret = self.data[self.indexes[0]]
self.indexes[0],self.indexes[self.count-1] = self.indexes[self.count-1],self.indexes[0]
self.count = self.count - 1
self.__shiftDown(0)
return ret
def extractMaxIndex(self):
if self.count < 0:
return
ret = self.indexes[0]
self.indexes[0],self.indexes[self.count-1] = self.indexes[self.count-1],self.indexes[0]
self.count = self.count - 1
self.__shiftDown(0)
return ret
def getItem(self,index):
return self.data[index]
def change(self,index,item):
self.data[index] = item
for j in range(self.count):
if( self.indexes[j] == index):
self.__shiftUp(j)
self.__shiftDown(j)
arr = [9,7,2,1,3,8,6,4,5,0]
n = len(arr)
maxHeap = MaxHeap(n)
for i in range(n):
maxHeap.insert(i,arr[i])
print maxHeap.data
print maxHeap.indexes
while( maxHeap.isEmpty() == False):
item = maxHeap.extractMax()
print item ,maxHeap.indexes
|
aebf9bbb1d764ce97990751abebc62d5b4977501 | ezhilarasi-g/code | /43player.py | 93 | 3.546875 | 4 | #ezhil
a,b=map(str,input().split())
if a.find(b)==-1:
print("no")
else:
print("yes")
|
dafa905b1b2a8abb6997d5e77564e11889028dd3 | dyiar/Sprint-Challenge--Data-Structures-Python | /names/heap.py | 1,618 | 3.71875 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage)-1)
def delete(self):
self.storage[0], self.storage[-1] = self.storage[-1], self.storage[0]
deletedValue = self.storage.pop(-1)
self._sift_down(0)
return deletedValue
def get_max(self):
return self.storage[0]
def get_size(self):
return len(self.storage)
def _bubble_up(self, index):
if index <= 0:
return
parent_index = (index-1) // 2
if self.storage[index] > self.storage[parent_index]:
temp = self.storage[index]
self.storage[index] = self.storage[parent_index]
self.storage[parent_index]=temp
self._bubble_up(parent_index)
def _sift_down(self, index):
left_child = (index*2) + 1
right_child = (index*2) + 2
temp = index
if len(self.storage) > left_child and self.storage[left_child] > self.storage[temp]:
temp = left_child
if len(self.storage) > right_child and self.storage[right_child] > self.storage[temp]:
temp = right_child
if index is not temp:
temp2 = self.storage[index]
self.storage[index] = self.storage[temp]
self.storage[temp] = temp2
self._sift_down(temp)
def sorted(arr):
sorted_arr = []
heap = Heap()
for i in arr:
heap.insert(i)
for i in range (len(arr)):
sorted_arr.append(heap.delete())
return sorted_arr
|
540216f1c817cfc3c3bcf2197ae6f4b30f7beeb9 | vega832/tr06_vega_cristina | /vega/doble_02.py | 461 | 3.578125 | 4 | #ejercicio 02
import os
#delclarion de variables
trabajador,renumeracion_mensual="",0
#INPUT VIA OS
trabajador=os.sys.argv[1]
renumeracion_mensual=int(os.sys.argv[2])
#PROCESSING
#si el la renumeracion mensual es mayor 100
#mostrar tiene renumeracion anual
#caso contrario se muestra "no tiene renumeracion anual"
if (renumeracion_mensual>100):
print(trabajador,"tiene reunmeracion anual")
else:
print(trabajador,"no tiene renumeracion anual")
#fin_if
|
cf4732669097279f738dbf54d546ec3daf4973ea | niuniu6niuniu/Leetcode | /LC-Defanged_IP.py | 876 | 3.71875 | 4 | # Given a valid (IPv4) IP address, return a defanged version of that IP address.
# A defanged IP address replaces every period "." with "[.]".
# Example 1:
# Input: address = "1.1.1.1"
# Output: "1[.]1[.]1[.]1"
# Example 2:
# Input: address = "255.100.50.0"
# Output: "255[.]100[.]50[.]0"
class Solution:
def defangIPaddr(self, address: str) -> str:
# Solution 1: ------ SPLIT ------
# Idea: 1. Split the str with "."
2. Concatenate the sub-str with "[.]"
newAdd = address.split('.')
newStr = ''
for num in newAdd:
newStr += num + '[.]'
return newStr[:len(newStr)-3]
# Solution 2: ------ REPLACE ------
# Idea: Rplace the "." with "[.]"
# return address.replace(".", "[.]")
new = defangIPaddr(None, '1.1.1.1')
print(new)
|
357c6249a100de27c334605cd39fad1cfb308c89 | andrei406/Meus-PycharmProjects-de-Iniciante | /PythonExercicios/ex031.py | 287 | 3.75 | 4 | n1 = int(input('Digite a distância em km para ser calculado o preço da passagem:'))
print('0,50 por quilometro se for uma viagem de até 200Km, superior, 0,45')
if n1 <= 200:
print('O preço é {:.2f}R$'.format(n1 * 0.50))
else:
print('O preço é {:.2f}R$'.format(n1 * 0.45))
|
eea90206039d83e9ee3b27ada1d281219ef14295 | rntva/JumpToPython | /Test_2018-01-03/csv_test.py | 5,999 | 3.6875 | 4 | import csv
import math
def get_csv_row_instance(primary_key, printing=1):
try:
primary_key_index = data[0].index(primary_key)
except:
print("No Primary Key Found - Row")
return None
get_row_instance = []
instance_type = ""
for row in data[1:]:
if printing == 1: print(row[primary_key_index])
try:
get_row_instance.append(float(row[primary_key_index]))
if instance_type != "str" : instance_type = "float"
except:
get_row_instance.append(row[primary_key_index])
instance_type = "str"
get_row_instance.append(instance_type)
return get_row_instance
def get_csv_col_instance(primary_key, printing=1):
for row in data[1:]:
if row[0] == primary_key:
if printing == 1:
title_name = 0
for col_instance in row:
print("%s : %s" % (data[0][title_name], col_instance), end=" ")
title_name += 1
return row
print("No Primary Key Found - Col")
return None
def my_sum(primary_key, printing=1):
total = 0.0
try:
temp_instance = get_csv_row_instance(primary_key, 0)
if temp_instance[-1] == "str":
print("str타입은 my_sum작업을 수행하지 않습니다.")
return None
elif temp_instance[-1] == "float":
for x in temp_instance[:-1] :
total += float(x)
if printing == 1:
print("%s : " %primary_key, end = '')
print(temp_instance)
print("Sum : %g " %total)
return total
except:
return None
def my_average(primary_key, printing = 1) :
average = 0.0
try:
temp_total = my_sum(primary_key, 0)
temp_length = len(get_csv_row_instance(primary_key, 0)[:-1])
if temp_total == None :
print("total값이 없어 my_average를 수행할 수 없습니다.")
return None
else :
average = temp_total / float(temp_length)
if printing == 1 : print("%s : total = %g, length = %g, average = %g" %(primary_key,\
temp_total, temp_length, average))
return average
except:
return None
def my_max(primary_key) :
try :
if get_csv_row_instance(primary_key, 0)[-1] == "str" :
print("str타입은 my_min을 수행하지 안습니다.")
return None
temp_max = max(get_csv_row_instance(primary_key, 0)[:-1])
print("%s의 최댓값은 %g" %(primary_key, temp_max))
return None
except :None
def my_min(primary_key) :
try :
if get_csv_row_instance(primary_key, 0)[-1] == "str" :
print("str타입은 my_min을 수행하지 안습니다.")
return None
temp_min = min(get_csv_row_instance(primary_key, 0)[:-1])
print("%s의 최댓값은 %g" %(primary_key, temp_min))
return None
except : None
def my_deviation(primary_key, printing = 1) :
temp_deviation = []
try:
temp_average = my_average(primary_key, 0)
if temp_average == None:
print("average값이 없어 my_deviation를 수행할 수 없습니다.")
return None
else:
for instance in get_csv_row_instance(primary_key, 0)[:-1] :
if printing == 1 : print("%s %3g - %3g = %g" %(primary_key, instance, temp_average,\
(instance- temp_average)))
temp_deviation.append(instance - temp_average)
return temp_deviation
except:
return None
def my_variation(primary_key, printing = 1) :
temp_variation = 0.0
temp_deviation = my_deviation(primary_key, 0)
temp_deviation_total = 0.0
try:
if temp_deviation == None:
print("average값이 없어 my_variation를 수행할 수 없습니다.")
return None
else:
for x in temp_deviation:
temp_deviation_total += float(x)**2
temp_variation = temp_deviation_total / len(get_csv_row_instance(primary_key, 0)[:-1])
if printing == 1: print("%s : sum_(deviation^2) = %5g, variation = %g"\
%(primary_key, temp_deviation_total, temp_variation))
return temp_variation
except:
return None
def my_standard_deviation(primary_key) :
try :
temp_variation = my_variation(primary_key, 0)
temp_stan_devi = math.sqrt(temp_variation)
print("%s : variation = %g, standard deviation = %6g" %(primary_key, temp_variation, temp_stan_devi))
except : None
def my_ascendant(primary_key, printing = 1) :
temp = get_csv_row_instance(primary_key, 0)[:-1]
temp = sorted(temp)
for x in temp :
if printing == 1 : print(x)
return temp
def my_descendant(primary_key) :
temp = my_ascendant(primary_key, 0)
temp = reversed(temp)
for x in temp :
print(x)
return temp
with open("Demographic_Statistics_By_Zip_Code.csv", newline='') as file:
data = list(csv.reader(file))
while 1:
test_input = input("원하는 동작을 입력하십시오.\n1:get_col 2:get_row 3:sum\
4:average 5:max 6:min 7:deviation 8:variance 9:standard_deviation\
10:ascendant 11:decendant 12:exit : ")
primaty_key = input("primary_key값을 입력하십시오 : ")
if test_input == '12' : break
elif test_input == '2' : get_csv_row_instance(primaty_key)
elif test_input == '1' : get_csv_col_instance(primaty_key)
elif test_input == '3' : my_sum(primaty_key)
elif test_input == '4' : my_average(primaty_key)
elif test_input == '5' : my_max(primaty_key)
elif test_input == '6' : my_min(primaty_key)
elif test_input == '7' : my_deviation(primaty_key)
elif test_input == '8' : my_variation(primaty_key)
elif test_input == '9' : my_standard_deviation(primaty_key)
elif test_input == '10' : my_ascendant(primaty_key)
elif test_input == '11' : my_descendant(primaty_key) |
773c87838a5ac1238533963b5a4a6696a37c9d27 | jrlindeman-geophysicist/hello-world | /oddeven.py | 630 | 4.09375 | 4 | #!/usr/bin/python
number = int(raw_input("Please enter a number: "))
if number % 4 == 0:
print("Your number (%r) is divisible by 4.\n") % number
elif number % 2 == 0:
print("Your number (%r) is even.\n") % number
elif number % 2 != 0:
print("Your number (%r) is odd.\n") % number
print("Now I will ask for two additional numbers.")
num = int(raw_input("Please enter the first number: "))
check = int(raw_input("Please enter the second number: "))
if num % check == 0:
print("Your second number evenly divides into your first.\n")
elif num % check != 0:
print("Your second number does not evenly divide into your first.\n")
|
0065e232beaa46ac2455c3cdb8156a597811fcce | benjaminkweku/Intro_To_Python | /Dev-Python/conditional.py | 346 | 4.125 | 4 | i = 8
if(i % 2 == 0): # % is modulo
print ("Even Number")
else:
print ("Odd Number")
def evens():
list = []
start = int(input("Enter Minimum Number"))
finish = int(input("Enter Maximum Number"))
for num in range(start,finish):#+1)
if (num % 2 == 0):
list.append(num)
return list
print(evens()) |
885936acb3237650efac25bd5c7918a0ba68c741 | AmbujaAK/practice | /python/nptel-Aug'18/week2/ques1.py | 236 | 3.515625 | 4 | # ques 1
def intreverse(n):
x = n
ans = 0
while n > 0:
r = n%10
ans = ans * 10 + r
n = n//10
l = len(str(x))
ans = ('%0' + str(l) + 'd') % ans
return ans
num = intreverse(3000)
print(num) |
a595154d474bcf796584069a94e2350e1a10bc32 | stathis-alexander/ac-2018 | /day3/aoc-3-2.py | 1,891 | 3.5 | 4 | #!/usr/bin/python
# This is the solution to part one of Advent of Code, day 3.
f = open("input.txt",'r')
lines = list(f)
f.close()
patches = []
for line in lines:
temp = line.split()
startstr = temp[2]
dimstr = temp[3]
startstr = startstr[:-1]
coords = [int(x) for x in startstr.split(",")]
dims = [int(x) for x in dimstr.split("x")]
ends = [a+b-1 for a,b in zip(coords,dims)]
patches.append([coords,ends])
patches.sort()
# takes two (x1,y1),(x2,y2) defining upper left and lower right corners of squares
# returns upper left (x,y) and lower right (w,z) of intersection of them
def compute_intersection(pair1,pair2):
x1 = pair1[0][0]
y1 = pair1[0][1]
x2 = pair1[1][0]
y2 = pair1[1][1]
u1 = pair2[0][0]
v1 = pair2[0][1]
u2 = pair2[1][0]
v2 = pair2[1][1]
output = []
if u1 > x2 or v1 > y2 or v2 < y1:
return output
elif y1 > v1:
output.append([u1,y1])
output.append([min(u2,x2),min(y2,v2)])
else:
output.append([u1,v1])
output.append([min(x2,u2),min(v2,y2)])
return output
intersected = False
winner = -1
for i in range(len(patches)):
for j in range(len(patches)):
if i < j:
intersection = compute_intersection(patches[i],patches[j])
elif i == j:
continue
else:
intersection = compute_intersection(patches[j],patches[i])
if intersection:
intersected = True
break
if not intersected:
print(i)
winner = i
else:
intersected = False
for line in lines:
temp = line.split()
startstr = temp[2]
dimstr = temp[3]
startstr = startstr[:-1]
coords = [int(x) for x in startstr.split(",")]
dims = [int(x) for x in dimstr.split("x")]
ends = [a+b-1 for a,b in zip(coords,dims)]
if coords[0] == patches[winner][0][0] and coords[1] == patches[winner][0][1] and ends[0] == patches[winner][1][0] and ends[1] == patches[winner][1][1]:
print(temp[0])
|
0d6251db6051527d4b34875eed44ff5eaf614cfd | kyungchul/openbigdata | /01_jumptopy/chap04/149.py | 254 | 3.515625 | 4 | def sum_add_mul(a,b):
return a+b,a*b
result = sum_add_mul(3,4)
print(result)
print("덧셈 연산 결과: "+str(result[0]))
if result[0] > 0:
print("덧셈 분석 결과 양의 결과입니다.")
print("곳셈 연산 결과: "+str(result[1]))
|
cd47857b8c7bdc94c512abac0136feebc7a0140d | oarecat/PythonPractice | /FilteredWords.py | 478 | 3.875 | 4 | #第0011题:敏感词文本文件filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出Freedom,否则打印出Human Rights.
userInput = input("请输入文字:")
#增加的encoding = "utf-8"表示读取文件时按照UTF-8的编码方式
filterWords = open("C:\\GitHub\\PythonPractice\\filtered_words.txt" , "r" , encoding="utf-8").read().split(",")
if userInput in filterWords:
print ("Freedom")
else:
print ("Human Rights")
|
446af91da59abe40ea599252c71685ba8b603581 | csherfield/PythonTrainingExercises | /Advanced/RomeoAndJuliet/util/parser.py | 4,808 | 3.578125 | 4 | """Parser for Romeo and Juliet.
Created on 18 Mar 2015
@author: paulross
"""
from Exercises.RomeoAndJuliet.util import play
def _is_stage_direction(line):
"""Returns True if the line is a stage direction."""
line = line.strip()
return line.startswith('[') and line.endswith(']')
def get_scenes():
"""Returns a list of scenes where each scene is a list of pairs:
[(line_number, actor), ...] """
scenes = []
scene = []
for line_num, line in enumerate(play.PLAY_TEXT.split('\n')):
words = line.split()
actor = None
if len(words):
if len(words) and words[0] in play.DRAMATIS_PERSONAE:
actor = words[0]
elif len(words) > 1 and ' '.join(words[:2]) in play.DRAMATIS_PERSONAE:
actor = ' '.join(words[:2])
elif words[0] == 'SCENE':
if len(scene):
scenes.append(scene)
scene = []
if actor is not None:
scene.append((line_num, actor))
return scenes
class Play(object):
"""Represents the complete play."""
def __init__(self, name):
self.name = name
self._acts = []
# dict of {name : description, ...}
self.dramatis_personae = play.DRAMATIS_PERSONAE
def add_act(self, act):
self._acts.append(act)
def gen_acts(self):
for act in self._acts:
yield act
def __str__(self):
lines = ['Play: %s' % self.name]
for act in self._acts:
lines.append('%s\n' % str(act))
return '\n'.join(lines)
class Act(object):
"""Represents an act in the play."""
def __init__(self, act_num):
self.act_num = act_num
self._scenes = []
def add_scene(self, scene):
self._scenes.append(scene)
def gen_scenes(self):
for scene in self._scenes:
yield scene
def __str__(self):
lines = ['Act %d' % self.act_num]
for scene in self._scenes:
lines.append(' %s' % str(scene))
return '\n'.join(lines)
class Scene(object):
"""Represents a scene in an act. This contains the ordered list of actor names."""
def __init__(self, scene_num):
self._index = 0
self.scene_num = scene_num
self._actors = []
def add_actor(self, actor):
self._actors.append(actor)
def gen_actors(self):
for actor in self._actors:
yield actor
def __str__(self):
return 'Scene %d, actors: %s' % (self.scene_num, ', '.join(self._actors))
def get_play():
"""Returns a Play object that has acts, scenes and actors names in speaking order.
"""
play = Play('Romeo and Juliet')
d = get_acts_scenes_actors()
for act_num in sorted(d.keys()):
act = Act(act_num)
for scene_num in sorted(d[act_num].keys()):
scene = Scene(scene_num)
for actor in d[act_num][scene_num]:
scene.add_actor(actor)
act.add_scene(scene)
play.add_act(act)
return play
def get_acts_scenes_actors():
"""Returns a dict of acts, scenes and actor names:
{act : {scene : [actors, ...], ...}, ...}
act and scene are integers
"""
ret_val = {}
act = None
act_num = scene_num = 0
actors = []
for line in play.PLAY_TEXT.split('\n'):
words = line.split()
if len(words):
if len(words) and words[0] in play.DRAMATIS_PERSONAE:
actors.append(words[0])
elif len(words) > 1 and ' '.join(words[:2]) in play.DRAMATIS_PERSONAE:
actors.append(' '.join(words[:2]))
elif len(words) > 1 and words[0] == 'ACT' and words[1] != act:
if len(actors):
ret_val[act_num][scene_num] = actors
actors = []
act_num += 1
ret_val[act_num] = {}
scene_num = 0
act = words[1]
elif act is not None and words[0] == 'SCENE':
if len(actors):
ret_val[act_num][scene_num] = actors
actors = []
scene_num += 1
if len(actors):
ret_val[act_num][scene_num] = actors
actors = []
return ret_val
if __name__ == '__main__':
# import pprint
# print get_scenes()
# pprint.pprint(get_acts_scenes_actors())
# p = get_play()
# print p
s = Scene(1)
s.add_actor('a')
s.add_actor('b')
s.add_actor('c')
s.add_actor('d')
g = s.gen_actors()
g
print next(g)
print next(g)
print next(g)
print next(g)
print next(g)
# print next(s)
# print next(s)
# print next(s)
# print next(s)
# print next(s)
|
1ea9934cd2982059e37166715964a986ce404f3d | sharathcshekhar/singleswitch | /prototypes/keypress.py | 439 | 3.953125 | 4 | import Tkinter as tk
# Demonstration of how to use Tkinter to capture keypress events
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
x = event.char
if x == "w":
print "W for Wonderful!!!"
elif x == "a":
print "A for APPLE!"
elif x == "d":
print "D for DANGEROUS!"
else:
print "NO ME GUSTA"
root = tk.Tk()
root.bind_all('<Key>', keypress)
root.mainloop()
|
eb431990fb827849f56e3ee454fa739ea7439d8e | arthijayaraman-lab/crease_ga | /crease_ga/utils/initial_pop.py | 802 | 3.59375 | 4 | import numpy as np
def initial_pop(popnumber, nloci, numvars):
'''
Produce a generation of (binary) chromosomes.
Parameters
----------
popnumber: int
Number of individuals in a population.
nloci: int
Number of binary bits to represent each parameter in a chromosome.
numvars: int
Number of parameters in a chromosome.
Returns
-------
pop: np.array of size (`popnumber`,`nloci`*`numvars`)
A numpy array of binary bits representing the entire generation,
with each row representing a chromosome.
'''
pop=np.zeros((popnumber,nloci*numvars))
for i in range(popnumber):
for j in range(nloci*numvars):
randbinary=np.random.randint(2)
pop[i,j]=randbinary
return pop
|
b5b4cdb25cb26776db1cb2cb8fadbaa1e2ac7744 | kongtianyi/cabbird | /leetcode/minimum_moves_to_equal_array_elements_II.py | 466 | 3.578125 | 4 | def minMoves2(nums):
_min=min(nums)
_max=max(nums)
res=1<<31
for i in range(_min,_max+1):
t=sum([abs(j-i) for j in nums])
if t<res:
res=t
return res
def _minMoves2(nums):
nums.sort()
median=nums[len(nums)/2]
return sum(abs(n-median) for n in nums)
if __name__=="__main__":
print minMoves2([1,2,3])
print minMoves2([-1,2,3])
print minMoves2([2,2,3])
print minMoves2([3,3,3])
|
19e6c2b167f74de02c5d3c807842ca89291905d6 | GUSuper60/Binary-Beast_08 | /BOB_.KHATU_STRING.py | 1,247 | 4.15625 | 4 | '''
Bob and Khatu both love the string. Bob has a string S and Khatu has a string T. They want to make both string S and T to anagrams of each other. Khatu can apply two operations to convert string T to anagram of string S which are given below:
1.) Delete one character from the string T.
2.) Add one character from the string S.
Khatu can apply above both operation as many times he want. Find the minimum number of operations required to convert string T so that both T and S will become anagram of each other.
Input:
First line of input contains number of test cases T. Each test case contains two lines. First line contains string S and second line contains string T.
Output:
For each test case print the minimum number of operations required to convert string T to anagram of string S.
Constraints:
1 ≤ T ≤ 10
1 ≤ |S|,|T| ≤ 105
SAMPLE INPUT:
4
abc
cba
abd
acb
talentpad
talepdapd
code
road
SAMPLE OUTPUT:
0
2
4
4
'''
#SOLUTIONS:
T = int(input())
from collections import Counter
def strFreq(s):
return Counter(s)
for _ in range(T):
a = strFreq(input())
b = strFreq(input())
total = sum((a - b).values()) + sum((b - a).values())
print(total) |
e7c87a1679654f126a28605e596f081a2de6ee22 | eliseuegewarth/uri-exercises | /beginner/1016/1016.py | 65 | 3.59375 | 4 |
x = int(input())
time = x * 2
print("{} minutos".format(time))
|
7027a9e71a149de5a2e5b629573f1f8bc15e39a5 | erinszabo/260week_1 | /chapter_1.py | 1,636 | 3.828125 | 4 | import random
"""
Chapter 1.10
"""
print()
print()
print("self_check_1:")
# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
wordlist = ['cat', 'dog', 'rabbit']
letterlist = []
for aword in wordlist:
for aletter in aword:
if aletter not in letterlist:
letterlist.append(aletter)
print(letterlist)
print()
print("self_check_2:")
# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
awordlist = ['cat', 'dog', 'rabbit']
aletterlist = [letter for word in awordlist for letter in word]
print(aletterlist)
print("extra challege:")
aletter_set = set(aletterlist)
new_letterlist = [letter for letter in aletter_set]
print(new_letterlist)
print()
print("self_check_3:")
quote = "methinks it is like a weasel" # goal string
qlen = 28 # length of quote
def monkey(qlen):
alphabet = "abcdefghijklmnopqrstuvwxyz "
res = ""
for i in range(qlen):
res = res + alphabet[random.randrange(27)]
return res
print(monkey(qlen))
print("self_check_3 Challenge:")
def luck(quote, guess):
num_same = 0
for i in range(qlen):
if quote == guess[i]:
num_same += 1
return num_same / qlen
def lucky_monkey():
new_guess = monkey(qlen)
best = 0
count = 0
mluck = luck(quote, new_guess)
while mluck < 1 or count < 10:
if mluck > best:
print(mluck, new_guess)
best = mluck
count += 1
new_guess = monkey(qlen)
mluck = luck(quote, new_guess)
print(new_guess)
# lucky_monkey()
print("not working but I realized I didn't need to do this one anyway...") |
ff63557ed48c541a63031a23037f5457093e337a | JakePrasad/memo | /fib.py | 392 | 3.765625 | 4 | init = parser.add_argument('--n', type=int)
args = parser.parse_args()
init = args.n
___
def isBase(curr):
return curr == 0 or curr == 1
___
def fBase(curr):
return curr
___
lambda n: n-1
lambda n: n-2
___
def merge(subproblems): return sum(subproblems)
# Format of this file
# Base values
# ___
# Subproblems - n is the current number
# ___
# Function to merge the subproblems together |
e6136334e00b1f07de6bc554c330ae42539bb333 | jasonwee/asus-rt-n14uhp-mrtg | /src/bin/SingletonPatternNew.py | 744 | 3.515625 | 4 | #!/usr/bin/python3.4
# http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
class OnlyOne(object):
class __OnlyOne:
def __init__(self):
self.val = None
def __str__(self):
return 'self' + self.val
instance = None
def __new__(cls): #__new__ always a classmethod
if not OnlyOne.instance:
OnlyOne.instance = OnlyOne.__OnlyOne()
return OnlyOne.instance
def __getattr__(self, name):
return getattr(self.instance, name)
def __setattr__(self, name):
return setattr(self.instance, name)
x = OnlyOne()
x.val = 'sausage'
print(x)
y = OnlyOne()
y.val = 'eggs'
print(y)
z = OnlyOne()
z.val = 'spam'
print(z)
print(x)
print(y)
|
9be3a944952112dd47d162ed48c7610c141108a6 | Dikshitha0812/class-105 | /std.py | 1,194 | 4.09375 | 4 | import pandas as pd
import statistics
import plotly.express as px
import math
data = pd.read_csv("./class1.csv")
markslist = data["Marks"].tolist()
print(markslist)
#HOW TO STANDARD DEVIATION
# first step you find the mean of the desired column.i.e. markslist
# second step you do subtraction of each marks value from mean , i.e mean - marks
# and you store in a list
#square each element of the subtracted list , i.e. (mean-marks)^2
# perform addition of each (mean-marks)^2
# divide the total sum by the total number of values, i.e. the length of markslist
# perform the square root to get the standard deviation.
mean = statistics.mean(markslist)
print(mean)
sub_list = []
for i in markslist:
value = mean - int(i)
sub_list.append(value)
print(sub_list)
square_list = []
for i in sub_list:
value = i * i
square_list.append(value)
print(square_list)
total = sum(square_list)
print(total)
final = total / len(markslist)
print(final)
std_deviation = math.sqrt(final)
print("the standard deviation for class 1 is ", std_deviation)
print("hence the data is scattered in the range ", mean-std_deviation, mean + std_deviation) |
8eeb9402a5d2bb4d57447a8d47c72868250b2e24 | knuu/competitive-programming | /hackerrank/algorithm/from-paragraphs-to-sentences.py | 408 | 3.8125 | 4 | def is_end(w):
if w == "Dr.":
return False
elif len(w) == 2 and w[0].isupper():
return False
elif w[-1] in '.!?':
return True
else:
return False
S = list(input())
for i, s in enumerate(S):
if i < len(S)-1 and s in '.!?' and S[i+1].isupper():
S[i] = s + ' '
S = ''.join(S).split()
for word in S:
print(word, end='\n' if is_end(word) else ' ')
|
d0d3608ad304a3a68362d3e88e4103cede709d22 | NikDestrave/Python_Algos_Homework | /Lesson_1.9.py | 878 | 4.15625 | 4 | """
Задание 9. Вводятся три разных числа. Найти, какое из них является средним
(больше одного, но меньше другого).
Подсказка: можно добавить проверку, что введены равные числа
"""
NUMBER_A = int(input('Введите первое число: '))
NUMBER_B = int(input('Введите второе число: '))
NUMBER_C = int(input('Введите третье число: '))
if NUMBER_B < NUMBER_A < NUMBER_C or NUMBER_C < NUMBER_A < NUMBER_B:
print(f'Среднее значение из трех: {NUMBER_A}')
elif NUMBER_A < NUMBER_B < NUMBER_C or NUMBER_C < NUMBER_B < NUMBER_A:
print(f'Среднее значение из трех: {NUMBER_B}')
else:
print(f'Среднее значение из трех: {NUMBER_C}') |
73663b5c265c56aae2b64d369262c50d3fee3455 | phoenix9373/Algorithm | /2020/자료구조/그래프의 최소 비용 문제/크루스칼 알고리즘.py | 1,010 | 3.734375 | 4 | tree = {}
rank = {}
def make_set(node):
tree[node] = node
rank[node] = 0
def find_set(node):
if node != tree[node]:
tree[node] = find_set(tree[node])
return tree[node]
def union(u, v):
root1 = find_set(u)
root2 = find_set(v)
if rank[root1] > rank[root2]:
tree[root2] = root1
else:
tree[root1] = root2
if rank[root2] == rank[root1]:
rank[root2] += 1 # root1을 root2에 붙였으므로
def kruskal(graph):
mst = []
mst_cost = 0
for i in range(V + 1):
make_set(i)
graph = sorted(graph, key=lambda x: x[2])
for g in graph:
u, v, w = g
if find_set(u) != find_set(v):
union(u, v)
mst.append(g)
return mst
for tc in range(1, int(input()) + 1):
V, E = map(int, input().split())
lines = sorted([list(map(int, input().split())) for _ in range(E)], key=lambda x: x[2])
res = sum([i[2] for i in kruskal(lines)])
print('#{} {}'.format(tc, res)) |
c9e3ed1b7a6ffa9e32ae7d3d725749da65a8e8d8 | a-gon/problem_solutions | /kth_largest.py | 388 | 3.703125 | 4 | import heapq
def kth_largest(a, k):
heapq.heapify(a)
result = None
for _ in range(k):
result = heapq.heappop(a)
return result
def kth_largest_(a, k):
result = None
sorted_array = sorted(a)
for _ in range(k):
result = sorted_array.pop(0)
return result
print(kth_largest([5,6,31,7,9,25,1,4], 3))
print(kth_largest_([5,6,31,7,9,25,1,4], 3)) |
3975256b18a99bdee7942545034673835916e426 | James-Oswald/IEEE-Professional-Development-Night | /5-3-21/planetTwisted.py | 355 | 3.671875 | 4 | #https://www.codewars.com/kata/58068479c27998b11900056e
def twistedSort(arr):
rv = arr.copy()
rv.sort(key=lambda e:int(str(e).replace("3", "x").replace("7", "3").replace("x", "7")))
return rv
print(twistedSort([1,2,3,4,5,6,7,8,9])) #[1,2,7,4,5,6,3,8,9]
print(twistedSort([12,13,14])) #[12,14,13]
print(twistedSort([9,2,4,7,3])) #[2,7,4,3,9] |
93407eb1c7030730bde7da5e5525a634adc3deeb | nikhildarocha/schaums-outline-prob-stats | /python/1.6/ex1.6_mean_median.py | 1,319 | 3.796875 | 4 | import numpy as np
import statistics
data = np.array([25000, 30000, 40000, 153000])
frequency = np.array([5, 7, 3, 1])
mul = data*frequency
print(mul)
total = sum(frequency)
print(total)
mean = sum(mul)/total
print(mean)
for i in range(len(frequency)-1):
frequency[i+1] = frequency[i] + frequency[i+1]
print(frequency)
n = frequency[len(frequency)-1]
median_value = 0
if n%2 != 0:
print("Odd number")
median_value = (n + 1)/2
print(median_value)
elif n%2 == 0:
print("Even number")
median_value = ((n/2) + (n/2)+1)/2
print("median value is " + str(median_value))
else:
print("The number is neither even nor odd")
sum_match_median = 0
for i in range(len(frequency)-1):
sum_match_median = frequency[i]
if sum_match_median <= median_value:
index_of_frequency_array = list(frequency).index(sum_match_median)
print(sum_match_median)
print(index_of_frequency_array)
calculated_median_index = index_of_frequency_array + 1
print(calculated_median_index)
print("Index of data array " + str(data[index_of_frequency_array]))
print("Calculated median is approximately " + str(data[calculated_median_index]))
print("Median through library is " + str(statistics.median(data)))
print("Median low is " + str(statistics.median_low(data)))
|
8585416810b61b95a7c3fba9f3a64e95297edfe6 | pawelk82/HackerRank | /Python/Numpy/Transpose_and_Flatten.py | 635 | 4.28125 | 4 | #! /usr/bin/python3
'''
Task
You are given a N X M integer array matrix with space
separated elements (N = rows and M = columns).
Your task is to print the transpose and flatten results.
Input Format
The first line contains the space separated values of N and M.
The next N lines contains the space separated elements of M columns.
Output Format
First, print the transpose array and then print the flatten.
Sample Input
2 2
1 2
3 4
Sample Output
[[1 3]
[2 4]]
[1 2 3 4]
'''
import numpy as np
arr = np.array([input().split() for _ in range(int(input().split()[0]))], int)
print (np.transpose(arr))
print (arr.flatten())
|
9b47b359317fd4fa442ff09abbbb052b0e578b88 | structuredcreations/Formal_Learning | /python_basics/C1_w5_if_else_groups.py | 453 | 3.96875 | 4 | ENT_SCORE=input("Enter score between 0 and 1")
ENT_SCORE_F=float(ENT_SCORE)
#print(ENT_SCORE_F)
if ENT_SCORE_F < 0.0 :
print("Number below 0")
elif ENT_SCORE_F > 1.0 :
print("Number above 1")
else:
if ENT_SCORE_F>=.9:
print("A")
elif ENT_SCORE_F>=.8:
print('B')
elif ENT_SCORE_F>=.7:
print("C")
elif ENT_SCORE_F>=.6:
print("D")
else:
print("F")
# Note, functions are case sensitive
|
c4155f3b449bad23249ba42d3d97201ef397240c | lichengchengchloe/leetcodePracticePy | /RemoveDuplicates.py | 594 | 3.609375 | 4 | # -*- coding: UTF-8 -*-
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n==0:
return 0
# 有序数组的重复项肯定是挨在一起的,将不重复的数字赋值到重复项即可
p = 0
q = 1
while q<n:
if nums[p]!=nums[q]:
p += 1
# 如果 p==q 也不需要赋值
nums[p]=nums[q]
q += 1
return len(nums[0:p+1])
nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(nums))
|
4fef1486743e0ce9db27202f458f974f7045c296 | himanshu-singh14/FSDP2019 | /Day 11, 20-May-2019/Program/space_numpy.py | 539 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:21:16 2019
@author: HIMANSHU SINGH
"""
"""
Code Challenge
Name:
Space Seperated data
Filename:
space_numpy.py
Problem Statement:
You are given a 9 space separated numbers.
Write a python code to convert it into a 3x3 NumPy array of integers.
Input:
6 9 2 3 5 8 1 5 4
Output:
[[6 9 2]
[3 5 8]
[1 5 4]]
"""
import numpy as np
ls = list(map(int,input("Enter 9 sapce seperated numbers : ").split(" ")))
arr = np.array(ls)
arr.reshape(3,3)
|
9ea9e90fb5bea2d8ad9a8b97f054ae6a27a553af | sahiljohari/basic_programming | /Linked list/reverseList.py | 1,236 | 4.21875 | 4 | # Reverse a linked list in-place
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# recursive
def reverse(head, prev = None):
'''
Time complexity: O(n)
Space complexity: O(n)
'''
if head is None:
return prev
next = head.next
head.next = prev
return reverse(next, head)
# iterative
def reverseList(head):
'''
Time complexity: O(n)
Space complexity: O(1)
'''
prev, current = None, head
while current:
next = current.next
current.next = prev
prev = current
current = next
return prev
def createLinkedList(list):
if not list:
return None
head = current = ListNode(list[0])
for i in range(1, len(list)):
current.next = ListNode(list[i])
current = current.next
return head
def printLinkedList(head):
if not head:
return None
while head:
print(head.val)
head = head.next
def main():
input_list = createLinkedList([1, 4, 5, 3, 6])
printLinkedList(reverse(input_list)) # [6, 3, 5, 4, 1]
printLinkedList(reverseList(input_list)) # [6, 3, 5, 4, 1]
if __name__ == "__main__":
main() |
fff286d05416333d104ced110748c9a13903f882 | Lay4U/RTOS_StepByStep | /Python for Secret Agents/0420OS_Code/Others/bonus_ex_1.py | 932 | 3.65625 | 4 | """Chapter 2, Example 2
HTTP GET with FORM
"""
import http.client
import urllib.parse
import contextlib
import pprint
host = "finance.yahoo.com"
form = {
's': 'YHOO',
'ql': '1',
}
query = urllib.parse.urlencode( form )
print( query )
with contextlib.closing( http.client.HTTPConnection( host ) ) as connection:
url = "{path}?{query}".format(path="/q", query=query)
connection.request( "GET", url )
response= connection.getresponse()
print( "Status:", response.status )
pprint.pprint( response.getheaders() )
page= response.read()
#print( page )
# Looking for <span class="time_rtq_ticker" id="yui_3_9_1_8_1400427694114_39">
# <span id="yfs_l84_yhoo">33.41</span></span>
from bs4 import BeautifulSoup
soup = BeautifulSoup(page)
print( "Reading", soup.html.head.title.text )
for tag in soup.find_all("span", class_="time_rtq_ticker"):
print( tag )
print( tag.span )
print( tag.text )
|
fb47a23ad30dfd0ef95a58c450969c5796386e1e | sfdye/leetcode | /wiggle-sort-ii.py | 285 | 3.625 | 4 | class Solution:
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i, num in enumerate(sorted(nums)[::-1]):
nums[(i * 2 + 1) % (len(nums) | 1)] = num
|
f8080d17d2a140bc79dd41b01e81f6304b768b56 | mominaadar/DataStructure-implementations | /a04.py | 4,426 | 3.6875 | 4 | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class Ring:
def __init__(self):
self.head = None
def __str__(self):
ret = '['
temp = self.head
while temp:
ret += str(temp.val) + ', '
temp = temp.next
if temp == self.head:
break
ret = ret.rstrip(', ')
ret += ']'
return ret
def _get_last(self):
if self.head is None:
return
temp = self.head.next
while temp.next != self.head:
temp = temp.next
return temp
def insert(self, index, val):
new_node = Node(val)
last = self._get_last()
if self.head is None:
self.head = new_node
new_node.next = self.head
return
if index == 0:
new_node.next = self.head
self.head = new_node
last.next = self.head
return
temp = self.head
counter = 0
while counter < index:
prev = temp
temp = temp.next
counter += 1
if new_node.next == self.head:
self.head = new_node
else:
new_node.next = temp
prev.next = new_node
def remove(self,val):
if self.head is None:
return
last = self._get_last()
temp = self.head
if temp.val == val:
if last == self.head:
self.head = None
else:
temp = temp.next
self.head = temp
last.next = self.head
return
prev = temp
temp = temp.next
while temp != self.head:
if temp.val == val:
break
prev = temp
temp = temp.next
if temp == self.head:
return
prev.next = temp.next
def remove_at(self, index):
if self.head is None:
return
last = self._get_last()
temp = self.head
if index == 0:
if last == self.head:
self.head = None
else:
temp = temp.next
self.head = temp
last.next = self.head
return
temp = self.head
count = 0
while count < index:
prev = temp
temp = temp.next
count += 1
if temp == self.head:
prev.next = temp.next
self.head = temp.next
prev.next = temp.next
def len(self):
last = self._get_last()
if self.head is None:
return 0
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
if temp == self.head:
break
return count
def get(self, index):
if self.head is None:
raise IndexError('List is empty')
if index == 0:
return self.head.val
temp = self.head
count = 0
while count < index:
temp = temp.next
count += 1
return temp.val
def push(self,val):
if self.head is None:
self.insert(0,val)
return
else:
length = self.len()
count = 0
temp = self.head
while count < length:
temp = temp.next
count += 1
self.insert(count,val)
def pop(self):
if self.head is None:
return
else:
length = self.len()
temp = self.head
count = 0
while count < length:
temp = temp.next
count += 1
print(self.get(length-1))
self.remove_at(count-1)
if __name__ == '__main__':
r = Ring()
r.insert(1, 1)
r.insert(0, 1)
r.insert(0, 2)
r.insert(1, 3)
r.insert(7, 5) # different behavrior since it's a ring!
print(r)
|
5f953697d2f9562ee9cc1eb9ff0b24d5a45aba31 | LipsaJ/PythonPrograms | /_InterviewPrep/dataframe05.py | 717 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 9 20:08:36 2021
@author: stlp
"""
## Replace values in Pandas dataframe using regex
import pandas as pd
df = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
'Cost':[10000, 5000, 15000, 2000, 12000]})
# create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
df.index = index_
print(df)
#update the words with regex
df_updated = df.replace(to_replace='[nN]ew ', value='New_', regex = True)
print(df_updated) |
077a9ed68f8b663b12481c5e5f49814c7fb94810 | yaroslav-tsarenko/simplepythonproject | /f_01.py | 248 | 4 | 4 | a=int(input("Введыть першу сторону:"))
b=int(input("Введыть другу сторону:"))
c=int(input("Введыть третю сторону:"))
p=(a+b+c)/2
s=(p*(p-a)*(p-b)*(p-c)**0.5)
print("S:",s)
print("P:",a+b+c)
|
c3eb5f25351f90a0c498b5c60574bb5e65b8f152 | Zac-Taylor/Python-2016 | /HW3_PartA.py | 419 | 4.125 | 4 | smallest= 0x
count = 0
smallest = int(input("Enter an integer or empty string to end: "))
count = 1
inputStr=input("Enter an integer or empty string to end: ")
while inputStr != "":
value = int(inputStr)
if value < smallest:
smallest = value
count = count + 1
inputStr=input("Enter an integer or empty string to end: ")
print("the smallest is: ",smallest)
print("the count is: ",count)
|
e55e0702afd61a06fa31bd0476998686d0d62fbe | hasadna/okscraper | /okscraper/storages.py | 3,113 | 4.09375 | 4 |
class BaseStorage(object):
"""
Abstract class, implementing classes must define the following methods:
* store - store data
* commit - (optional, commit the data)
* get - (optioanl, return stored data or pointer to stored data)
"""
def store(self):
raise Exception('store must be implemented by extending classes')
def commit(self):
pass
def get(self):
return None
class DataBasedStorage(BaseStorage):
"""Base storage for the DictStorage and ListStorage - should not be used directly"""
# commitInterval of -1 puts the object into single-commit mode
# in this mode there can be only one! (commit)
_commitInterval = 20
def __init__(self):
self._storeCounter = 0
self._data = self._getEmptyData()
self._tmpData = self._getEmptyData()
self._isCommitted = False
def _getEmptyData(self):
raise Exception('_getEmptyData needs to be implemented by extending classes')
def _addValueToData(self, data, *args, **kwargs):
raise Exception('_addValueToData needs to be implemented by extending classes')
def _addDataToData(self, targetData, sourceData):
raise Exception('_addDataToData needs to be implemented by extending classes')
def store(self, *args, **kwargs):
self._addValueToData(self._tmpData, *args, **kwargs)
self._storeCounter = self._storeCounter + 1
if self._commitInterval > -1 and self._storeCounter > self._commitInterval:
self.commit()
def commit(self):
if self._isCommitted and self._commitInterval == -1:
raise Exception('if commitInterval is -1 then only one commit is allowed')
else:
self._isCommitted = True
self._addDataToData(self._data, self._tmpData)
self._storeCounter = 0
self._tmpData = self._getEmptyData()
def get(self):
if self._commitInterval > -1 or not self._isCommitted:
self.commit()
return self._data
class DictStorage(DataBasedStorage):
"""Storage to store dict data"""
def _getEmptyData(self):
return {}
def _addValueToData(self, data, key, value):
data[key] = value
def _addDataToData(self, targetData, sourceData):
targetData.update(sourceData)
def getBaseStorage(self):
return DictStorage
def assertEquals(self, testCase, expected_data):
testCase.assertDictEqual(self._data, expected_data)
def storeDict(self, data):
for key in data:
self.store(key, data[key])
class ListStorage(DataBasedStorage):
"""Storage to store list data"""
def _getEmptyData(self):
return []
def _addValueToData(self, data, value):
data.append(value)
def _addDataToData(self, targetData, sourceData):
for item in sourceData:
targetData.append(item)
def getBaseStorage(self):
return ListStorage
def assertEquals(self, testCase, expected_data):
testCase.assertListEqual(self._data, expected_data) |
b137461fcd332235f41c68c9c830b274418e8581 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4147/codes/1593_1802.py | 174 | 3.828125 | 4 | from math import*
v = float(input("Pontos de vida: "))
vd1 = int(input("Dado 1: "))
vd2 = int(input("Dado 2: "))
d = int(sqrt(5 * vd1) + (pi ** (vd2 / 3)))
print(int(v - d)) |
14731d266fc8e5168e1715a51b23743cf341e91e | Trapman/trading | /money flow multiplier/money_flow_multiplier.py | 1,590 | 3.734375 | 4 | """
Creating & Back-testing the Strategy
Now, we can proceed to back-test the Money Flow Multiplier strategy on some currency pairs within the hourly time frame. The trading conditions are therefore:
Go long (Buy) whenever the Money Flow Multiplier touches the lower barrier at -90.00 with the previous two values above -90.00.
Go short (Sell) whenever the Money Flow Multiplier touches the upper barrier at 90.00 with the previous two values below 90.00.
https://medium.com/swlh/creating-a-trading-strategy-from-scratch-in-python-fe047cb8f12
"""
def money_flow_multiplier(Data, what, high, low, where):
# Numerator
Data[:, where] = Data[:, what] - Data[:, low]
Data[:, where + 1] = Data[:, high] - Data[:, what]
# Denominator
Data[:, where + 2] = Data[:, where] - Data[:, where + 1]
Data[:, where + 3] = Data[:, high] - Data[:, low]
# Avoiding NaN values (Division by zero in case the High equals the Low)
for i in range(len(Data)):
if Data[i, where + 3] == 0:
Data[i, where + 3] = 0.0001
# Money Flow Multiplier Formula
Data[:, where + 4] = (Data[:, where + 2] / Data[:, where + 3]) * 100
return Data
def signal(Data, what, buy, sell):
for i in range(len(Data)):
if Data[i, what] < lower_barrier and Data[i - 1, what] > lower_barrier and Data[i - 2, what] > lower_barrier :
Data[i, buy] = 1
if Data[i, what] > upper_barrier and Data[i - 1, what] < upper_barrier and Data[i - 2, what] < upper_barrier :
Data[i, sell] = -1
|
bdd39a4cadcfa63d78f734a1413f9f6a602e1ee0 | zhouyswo/zzjz_py | /com/zzjz/senior/iteratorAndCoroutine.py | 4,896 | 3.875 | 4 | # 迭代器
# 可迭代(iterable):直接作用于for循环的变量
# 迭代器(iterator):不仅可以用于for循环,还可以被next调用
# list 是典型的可迭代对象,但不是迭代器
# 可迭代的对象不一定是迭代器,迭代器一定是可迭代对象
# 可通过isinstance判断
from collections import Iterable
from collections import Iterator
l = [1, 2, 3, 4]
# print(isinstance(l,Iterable))
# print(isinstance(l,Iterator))
# 可迭代对象转换为迭代器
# it = iter(l)
# print(isinstance(it, Iterable))
# print(isinstance(it, Iterator))
# 生成器
# generator:一边循环,一边计算下一个元素的机制或算法
# 需要满足3个条件:
# -每次调用都产生出for循环需要的下一个元素
# -如果达到最后一个后,爆出stopIteration异常
# -可以被next函数调用
# 列表生成器
l = [x * x for x in range(6)]
# 放在小括号中就是生成器
g = (x * x for x in range(6))
# 定义生成器
# 如果包含yield,则这个函数就叫做生成器
# next调用函数,遇到yield返回
# def ff():
# print(1)
# yield 1
# print(2)
# yield 2
#
#
# g = ff()
# n = next(g)
# print(n)
# n2 = next(g)
# print(n2)
# 协程
# 3.4引入协程,用yield实现
# 实现协程比较好的包有asyncio,tornado,gevent
# 协程:是为抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序
# 从技术角度讲,协程就是一个可以暂停执行的函数
# 协程的实现:yield返回、send调用
# def simple_coroutine():
# print("->start")
# x = yield
# print("->recived", x)
#
#
# # 主线程
# sc = simple_coroutine()
# print("aaaa")
# # 预激 可以使用sc.send(None),效果一样
# next(sc)
# print("bbbb")
# sc.send("cccc")
# 协程的4个状态
# inspect.getgeneratorstate(...)函数确定,该函数会返回下述字符串中的一个
# GEN_CREATED:等待开始执行
# GEN_RUNNING:解释器正在执行
# GEN_SUSPENED:在yield表达式处暂停
# GEN_CLOSED:执行结束
# next预激活
# def simple_coroutine(a):
# print("->start")
# b = yield a
# print("->recived", a, b)
# c = yield a + b
# print("->recived", a, b, c)
#
#
# # 主线程
# sc = simple_coroutine(3)
# aa = next(sc)
# print(aa)
# bb = sc.send(4)
# print(bb)
# cc = sc.send(5)
# print(cc)
# 协程中未处理的异常会向上冒泡,传给next函数或send方法的调用方(即触发协程对象)
# 停止协程的一种方式:发送某个哨符值,让协程退出,内置的None和Ellipsis等常亮经常用作哨符值
# yield from
# 调用协程为了得到返回值,协程必须正常终止
# 生成器正常终止会发出StopIteration异常,异常对象的vlaue属性保存返回值
# yield from从内部捕获StopIteration异常
# 委派生成器
# -包含yield from表达式生成器函数
# -委派生成器在yield from表达式处暂停,调用方可以直接把数据发给生成器
# -子生成器把产出的值发给调用方
# -子生成器在最后,解释器会抛出StopIteration异常,并且把返回值附加到异常对象上
# def gen():
# for c in "ab":
# yield c
#
#
# def gen_new():
# yield from "cd"
#
#
# print(list(gen()))
# print(list(gen_new()))
# asyncio
# 使用方式如下
import asyncio
# 使用协程
# @asyncio.coroutine
# def aaa():
# print("sds")
# yield from asyncio.sleep(10)
# print("ius")
#
#
# # 启动消息循环
# loop = asyncio.get_event_loop()
# # 定义任务
# tasks = [aaa(), aaa()]
# # asyncio使用wait等待task执行完毕
# loop.run_until_complete(asyncio.wait(tasks))
# # 关闭消息循环
# loop.close()
# aiohttp
# asyncio实现单线程的并发,在客户端用处不大
# 在服务器端可以asyncio+coroutine配合,因为http是io操作
# asyncio实现了tcp,udp,ssl等协议
# aiohttp是给予asyncio实现的http框架
from aiohttp import web
#
#
# async def index(request):
# await asyncio.sleep(0.5)
# return web.Response(body=b'<h1>Index</h1>')
#
#
# async def hello(request):
# await asyncio.sleep(0.5)
# text = '<h1>hello,%s!</h1>'
# concurrent.futures
# 类似其他语言的线程池,利用multiprocessiong实现真正的并行计算
# 核心原理:以子进程的形式,并行运行多个python解释器,从而令python程序可以利用多核CPU来提升速度,
# 由于子进程与主解释器相分离,所以他们的全局解释器锁也是相互独立的,每个子进程都能完整的使用一个CPU内核。
# concurrent.futures.Executor
# -ThreadPoolExecutor
# -ProcessPoolExecutor
# 执行的时候需要自动选择
# submit(fn,args,kwargs)
# fn:异步执行的函数
# args,kwargs参数
# current中的map函数
# map(fn,iterables,timeout=NONE)
# fn:可执行函数,异步执行
# timeout:超时时间
|
5f9ccbd0b6d5df8ca78f0ce689ef73f71c08f8e2 | PdxCodeGuild/20170724-FullStack-Night | /Code/sam/python/Lab12_practice4.py | 376 | 4.125 | 4 | x = 2 # setting x equal to 2
i = 0 # setting i equal to 0
for i in range(21): # creating a for loop in range of 21
exponent = x ** i # creating a variable and setting it to x ** i
print(exponent)
i += 1 # adding 1 to i for each iteration of the loop |
44ea12790778062af23981786ec8361e4590393b | luisavitoria/introducao-curso-basico-python | /code/COH-PIAH.py | 4,833 | 4 | 4 | import re
def main():
ass_cp = le_assinatura()
textos = le_textos()
infectado = avalia_textos(textos, ass_cp)
print("O autor do texto",infectado,"está infectado com COH-PIAH")
def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos'''
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno infectado:\n")
wal = float(input("Entre o tamanho médio de palavra:"))
ttr = float(input("Entre a relação Type-Token:"))
hlr = float(input("Entre a Razão Hapax Legomana:"))
sal = float(input("Entre o tamanho médio de sentença:"))
sac = float(input("Entre a complexidade média da sentença:"))
pal = float(input("Entre o tamanho medio de frase:"))
print()
return [wal, ttr, hlr, sal, sac, pal]
def le_textos():
'''A funcao le todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento'''
i = 1
textos = []
texto = input("Digite o texto " + str(i) +" (aperte enter para sair):")
print()
while texto:
textos.append(texto)
i += 1
texto = input("Digite o texto " + str(i) +" (aperte enter para sair):")
print()
return textos
def separa_sentencas(texto):
'''A funcao recebe um texto e devolve uma lista das sentencas dentro do texto'''
sentencas = re.split(r'[.!?]+', texto)
if sentencas[-1] == '':
del sentencas[-1]
return sentencas
def separa_frases(sentenca):
'''A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca'''
return re.split(r'[,:;]+', sentenca)
def separa_palavras(frase):
'''A funcao recebe uma frase e devolve uma lista das palavras dentro da frase'''
return frase.split()
def n_palavras_unicas(lista_palavras):
'''Essa funcao recebe uma lista de palavras e devolve o numero de palavras que aparecem uma unica vez'''
freq = dict()
unicas = 0
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
if freq[p] == 1:
unicas -= 1
freq[p] += 1
else:
freq[p] = 1
unicas += 1
return unicas
def n_palavras_diferentes(lista_palavras):
'''Essa funcao recebe uma lista de palavras e devolve o numero de palavras diferentes utilizadas'''
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
freq[p] = 1
return len(freq)
def compara_assinatura(as_a, as_b):
'''IMPLEMENTAR. Essa funcao recebe duas assinaturas de texto e deve devolver o grau de similaridade nas assinaturas.'''
i = 0
diferenca = 0
while i <= 5:
diferenca = diferenca + abs(as_a[i] - as_b[i])
i = i + 1
similaridade = diferenca / 6
return similaridade
def calcula_assinatura(texto):
'''IMPLEMENTAR. Essa funcao recebe um texto e deve devolver a assinatura do texto.'''
lista_palavras = []
lista_frases = []
lista_sent = separa_sentencas(texto)
soma_caracteres_palavras = 0
soma_caracteres_sentencas = 0
soma_caracteres_frases = 0
for sent in lista_sent:
novas_frases = separa_frases(sent)
soma_caracteres_sentencas = soma_caracteres_sentencas + len(sent)
lista_frases.extend(novas_frases)
for fr in lista_frases:
novas_palavras = separa_palavras(fr)
soma_caracteres_frases = soma_caracteres_frases + len(fr)
lista_palavras.extend(novas_palavras)
for palavra in lista_palavras:
soma_caracteres_palavras = soma_caracteres_palavras + len(palavra)
wal_texto = soma_caracteres_palavras / len(lista_palavras)
ttr_texto = n_palavras_diferentes(lista_palavras) / len(lista_palavras)
hlr_texto = n_palavras_unicas(lista_palavras) / len(lista_palavras)
sal_texto = soma_caracteres_sentencas / len(lista_sent)
sac_texto = len(lista_frases) / len(lista_sent)
pal_texto = soma_caracteres_frases / len(lista_frases)
assinatura = [wal_texto, ttr_texto, hlr_texto, sal_texto, sac_texto, pal_texto]
return assinatura
def avalia_textos(textos, ass_cp):
'''IMPLEMENTAR. Essa funcao recebe uma lista de textos e uma assinatura ass_cp e deve devolver o numero (1 a n) do texto com maior probabilidade de ter sido infectado por COH-PIAH.'''
lista_comparacao = []
for cada_texto in textos:
as_texto = calcula_assinatura(cada_texto)
comparar = compara_assinatura(as_texto, ass_cp)
lista_comparacao.append(comparar)
minimo = min(lista_comparacao)
texto_infectado = lista_comparacao.index(minimo) + 1
return texto_infectado
main()
|
ea885394228ef3465935c3020ef4f732bc5e1a5a | Kanefav/exercicios | /ex079.py | 232 | 3.84375 | 4 | lista = []
tlist = 0
while True:
num = lista.append(int(input('Digite um valor: ')))
cont = str(input('Quer continuar? [S/N] ')).upper()
if cont == 'N':
break
else:
continue
lista.sort()
print(lista)
|
0032616a6e196f84fdec6ff9267dee28006af2d1 | wsyhGL/Python | /python/fun_print.py | 169 | 3.71875 | 4 | def fun_add(a,b):
result = a+b
print("%d+%d=%d"%(a,b,result))
num = int(input("请输入数字1:"))
num1 = int(input("请输入数字2:"))
fun_add(num,num1)
|
12527b261943cc4df52b8c59398ccf26e3c58fea | Aludeku/Python-course-backup | /lista exercícios/PythonTeste/desafio090.py | 479 | 3.84375 | 4 | aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = float(input(f'Média de {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['status'] = 'aprovado'
elif 5 <= aluno['media'] <= 7:
aluno['status'] = 'recuperação'
else:
aluno['status'] = 'reprovado'
print('-=' * 20)
print(f' -O nome é igual a {aluno["nome"]}.')
print(f' -A média é igual à {aluno["media"]}.')
print(f' -A situação de {aluno["nome"]} é de {aluno["status"]}.')
print(' -end.') |
e851e472a115704f46016f6f77db2bff6dd03e24 | ArthurLCastro/Python | /Adição de dados em MySQL com Python/add_linha_em_tabela_MySQL.py | 636 | 3.53125 | 4 | # Adicionar linha em Tabela MySQL com Python
# Arthur Castro
# 09 de abril de 2018
import mysql.connector
print("---------- Cadastro de Clientes ----------")
nome = raw_input("Nome: ")
email = raw_input("e-mail: ")
fone = raw_input("Telefone: ")
print("------------------------------------------")
conn = mysql.connector.connect(
user='root',
password='root',
host='localhost',
database='Cadastro')
cur = conn.cursor()
query = ("INSERT INTO CLIENTES (NOME, EMAIL, FONE) VALUES ('" + nome + "','" + email + "','" + fone + "')")
cur.execute(query)
conn.commit()
print("Novo cliente adicionado!")
cur.close()
conn.close()
|
85644eb8d750180453643b52aed7136bd3c4685f | SSalaPla/dynamical-systems-with-applications-using-python | /Anaconda-files/Program_3c.py | 296 | 3.6875 | 4 | # Program 3c: Finding critical points.
# See Example 9.
import sympy as sm
x, y = sm.symbols('x, y')
P = x*(1-x/2-y)
Q = y*(x-1-y/2)
# Set P(x,y)=0 and Q(x,y)=0.
Peqn = sm.Eq(P, 0)
Qeqn = sm.Eq(Q, 0)
# Locate critical points.
criticalpoints = sm.solve((Peqn, Qeqn), x, y)
print(criticalpoints) |
48b28a588d7e6b0572613e1245ad59e458cdd8c1 | Satyajit99p/sample-differentiation-and-integration-using-Sympy-python-module | /derivative_trial_1.py | 1,285 | 3.96875 | 4 | from sympy import*
x = Symbol('x')
def linear_function():
print('welcome to linear function differentiation')
a=int (input('enter coefficient of degree 2:'))
b=int(input('enter constatnt:'))
return(diff(a*x+b))
def quadractic_function():
print('welcome to quadractic function differentiation')
a = int(input('enter coefficient of degree 2:'))
b = int(input('enter coefficient of degree 1:'))
c = int(input('enter constant:'))
return(diff(a * x ** 2 + b * x + c))
def cubic_function():
print('welcome to cubic equation differentiation')
a=int(input('enter the coefficient of degree 3:'))
b=int(input('enter the coefficient of degree 2:'))
c=int(input('enter the coefficient of degree 1:'))
d=int(input('enter the constant:'))
return(diff(a*x**3+b*x**2+c*x+d))
def quartic_function():
print('welcome to cubic equation differentiation')
a = int(input('enter the coefficient of degree 4:'))
b = int(input('enter the coefficient of degree 3:'))
c = int(input('enter the coefficient of degree 2:'))
d = int(input('enter the coefficient of degree 1:'))
e = int(input('enter the constant:'))
return(diff(a*x**4+b*x**3+c*x**2+d*x+e))
|
e31817d62b776436a16c50fd681c4d2b8624d515 | Aasthaengg/IBMdataset | /Python_codes/p02419/s041976628.py | 177 | 3.78125 | 4 | w = input().lower()
text = ''
while True:
t = input()
if t == 'END_OF_TEXT':
break
text += t.lower() + ' '
print(len([t for t in text.split(' ') if t == w])) |
7efb91bdcc88df5085f86b2326a94a21d8c991d6 | xuefeihexue/IPND_project4 | /media.py | 1,193 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import webbrowser
# Crete a Movie class
class Movie:
def __init__(
self,
movie_title,
movie_storyline,
poster_image,
trailer_youtube,
):
''' When a initial function is called, it will create a new space for the movie object.
The arugments are assigned to the corresponding instance variables:
Args:
movie_title(str): hold the title of movie
movie_storyline(str): hold the plot of movie
poster_image:(str): hold the url link to poster of movie
trailer_youtube(str): hold the url link to the youtube of movie
Returns:
returns an object of movie with four attributs as the same as input arguments.
'''
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def showtrailer(self):
# This fuchtion shows the trailer of the movie instance
webbrowser.open(self.trailer_url)
# use the webbrowser.open function to open the browser with the link as input
|
f457cd3c7346dfed8ad422b3b12f1732ea90fd0d | ghj3/lpie | /untitled38.py | 301 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 22:55:21 2018
@author: k3sekido
"""
class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)
clock = Clock('5:30')
clock.print_time() |
54e0970ec836655490bf75aa1e01dd03f5ea76e4 | franghie/pytutorial | /ref_value_demo.py | 595 | 3.703125 | 4 | # All variable is a reference. In order to write a value, need to dereference. Scalar -> Need to use key or index
llist = [['a', 'b'], ['c'], ['d', 'e']]
for loc in llist:
loc = ['a','b','c']
print(llist)
llist = [['a', 'b'], ['c'], ['d', 'e']]
for loc in llist:
loc[0] = '1'
print(llist)
m = {'a':'1',
'c':'2'}
lst = ['a', 'b', 'c']
for l in lst:
l = '1'
print(lst)
lst = ['a', 'b', 'c']
for i in range(len(lst)):
lst[i] = '1'
print(lst)
dvalue = {
"key1": "value1",
"key2": 2
}
print(dvalue["key1"])
print(dvalue["key2"])
|
f13c5da112a519aa9afce470116623aca88dc30c | alex2rive3/practicaPython | /suma numeros inpares.py | 293 | 3.8125 | 4 | numero = 20
acumulador =0
if numero%2==0:
numero = numero-1
for x in range(numero,0,-2):
print(x)
acumulador += x
else:
for x in range (numero,0,-2):
print(x)
acumulador += x
print("La suma de los n primeros numeros impares es ", acumulador)
input() |
49dd52170155b4285192ee7b3cab9c88d5947854 | mpirnat/aoc2016 | /day21/day21.py | 4,906 | 3.953125 | 4 | #!/usr/bin/env python
"""
Solve day 21 of Advent of Code.
http://adventofcode.com/2016/day/21
"""
from collections import deque
from itertools import permutations
grammar = {
('swap', 'position'): lambda x: (swap_position, [int(x[2]), int(x[5])]),
('swap', 'letter'): lambda x: (swap_char, [x[2], x[5]]),
('reverse', 'positions'): lambda x: (reverse, [int(x[2]), int(x[4])]),
('rotate', 'left'): lambda x: (rotate, [-int(x[2])]),
('rotate', 'right'): lambda x: (rotate, [int(x[2])]),
('move', 'position'): lambda x: (move, [int(x[2]), int(x[5])]),
('rotate', 'based'): lambda x: (rotate_position, [x[6]]),
}
def parse(instr):
instr = instr.split()
fn, args = grammar[(instr[0], instr[1])](instr)
return fn, args
def swap_position(string, pos1, pos2):
"""
swap position X with position Y means that the letters at indexes X and Y
(counting from 0) should be swapped.
"""
new_string = list(string)
new_string[pos1] = string[pos2]
new_string[pos2] = string[pos1]
return ''.join(new_string)
def swap_char(string, char1, char2):
"""
swap letter X with letter Y means that the letters X and Y should be swapped
(regardless of where they appear in the string).
"""
pos1 = string.find(char1)
pos2 = string.find(char2)
return swap_position(string, pos1, pos2)
def reverse(string, pos1, pos2):
"""
reverse positions X through Y means that the span of letters at indexes X
through Y (including the letters at X and Y) should be reversed in order.
"""
a = list(string)
b = a[pos1:pos2+1]
b.reverse()
return ''.join(a[:pos1] + b + a[pos2+1:])
def rotate(string, steps):
"""
rotate left/right X steps means that the whole string should be rotated; for
example, one right rotation would turn abcd into dabc.
"""
new_string = deque(string)
new_string.rotate(steps)
return ''.join(new_string)
def rotate_position(string, char):
"""
Rotate based on position of letter X means that the whole string should be
rotated to the right based on the index of letter X (counting from 0) as
determined before this instruction does any rotations. Once the index is
determined, rotate the string to the right one time, plus a number of times
equal to that index, plus one additional time if the index was at least 4.
"""
new_string = deque(string)
pos = string.find(char)
steps = 1 + pos if pos < 4 else 2 + pos
new_string.rotate(steps)
return ''.join(new_string)
def rotate_position_inverse(string, char):
"""
Invert the 'rotate based on position of letter X' operation by rotating
left and seeing if a forward rotate_position gets back to where we started.
"""
for i in range(len(string)):
test_string = rotate(string, -i)
if rotate_position(test_string, char) == string:
return test_string
def move(string, pos1, pos2):
"""
move position X to position Y means that the letter which is at index X
should be removed from the string, then inserted such that it ends up at
index Y.
"""
new_string = list(string)
new_string.insert(pos2, new_string.pop(pos1))
return ''.join(new_string)
def invert_instruction(f, args):
"""
Transform a parsed instruction into its inverse
"""
if f in (swap_position, swap_char, move):
args.reverse()
elif f == rotate:
args[0] = -args[0]
elif f == rotate_position:
f = rotate_position_inverse
return f, args
def scramble(instructions, string):
"""
Part 1: apply the scrambling instructions verbatim
"""
for instr in instructions:
f, args = parse(instr)
string = f(string, *args)
return string
def unscramble_brutally(instructions, string):
"""
Part 2: Brute force the unscrambled string by applying the
instructions to every permutation of our possible characters.
"""
for test_string in permutations('abcdefgh'):
if scramble(instructions, test_string) == string:
return ''.join(test_string)
def unscramble_elegantly(instructions, string):
"""
Part 2: Unscramble the string by inverting the instructions
and applying them in reverse order to find the starting string.
"""
parsed = [invert_instruction(*parse(x)) for x in instructions]
parsed.reverse()
for f, args in parsed:
string = f(string, *args)
return string
if __name__ == '__main__':
with open('input.txt') as f:
instructions = f.read().splitlines()
string = 'abcdefgh'
print("Part 1:", scramble(instructions, string))
string = 'fbgdceah'
print("Part 2:", unscramble_elegantly(instructions, string))
# Don't need to do this any more
#print("Part 2:", unscramble_brutally(instructions, string))
|
54c4224ebdfb29022fb115c25d74c82a91ede283 | DotPeriodCom/100-Days-of-Python | /Day 2 - Understanding Data Types/Day 2 - Code Lessons/day-2-end.py | 476 | 4.03125 | 4 | a = float(123)
print(type(a))
# print(70 + float("100.5"))
print(str(70) + str(100))
# a = str(123)
# print(type(a))
# num_char = len(input("What is your name?"))
# new_num_char = str(num_char)
# print("Your name has " + new_num_char + " characters.")
# print("Your name has " + num_char + " characters.")
# print(type(num_char))
# len("Hello")
# len(4837)
# Notes
# TypeError: object of type 'int' has no len()
# TypeError: can only concatenate str (not "int") to str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.