blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
8610e7891577aa5089617fc6e499d40a9f234d3d
|
Csson/py-bth-adventure
|
/tictactoe.py
| 3,002 | 4.21875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Handles the tic-tac-toe games"""
from adventurehelpers import clear, say
import random
def show_tictactoe(toe):
"""Determine current state of tic-tac-toe game"""
return """
-------------
| {} | {} | {} |
-------------
| {} | {} | {} |
-------------
| {} | {} | {} |
-------------
""".format(toe['1'], toe['2'], toe['3'], toe['4'], toe['5'], toe['6'], toe['7'], toe['8'], toe['9'])
def play_tictactoe():
"""Play a game of tic-tac-toe!"""
clear()
toe = {'1' : '1', '2' : '2', '3' : '3', '4' : '4', '5' : '5', '6' : '6', '7' : '7', '8' : '8', '9' : '9'}
say("""Not again, you think. "Okay", you say as you sit down to yet another match.""")
say("The game looks like this:")
say(show_tictactoe(toe))
say("""""I am O, you are X.", says Guybrush." """)
move_count = 0
while True:
move = input("""\n"Make your move!" """)
try:
intmove = int(move)
except ValueError:
say("""Don't you know the rules?", Guybrush says.""")
continue
if intmove < 1 or intmove > 9:
say(""""We don't have all day, dude", Guybrush says a bit angry.""")
continue
move = str(intmove)
if toe[move] != move:
say(""""That's already taken, try again my friend", Guybrush says confidently.""")
continue
toe[move] = 'X'
say(show_tictactoe(toe))
move_count += 1
if analyze_tictactoe(toe, 'X'):
say(""""You win! By the way, I think you should place something heavy on this table..." """)
break
if move_count == 9:
say(""""It's a draw. That's boring. Can't we play again, please? Pretty please? With sugar on top?" """)
break
say(""""My move" """)
guybrush_hasnt_moved = 1
while guybrush_hasnt_moved:
gmove = str(random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9]))
if toe[gmove] == gmove:
toe[gmove] = 'O'
move_count += 1
guybrush_hasnt_moved = 0
say(show_tictactoe(toe))
if analyze_tictactoe(toe, 'O'):
say(""""I win, I win, I win! I knew I could beat you!", Guybrush rejoices victoriously.""")
break
def analyze_tictactoe(toe, player):
"""Has player won?"""
has_won = 0
if player == toe['1'] == toe['2'] == toe['3']:
has_won = 1
if player == toe['4'] == toe['5'] == toe['6']:
has_won = 1
if player == toe['7'] == toe['8'] == toe['9']:
has_won = 1
if player == toe['1'] == toe['4'] == toe['7']:
has_won = 1
if player == toe['2'] == toe['5'] == toe['8']:
has_won = 1
if player == toe['3'] == toe['6'] == toe['9']:
has_won = 1
if player == toe['1'] == toe['5'] == toe['9']:
has_won = 1
if player == toe['3'] == toe['5'] == toe['7']:
has_won = 1
return has_won
|
dc3ccdec12d49e2f1707d25d7995574890f2a4a0
|
Leahxuliu/Data-Structure-And-Algorithm
|
/Python/LeetCode2.0/Linkedlist/2.Add Two Numbers.py
| 1,160 | 3.859375 | 4 |
'''
Method:
Linkedlist --> int --> Linkedlist
Steps:
1. convert l1 and l2 to integers
a. traverse listnodes from l1 and l2
b. int =+ listnode.val * 10^n
2. calculate temp = int1 + int2
3. convert temp to ListNode
Time Complexity: O(N), N = max(m,n)
Space: O(N)
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None:
return l2
if l2 == None:
return l1
int1 = 0
n = 1
while l1:
int1 += l1.val * n
n *= 10
l1 = l1.next
int2 = 0
m = 1
while l2:
int2 += l2.val * m
m *= 10
l2 = l2.next
# 构建新的linkedlist
temp = str(int1 + int2)
dummy = p = ListNode(0)
for i in range(len(temp) - 1, -1, -1):
p.next = ListNode(int(temp[i]))
p = p. next
return dummy.next
|
45873beb20988f2a47a08b79c0deaca1be94decc
|
hoodielive/modernpy
|
/2020/archive/binary-search.py
| 394 | 3.640625 | 4 |
def binary_contains(gene: Gene, key_codon: Codon) -> bool:
low: int = 0
high: int = len(gene) - 1
while low <= high:
mid: int = (low + high)
if gene[mid] < key_codon:
low = mid + 1
elif gene[mid] > key_codon:
high = mid - 1
else:
return True
return False
binary_contains('gene': True, 'key_codon': False)
|
a990ef2995682cabe31f86e64f304759caf3c73e
|
Dharani80/bestinlist-internship
|
/day5.py
| 1,873 | 3.96875 | 4 |
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> n=4
>>> M=[855,5,2,74,33,]
>>> M=M*n
>>> print(M)
[855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33]
>>> print('updated M list:',M)
updated M list: [855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33]
>>> # add an item in list
>>> M.append(6)
>>> print(M)
[855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 6]
>>> print('updated M list:',M)
updated M list: [855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 6]
>>> #Delete an item in list
>>> M.remove(855)
>>> print(M)
[5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 6]
>>> # Storing the largest number from the list
>>> P=max(M)
>>> print(P)
855
>>> #storing the smallest number from the list
>>> Q=min(M)
>>> print(M)
[5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 855, 5, 2, 74, 33, 6]
>>> print(Q)
2
>>> #creating a tuple and reverse of the created tuple
>>> X=('d','h','a','r','a','n','i', '84','hello','world')
>>> print(X)
('d', 'h', 'a', 'r', 'a', 'n', 'i', '84', 'hello', 'world')
>>> Z=reversed(X)
>>> print(tuple(Z))
('world', 'hello', '84', 'i', 'n', 'a', 'r', 'a', 'h', 'd')
>>> #Tuple to convert into list
>>> R=( 582,'am','abc',5,2)
>>> S=list(R)
>>> print"list elements:",S
SyntaxError: invalid syntax
>>> print"list elements :",S
SyntaxError: invalid syntax
>>> type(R)
<class 'tuple'>
>>> S=list(R)
>>> type(S)
<class 'list'>
>>> print(S)
[582, 'am', 'abc', 5, 2]
>>> print(R)
(582, 'am', 'abc', 5, 2)
>>> R=(582,'am','abc',5,2)
>>> type(R)
<class 'tuple'>
>>> R=list(R)
>>> type(R)
<class 'list'>
>>> print(R)
[582, 'am', 'abc', 5, 2]
>>>
|
f5a4006b5d913c6d6798b11fbf403a89a259fb18
|
BEPCTA/Coding_Games
|
/n_ary_function.py
| 485 | 4.21875 | 4 |
# ---------------
# User Instructions
#
# Write a function, n_ary(f), that takes a binary function (a function
# that takes 2 inputs) as input and returns an n_ary function.
def n_ary(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
def n_ary_f(x, *args):
if not args:
return x
else:
return f(x, n_ary_f(*args))
return n_ary_f
def func_add(x, y): return x+y
print n_ary(func_add)(1,3,5,8)
|
cf0bcfcf23f3a818d712d7de8e8a825af8b7cc59
|
fernandoeqc/Project_Euler_Python
|
/dificuldade 5/3 - Largest prime factor.py
| 471 | 3.75 | 4 |
""" The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ? """
numero = 600851475143
maxFator = 0
def divide(num):
divisor = 2
global maxFator
while (num % divisor != 0):
divisor+=1
if (divisor > maxFator):
maxFator = divisor
resultado = num / divisor
return resultado
while (numero > 2):
numero = divide(numero)
print(numero)
print("max: ",maxFator)
|
8f0f4eeddf40e2982a2fd67240e26c1ca77860c8
|
liuxiang0/pi
|
/Gregory_Leibniz_pi.py
| 3,167 | 3.53125 | 4 |
#!/usr/bin/python
# -*- encoding: UTF-8 -*-
"""
Algorithms of Gregory-Leibniz series sum for calculating π
收敛极慢的 π/4=1-1/3+1/5-1/7+...
从 反正切函数泰勒级数展开获得
arctan(x) = x-x^3/3+x^5/5-x^7/7+...
令 x=1,得到:π/4 = summation((-1)**k/(2*k+1),(k,0,oo))
区别 sin(x) = summation((-1)**k * x**(2*k+1)/factorial(2*k+1),(k,0,oo))
1. Iterations: Leibniz_iter(n)
2. Epson : Leibniz_epson(eps)
Discussion:
"if you want to get the error (epson) 10^(-n), you should iterated 10^n."
"""
import timeit
#from math import log10, pi
import math
from sympy import Rational, pi
math_pi = pi # math.pi
""" def reciprocal_of_odd(n):
# series for reciprocal of an odd number: 1, -1/3,1/5,-1/7,...
return (-1)**n/(2*n+1) """
def series_for_reciprocal_of_odd():
# generate series for reciprocal of odd number
n = 0
while True:
yield Rational(1, 2*n+1) # 1.0/(2*n+1)
n += 1
def sum_recipodd_series(n):
# sum for Gregory-Leibniz series 1-1/3+1/5-1/7+...
_rodd = series_for_reciprocal_of_odd()
s, k = 0, 1
for _ in range(n):
s += k * next(_rodd)
k = -k
return s
def Leibniz_iter(n):
# get PI from 4*(1-1/3+1/5-1/7+...)
return 4*sum_recipodd_series(n)
def test_Gregory():
n = 1000
print('Elapsed(s), \t Iterations, \t PI')
start = timeit.default_timer()
mypi = Leibniz_iter(n).evalf(100)
stop = timeit.default_timer()
print('{T}, \t {N}, \t {Pai}'.format(T=stop-start, N=n, Pai=mypi))
def test_Leibniz_iter():
log_nlist = range(4, 8, 2) # don't greater than 8
print("**Gregory Leibniz Series Generator with Iterations for PI**")
for log_n in log_nlist:
n = 10**log_n
res = Leibniz_iter(n)
epson = abs(res - math_pi) #.evalf(50)
print("Iterations=10^{N}, PI={Pai}, Epson={E}~10^{LE}".format(\
N=log_n, Pai=res.evalf(50), E=epson.evalf(50), LE=round(math.log10(epson.evalf(50)))) )
def Leibniz_epson(eps, limit=float("inf")):
'''
π = 4*(1-1/3+1/5-1/7+1/9-1/11+...)
Gregory-Leibniz Series sum
Input: deviation 'eps'
Output: PI and iterations
'''
s, k, i = 0, 1, 1
''' given iteration upper number 'up':
for i in range(1, up):
s += k*1/(2*i-1.0)
k = -k
#for i in range(1, up, 4): # odd number, period is 4.
# s += 1.0/i - 1.0/(i+2)
'''
#global math_pi
a = series_for_reciprocal_of_odd()
while (abs(4*s-math_pi) > eps) and (i < limit):
s += k * next(a)
k = -k
i += 1
return (4*s, i)
def test_Leibniz_epson():
print("===Gregory Leibniz series sum for PI with epson===")
for j in range(7, 9): # don't greater than 8
epson = 10**(-j)
start = timeit.default_timer()
mypi, n_iter = Leibniz_epson(epson)
stop = timeit.default_timer()
print('Elapsed(s)={T}, Iterations={N}~10^{NL}, Epson={Eps}, PI={Pai}'.format(
T=stop-start, N=n_iter, NL=round(math.log10(n_iter)), Eps=epson, Pai=mypi))
if __name__ == '__main__':
#test_Gregory()
test_Leibniz_iter()
# test_Leibniz_epson()
|
d44af8a2e8befb3c9c500b305c6fc5f600197998
|
tonylixu/devops
|
/algorithm/sorting/merge-sort.py
| 1,201 | 4.28125 | 4 |
# Mergesort is a divideand conquer algorithm
# which means we break the problem into sub-problems and
# find solution to sub-problems, and from the solution to
# sub-problems we construct a solution of the actual problem.
#
# Mergesort is a stable algorithm, it preserves the relative order
# of records with same key.
#
# Mergesort is not a In-place algorithm. The extra space it will take is
# propotional to the number of elements in the array
def merge_sort(array):
# Only one element in the array, consider sorted
if len(array) < 2:
return array
# Fidn the middle of the array
mid = len(array) / 2
array_l = array[:mid]
array_l = merge_sort(array_l)
array_r = array[mid:]
array_r = merge_sort(array_r)
array = merge(array_l, array_r)
return array
def merge(al, ar):
c = []
while len(al) != 0 and len(ar) != 0:
if al[0] < ar[0]:
c.append(al[0])
al.remove(al[0])
else:
c.append(ar[0])
ar.remove(ar[0])
if len(al) == 0:
c += ar
else:
c += al
return c
if __name__ == "__main__":
cards = [2, 4, 1, 6, 8, 5, 3, 7]
print merge_sort(cards)
|
087b3113ce491937eddfd37c0584ca12156ccb27
|
Yasara123/Grade-Prediction-System
|
/final_SFT/UnitTesting/win_Help.py
| 608 | 3.53125 | 4 |
__author__ = 'Yas'
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
imageFile = "logo4.jpg"
logo = ImageTk.PhotoImage(Image.open(imageFile))
w1 = Label(root, image=logo).pack(side="right")
explanation = """By using this software you can increase the marks of your students.For that following functions can be done:\nShow Student Progress:This function shows the all students progress by using grphs\nPredict Future Result:\nEnrollment Aproval:\nLecture process:"""
w2 = Label(root,
justify=LEFT,
padx = 10,
text=explanation).pack(side="left")
root.mainloop()
|
bdfe1bc773f47eb21b509955aad38af53605ef8b
|
bing1zhi2/algorithmPractice
|
/pyPractice/algoproblem/Intersection_of_two_arr_349.py
| 1,574 | 4.34375 | 4 |
"""
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
"""
class Solution(object):
def intersection(self, nums1, nums2):
"""
此解法很幼稚 官方答案说
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
d = dict()
d2 = {}
for i in nums1:
d[i] = 1
for i in nums2:
if d.get(i):
d2[i] = 1
return list(d2.keys())
def intersection2(self, nums1, nums2):
"""
内置函数
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
n1 = set(nums1)
n2 = set(nums2)
return list(n1 & n2)
def set_intersection(self, set1, set2):
return [x for x in set1 if x in set2]
def intersection3(self, nums1, nums2):
"""
把小的一边进行比较
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
if len(set1) < len(set2):
return self.set_intersection(set1, set2)
else:
return self.set_intersection(set2, set1)
nums1 = [1, 2, 2, 1]
nums2 = [3, 2, 2]
s = Solution()
r = s.intersection3(nums1, nums2)
print(r)
|
3e2c18187040b0a46188af335e199d8c93b20ab2
|
artorious/python3_dojo
|
/find_factors.py
| 1,115 | 4.1875 | 4 |
#!/usr/bin/env python3
'''Prints all the integers and their associated factors from 1-n'''
from custom_modules.get_positive_number_from_user import get_positive_num
print(__doc__) # Program Greeting
# init
count = 1 # Start from 1 (The numbers being examined)
value = int(get_positive_num()) # Get positive integer from user
##------- The Algorithm -------- ##
while count <= value: # Dont go past max
factor = 1 # 1 is a universal factor
print('{0:>3}: '.format(repr(count)), end='') # Which integer are we examining?
while factor <= count: # Factors are <= the number being examined
if count % factor == 0: # Test whether factor is a factor of the number being examined
print(factor, end=' ') # Dispaly the factor if yes
factor += 1 # Try next possible factor
print() # Move to the next line
count += 1 # Examine next number
|
174b7bc473f02157e9d552bd54bee792779abd02
|
IsabellaFSilva/Exercicios_Python
|
/EstruturaSequencial/EstruturaSequencial_6.py
| 249 | 4.09375 | 4 |
# -*- coding: utf-8 -*-
"""
Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
"""
r = int(input("Insira o raio do círculo: \n"))
pi = 3.14
a = pi * (r * r)
print("A área do circulo è: %.2f cm aproximadamente" %(a))
|
890c48343b178a3cdabb810722500fac2d92c1ba
|
imyoungmin/cs8-s20
|
/W10/p1.py
| 667 | 4 | 4 |
"""
Problem 1. 2D Barcode.
"""
import random
def twoDBarCode( n ):
"""
Create a 2D bar code.
:param n: Side length.
:return: A two dimensional random 2D code with * and spaces.
"""
code = ""
code += "+" + "-" * n + "+\n" # Header.
for _ in range( n ):
code += "|"
for _ in range( n ):
r = random.randrange( 2 ) # Generate a random number between 0 and 1.
if r == 0:
code += "*"
else:
code += " "
code += "|\n"
code += "+" + "-" * n + "+" # Footer.
return code
if __name__ == "__main__":
n = int( input( "Side length: " ) )
n = max( 2, n ) # Make sure the side length is at least 2.
print()
print( twoDBarCode( n ) )
|
ae5e8b24813c84e195bd63d38f6e6913d47e4776
|
Alone-elvi/Learinig_Python_book_ex
|
/unittests/test_cities.py
| 517 | 3.734375 | 4 |
import unittest
from unittests.city_functions import get_city_country
class CityTestCase(unittest.TestCase):
def test_get_city_country(self):
city_country_name = get_city_country('mocsow', 'russia')
self.assertEqual(city_country_name, 'Mocsow Russia')
def test_get_city_country_populations(self):
city_country_name = get_city_country('mocsow', 'russia', '50000')
self.assertEqual(city_country_name, 'Mocsow Russia — 50000')
if __name__ == '__main__':
unittest.main()
|
5df1eaf8e03f0265d3320bae6b9d22ea2feb5191
|
huyuan95/Learn-Python
|
/Python Crash Course/chapter15/random_walk.py
| 1,129 | 4.25 | 4 |
from random import choice
class RandomWalk():
""" a class to generate random walk"""
def __init__(self, num_points = 5000):
"""initiate attribute of random walk"""
self.num_points = num_points
# all random walk begins at (0, 0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""calculate all points in random walk"""
# walk on until assigned distance reached
while len(self.x_values) < self.num_points:
# decide direction and distance to the direction
x_step = self.get_step()
y_step = self.get_step()
# refuse to stay
if x_step == 0 and y_step == 0:
continue
# calculate x and y value of next point
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
def get_step(self):
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
return direction*distance
|
b1786bf9070ecfd8cd3d306e241d7258b1ebfe71
|
idanyamin/IMDB_review_classifier-Machine-Learning-
|
/menu.py
| 7,542 | 3.671875 | 4 |
"""
author: Idan Yamin
"""
import graphs_and_results
import sklearn
import sklearn.linear_model
def ridge_menu(x_train, x_test, y_train, y_test):
"""
Opens the ridge menu
:param x_train: train data
:param x_test: test data
:param y_train: train labels
:param y_test: test labels
"""
print('You choose Ridge Regression')
while True:
user_input = input('1.plot graph of 0-1 mean loss as a function of lambda\n'
'2.plot regularization path\n')
try:
val = int(user_input)
if not (1 <= val <= 2):
raise ValueError
print('It may take a while')
if val == 1:
graphs_and_results.plot_ridge_error_as_function_of_lambda(x_train, x_test, y_train, y_test)
break
if val == 2:
graphs_and_results.plot_ridge_regularization_path(x_train, y_train)
break
except ValueError:
print('Enter a number between 1 and 3')
def menu():
"""
This functions manges the main menu.
"""
x_train, x_test, y_train, y_test = graphs_and_results.get_data()
while True:
user_input = input('1.Base line classifier (Logistic Regression)'
'\n2.Linear classifier mean 0-1 loss (an example of bad classifier)\n'
'3.Ridge regression\n'
'4.Lasso regression, plot regularization path\n'
'5.Adaboost\n'
'6.Random Forest\n'
'7.Describe the data\n')
try:
val = int(user_input)
if not (1 <= val <= 7):
raise ValueError
if val == 1:
classifier = sklearn.linear_model.LogisticRegression
logistic_regression_menu('You choose logistic regression', x_train, x_test, y_train, y_test, classifier)
break
if val == 2:
graphs_and_results.linear_classifier(x_train, x_test, y_train, y_test)
break
if val == 3:
ridge_menu(x_train, x_test, y_train, y_test)
break
if val == 4:
graphs_and_results.plot_lasso_regularization_path(x_train, y_train)
break
if val == 5:
adaboost_menu(x_train, x_test, y_train, y_test)
break
if val == 6:
random_forest_menu(x_train, x_test, y_train, y_test)
break
if val == 7:
graphs_and_results.describe(x_train)
break
except ValueError:
print('Enter a number between 1 and 7')
continue
def random_forest_menu(x_train, x_test, y_train, y_test):
"""
opens the random forest menu
:param x_train: train data
:param x_test: test data
:param y_train: train labels
:param y_test: test labels
:return:
"""
while True:
user_input = input('1.Mean error as a function of leaves graph (max_features=sqrt)\n'
'2.Mean error as a function of leaves graph (max_features=log2)\n'
'3.Mean error as a function of tree\'s depth graph\n'
'4.Mean error as a function of the number of features\n'
'5.Mean error as a function of the number of tress\n'
'6.Mean error of boosted optimal tree\n')
try:
val = int(user_input)
if not (1 <= val <= 6):
raise ValueError
if val == 1:
graphs_and_results.random_forest_error_as_a_function_of_leafs(x_train, x_test, y_train, y_test, 45, 100, 'sqrt')
break
if val == 2:
graphs_and_results.random_forest_error_as_a_function_of_leafs(x_train, x_test, y_train, y_test, 600, 25, 'log2')
break
if val == 3:
graphs_and_results.random_forest_error_as_a_function_of_depth(x_train, x_test, y_train, y_test, 200, 2,
'log2')
break
if val == 4:
graphs_and_results.random_forest_error_as_a_function_of_features_num(x_train, x_test, y_train, y_test, 25, 1000, 'log2')
break
if val == 5:
graphs_and_results.random_forest_error_as_a_function_of_trees_num(x_train, x_test, y_train, y_test, 10, 40, 'log2')
break
if val == 6:
graphs_and_results.boosting_optimal_tree(x_train, x_test, y_train, y_test)
break
except ValueError:
print('Enter a number between 1 and 6')
continue
def adaboost_menu(x_train, x_test, y_train, y_test):
"""
Opens Adaboost menu
:param x_train: train data
:param x_test: test data
:param y_train: train labels
:param y_test: test labels
"""
print('AdaBoost')
while True:
user_input = input('1.Decision stump classifier\n'
'2.boost decision stump\n')
try:
val = int(user_input)
if not (1 <= val <= 2):
raise ValueError
if val == 1:
print('mean 0-1 loss: ' +
str(graphs_and_results.decision_stump_loss(x_train, x_test, y_train, y_test)))
if val == 2:
graphs_and_results.adaboost(x_train, x_test, y_train, y_test)
except ValueError:
print('Enter a number between 1 and 10')
def logistic_regression_menu(text, x_train, x_test, y_train, y_test, classifier):
"""
Opens logistic regression menu
:param text: text to print
:param x_train: train data
:param x_test: test data
:param y_train: train labels
:param y_test: test labels
:param classifier: classifier
"""
print(text)
while True:
user_input = input('Choose one of the options below\n'
'1.plot 0-1 loss as a function of the number of features (a couple of minutes)\n'
'2.Get mean 0-1 loss on all the words in the bag of words\n')
try:
val = int(user_input)
if not (1 <= val <= 2):
raise ValueError
if val == 1:
user_input = input('Choose one of the options below\n'
'1.use test set for validation\n'
'2.use cross validation\n')
val = int(user_input)
if not (1 <= val <= 2):
raise ValueError
if val == 1:
graphs_and_results.feature_selection_graph(classifier, x_train, x_test, y_train, y_test)
break
else:
graphs_and_results.feature_selection_graph(classifier, x_train, x_test, y_train, y_test, True)
break
if val == 2:
print('mean 0-1 loss: ' + str(graphs_and_results.zero_one_loss(classifier, x_train, x_test, y_train, y_test)))
except ValueError:
print('Enter a number between 1 and 2')
continue
|
b6d1801c521113a4bc960be245fe0e0564ec29a8
|
krishxx/python
|
/practice/cp_sols/Pr26.py
| 381 | 3.96875 | 4 |
'''Question:26
Define a function which can compute the sum of two numbers.
Hints:
Define a function with two numbers as arguments.
You can compute the sum in the function and return the value.
Solution'''
def SumFunction(number1, number2):
return number1+number2
print (SumFunction(100000000000000000000000000000000000,200000000000000000000000000000000000000000000000000000))
|
6977da6394d22e09c93cb5b2a717e310b8d8a0e1
|
ChristopherHOliveira/Sistema-Biblioteca
|
/biblioteca.py
| 4,906 | 3.59375 | 4 |
# importando funções do SQLalchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text
# usando o banco de dados contido no arquivo 'bib.db', no formato SQLite
engine = create_engine('sqlite:///bib.db')
# definindo uma classe que herda todas as funcionalidades, métodos e atributos de Exception
class AlunoNaoExisteException(Exception):
# não há diferenças de execução em relação à Exception
pass
# função que recebe o parâmetro 'id_aluno' e devolve um dicionário com os dados desse aluno
def consulta_aluno(id_aluno):
# conectando ao BD
with engine.connect() as con:
# selecionando tudo da tabela 'aluno' onde 'id' (coluna na tabela) == 'id_do_aluno'(espaço definido na query SQL)
sql_consulta = text ("SELECT * FROM aluno WHERE id = :id_do_aluno")
# executando a query definida em sql_consulta, preenchendo o "espaço" 'id_do_aluno' com o argumento passado em 'id_aluno'
rs = con.execute(sql_consulta, id_do_aluno = id_aluno)
# fetchone() para pegar apenas uma linha do resultado
result = rs.fetchone() # caso hajam mais linhas, executar outro fetchone()
# se a query retornou 0 linhas
if result == None:
# levantar exceção
raise AlunoNaoExisteException
# retornando o resultado do SQLalchemy convertido em um dicionário
return dict(result)
# Função que retorna um lista com um dicionario para cada aluno
def todos_alunos():
with engine.connect() as con:
# selecionando tudo da tabela 'aluno'
sql_consulta = text ("SELECT * FROM aluno")
# executando a query
rs = con.execute(sql_consulta)
# criando uma lista vazia
resultados = []
# sempre executar
while True:
# pega uma linha do resultado e guarda na var 'result'
result = rs.fetchone()
# se o resultado for None
if result == None:
# parar
break
# guardando o resultado convertido em dicionário na var 'd_result'
d_result = dict(result)
# adicionando o resultado na lista 'resultados'
resultados.append(d_result)
# retornando o resutado
return resultados
# função que retorna um lista com um dicionario para cada livro
def todos_livros():
with engine.connect() as con:
sql_consulta = text ("SELECT * FROM livro")
rs = con.execute(sql_consulta)
resultados = []
while True:
result = rs.fetchone()
if result == None:
break
d_result = dict(result)
resultados.append(d_result)
return resultados
# função que recebe os dados de um livro e adiciona o livro no banco de dados
def cria_livro(id_livro, descricao):
with engine.connect() as con:
sql_create = text ("INSERT INTO livro (id_livro, descricao) VALUES (:id_livro, :descricao)")
con.execute(sql_create, id_livro = id_livro, descricao = descricao)
# função que recebe a id de um livro, a id de um aluno e marca o livro como emprestado pelo aluno
def empresta_livro(id_livro, id_aluno):
with engine.connect() as con:
sql_create = text ("UPDATE livro SET id_aluno = :id_aluno WHERE id_livro = :id_livro")
con.execute(sql_create, id_livro=id_livro, id_aluno=id_aluno)
# função que recebe a id de um livro, e marca o livro como disponível
def devolve_livro(id_livro):
with engine.connect() as con:
sql_create = text ("UPDATE livro SET id_aluno = NULL WHERE id_livro = :id_livro")
con.execute(sql_create, id_livro = id_livro)
# função que devolve uma lista (de dicionários) dos livros que não estão emprestados
def livros_parados():
with engine.connect() as con:
sql_consulta = text ("SELECT * FROM livro WHERE id_aluno ISNULL")
rs = con.execute(sql_consulta)
resultados = []
while True:
result = rs.fetchone()
if result == None:
break
d_result = dict(result)
resultados.append(d_result)
return resultados
# função que recebe o nome do aluno e devolve uma lista (de dicionários) dos livros que estão com o aluno no momento
def livros_do_aluno(nome):
with engine.connect() as con:
sql_consulta = text ('''SELECT id_livro, id_aluno, descricao
FROM livro
JOIN aluno ON livro.id_aluno = aluno.id
WHERE nome = :nome''')
rs = con.execute(sql_consulta, nome = nome)
resultados = []
while True:
result = rs.fetchone()
if result == None:
break
d_result = dict(result)
resultados.append(d_result)
return resultados
|
e12ec0b97218fc42be8f7823f582c0aa0142bc22
|
ganqzz/sandbox_py
|
/algo/sorting/quick_sort.py
| 767 | 3.84375 | 4 |
# O(nlogn), in worst case O(n2)
# divide-and-conquer
def quick_sort(dataset, left, right):
i, j = left, right
pivot = dataset[(left + right) // 2]
while i <= j:
while dataset[i] < pivot:
i += 1
while dataset[j] > pivot:
j -= 1
if i <= j:
dataset[i], dataset[j] = dataset[j], dataset[i]
i += 1
j -= 1
# now sort the two partitions
if j > left:
quick_sort(dataset, left, j)
if i < right:
quick_sort(dataset, i, right)
def main():
list1 = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
print("Starting:", list1)
quick_sort(list1, 0, len(list1) - 1)
print("Finished:", list1)
if __name__ == "__main__":
main()
|
13cadd8f3d8986a0bd1a336e227d414d77e398a9
|
telescopeuser/AI_playground
|
/notebooks/exercises/src/text/jupyter_selection_table.py
| 6,455 | 3.609375 | 4 |
import pandas as pd
from ipywidgets import Button, HBox, VBox, Label
from ipywidgets import HTML
class SelectionTable:
def __init__(self, data, row_height=28, column_width=80, row_button_width=50, table_cell_paddings=8.16,
button_padding="0pt 0pt 0pt 0pt"):
"""
Class for creating a pandas table in jupyter in which specific rows and columns can be selected.
:param pd.DataFrame data: The data for the table. Made for text-elements but may also work for other types.
:param int row_height: Height of rows in pt.
:param int column_width: Width of columns in pt.
:param int row_button_width: Width of buttons in rows in pt.
:param int table_cell_paddings: Padding of cells in table in pt.
:param str button_padding: CSS padding of buttons.
"""
# Store dimensions and convert to strings for html
self._row_height = row_height
self._column_width = column_width
self._row_button_width = row_button_width
self._table_cell_paddings = table_cell_paddings
self.row_height = "{}pt".format(self._row_height)
self.column_width = "{}pt".format(self._column_width)
self.row_button_width = "{}pt".format(self._row_button_width)
self.table_cell_paddings = "{}pt".format(self._table_cell_paddings)
self.button_padding = button_padding
# Initialize
self.observers = []
self.df = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)
# Make a button for each row
self.row_button_list = [
Button(
description='select',
layout=dict(height=self.row_height,
width=self.row_button_width,
padding=self.button_padding),
) for _ in range(self.df.shape[0])
]
self.row_on = [True] * self.df.shape[0]
for nr, button in enumerate(self.row_button_list):
button.on_click(self._row_button_clicked(nr=nr))
# Make a button for each column
self.column_button_list = [
Button(
description='select',
layout=dict(height=self.row_height,
width=self.column_width,
padding=self.button_padding),
) for _ in range(self.df.shape[1])
]
self.col_on = [True] * self.df.shape[1]
for nr, button in enumerate(self.column_button_list):
button.on_click(self._col_button_clicked(nr=nr))
# Compute total width of table
self.table_width = max((self.df.shape[1] + 1) * self._column_width + self._row_button_width, 500)
# Make the table
self._make_table()
def observe(self, method):
"""
Pass a method for being called when table is interacted with.
:param Callable method:
:return:
"""
self.observers.append(method)
def _note_change(self):
"""
Notify observers.
"""
for method in self.observers:
method()
def _row_button_clicked(self, nr):
"""
Note click of a button in a row.
:param nr:
"""
def set_bool(_=None):
self.row_on[nr] = not self.row_on[nr]
self._make_table()
self._note_change()
return set_bool
def _col_button_clicked(self, nr):
"""
Note click of a button in a column.
:param nr:
"""
def set_bool(_=None):
self.col_on[nr] = not self.col_on[nr]
self._make_table()
self._note_change()
return set_bool
def selection_colorize(self, _=None):
"""
Colorize table depending on selection on rows and columns.
:param _:
"""
formatters = pd.DataFrame([
["color: black" if row and col else "color: lightgrey" for col in self.col_on]
for row in self.row_on
])
return formatters
def _make_table(self):
# Global styles
styles = [
dict(selector="tr", props=[
("height", self.row_height),
("vertical-align", "middle"),
("text-align", "center"),
("width", self.column_width),
]),
dict(selector="td", props=[
("padding-bottom", self.table_cell_paddings),
("padding-top", self.table_cell_paddings),
("vertical-align", "middle"),
("text-align", "center"),
("width", self.column_width),
]),
dict(selector="th", props=[
("padding-bottom", self.table_cell_paddings),
("padding-top", self.table_cell_paddings),
("vertical-align", "middle"),
("text-align", "center"),
("width", self.column_width),
]),
]
# Make styler for DataFrame
styler = self.df.style.set_table_attributes('class="table"') \
.set_table_styles(styles) \
.apply(self.selection_colorize, axis=None)
# Render HTML table from DataFrame
html = styler.render()
# Build visual components
v_row_buttons = VBox(
[Label(description='', layout=dict(height=self.row_height,
width=self.row_button_width,
padding=self.button_padding)),
*self.row_button_list],
)
v_bottom = HBox([
v_row_buttons,
HTML(html)
])
v_col_buttons = HBox(
[Label(description='', layout=dict(height=self.row_height,
width=self.row_button_width,
padding=self.button_padding)),
Label(description='', layout=dict(height=self.row_height,
width=self.column_width,
padding=self.button_padding)),
*self.column_button_list],
)
# Make dashboard
self._table = VBox(
(v_col_buttons, v_bottom,),
layout=dict(width="{}pt".format(self.table_width))
)
@property
def table(self):
return self._table
|
83982198ded1472e4c930661ad2be006c38ae5a4
|
cmcdowell/weatherpy
|
/weatherpy/image.py
| 828 | 3.75 | 4 |
class Image(object):
"""
The image use to identify the RSS feed
Attributes:
height: The height of the image in pixels (int).
link: Link to Yahoo weather.
title: The title of the image (string).
url: The url of the image (string).
width: The width of the image in pixels (int).
"""
def __init__(self, image):
self.title = image['title']
self.width = image['width']
self.height = image['height']
self.link = image['link']
self.url = image['url']
def as_html(self):
"""
Returns the image of the Yahoo rss feed as an html string
"""
return '<a href="{0}"><img height="{1}" width="{2}" src="{3}" alt="{4}"></a>'.format(
self.link, self.height, self.width, self.url, self.title)
|
11ca7dfda12573ca31b74b402000ee5b449dd0af
|
satishvbs/Master-Thesis-17-18
|
/find-all-Link-from-A-Page.py
| 710 | 3.703125 | 4 |
#Web scraping in python finding all links
'''
Some web links starts '#', some statrs with './' and rest proper link
task
Print all the links
1.if link starts with #, skip it
2.if link starts with ./ then replace ./ with 'https://' and print rest of the things
'''
import bs4
import requests
req_obj =requests.get('https://learncodeonline.in')
soup = bs4.BeautifulSoup(req_obj.content,'lxml')
links =soup.find_all('a',href=True)
print(links)
new_link=""
b= "https://"
#print(links)
for link in links:
if link['href'] is "#":
pass
if link['href'].startswith('./'):
temp_link = link['href']
new_link = b+temp_link[2:]
link['href'] = new_link
print(link['href'])
|
edcee71a09fa5b9ee6b20558f284393a021e4220
|
Bing-Violet/Code-Like-a-Girl
|
/python_tutorial/Session 2/if_statement.py
| 210 | 4.0625 | 4 |
#if statement demo
year = 2020
year_of_birth = input("Enter your year of birth:")
age = year - int(year_of_birth)
if age > 20:
print('Congratulations! You are an adult!')
else:
print("You're still young.")
|
7f22d28adf9343de18ac73aa427bd4ed1f4cbfc8
|
RongYu98/SoftwareDevHW
|
/IDK/lab.py
| 1,347 | 3.734375 | 4 |
import time
import quicksort
def wrapper( f ):
def inner( *arg ):
t1 = time.time()
funct = f(*arg)
t2 = time.time()
print "Time Taken for Function: ["+f.func_name+"] is " + str(t2-t1)
return funct
return inner
def foo( num1, num2, string):
return str(num1)+str(num2)+string
def wait( num ):
time.sleep(num)
return num
#foo = 3, in is not callable, foo has to be function?
#print time.time()
#closure = wrapper(foo)
#closure( -2, 3, 'hello' )
#closure2 = wrapper(wait)
#print closure2( 2 )
#closure3 = wrapper( quicksort.
x = """
def make_bold(fn):
return lambda : "<b>" + fn() + "</b>"
def make_italic(fn):
return lambda : "<i>" + fn() + "</i>"
@make_bold
@make_italic
def hello():
return "hello world"
helloHTML = hello()
print helloHTML
"""
def what_time(fn):
t1 = time.time()
fn()
t2 = time.time()
return "Time Taken for Function: ["+fn.func_name+"] is " + str(t2-t1)
##return f
def what_name(fn):
n = fn.func_name
args = fn.func_code.co_varnames
print "The function name is: ["+n+"]. The args are [",
print args,
#print "]."
return "]."#"The function name is: ["+n+"]. The args are ["+args+"]." #fn()
@what_time
@what_name
def stuff():
return quicksort.QS(quicksort.c, 0, len(quicksort.c)-1)
S = stuff()
print S
|
7750cda6e199021fcc158491e776c77daea9bee1
|
953250587/leetcode-python
|
/CatAndMouse_HARD_913.py
| 7,686 | 4.125 | 4 |
"""
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in 3 ways:
If ever the Cat occupies the same node as the Mouse, the Cat wins.
If ever the Mouse reaches the Hole, the Mouse wins.
If ever a position is repeated (ie. the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse, 2 if the game is won by Cat, and 0 if the game is a draw.
Example 1:
Input: [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
Output: 0
Explanation:
4---3---1
| |
2---5
\ /
0
Note:
3 <= graph.length <= 50
It is guaranteed that graph[1] is non-empty.
It is guaranteed that graph[2] contains a non-zero element.
"""
class Solution(object):
def catMouseGame(self, graph):
"""
:type graph: List[List[int]]
:rtype: int
"""
memory = {}
def dfs(cat_position, mouse_position, time):
# 判断是否已经结束,老鼠赢或者猫赢
if mouse_position == 0: #or (time == 0 and 0 in graph[mouse_position]):
return 1
# print(cat_position)
if mouse_position == cat_position:# or (time == 1 and mouse_position in graph[cat_position]):
return 2
# 判断是否已经遇到过这种情况
if (cat_position, mouse_position, time) in memory:
# 如果遇到过,并且是未求解出来的,说明循环了,可以跳出这种情况
if memory[(cat_position, mouse_position, time)] == -1:
return 0
# 否则返回记录值
return memory[(cat_position, mouse_position, time)]
# 记录下,这种情况开始考虑
memory[(cat_position, mouse_position, time)] = -1
# 所有可能发生的情况
possible = []
# 老鼠的回合
if time == 0:
for next_position in graph[mouse_position]:
temp = dfs(cat_position, next_position, 1)
possible.append(temp)
if temp == 1:
break
# if cat_position == 7 and mouse_position == 5:
# print('possible_mouse:', possible, cat_position, next_position)
# print(memory)
# if cat_position == 9 and mouse_position == 6:
# print('possible_mouse_1:', possible, cat_position, next_position)
# print(memory)
# 如果存在一种方式使得老鼠赢,则最后是老鼠赢
if 1 in possible:
flag = 1
# 如果所有情况都是猫赢,则最后是猫赢
elif 0 not in possible:
flag = 2
else:
flag = 0
else:
# 这种情况类似
for next_position in graph[cat_position]:
if next_position != 0:
temp = dfs(next_position, mouse_position, 0)
possible.append(temp)
if temp == 2:
break
# if cat_position == 9 and mouse_position == 5:
# print('possible_cat:', possible, next_position, mouse_position)
# print(memory)
# if cat_position == 7 and mouse_position == 6:
# print('possible_cat_1:', possible, next_position, mouse_position)
# print(memory)
if 2 in possible:
flag = 2
elif 0 not in possible:
flag = 1
else:
flag = 0
# used.remove((cat_position, mouse_position, time))
memory[(cat_position, mouse_position, time)] = flag
# print('flag:',flag, 'cat_position, mouse_position, time',cat_position, mouse_position, time)
return flag
temp = dfs(cat_position=2, mouse_position=1, time=0)
a = sorted(memory.keys(), key=lambda a:(-a[0],a[1], a[2]))
for i in a:
print(i, ':', memory[i])
return temp
# graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
# print(Solution().catMouseGame(graph))
#
#
# graph = [[2],[5,4],[3],[4,5],[1,5],[1,4]]
# print(Solution().catMouseGame(graph))
graph = [[6],[4],[9],[5],[1,5],[3,4,6],[0,5,10],[8,9,10],[7],[2,7],[6,7]]
print(Solution().catMouseGame(graph))
class Solution(object):
def catMouseGame(self, graph):
"""
512 ms,
:param graph:
:return:
"""
import collections
N = len(graph)
# What nodes could play their turn to
# arrive at node (m, c, t) ?
def parents(m, c, t):
if t == 2:
for m2 in graph[m]:
yield m2, c, 3-t
else:
for c2 in graph[c]:
if c2:
yield m, c2, 3-t
DRAW, MOUSE, CAT = 0, 1, 2
color = collections.defaultdict(int) # 默认平局
# degree[node] : the number of neutral children of this node
degree = {}
for m in range(N):
for c in range(N):
degree[m,c,1] = len(graph[m])
degree[m,c,2] = len(graph[c]) - (0 in graph[c])
# enqueued : all nodes that are colored
queue = collections.deque([]) # 只存入确定的位置
for i in range(N):
for t in range(1, 3):
color[0, i, t] = MOUSE # 记录所有老鼠赢的位置
queue.append((0, i, t, MOUSE)) # 记录老鼠赢的位置到队列中
if i > 0:
color[i, i, t] = CAT # 记录所有猫赢的位置
queue.append((i, i, t, CAT)) # 记录猫赢的位置到队列中
# percolate
while queue: # 反推
# for nodes that are colored :
i, j, t, c = queue.popleft()
# for every parent of this node i, j, t :
for i2, j2, t2 in parents(i, j, t):
# if this parent is not colored :
if color[i2, j2, t2] is DRAW: # 如果是平局,则有可能是还没遍历过的情况
# if the parent can make a winning move (ie. mouse to MOUSE), do so
if t2 == c: # winning move
color[i2, j2, t2] = c
queue.append((i2, j2, t2, c))
# else, this parent has degree[parent]--, and enqueue if all children
# of this parent are colored as losing moves
else:
degree[i2, j2, t2] -= 1 # 确保不重复
if degree[i2, j2, t2] == 0: # 平局情况
color[i2, j2, t2] = 3 - t2
queue.append((i2, j2, t2, 3 - t2))
return color[1, 2, 1]
|
073f78fc9c3f4652ab1b420580ec0a45f7972608
|
vany-oss/python
|
/pasta para baixar/netcha/exr29 velocidade de caro.py
| 394 | 3.796875 | 4 |
velo = float(input('velocidade actual? '))
if velo > 80:
print('multado voce esxcedeu o limitite permitido')
multa = (velo -80 ) * 0.50
print('voce deve pagar a multa de {} euros'.format(multa))
print('bom dia faca uma boa conducao')
# pg que calcula a multa d caro se a velocidade permida for escnxcedida o valor da multae 0.50 claro que se podia utilizar else mas e uma condicao simples
|
268b22f60229f25a05575124a91dc7ddf3c02e5b
|
abhireddy96/Leetcode
|
/747_Largest_Number_At_Least_Twice_of_Others.py
| 795 | 3.875 | 4 |
"""
https://leetcode.com/problems/largest-number-at-least-twice-of-others/
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.
"""
__author__ = 'abhireddy96'
from typing import List
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
# Find max element
m = max(nums)
# Check if max element is greater than twice the all other elements present in list excluding itself
if all(m >= 2*x for x in nums if x != m):
return nums.index(m)
return -1
if __name__ == "__main__":
print(Solution().dominantIndex([3, 6, 1, 0]))
|
b75b07d997e307ee9fee637c5a8b6c1dd412113a
|
kerxon/python-course-code
|
/file-handling/filehandling.py
| 1,504 | 4.28125 | 4 |
# r opens for reading only, pointer is placed at the beginning of the file. this is default mode
# r+ opens a file for both reading and writing. The file pointer is placed at the beginning of the file.
# w Opens a file for writing only. Overwrites the file if it exists.If the file doesn't exist, creates a new file
# w+ opens a file for both reading and writing. Overwrites the file if it exists.If the file doesn't exist, creates a new file
# a opens a file for appending. The file pointer is at the end if it exists. If file doesn't exist creates a new one for writing.
# a+ Opens a file for both appending and reading.Pointer at end if exists. file opens in append mode. If file nonexistant, creates new one for reading and writing.
# read files
# file=open("./files/example.txt",'r')
# print(type(file))
# content=file.read()
# content=file.readlines()
# print(content)
# file.seek(0)
# content1=[i.rstrip("\n") for i in content]
# print(content1)
# file.close()
#write files
## cannot write multiple lines without executing multiple times with \n using write method
# file=open("example2.txt",'w')
# file.write("show me the moneys")
# file.close()
# file2=open("example1.txt",'w')
# text = ["show","me","the","moneys"]
# for word in text:
# file2.write(word + "\n")
# file2.close()
#appending
# file=open("example2.txt",'a')
# file.write("Line 4")
# file.close()
# with
with open("example.txt","a+") as file:
file.seek(0)
content=file.read()
file.write("\nLine 6")
content
|
e101ad1c2d70ee89cb62e77da55ab3f5d02594fe
|
thomashirtz/leetcode
|
/solutions/1447-simplified-fractions.py
| 543 | 3.9375 | 4 |
from typing import List
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
answer = []
set_ = set()
for denominator in range(1,n+1):
for numerator in range(1,n):
if numerator/denominator<1 and numerator/denominator not in set_:
answer.append(f'{numerator}/{denominator}')
set_.add(numerator/denominator)
return answer
examples = [1, 2, 3, 4]
for example in examples:
print(Solution().simplifiedFractions(example))
|
5e5ac3a6e5aea7f803a66a4f2751e5ac551e647e
|
johnoro/Data-Structures
|
/binary_search_tree/binary_search_tree.py
| 1,164 | 3.578125 | 4 |
# each 'node' will be a B.S.T.
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_to(self, value, direction):
if getattr(self, direction) is None:
setattr(self, direction, BinarySearchTree(value))
else:
getattr(self, direction).insert(value)
def insert(self, value):
if value > self.value:
self.insert_to(value, 'right')
else:
self.insert_to(value, 'left')
def is_in(self, target, direction):
node = getattr(self, direction)
if node is None:
return False
if target == node.value:
return True
return node.contains(target)
def contains(self, target):
if target > self.value:
return self.is_in(target, 'right')
elif target == self.value:
return True
else:
return self.is_in(target, 'left')
def get_max(self):
node = self
while node.right is not None:
node = node.right
return node.value
def for_each(self, cb):
cb(self.value)
if self.left is not None:
self.left.for_each(cb)
if self.right is not None:
self.right.for_each(cb)
|
639e6016b0fc13054ced217f35fd037d7ab082dc
|
coolczyk/szkolenie
|
/user_input.py
| 91 | 4.15625 | 4 |
variable = input ("What is your name?: ")
#variable = 5
print ("Hello " + variable + " !")
|
e142320cf537e5968d8c1a986801cf9a018fd71e
|
VivekMaran27/coding-practice
|
/python/trapping_rain_water_lc42.py
| 1,037 | 3.609375 | 4 |
class Solution:
def trap(self, height: List[int]) -> int:
maxSeenSoFar = 0
maxSeenRight = [None]*len(height)
maxSeenLeft = 0
numRainBlocks = 0
#Track the max value in right
for i in range(len(height)-1,-1,-1):
if(height[i] > maxSeenSoFar):
maxSeenSoFar = height[i]
maxSeenRight[i] = maxSeenSoFar
"""
1. Track maxSeenLeft
2. Check if the current index has one tower left and one tower right
3. If so, the number of water blocks in that tower is:
min(maxSeenLeft,maxSeenRight) - currentTowerHeight
"""
maxSeenSoFar = 0
for i in range(0,len(height)):
if(height[i] > maxSeenLeft):
maxSeenLeft = height[i]
#print(f"maxSeenRight[{i}]={maxSeenRight[i]}, maxSeenLeft={maxSeenLeft}, height[{i}]={height[i]}")
numRainBlocks += max((min(maxSeenRight[i],maxSeenLeft)-height[i]),0)
return numRainBlocks
|
902e1ceca9b14cf04982e7be9811fec0c0cc9e16
|
Logavani16/python1
|
/66.py
| 117 | 3.734375 | 4 |
vani=int(input())
for v in range(2,vani):
if vani%v==0:
print("no")
break
else:
print("yes")
|
0aa3a99e232fb3357bb4f24797c7f280bf611db7
|
olukaemma/py
|
/testcode/temp.py
| 490 | 3.765625 | 4 |
#!/usr/bin/env python3
__author__ = 'Emmanuel Oluka'
'''using Templats in string'''
from string import Template
def Main():
cart = []
cart.append(dict(item='Coke', price=8, qty=2))
cart.append(dict(item='Sugar', price=10, qty=3))
cart.append(dict(item='rice', price=5, qty=5))
tmp = Template("$qty x $item = $price")
total = 0
print("Cart: ")
for data in cart:
print(tmp.substitute(data))
total += data["price"]
print('Total: '+ str(total))
|
c1bd4e46769be72961168f3566fff13d6b327a6a
|
michaelzap94/mz-python
|
/Concurrency/Async/10_yield_to_receive_data.py
| 950 | 4.09375 | 4 |
# SIMPLE
def greet():
# SUSPEND THE FUNCTION, BUT assign the value we receive to a variable ('friend')
friend = yield
print(f'Hello, {friend}')
try:
g = greet()
g.send(None) # Priming the generator: runs up to yield and then do:
g.send('Adam') # This is what goes into the 'yield' of the generator
except StopIteration:
pass
# ADVANCED
from collections import deque
friends = deque(('Rolf', 'Jose', 'Charlie', 'Jen', 'Anna'))
def friend_upper():
while friends:
friend = friends.popleft().upper() # get a friend from deque
# SUSPEND THE FUNCTION, BUT assign the value we receive to a variable ('greeting')
greeting = yield
print(f'{greeting} {friend}')
def greet(friend_upper_generator):
yield from friend_upper_generator
# SAME AS:
greeter = greet(friend_upper())
greeter.send(None)
greeter.send('Hello')
print('Hello, world! Multitasking...')
greeter.send('How are you,')
|
d7494be4817349002aff937d8a33a6720e11fd8b
|
ArDrift/InfoPy_scripts
|
/9_het/8_dolgozatok.py
| 824 | 4.03125 | 4 |
#!/usr/bin/env python3
# A rendezéshez felhasználtam: https://docs.python.org/3/howto/sorting.html#key-functions
class Hallgato:
def __init__(self, neptun, nev, pont):
self.neptun = neptun
self.nev = nev
self.pont = pont
def __str__(self):
return "Név: {}, Neptun: {}, Pont: {}".format(self.nev, self.neptun, self.pont)
def beolvas(file):
diaklista = []
with open(file, "rt") as f:
for sor in f:
diaklista.append(Hallgato(sor.split(":")[0], sor.split(":")[1], int(sor.split(":")[2])))
return diaklista
def main():
lista1 = beolvas("8_zheredmeny.txt")
lista2 = list(lista1)
lista1[0].pont = 27
lista1 = sorted(lista1, key=lambda hallgato: hallgato.nev)
lista2 = sorted(lista2, key=lambda hallgato: hallgato.pont)
for elem in lista2:
print(elem)
main()
|
151ca015010ff7397e96505afe973ae2de610993
|
Kunal352000/python_program
|
/c10.py
| 97 | 3.625 | 4 |
#print 1-10
for i in range(1,11):
print(i)
for i in range(1,11):
print(i,end=" ")
|
fbc89a2ae3c41b2673f6245c203c7f0f4b934b07
|
joegle/grimoire
|
/python/simple.py
| 183 | 3.859375 | 4 |
#!/usr/bin/env python2
# return the sorted array
a = [2, 3, 1]
print sorted(a)
# in place sort returning None
a.sort()
# sort by a function key
a.sort(key=str.lower, reverse=True)
|
3a02e733d8faa8be72d66fd2b012711bff96b3b3
|
Subhadarsini-10/Beg.-python
|
/beg-python.py
| 7,801 | 4.28125 | 4 |
#!/usr/bin/env python
# coding: utf-8
# <ol><p><b>math module</b></p></ol>
# In[3]:
import math
print(round(2.9))
# In[6]:
import math
print(math.ceil(2.9))
# In[7]:
import math
print(math.floor(2.9))
# In[8]:
x=2.9
print(abs(x))
# In[9]:
x=-2.9
print(abs(x))
# <p><b>if statements</b></p>
# In[3]:
is_hot=True
is_cold=True
if is_hot:
print("it's a hot day")
print("drink plenty of water")
if is_cold:
print("it's a cold day")
print("wear warm clothes")
else:
print("it's a lovely day")
print("a wonderful day")
# In[7]:
price =1000000
has_good_credit=True
if has_good_credit:
down_payment=0.1*price
else:
doen_payment=0.2*price
print(f"Down payment:",down_payment)
# <p><b>logical operator</b></p>
# In[23]:
has_high_income=False
good_credit=True
if has_high_income or good_credit:
print("eligible for loan")
# In[26]:
has_good_credit=True
has_criminal_records=False
if has_good_credit and not has_criminal_records:
print("eligible for loan")
# <p> the not operator gives the opposite of the declared statement</p>
# In[9]:
temp=40
if temp>30:
print("it's a hot day")
elif temp<10:
print("it's a cold day")
else:
print("it's neither hot nor cold")
# In[30]:
name="subha"
if len(name)<3:
print("name must be atleast 3 characters")
elif len(name)>50:
print("it can be a maximum of 50 characters")
else:
print("the name is beautiful")
# <p><b>Project:Weight converter</b></p>
# In[37]:
weight=int(input('weight:'))
unit=input('(L)bs or (K)g')
if unit.upper()=="L":
converted=weight*0.45
print(f"you are {converted} kilos")
else:
converted=weight//0.45
print(f"you are {converted} pounds")
# <p><b>while loop</b></p>
# In[3]:
i=1
while i<=5:
print('*'* i)
i+=1
print("Done")
# <p><b>guessing game</b></p>
# In[10]:
secret_number=9
guess_count=0
guess_limit=3
while guess_count < guess_limit:
guess=int(input('Guess:'))
guess_count+=1
if guess == secret_number:
print('you won!')
break
else:
print('you lost!')
# <p><b>Car game</b></p>
# In[1]:
command=""
started=False
while True:
command=input(">").lower()
if command == "start":
if started:
print("the car is already started")
else:
started=True
print("car started..")
elif command == "stop":
if not started:
print("the car is already stopped")
else:
started = False
print("car stopped.")
elif command == "help":
print("""
start-to start the car
stop-to stop the car
quit-to quit the game
""")
elif command =="quit":
break
else:
print("i don't understand")
# <p><b>For Loop</b></p>
# In[3]:
for item in 'python':
print(item)
# In[7]:
for item in range(2,10,2):
print(item)
# In[8]:
my_cart=[10,20,30]
total=0
for prices in my_cart:
total+=prices
print(f"total:",total)
# <i>Nested List</i>
# In[10]:
for x in range(4):
for y in range(3):
print(f"({x},{y})")
# In[12]:
numbers=[5,2,5,2,2]
for x_count in numbers:
print('x' * x_count)
# In[17]:
numbers=[5,2,5,2,2]
for x_counts in numbers:
output=''
for count in range(x_count):
output+='x'
print(output)
# <p><b>list</b></p>
# In[25]:
name=['subha','sara','fanny','happy']
print(name[2])
print(name[-1])
print(name[1:3])
print(name[:])
print(name[0:])
# <p><b>Write a program to find the largest number in a list.</b></p>
# In[26]:
numbers=[1,3,4,90,64,10]
max=numbers[0]
for number in numbers:
if number >max:
max=number
print(max)
# In[28]:
numbers=[1,7,4,6,4]
min=numbers[0]
for number in numbers:
if number < min:
number=min
print(min)
# <p><b>2D list</b></p>
# In[33]:
matrix=[
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in matrix:
for item in row:
print(item)
# In[52]:
numbers=[1,4,5,6,8,4]
numbers.append(13)
print(numbers)
numbers.sort()
print(numbers)
numbers.insert(0,7)
print(numbers)
numbers.remove(8)
print(numbers)
numbers.pop()
print(numbers)
print(numbers.count(4))
print(50 not in numbers)
# In[56]:
numbers=[2,3,4,3,4,6,4,3,5,6,5]
unique=[]
for number in numbers:
if number not in unique:
unique.append(number)
print(unique)
# <p><b>Tuple</b></p>
# In[3]:
number=(1,3,4,7)
print(number)
# <p>in tuple we can't do any kind insert ,append or anything,</p>
# <p><b>unpacking</b></p>
# In[5]:
coordinate=(1,2,3)
x,y,z=coordinate
print(y)
# <p><b>Dictionary</b></p>
# In[9]:
phone=input("Phone:")
digital_mapping={
"1":"one",
"2":"two",
"3":"three",
"4":"four"
}
output=""
for ch in phone:
output+=digital_mapping.get(ch,"!")+" "
print(output)
# <p><b>Functions</b></p>
# In[17]:
def greet_user():
print("hey there")
print("welcome to india")
print("start")
greet_user()
print("finish")
# <p><b>Parameters</b></p>
# In[22]:
def greet_user(name):
print(f"hi {name}")
print("a warm welcome")
print("start")
greet_user("subha")
greet_user("fany")
print("finish")
# In[25]:
def greet_user(first_name,last_name):
print(f"hi {first_name} {last_name}")
print("welcome back")
print("Start")
greet_user("subhadarsini", "pattnaik")
print("Finish")
# <p><b>Keyword arguments</b></p>
# In[26]:
def square(number):
return number*number
result=square(4)
print(result)
# <p><b>exception</b></p>
# <p>without trashing your code to get rid of valueerror just go with try and except</p>
# 1<p>ValueError</p>
# In[29]:
try:
age=int(input("Age:"))
print(age)
except ValueError:
print("invalid value")
# 2<p>ZeoDivisionError</p>
# In[30]:
try:
age=int(input('Age:'))
print(age)
income=2000
risk=income/0
except ZeroDivisionError:
print('Age cannot be 0.')
except ValueError:
print('Invalid value')
# <p><b>Constructor</b></p>
# In[63]:
class person:
def __init__(self,name):
self.name=name
def talk(self):
print("talk")
herry=person("herry smith")
print(herry.name)
herry.talk()
# <p>Create a new type called person,the person object should have name attribute as well as talk.</p>
# In[45]:
class Person:
def __init__(self,name):
self.name=name
def talk(self):
print(f"Hi,i'm {self.name}")
john=Person("john smith")
john.talk()
boby=Person("Bobby deol")
boby.talk()
# <p>Inheritance</p>
# In[52]:
class Mammal:
def walk(self):
print("walk")
class dog(Mammal):
def bark(self):
print("bark")
class cat(Mammal):
def be_annoying(self):
print("annoying")
dog1=dog()
dog1.bark()
cat1=cat()
cat1.be_annoying()
# <p><b>Generating random variables</b></p>
# <p>a task to get random values when we roll a dice.Define a class Dice and a function roll along with the tuple</p>
# In[4]:
import random
class Dice:
def roll(self):
first = random.randint(1,6)
second = random.randint(1,6)
return first,second
dice=Dice()
print(dice.roll())
# In[6]:
import random
for i in range(3):
print(random.random())
# In[11]:
import random
for i in range(3):
print(random.randint(10,20))
# <p><b>Machine Learning</b></p>
# 1-<p>import the data</p>
# 2-<p>claen the data</p>
# 3-<p>split the data into test cases</p>
# 4-<p>create a model</p>
# 5-<p>train a model</p>
# 6-<p>make preictions</p>
# 7=<p>evaluate and improve</p>
#
# <p><b>Libraries and tools</b></p>
# <p>Numpy</p>
# <p>Panadas</p>
# <p>Matplotlib</p>
# <p>Scikit Learn</p>
# In[ ]:
|
3f28b0768fa50df7d2f5b825cc64abc9fdfdcbbb
|
EhODavi/curso-python
|
/exercicios-secao07-parte1/exercicio35.py
| 879 | 3.65625 | 4 |
a = input('Informe o número a: ')
b = input('Informe o número b: ')
vetor_a = list(a[::-1])
vetor_b = list(b[::-1])
vetor_c = []
if len(vetor_a) <= len(vetor_b):
for i in range(len(vetor_b)):
vetor_c.append(vetor_b[i])
for i in range(len(vetor_a)):
vetor_c[i] = str(int(vetor_a[i]) + int(vetor_c[i]))
else:
for i in range(len(vetor_a)):
vetor_c.append(vetor_a[i])
for i in range(len(vetor_b)):
vetor_c[i] = str(int(vetor_b[i]) + int(vetor_c[i]))
for i in range(len(vetor_c)):
if int(vetor_c[i]) >= 10:
if i == len(vetor_c) - 1:
vetor_c.append(vetor_c[i][0])
else:
vetor_c[i + 1] = str(int(vetor_c[i + 1]) + int(vetor_c[i][0]))
vetor_c[i] = vetor_c[i][1]
print(f'\n{a} + {b} = ', end="")
for i in range(len(vetor_c) - 1, -1, -1):
print(vetor_c[i], end="")
print()
|
5bef4ddce4a003404320fca7a0ffaf0239f93cbb
|
Aasthaengg/IBMdataset
|
/Python_codes/p02789/s253976007.py
| 83 | 3.5 | 4 |
n, m = [int(s) for s in input().split()]
ans = "Yes" if m == n else "No"
print(ans)
|
153d539dd41961915c3d4de482d87c081b5d065f
|
adithyadn/DS-Algorithms
|
/Udacity-DS-Project1/Task1.py
| 806 | 4.0625 | 4 |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
from functools import reduce
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
flatten_texts_list = reduce(lambda z, y: z + y, list(map(lambda lst: lst[:2], texts)))
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
flatten_calls_list = reduce(lambda z, y: z + y, list(map(lambda lst: lst[:2], calls)))
teleList = set(flatten_calls_list + flatten_texts_list)
print('There are ' + str(len(teleList)) + ' different telephone numbers in the records.')
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
|
7f1554d8d3737dce79a233eda24c93180e1c8eda
|
edt-yxz-zzd/python3_src
|
/nn_ns/graph2/bucket_sort/ChainFuncs.py
| 983 | 3.8125 | 4 |
'''
example:
>>> mul = lambda x:x*2
>>> add = lambda x:x+2
>>> funcs = [mul, add]
>>> ChainFuncs(funcs)(3)
10
>>> apply(3, funcs)
8
>>> may_apply(3, [mul, None, add])
8
'''
__all__ = '''
ChainFuncs
apply
may_apply
filterout_None
'''.split()
def filterout_None(iterable):
return (x for x in iterable if x is not None)
class ChainFuncs:
# call in reversed order
def __init__(self, __mayfuncs):
self.funcs = tuple(filterout_None(__mayfuncs))
def __call__(self, __obj):
return apply(__obj, reversed(self.funcs))
def may_apply(__obj, __mayfuncs):
# __mayfuncs :: iter<callable|None>
# apply from left to right
return apply(__obj, filterout_None(__mayfuncs))
def apply(__obj, __funcs):
# __funcs :: iter<callable>
# apply from left to right
x = __obj
for f in __funcs:
x = f(x)
return x
if __name__ == "__main__":
import doctest
doctest.testmod()
|
6d071d3d524cc0722590f0507f5ed413ed0c2fb9
|
ezbins/exec_python
|
/exec10.py
| 1,510 | 3.984375 | 4 |
#!/usr/bin/env python3
# coding: utf-8
import sys
prices = []
quantities = []
total_sum = 0
tax = 0
def checkNumberic(value):
if value.isnumeric():
return int(value)
else:
print("Please input numberic.")
sys.exit()
def calcu_total(prices, quantities):
global total_sum, tax
for price, quantity in zip(prices, quantities):
total_sum = total_sum + (price * quantity)
tax = total_sum * (5.5 / 100)
return total_sum, tax
print("Enter the price of item 1:", end=' ')
input_price_1 = input()
price1 = checkNumberic(input_price_1)
prices.append(price1)
print("Enter the quantity of item 1:", end=' ')
input_quantity_1 = input()
quantity1 = checkNumberic(input_quantity_1)
quantities.append(quantity1)
print("Enter the price of item 2:", end=' ')
input_price_2 = input()
price2 = checkNumberic(input_price_2)
prices.append(price2)
print("Enter the quantity of item 1:", end=' ')
input_quantity_2 = input()
quantity2 = checkNumberic(input_quantity_2)
quantities.append(quantity2)
print("Enter the price of item 3:", end=' ')
input_price_3 = input()
price3 = checkNumberic(input_price_3)
prices.append(price3)
print("Enter the quantity of item 3:", end=' ')
input_quantity_3 = input()
quantity3 = checkNumberic(input_quantity_3)
quantities.append(quantity3)
all_total, only_tax = calcu_total(prices, quantities)
print("Subtotal ${:04.2f}".format(all_total))
print("Tax ${:04.2f}".format(only_tax))
print("Total ${:04.2f}".format(all_total + only_tax))
|
698efe743d29b80f7a4c1c768c192211bbf9ea42
|
aaryan325/Easy-to-use-calculator
|
/calculator.py
| 3,277 | 3.671875 | 4 |
import tkinter as tk
import tkinter.messagebox
root = tk.Tk()
root.title("Calculator By @AaryanSarda")
expression = ""
def add(value) :
global expression
expression += value
label_result.config(text=expression)
def clear():
global expression
expression = ""
label_result.config(text=expression)
def calculate():
global expression
result = ""
if expression != "":
try:
result = eval(expression)
label_result.config(text=result)
except:
result = "error"
expression = ""
tk.messagebox.showerror(title="Error", message="expression you entered does not have perfect terms")
label_result.config(text=result)
#Create GUI
label_result = tk.Label(root, text="")
label_result.grid(row=0, column=0, columnspan=4)
button_1 = tk.Button(root, text="1", command=lambda: add("1"), width=5)
button_1.grid(row=1, column=0)
button_2 = tk.Button(root, text="2", command=lambda: add("2"), width=5)
button_2.grid(row=1, column=1)
button_3 = tk.Button(root, text="3", command=lambda: add("3"), width=5)
button_3.grid(row=1, column=2)
button_divide = tk.Button(root, text="/", command=lambda: add("/"), width=5)
button_divide.grid(row=1, column=3)
button_4 = tk.Button(root, text="4", command=lambda: add("4"), width=5)
button_4.grid(row=2, column=0)
button_5 = tk.Button(root, text="5", command=lambda: add("5"), width=5)
button_5.grid(row=2, column=1)
button_6 = tk.Button(root, text="6", command=lambda: add("6"), width=5)
button_6.grid(row=2, column=2)
button_multiply = tk.Button(root, text="*", command=lambda: add("*"), width=5)
button_multiply.grid(row=2, column=3)
button_7 = tk.Button(root, text="7", command=lambda: add("7"), width=5)
button_7.grid(row=3, column=0)
button_8 = tk.Button(root, text="8", command=lambda: add("8"), width=5)
button_8.grid(row=3, column=1)
button_9 = tk.Button(root, text="9", command=lambda: add("9"), width=5)
button_9.grid(row=3, column=2)
button_subtract = tk.Button(root, text="-", command=lambda: add("-"), width=5)
button_subtract.grid(row=3, column=3)
button_clear = tk.Button(root, text="C", command=lambda: clear(), width=5)
button_clear.grid(row=4, column=0)
button_0 = tk.Button(root, text="0", command=lambda: add("0"), width=5)
button_0.grid(row=4, column=1)
button_decimal = tk.Button(root, text=".", command=lambda: add("."), width=5)
button_decimal.grid(row=4, column=2)
button_add = tk.Button(root, text="+", command=lambda: add("+"), width=5)
button_add.grid(row=4, column=3)
button_sq_root = tk.Button(root, text="√", command=lambda: add("**0.5"), width=5)
button_sq_root.grid(row=5, column=0)
button_sq = tk.Button(root, text="x²", command=lambda: add("**2"), width=5)
button_sq.grid(row=5, column=1)
button_cube = tk.Button(root, text="x³", command=lambda: add("**3"), width=5)
button_cube.grid(row=5, column=2)
button_cube = tk.Button(root, text="³√", command=lambda: add("**(1/3)"), width=5)
button_cube.grid(row=5, column=3)
button_equals = tk.Button(root, text="=", width=25, command=lambda: calculate())
button_equals.grid(row=7, column=0, columnspan=4)
root.mainloop()
|
89d7b2d75353ac4d05494bff27bd6c2426e8a7a0
|
kirumalai/python
|
/player1.py
| 113 | 4.21875 | 4 |
def reverse(string):
string="".join(reversed(string))
return string
s=input()
print(reverse(s))
|
03016ee3901fdcbb8f2f7938887229af66d6e34c
|
Ayman-Yahia/CodingDojo-Python
|
/Python_Assignments/3.py
| 129 | 3.796875 | 4 |
def count_substring(string,sub_string):
count=string.count(sub_string)
print(count)
count_substring('ABSHIZLMSHIZ','HIZ')
|
6b2b7ecb06f7702ff0836c9c5ec9ba60373fe24f
|
aswathiedayillyam/luminarpython
|
/flowcontrolls/loopingstmts/sumofnumbers.py
| 115 | 3.59375 | 4 |
limit=int(input("enter limit"))#10
#sum of 1 to 10
i=1
sum=0
while(i<=limit):
sum=sum+1
i+=1
print(sum)
|
4b735f8a0cc6880967b629d05d895d882064831f
|
aditya8081/Project-Euler
|
/problem2.py
| 410 | 3.734375 | 4 |
x=0
y=1 #Starts with the two first fibonacci numbers
sum=0 # initializes a sum variable
while y < 4000000: # while the fibonacci term is less than 4 million
z=x+y # find the next term
if z%2 == 0:
sum += z # add it to the sum if it is even
x=y #refresh the variables for the next iteration
y=z
print sum
|
759582d81c8b63cae27770c4683662f5a9ec8a45
|
iyerikuzwe/Password-Locker1
|
/credentials_test.py
| 2,741 | 3.765625 | 4 |
import unittest
from credentials import Credentials
class TestCredentials(unittest.TestCase):
'''
Test class that defines test cases for the credentials class behaviours.
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_credentials = Credentials("Fb", "12@34")
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_credentials.acc_name,"Fb")
self.assertEqual(self.new_credentials.acc_password, "12@34")
def test_save_credentials(self):
'''
test_save_credentials test case to test if the credentials object is saved into the list_of_creds
'''
self.new_credentials.save_credentials() # saving the new credentials
self.assertEqual(len(Credentials.list_of_creds), 1)
def test_save_several_credentials(self):
'''
test_save_several_credentials method adds new multiple credentials to list_of_creds
'''
self.new_credentials.save_credentials()
test_credentials = Credentials("Pinterest", "56@78") # new credential
test_credentials.save_credentials()
self.assertEqual(len(Credentials.list_of_creds), 2)
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
Credentials.list_of_creds = []
def test_delete_credentials(self):
'''
test_delete_credentials to test if we can remove a credential from our list of credentials
'''
self.new_credentials.save_credentials()
test_credentials = Credentials("Pinterest", "56@78") # new credential
test_credentials.save_credentials()
self.new_credentials.delete_credentials() # Deleting a credentials object
self.assertEqual(len(Credentials.list_of_creds), 1)
def test_find_credentials_by_name(self):
'''
test to check if we can find a credentials by nameand display information for user
'''
self.new_credentials.save_credentials()
test_credentials = Credentials("Pinterest", "56@78") # new credential
test_credentials.save_credentials()
found_credentials = Credentials.find_by_name("Pinterest")
self.assertEqual(found_credentials.acc_name, test_credentials.acc_name)
def test_display_all_credentials(self):
'''
method that returns a list of all credentials saved
'''
self.assertEqual(Credentials.display_credentials(), Credentials.list_of_creds)
if __name__ == '__main__':
unittest.main()
|
3da168ec89c1b823ea198ab36fe84173438968c4
|
terracenter/Python3-CodigoFacilito
|
/Scripts/Variables/Listas.py
| 862 | 4.40625 | 4 |
#Parentisis cuadrados significa listas
#Soporta cualquier tipo de datos.
myList = ["String", 15, 15.6, True]
print(myList)
print()
print()
#Pueden crecer o decrecer
#Agregar
myList.append(6) #Lo colca en la parte final
print(myList)
print()
print()
myList.insert(1, "Insert") #Agrega un elemento en una posicion dada
print(myList)
print()
print()
print(myList[1]) #Acceder a un elemento
print()
print()
#Eliminar
myList.remove(6) #Elimina el 6
print(myList)
print()
print()
#Ultimo valor
lastValue = myList.pop()
print(myList)
print(lastValue)
print()
print()
#Ordenar solo entero
myListInteger = [1,5,4,2,4,5,6]
print(myListInteger)
myListInteger.sort()
print(myListInteger)
print()
print()
#Como unir dos listas
myList01 = [1, 2, 3, 5]
myList02 = [11, 21, 31, 51]
myList01.extend(myList02)
print(myList01)
print()
#Una lista puede almacenar otra lista.
|
f3de2b4d8e496d458dc9a305b0274dd69bb7225e
|
hastorojas/prueba100
|
/ejercicio_lista.py
| 382 | 3.90625 | 4 |
try:
lista=[]
cant = int(input('De que tamaño quieres tu lista: '))
i = 0
while i < cant:
valor = input('Agregue un nombre a la lista: ')
lista.append(valor)
i = i + 1
print('El listado es el siguiente: ')
print(lista)
except Exception as ex:
print('Hubo un problemilla; '+str(ex))
finally:
print('Se termino de ejecutar')
|
a8b46694da414165e907143e863ddf2171a03446
|
sandipan898/crash-course-on-python-coursera-codes
|
/basic-syntax/expressions-variables/eg-4.py
| 195 | 4.0625 | 4 |
"""
This code is supposed to display "2 + 2 = 4" on the
screen, but there is an error. Find the error in the
code and fix it, so that the output is correct.
"""
print("2 + 2 = " + str(2 + 2))
|
a6c955edfabaf3d952c98aa0886d0f346604c1a8
|
adarsh0806/anProjects
|
/Projects/unit2/lesson1/project1/stats.py
| 1,326 | 3.578125 | 4 |
import pandas as pd
data = '''Region, Alcohol, Tobacco
North, 6.47, 4.03
Yorkshire, 6.13, 3.76
Northeast, 6.19, 3.77
East Midlands, 4.89, 3.34
West Midlands, 5.63, 3.47
East Anglia, 4.52, 2.92
Southeast, 5.89, 3.20
Southwest, 4.79, 2.71
Wales, 5.27, 3.53
Scotland, 6.08, 4.51
Northern Ireland, 4.02, 4.56'''
data = data.splitlines()
#data.split('\n')
#print data
data = [i.split(', ') for i in data]
col_names = data[0]
#print "col_names",col_names
data_rows = data[1::]
df = pd.DataFrame(data_rows, columns = col_names)
df['Alcohol'] = df['Alcohol'].astype(float)
df['Tobacco'] = df['Tobacco'].astype(float)
print "\nThe mean Alcohol consumption is:",df['Alcohol'].mean()
print "\nThe median Alcohol consumption is:",df['Alcohol'].median()
#stats.mode(df['Alcohol'])
print "\nThe mean Tobacco consumption is:",df['Tobacco'].mean()
print "\nThe median Tobacco consumption is:",df['Tobacco'].median()
#stats.mode(df['Tobacco'])
max(df['Alcohol']) - min(df['Alcohol'])
print "\nThe standard deviation of Alcohol consumption is:",df['Alcohol'].std()
print "\nThe variance Alcohol of consumption is:",df['Alcohol'].var()
max(df['Tobacco']) - min(df['Tobacco'])
print "\nThe standard deviation of Tobacco consumption is:",df['Tobacco'].std()
print "\nThe variance of Tobacco consumption is:",df['Tobacco'].var()
|
51bfa70aa9921e4643ac6e66e07ad13d7dca15e5
|
ravalrupalj/BrainTeasers
|
/Edabit/Profit_Margin.py
| 636 | 4.09375 | 4 |
#Profit Margin
#Create a function that calculates the profit margin given cost_price and sales_price. Return the result as a percentage formated string, and rounded to one decimals. To calculate profit margin you subtract the cost from the sales price, then divide by salesprice.
#Remember to return the result as a percentage formated string.
#Only one decimal should be included.
def profit_margin(cost_price, sales_price):
t=((sales_price-cost_price)/sales_price)*100
return str(round(t,1))+'%'
print(profit_margin(50, 50) )
#➞ "0.0%"
print(profit_margin(28, 39) )
#➞ "28.2%"
print(profit_margin(33, 84) )
#➞ "60.7%"
|
9f30ad4ecba66e5da6cbd8126ac6da82175ef3c5
|
Planetfunky/CodiGo
|
/Python/condicionales04.py
| 231 | 3.71875 | 4 |
weight = int(input('Weight: '))
metric = input('(L)bs or (K)g: ').lower()
if metric == 'k':
converted = weight / 0.45
print(f'You are {converted} kilos')
else:
converted = weight * 0.45
print(f'You are {converted} kilos')
|
6f17d70cdd29448a45dad0b6668b49e7e8484485
|
CvetelinaS/pyladies
|
/02/heslo.py
| 167 | 3.921875 | 4 |
heslo = input('Zadej heslo:')
print (heslo=='cokolada')
if heslo =='cokolada':
print('Spravne! Racte dale!')
else:
print ('Spatne!')
print('ALARM!' * 3)
|
d67e64c0beb255a72d14317c94f399af905bb05a
|
mtahir08/pythonDemo
|
/level-01/question-4.py
| 434 | 3.984375 | 4 |
#####################
## -- PROBLEM 4 -- ##
#####################
# Given a string, return a string where for every char in the original,
# there are two chars.
# doubleChar('The') → 'TThhee'
# doubleChar('AAbb') → 'AAAAbbbb'
# doubleChar('Hi-There') → 'HHii--TThheerree'
def doubleChar(str):
# CODE GOES HERE
new_str = ""
for i in str:
new_str += i+i
return new_str
result = doubleChar('AAbb')
print(result)
|
dff9eceb254322fb4b8b542a23a7952385c299f6
|
daniel-reich/ubiquitous-fiesta
|
/EL3vnd5MWyPwE4ucu_3.py
| 135 | 3.953125 | 4 |
def fibonacci(n):
numbers = [0,1]
for i in range(2,n+1):
numbers.append(numbers[i-2]+numbers[i-1])
return str(numbers[-1])
|
7c3f268041f3c315c0f7102122e4fb5b9bd77629
|
samurai-yuji/word_count_test
|
/yuji_lib.py
| 180 | 3.75 | 4 |
import random
def make_word(size):
words="abc"
new=[]
for i in range(0,size):
i=int(random.random()*3)
new.append(words[i])
return "".join(new)
|
d69aee42e1b1dc808fa1659f265da13f291f4caf
|
andismail/python-basic
|
/py_native_datatype_string.py
| 11,480 | 4.46875 | 4 |
# +A string is a sequence of characters.
# A character is simply a symbol. For example, the English language has 26 characters.
# Computers do not deal with characters, they deal with numbers (binary). Even though you
# may see characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's.
# This conversion of character to a number is called encoding, and the reverse process is
# decoding. ASCII and Unicode are some of the popular encoding used.
# In Python, string is a sequence of Unicode character. Unicode was introduced to include
# every character in all languages and bring uniformity in encoding. You can learn more about Unicode from here.
# +How to create a string?
my_string = 'Hello'
my_string1 = "Hello"
my_string2 = '''Hello'''
# triple quotes string can extend multiple lines
my_string3 = """Hello, welcome to
the world of Python"""
# +How to access characters in a string?
# We can access individual characters using indexing and a range of characters using slicing.
str = 'programiz'
print('str = ', str)
print('str[0] = ', str[0]) # first character
print('str[-1] = ', str[-1]) # last character
print('str[1:5] = ', str[1:5]) # slicing 2nd to 5th character
print('str[5:-2] = ', str[5:-2]) # slicing 6th to 2nd last character
# +How to change or delete a string?
# Strings are immutable. This means that elements of a string cannot be changed once it has been assigned.
# But we can simply reassign different strings to the same name.
my_string4 = 'programiz'
my_string4[5] = 'b' # TypeError: 'str' object does not support item assignment
# We also can't delete or remove characters from a string.
# But deleting the string entirely is possible using the keyword del.
del my_string[1] # TypeError: 'str' object doesn't support item deletion
# +Python String Operations
# -Concatenation of Two or More Strings
str1 = 'Hello'
str2 = 'World!'
print('str1 + str2 = ', str1 + str2) # using +
print('str1 * 3 =', str1 * 3) # using *
# Iterating Through String
count = 0
for letter in 'Hello World':
if (letter == 'l'):
count += 1
print(count, 'letters found')
# String Membership Test
is_in = 'a' in 'program'
is_not_in = 'at' not in 'program'
# Built-in functions to Work with Python
# Various built-in functions that work with sequence, works with string as well.
# Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object.
# It contains the index and value of all the items in the string as pairs. This can be useful for iteration.
# Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
str_enum = enumerate(str) # enumerate()
print('list(enumerate(str) = ', list(str_enum))
print('len(str) = ', len(str)) # character count
# +Python String Formatting
# -Escape Sequence(转义序列)
print('He said, "What\'s there?"')
print("He said, \"What's there?\"")
print('''He said, "What's there?"''')
print("This is printed\nin two lines")
# +Raw String to ignore escape sequence(原始字符串)
print("This is \x61 \ngood example")
print(r"This is \x61 \ngood example")
# +The format() Method for Formatting Strings
# default(implicit) order
default_order = "{}, {} and {}".format('John', 'Bill', 'Sean')
print(default_order) # --- Default Order ---
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John', 'Bill', 'Sean')
print(positional_order) # --- Positional Order ---
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John', b='Bill', s='Sean')
print(keyword_order) # --- Keyword Order ---
# +Specifications format
"Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
"Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
# +Old format
x = 12.3456789
print('The value of x is %3.2f' % x) # The value of x is 12.35
print('The value of x is %3.4f' % x) # The value of x is 12.3457
# +String Method
#
# str.strip()
'0000000this is string example....wow!!!0000000'.strip('0') # output :'this is string example....wow!!!'
'www.example.com'.strip('w.moc') # output: 'example'
' py '.strip() # output: 'py'
# str.lstrip()
# str.rstrip()
'python'.capitalize() # output: Python
# Return a copy of the string with its first character capitalized and the rest lowercased.
#
# str.center(width[, fillchar])
'python'.center(10,'*') # output: '**python**'
# Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space).
# The original string is returned if width is less than or equal to len(s).
#
# str.count(sub[, start[, end]])
'python3.6'.count('3') # output: 1
# Return the number of non-overlapping occurrences of substring sub in the range [start, end].
# Optional arguments start and end are interpreted as in slice notation.
#
#str.startswith(prefix[, start[, end]])
'python3.6'.startswith('t',2)
# Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.
# With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
#
# str.endswith(suffix[, start[, end]])
'python3.6'.endswith('3',0,-2)
# Return True if the string ends with the specified suffix, otherwise return False.
# suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position.
# With optional end, stop comparing at that position.
#
# str.find(sub[, start[, end]])
'python3.6'.find('3') # output 6
# Return the lowest index in the string where substring sub is found within the slice s[start:end].
# Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
#
# str.rfind(sub[, start[, end]])
'abacadef'.rfind('a') # output: 4
# Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end].
# Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
#
# str.index(sub[, start[, end]])
'python3.6'.index('3') # output 6
# Like find(), but raise ValueError when the substring is not found. ValueError: substring not found
#
# str.rindex(sub[, start[, end]])
'abacadef'.rindex('a') # output: 4
# Like rfind() but raises ValueError when the substring sub is not found.
#
# str.isalnum()
'python3.6'.isalnum() # True
# Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
# A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().
#
# str.isalpha()
'python3.6'.isalpha() # False
# Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
#
# str.isdecimal()
'python3.6'.isdecimal() # False
# Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. 10!!
#
# str.isdigit()
'python3.6'.isdigit() # False
# Return true if all characters in the string are digits and there is at least one character, false otherwise.
# Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits.
#
# str.isidentifier()
# Return true if the string is a valid identifier according to the language definition.
#
# str.islower()
'python3.6'.islower()
# Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
#
# str.lower()
'PYTHON3.6'.lower() # 'python3.6'
# Return a copy of the string with all the cased characters [4] converted to lowercase.
#
# str.isupper()
'python3.6'.isupper()
# Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise.
#
# str.upper()
'python3.6'.isupper()
# Return a copy of the string with all the cased characters [4] converted to uppercase.
# Note that str.upper().isupper() might be False
#
# str.isnumeric()
# Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise.
#
# str.isspace()
' '.isspace() # True
#
#
# str.istitle()
'I Am A Title'.istitle()
# Return true if the string is a titlecased string and there is at least one character,
# for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
#
# str.join(iterable)
','.join(['1', '2', '3', '4', '5'])
# Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values
# in iterable, including bytes objects. The separator between elements is the string providing this method.
#
# str.ljust(width[, fillchar])
'python3.6'.ljust(15,'*') # output: 'python3.6******'
# Return the string left justified in a string of length width. Padding is done using the specified
# fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
#
# str.rjust(width[, fillchar])
'python3.6'.rjust(15,'*') # output: '******python3.6'
# Return the string right justified in a string of length width. Padding is done using the specified
# fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
#
# str.partition(sep)
# str.rpartition(sep)
'abcdef'.partition('abc') # output :('', 'abc', 'def')
# Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator,the separator itself,
# and the part after the separator.If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
#
# str.replace(old, new[, count])
'abacadef'.replace('a','A', 2) # output: 'AbAcadef'
# Return a copy of the string with all occurrences of substring old replaced by new.
# If the optional argument count is given, only the first count occurrences are replaced.
#
# str.split(sep=None, maxsplit=-1)
# str.rsplit(sep=None, maxsplit=-1)
'1,1,1,1,1'.split(',',1) # ['1', '1,1,1,1']
'1,1,1,1,1'.rsplit(',',1) # ['1,1,1,1', '1']
# Return a list of the words in the string, using sep as the delimiter string.
# If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).
# If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
#
# str.swapcase()
'Python3.6'.swapcase() # output: 'pYTHON3.6'
# Return a copy of the string with uppercase characters converted to lowercase and vice versa.
# Note that it is not necessarily true that s.swapcase().swapcase() == s.
# Truth Value Testing
# Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.
# The following values are considered false:
# None
# False
# zero of any numeric type, for example, 0, 0.0, 0j.
# any empty sequence, for example, '', (), [].
# any empty mapping, for example, {}.
# instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.
# check string is empty or all whitespace or None
s = 'str'
if not isinstance(s,str) or not s or s.isspace(): print(s + ' is empty or None or all whitespace')
|
5fbf3aeebfc1b8b53745fcd9743f5760cf00a006
|
CP-Unibo/sunny-cp
|
/src/features.py
| 2,966 | 3.546875 | 4 |
'''
Module for defining a feature extractor that computes the feature vector of a
problem. A feature extractor is simply a class that implements the static
method extract_features(args) to return the feature vector.
The default extractor is mzn2feat, but the user can define its own extractor by
simply implementing a corresponding new class (see example below).
Actually using a static class is no more powerful than using only functions.
This is done for keeping all the auxiliary functions in the same class and for
possible future extensions.
'''
from math import isnan
from subprocess import PIPE
import os
import json
import psutil
class mzn2feat:
@staticmethod
def extract_features(args):
problem = args[0]
not_norm_vector = mzn2feat.extract(problem)
if not not_norm_vector:
return None
with open(args[1], 'r') as infile:
lims = json.load(infile)
return mzn2feat.normalize(not_norm_vector, lims)
@staticmethod
def extract(problem):
"""
Extracts the features from a MiniZinc model by exploiting the mzn2feat
features extractor.
"""
mzn_path = problem.mzn_path
dzn_path = problem.dzn_path
cmd = 'mzn2feat -i ' + mzn_path
if dzn_path:
cmd += ' -d ' + dzn_path
proc = psutil.Popen(cmd.split(), stdout=PIPE)
(out, err) = proc.communicate()
# Failure in features extraction.
if proc.returncode != 0:
return []
feat_vector = [float(f) for f in out.decode().split(",")]
return feat_vector
@staticmethod
def normalize(feat_vector, lims, lb=-1, ub=1, def_value=-1):
"""
Given a feature vector, it returns a normalized one in which constant
features are removed and feature values are scaled in [lb, ub] by
exploiting the information already computed in lims dictionary.
"""
norm_vector = []
# if not limits are defined then return the feature vector
if len(lims) == 0:
return feat_vector
for i in range(0, len(feat_vector)):
j = str(i)
if lims[j][0] != lims[j][1]:
val = float(feat_vector[i])
if isnan(val):
val = def_value
min_val = float(lims[j][0])
max_val = float(lims[j][1])
if val <= min_val:
norm_val = lb
elif val >= max_val:
norm_val = ub
else:
x = (val - min_val) / (max_val - min_val)
norm_val = (ub - lb) * x + lb
assert lb <= norm_val <= ub
norm_vector.append(norm_val)
return norm_vector
'''
# Example.
class new_extractor:
@staticmethod
def extract_features(args):
#args parsing and processing
...
return feature_vector
'''
|
30a1bf3451fe345ab820d5c89b6b729bf0039108
|
okadakousei/Education-Project-for-newcomer
|
/submit/age_guess/age_guess_ogi.py
| 606 | 3.515625 | 4 |
b=50
for t in range (100):
print("are you older than "+str(b)+"?")
a=input("input yes or no:",)
if a=="yes":
for i in range (1,10):
c=input("are you older than "+str(d)+"? input yes or no:",)
d=50+b/2
if c=="yes":
print("you are "+str(d)+"!")
else:
None
elif a=="no":
for i in range (1,10):
e=input("are you older than "+str(d)+"? input yes or no:",)
d=50-b/2
if e=="yes":
print("you are "+str(d)+"!")
else:
None
|
5fddc4e911c443da36d12c1ef4dab0b6a02eb3d9
|
matheusglemos/Python_Udemy
|
/Conceitos básicos de estrutura de dados e objetos em Python/Dicionarios/dicionario.py
| 2,229 | 4.46875 | 4 |
# Projeto em python 3 referente a aula 16 do Curso python da plataforma Udemy.
# Objetos
dados = {'nome':'Matheus','idade':'21','status':'namorando'}
d = {'anos':{'meses':{'dias':'minutos'}}}
dic_01 = {'chave_01':123,'chave_02':[12,23,33],'chave_03':['item0','item1','item2']}
dic_02 = {}
# Construindo um dicionário
# sintaxe = {"key":"value"}'
# Exibindo o valor associado a uma chave do meu dicionário, resultado '['item0','item1','item2']'
print(dic_01['chave_03'])
# Exibindo o valor associado ao índice 1 da chave 3 do dicionário, resultado 'item1'
print(dic_01['chave_03'][1])
# Exibindo saida usando métodos nos itens, resultado 'MATHEUS'
print(dados['nome'].upper())
# Alterando valores através das chaves
# Modificando o status de relacionamento, resultado 'casado'
dados['status'] = 'casado'
print(dados['status'])
# Criando chaves por atribuição
# Começando com um dicionário vazio, poderíamos adicionar-lhe continuamente, resultado '{'cachorro': 'ringo','raca': 'Pastor Alemão'}'
dic_02['cachorro'] ='ringo'
dic_02['raca'] ='Pastor Alemão'
print(dic_02)
# Aninhamento de dicionários
# Exibindo o valor 'MINUTOS' que está dentro do dicionário dias, o dicionário dias está dentro do dicionário meses, o dicionário meses está dentro do dicionario anos que por sua vez está dentro do dicionario dic_aninhados
# resultado 'MINUTOS'
print(d['anos']['meses']['dias'].upper())
# Métodos para dicionários
# Método 'keys', retorna uma lista com todas as chaves associadas ao dicionário
# resultado '['status','idade','nome']', OBS: dicionários não possuem ordem, já que os valores são associados as suas chaves e não à posições.
print(dados.keys())
# Método 'values', retorna uma lista com todos os valores associados ao dicionário
# resultado '['casado','21','Matheus']', OBS: dicionários não possuem ordem, já que os valores são associados as suas chaves e não à posições.
print(dados.values())
# Método 'itens', retorna tuplas de todos os itens (key,value)
# resultado '[('status', 'casado'),('idade', '21'),('nome', 'Matheus')]', OBS: dicionários não possuem ordem, já que os valores são associados as suas chaves e não à posições.
print(dados.items())
|
de9de2f1e58fe6ca656375870f99ff650ade830f
|
Fox5113/Compression
|
/_compression.py
| 274 | 3.578125 | 4 |
#!/bin/python3
if __name__ == '__main__':
a = list(map(int, input("Введите список для сжатия ").split()))
count_zero = a.count(0)
while count_zero > 0 :
d = a.remove(0)
count_zero -= 1
a.append(0)
print(a)
|
71393994164d88eb86be3e7b1f4bc80b39911673
|
Amankhalsa/Aman_code-html-php-python
|
/preet/Loop/w3_nested_for_5.py
| 163 | 3.765625 | 4 |
'''
Created on Apr 22, 2021
@author: hp
'''
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
|
a623945ebbc5f46dc7588360ce161b3120ba641f
|
Danny-Dasilva/Search_Biopython
|
/split_sentence.py
| 288 | 3.546875 | 4 |
import re
s = """Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't."""
m = re.split(r'(?<=[^A-Z].[.?]) +(?=[A-Z])', s)
for i in m:
print(i)
|
0cf5eb5894084e9f2faa115ebf380d406c1f20aa
|
MoAbd/codedoor3.0
|
/student_id.py
| 1,030 | 3.640625 | 4 |
"""
Given a school with a number of classes. Every class has a specific number of students in it. Students are sorted alphabetically inside classes and among them. Every student has a local id, which is his index in the class If we sort it alphabetically, and a global id which is its index among the school. ID’s always start from 1. Given a list of numbers of students in each class, and the global id of a student. what is the local id of that student?
Input Format
N(student global id) M(Number of classes)
A space seperated list of number of students in each class
Constraints
1 <= N < total number of students
1 <= M < 1000
1 <= number of students in a class < 1000
Output Format
a single number containing the student local id
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, clas = raw_input().split()
n, clas = [int(n), int(clas)]
c = [int(i) for i in raw_input().split()]
def classes(n,c,clas):
for i in c :
if n <= i :
return n
else:
n = n-i
print(classes(n,c,clas))
|
ca0a127de2ac1a3c587125706520716e0b673633
|
harshonyou/SOFT1
|
/week4/Answer/week04exercise1.py
| 1,638 | 4.4375 | 4 |
# For the three exerices, you should refactor the code you wrote in week 3
# 1- Write a function sum_all(n) that returns the sum of the first n positive
# natural numbert. The function should return -1 if n<0.
def sum_all(n):
if n < 0:
return -1
total = 0
for value in range(n):
total += value
return total
number = 5
print('The sum of the first', number, 'natural number is:', sum_all(number))
# 2- Write a mul_table(n) that prints the multiplication table of the number n
# (see below). The function should print an error message if n<0.
# 1 x 3 = 3
# 2 x 3 = 6
# ...
# 10 x 3 = 30
# Note, you could have a much simpler implementation if you don't mind a messy table
# You should read the page about string formating at:
# https://realpython.com/python-formatted-output/
# to understand the code below
def mul_table(number):
if number < 0:
print("Error: the number should be a positive natural number!")
number_length = len(str(number)) # value used to have a nice table formating
table = ''
for i in range(1, 11):
table += '{0:>2d} x {1} = '.format(i, number)
# create formatting for the right hand side of the -= in table
formatting =('{0:>' + str(number_length + 1) + 'd}\n')
table += formatting.format(number * i)
print(table)
mul_table(3) # calling/invoking the function mul_table
# 3- Write a function factorial(n) that returns n!. The function should return
# -1 if n < 0.
def factorial(number):
fact = 1
for i in range(1, number + 1):
fact *= i
return fact
n = 6
print(str(n) + '! =', factorial(n))
|
620e63b0c494ef42092870addb0ac24dd6ba769a
|
nitya108/leetcode
|
/max_path_sum_trees.py
| 875 | 3.515625 | 4 |
# Input: [-10,9,20,null,null,15,7]
# -10
# / \
# 9 20
# / \
# 15 7
# Output: 42
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def maxutil(root):
if root is None:
return 0
l = maxutil(root.left)
r = maxutil(root.right)
maxsingle=max(max(l,r)+root.val,root.val)
maxtop=max(maxsingle,l+r+root.val)
maxutil.res=max(maxutil.res,maxtop)
return maxsingle
maxutil.res=float('-inf')
maxutil(root)
return maxutil.res
|
295c8f77a7cc754862f64c1d0e45523867a64bd8
|
osasanchezme/skyciv-pip
|
/src/skyciv/utils/helpers.py
| 1,711 | 3.59375 | 4 |
import copy
import types
def clone(dict: dict) -> dict:
"""Create a deep clone of a dictionary or array.
Args:
dict (dict): The dictionary to clone.
Returns:
dict: A clone of the input dictionary.
"""
return copy.deepcopy(dict)
def next_object_key(dict: dict) -> int:
"""Gets next available numerical key in an object starting from 1.
Args:
dict (dict): The dictionary of which to get the next available key.
Returns:
int: The next a available integer.
"""
nextKey = 1
keys = dir(dict)
while str(nextKey) in keys:
nextKey += 1
return nextKey
def has_get_method(dict: dict) -> bool:
"""Check if custom get method is present
Args:
dict (dict): The object to check.
Returns:
bool: Whether there is a custom get method.
"""
get_method = getattr(dict, "get", None)
if callable(get_method):
if get_method != None and not isinstance(get_method, types.BuiltinFunctionType):
# s3d_model[k] = v.get()
return True
return False
def keyvals(obj: dict) -> list[list]:
"""Return the key value pairs of a class or dictionary.
Args:
obj (dict): A class or dictionary.
Returns:
list[list]: An array of keyvalue pairs
"""
if type(obj) is dict:
return obj.items()
else:
return vars(obj).items()
def keys(obj: dict) -> list[list]:
"""Return the keys of a class or dictionary.
Args:
obj (dict): A class or dictionary.
Returns:
list[list]: An array of keys
"""
if type(obj) is dict:
return obj.keys()
else:
return vars(obj).keys()
|
1628cf4017354ea88ac9dc42165b3f51074a1219
|
amlinger/AdventOfCode
|
/2016/python/day02/part1.py
| 2,961 | 4.28125 | 4 |
"""
Advent of code 2016 - Day 2, Part 1
Bathroom security
===
You arrive at Easter Bunny Headquarters under cover of darkness. However, you
left in such a rush that you forgot to use the bathroom! Fancy office buildings
like this one usually have keypad locks on their bathrooms, so you search the
front desk for the code.
"In order to improve security," the document you find says, "bathroom codes
will no longer be written down. Instead, please memorize and follow the
procedure below to access the bathrooms."
The document goes on to explain that each button to be pressed can be found by
starting on the previous button and moving to adjacent buttons on the keypad: U
moves up, D moves down, L moves left, and R moves right. Each line of
instructions corresponds to one button, starting at the previous button (or,
for the first line, the "5" button); press whatever button you're on at the end
of each line. If a move doesn't lead to a button, ignore it.
You can't hold it much longer, so you decide to figure out the code as you walk
to the bathroom. You picture a keypad like this:
1 2 3
4 5 6
7 8 9
Suppose your instructions are:
ULL
RRDDD
LURDL
UUUUD
You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and
stay on "1"), so the first button is 1.
Starting from the previous button ("1"), you move right twice (to "3") and then
down three times (stopping at "9" after two moves and ignoring the third),
ending up with 9. Continuing from "9", you move left, up, right, down, and left,
ending with 8. Finally, you move up four times (stopping at "2"), then down
once, ending with 5.
So, in this example, the bathroom code is 1985.
Your puzzle input is the instructions from the document you found at the front
desk. What is the bathroom code?
"""
import fileinput
import operator as op
def within(pos, keypad):
return (pos[0] >= 0 and pos[0] < len(keypad)) and \
(pos[1] >= 0 and pos[1] < len(keypad[pos[0]])) and \
keypad[pos[0]][pos[1]] is not None
# Vector operations.
def vect_add(vect1, vect2): return map(op.add, vect1, vect2)
default_keypad = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def bathroom_security(keypad, description):
# Starting in the middle, at 5, by finding the index of 5
pos = next([i, s.index(5)] for i, s in enumerate(keypad) if 5 in s)
direction_map = {
'L': [ 0, -1],
'R': [ 0, 1],
'D': [ 1, 0],
'U': [-1, 0]}
code = ""
for line in description:
for direction in line.strip():
new_pos = vect_add(pos, direction_map[direction])
if within(new_pos, keypad):
pos = new_pos
code = code + str(keypad[pos[0]][pos[1]])
return code
# Sanity check
assert bathroom_security(default_keypad, ["ULL", "RRDDD", "LURDL", "UUUUD"]) \
== "1985"
if __name__ == '__main__':
print bathroom_security(default_keypad, fileinput.input())
|
eda32f156fea6fd35c9e9916cbcc1ae08eff8a7b
|
MNikov/Python-Advanced-September-2020
|
/Old/Python-Advanced-Preliminary-Homeworks/Tuples and Sets/02E. Sets of Elements.py
| 427 | 3.671875 | 4 |
def fill_sets(n, m):
n_set = set()
m_set = set()
counter = 1
for _ in range(n + m):
number = int(input())
if counter <= n:
n_set.add(number)
else:
m_set.add(number)
counter += 1
return n_set.intersection(m_set)
def print_result(result_set):
[print(i) for i in result_set]
n, m = [int(i) for i in input().split()]
print_result(fill_sets(n, m))
|
de8970866d90269d318cf437fe50865482f25379
|
supriyo-pal/Joy-Of-Computing-Using-Python-All-programms
|
/Push the zero.py
| 346 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 11:10:47 2020
@author: Supriyo
"""
a = list(map(int,input("\nEnter the numbers : ").strip().split()))
def move_zero(num_list):
a = [0 for i in range(num_list.count(0))]
x = [ i for i in num_list if i != 0]
x.extend(a)
return(x)
call=move_zero(a)
print(*call,sep=' ')
|
82cf112ca3c8154091d2c353f7430a2d1b76195e
|
petpetshoy/comp_272
|
/lab_5/skeleton_TCPWebServer.py
| 1,985 | 3.953125 | 4 |
#import socket module
from socket import *
#choose a port from 1024 -> 65535 to listen on and
#assign to variable serverPort
#--TODO--
#Create TCP welcoming socket
#Notice the use of SOCK_STREAM for TCP
serverSocket = socket(AF_INET, SOCK_STREAM)
#Bind the port and prepare the socket to
#listen for client requests (maximum 1)
#--TODO--
#Server is ready for requests
print 'Server is listening for requests...'
while True:
#Request received, do three-way handshake,
#and make a new connectionSocket
#--TODO--
try:
#Fetch the message from the socket (use 1024 bytes buffer size)
#--TODO--
#---Start of Parsing HTTP request (Do not edit this section) ---
#Extract the path of the requested object from the message
#Path is second part of the HTTP header, identified by [1]
filename = message.split()[1]
#Because the extracted path of the HTTP request includes a
# '\' character, we read the path from the second character
f = open(filename[1:])
#store the entire content of the requested file in a
#temporary buffer
outputdata = f.read()
#--------------- End of Parsing HTTP request --------------------
#Send the proper HTTP response header line to the connectionSocket
#--TODO--
#Send the content of the requested file
#to the connectionSocket
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
#close the connectionSocket to this client
#--TODO--
except IOError:
#Problem fetching the file
#Send a proper HTTP response message:
#a) Send proper status code and phrase in header
#b) Send html page with '404 File Not Found'
#--TODO--
#close the connectionSocket to this client
#--TODO--
|
f891c7d4ee47dde1deec49529f383e8cc2006c17
|
nitinsurya/MinorProjects
|
/NeuralNetworks/hw1/Test.py
| 571 | 3.65625 | 4 |
import random
import matplotlib.pyplot as plt
import numpy as np
def plotPoints( ):
list_of_lists = [[1, 2], [3, 3], [4, 4], [5, 2]]
x_list = [x for [x, y] in list_of_lists]
y_list = [y for [x, y] in list_of_lists]
# plt.plot([1,2], [2,3], 'or')
# plt.plot([1,2], [3,4], 'ob')
plt.scatter(1,2, color='r')
plt.scatter(2,3, color='b')
plt.axis([0, 5, 0, 5])
#plt.plot([2,3], 'b')
plt.show(block=True)
def printme( str ):
#"This prints a passed string into this function"
print (str)
return
printme("hello")
plotPoints()
|
0abf66bb1c93031d7b16a2e21436030010f30b40
|
gaurihatode23/Assignment-1
|
/Task1.py
| 990 | 3.734375 | 4 |
#Question1 of Task 1
a=10,;b=20.1;c='New York'
#Question2 of Task 1
d=(2j+3)
a,d=d,a
#Question3 of Task 1
x=20,y=30
Result=x
x=y
y=Result
Print("Value of x after swapping",x)
Print("Value of y after swapping",y)
#Question4 of Task 1
#python version2x
input1=raw_input("Enter a number of your choice")
print input1
#python version3x
input1=eval(input("Enter a number of your choice"))
print input1
#Question5 of Task 1
#part1
x=input("Enter a number in between1-10:")
y=input("Enter a number in between1-10:")
z=x+y
print("Value of z is:")
#part2
z=9
z+=30
print("Value of z is:",z)
#Question6 of Task 1
x=input("Enter the value of x:")
print("The input values data type is:",x)
#Question7 of Task 1
a='NewCamelCase'
b='ladderCase'
c='NEWCAMELCASE'
#Question8 of Task 1
>>> a=20
>>> a
20
>>> a="NewValue"
>>> a
'NewValue'
Yes, the value of the variable will change as the variable with same name already exist in the memory.
The system will override the new value with the old one.
|
fb46bb5c6776602d06d6a435f07588cc8e89efc5
|
bharaththippireddy/pythoncoreandadvanced
|
/exceptionhandling/demo.py
| 561 | 3.71875 | 4 |
import logging
logging.basicConfig(filename="mylog.log",level=logging.DEBUG)
try:
f = open("myfile","w")
a,b = [int(x) for x in input("Enter two numbers:").split()]
logging.info("Division in progress")
c = a/b
f.write("Writing %d into file" %c)
except ZeroDivisionError:
print("Division by zero is not allowed")
print("Please enter a non zero number")
logging.error("Division by zero")
else:
print("You have entered a non zero number")
finally:
f.close()
print("File Closed")
print("Code after the exception")
|
3dc3e68014bc9ed42ad2ebcff660ba585c55e7da
|
GermanDZ/rt_robots
|
/robot_python/flopezluis.py
| 1,043 | 3.84375 | 4 |
players = ('0','X')
turn = 0
exit = False
board = {0:'-', 1:'-',2:'-', 3:'-', 4:'-',5:'-',6:'-', 7:'-',8:'-'}
win_combinatios= [[0,1,2], \
[3,4,5], \
[6,7,8], \
[0,3,6], \
[1,4,7], \
[2,5,8], \
[0,4,8], \
[2,4,6]]
def get_string_board():
str_board = [''.join(row) for row in board.values()]
return ''.join(board.values())
def check_win(key):
for com in win_combinatios:
if key in com:
com[com.index(key)] = board[key]
if com.count(board[key]) == 3: return True
return False
if __name__ == "__main__":
while (not exit):
new_turn = input(get_string_board() + "\n:")
if board[new_turn] != "-":
print "Repeat please\n"
else:
board[new_turn]=players[turn]
turn = not turn
if check_win(new_turn):
print "WIN ->%c" %board[new_turn]
exit = True
|
4290a8106e898c02be9530053a9aa047d100b04d
|
ibby360/python-crash-course
|
/chapter5/alien_color#2.py
| 243 | 3.75 | 4 |
alien_color = 'red'
if (alien_color == 'green'):
print("You have just earned 5 points.")
elif (alien_color == 'yellow'):
print('You have just earned 10 points.')
elif (alien_color == 'red'):
print('You have just earned 15 points.')
|
9514d89696ef8c8e0ccfdd3467f73b9617f7e5dc
|
lixiang2017/leetcode
|
/problems/2348.0_Number_of_Zero-Filled_Subarrays.py
| 1,055 | 3.640625 | 4 |
'''
Runtime: 1087 ms, faster than 78.80% of Python3 online submissions for Number of Zero-Filled Subarrays.
Memory Usage: 24.7 MB, less than 30.39% of Python3 online submissions for Number of Zero-Filled Subarrays.
'''
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = zero = 0
for x in nums:
if x == 0:
zero += 1
else:
ans += zero * (zero + 1) // 2
zero = 0
return ans + zero * (zero + 1) // 2
'''
Runtime: 1073 ms, faster than 83.39% of Python3 online submissions for Number of Zero-Filled Subarrays.
Memory Usage: 24.5 MB, less than 78.09% of Python3 online submissions for Number of Zero-Filled Subarrays.
'''
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = zero = 0
for x in nums:
if x == 0:
zero += 1
else:
zero = 0
ans += zero
return ans
|
e6134713c76a332044b89c8fbfb7e525c198185e
|
wangpeibao/leetcode-python
|
/easy/easy796.py
| 754 | 3.9375 | 4 |
'''
796. 旋转字符串
给定两个字符串, A 和 B。
A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。
如果在若干次旋转操作之后,A 能变成B,那么返回True。
示例 1:
输入: A = 'abcde', B = 'cdeab'
输出: true
示例 2:
输入: A = 'abcde', B = 'abced'
输出: false
注意:
A 和 B 长度不超过 100。
通过次数9,860提交次数19,695
'''
class Solution:
def rotateString(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
return True if A in B * 2 else False
so = Solution()
print(so.rotateString("abcde", "cdeab") == True)
print(so.rotateString("abcde", "abced") == False)
|
3fd0f6838262c699cc6e3cc363e07b122843f6cd
|
Evidlo/advent_of_code
|
/2019/2/2.py
| 934 | 3.5 | 4 |
#!/bin/env python3
# Evan Widloski - 2019-12-01
def compute(noun, verb):
intcodes = list(map(int, open('input', 'r').read().split(',')))
intcodes[1] = noun
intcodes[2] = verb
index = 0
while True:
if intcodes[index] == 1:
intcodes[intcodes[index + 3]] = (
intcodes[intcodes[index + 1]] +
intcodes[intcodes[index + 2]]
)
index += 4
elif intcodes[index] == 2:
intcodes[intcodes[index + 3]] = (
intcodes[intcodes[index + 1]] *
intcodes[intcodes[index + 2]]
)
index += 4
elif intcodes[index] == 99:
break
return intcodes
print(compute(12, 2)[0])
# %% part2
from itertools import product
for noun, verb in product(range(100), range(100)):
result = compute(noun, verb)[0]
if result == 19690720:
print(100 * noun + verb)
|
e4ad992eb44abc0a4f8591071109486c3cf185b6
|
NenadGvozdenac/Python
|
/Pocetak/strings.py
| 356 | 3.765625 | 4 |
def main():
stringNiz = []
unesi_elemente(stringNiz)
ispisi_elemente(stringNiz)
def unesi_elemente(strNiz):
brEl = int(input("Unesite broj elemenata: "))
for i in range(0, brEl):
strNiz.append(str(input(f"Unesite string element {i}: ")))
def ispisi_elemente(strNiz):
print(strNiz)
if __name__ == '__main__':
main()
|
532811fae765c4d3183e64376a0e0c93af603671
|
yaolizheng/leetcode
|
/328/even_list.py
| 549 | 4.125 | 4 |
from linked_list import LinkedList, print_list
def even_list(head):
prev = head
cur = head.next
while cur and cur.next:
tmp = prev.next
prev.next = cur.next
cur.next = cur.next.next
prev.next.next = tmp
cur = cur.next
prev = prev.next
return head
if __name__ == '__main__':
head = LinkedList(1)
head.next = LinkedList(2)
head.next.next = LinkedList(3)
head.next.next.next = LinkedList(4)
head.next.next.next.next = LinkedList(5)
print_list(even_list(head))
|
0c5137671720fb3a5e7349f492eac1413a4fe3cf
|
jaivrat/python_codes
|
/learn/python_algo/test_iqr.py
| 1,054 | 3.84375 | 4 |
import math
import os
import random
import re
import sys
#
def interQuartile(values, freqs):
# Print your answer to 1 decimal place within this function
data = []
for i in range(len(values)):
data.extend([values[i]]*freqs[i])
data.sort()
#print(data)
if len(data)%2==0:
# even
first_half = data[0:int(len(data)/2)]
second_half = data[int(len(data)/2):len(data)]
else:
# odd
first_half = data[0:int(len(data)/2)]
second_half = data[(1 + int(len(data)/2)):len(data)]
#print("first_half" + str(first_half))
#print("second_half" + str(second_half))
def median(arr):
if len(arr)%2 == 0:
return 0.5 * ( arr[int(len(arr)/2)-1] + arr[int(len(arr)/2)])
else:
return arr[int(len(arr)/2)]
q1 = median(first_half)
q3 = median(second_half)
print(float(q3- q1))
if __name__ == '__main__':
val = [10, 40, 30, 50, 20]
freq = [1,2,3,4,5]
interQuartile(val, freq)
print("exit..")
|
2d5b8f920c10f93f115e55fdda099058ac90b8ab
|
capic/installeur
|
/scripts/lib/menu/menu.py
| 5,156 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
"""
"""
import os
MAX_COMMAND_KEY_LEN = 5
MENU_COMMAND_TEMPLATE = '%5s -> %s'
COMMAND_EXIT = 'E'
#define Exceptions
class MenuError(Exception): pass
class MissingVoicesError(MenuError): pass
class DuplicateKeyError(MenuError): pass
def clear_console():
try:
# Windows
os.system('clear')
except:
try:
# basch (Linux and Mac)
os.system('clear')
except:
pass
class Menu():
""""""
def __init__(self):
pass
def __str__(self):
return "Menu class"
def add_voice(self, key, text):
#create dictionary if it is not also created
if not hasattr(self, 'voices'):
self.voices = {}
#check if key also exists
if self.voices.has_key(key):
raise DuplicateKeyError, 'The key "%s" is already present' % key
#check if key also exists (case-insensitive)
for k in self.voices.iterkeys():
if k.lower() == key.lower():
raise DuplicateKeyError, 'The key "%s" is already present (keys names are case-insensitive)' % key
self.voices[key] = text
def show(self, voices=None, title=None, prompt=None, show_exit=True):
"""Show the menu with the given voices.
param @title = Show the title if given.
param @prompt = Show a default text to invite user to make a selection
param @show_exit = Show "Exit" command if requested.
Return the user selection
"""
if not voices and not hasattr(self, 'voices'):
error = 'No voices defined for menu'
raise MissingVoicesError, error
#use pre-assigned voices
if not voices:
voices = self.voices
else:
#check if voices is a dictionary
if not isinstance(voices, dict):
raise ValueError, 'voices must be a dictionary'
#check duplicate keys in passed dictionary (if key exists in lower and upper case)
for k in voices.iterkeys():
k_lower = k.lower()
k_upper = k.upper()
if k_lower != k_upper:
if voices.has_key(k_lower) and voices.has_key(k_upper):
raise DuplicateKeyError, 'The key "%s" is already present (keys names are case-insensitive)' % k
# check that voice keys are all string (else cannot compare user input)
for key in voices.iterkeys():
# old code: type(key) != str
if not isinstance(key, str) or len(key) > MAX_COMMAND_KEY_LEN:
error = "All keys must be strings with max length of %i chars." % MAX_COMMAND_KEY_LEN
raise TypeError, error
# check if voices contains "Exit" command and "Exit" command is required.
if show_exit and voices.has_key(COMMAND_EXIT):
error = 'Voice items cannot contain "Exit" command key (%s).' % COMMAND_EXIT
raise ValueError, error
# set a default prompt if not passed
if not prompt:
prompt = 'Make a selection: '
retry_message = None # message to explain cause that make selection not valid
while True:
#ref: http://stackoverflow.com/questions/2726343/how-to-create-ascii-animation-in-a-console-application-using-python-3-x
error = None
clear_console()
menu_width = 30
if title:
#calculate left and right spaces
left_spaces = ((menu_width-len(title))/2)
pad_left = ' ' * left_spaces
pad_right = ' ' * (menu_width-len(title)-left_spaces)
print '''\
--------------------------------
|%(pad_left)s%(title)s%(pad_right)s|
--------------------------------
''' % {'title':title, 'pad_left':pad_left, 'pad_right':pad_right}
for command, description in voices.items():
print MENU_COMMAND_TEMPLATE % (command, description)
print MENU_COMMAND_TEMPLATE % (COMMAND_EXIT, "Exit")
if retry_message:
print retry_message
selected_voice = raw_input(prompt)
#if not voices.has_key(selected_voice):
# error = "Invalid value, retry..."
# make a case insensitive search of the key
found = False
for key in voices.iterkeys():
if key.lower() == selected_voice.lower():
selected_voice = key
found = True
break
if not found:
error = "Invalid value, retry..."
retry_message = "Value '%s' is not in the list." % selected_voice
if not error:
self.last_selection = selected_voice
# return selected value
return selected_voice
|
18c8ffd2d5f6379ec7e3c57783f1b2204187e2ba
|
czacarias905/Lab-5
|
/Lab5P2.py
| 372 | 4.5 | 4 |
#Cecilia Zacarias
#2/13/2020
#This program prints each number in a new line these number are 12, 10, 32, 3, 66, 17, 42, 99, 20
#This program also prints each number and its square on a new line.
numbers = [12,10,32,3,66,17,42,99,20]
for x in numbers:
print(x)
squared =[12,10,32,3,66,17,42,99,20]
for x in numbers:
print("The square of", x, "is", x**2)
|
45824edd3ac4f2dd2f97d4307379d83d394c39b1
|
hack9521/python3-projects
|
/sum_squares.py
| 342 | 3.53125 | 4 |
# sum_squares=[i**2 for i in range(1,101)]
# print(sum(sum_squares))
# # total=[i for i in range(1,101)]
# # 5050*5050--applicable but hard coded
# total_square= #(sum(total))**2
# print(total_square)
# diff=total_square-sum(sum_squares)
# print(diff)
def problem6(r): return sum(r)** 2- sum([x** 2 for x in r])
print(problem6(range(1,101)))
|
db319b29b890297db1dbebe583c48235328d0d8e
|
Ammy-Pond/PythonAcademy
|
/multiples 3or5.py
| 162 | 4.03125 | 4 |
3 multiples 3 or 5
def solution(number):
sum1=0
for i in range(number):
if i%3==0 or i%5==0:
sum1=sum1+i
return sum1
solution(10)
|
7407c80656bfd4e350a7e60a2fb4fdf5b20fdae7
|
Ekeopara-Praise/python-challenge-solutions
|
/Ekeopara_Praise/Phase 2/SET/Day56 Tasks/Task4.py
| 269 | 4.46875 | 4 |
'''4. Write a Python program to find maximum and the minimum value in a set.'''
set1 = {1, 2, 3, 4, 5, 6, 7, 8}
max_val = max(list(set1))
min_val = min(list(set1))
print("The maximum value in the set is: ", max_val)
print("The minimum value in the set is: ", min_val)
|
b9ac8cd582463f1970dfc812bd7c278dbf6d6839
|
vdv85/PyNEng
|
/3/Задание 3.9 не решено.py
| 1,012 | 3.890625 | 4 |
'''
Найти индекс последнего вхождения элемента с конца.
Например, для списка num_list, индекс последнего вхождения элемента 10 - 4; для списка word_list, индекс последнего вхождения элемента 'ruby' - 6.
Сделать решение общим (то есть, не привязываться к конкретному элементу) и проверить на разных списках и элементах.
Не использовать для решения циклы (for, while) и условия (if/else).
Подсказка: функция len() возвращает длину списка.
num_list = [10, 2, 30, 100, 10, 50, 11, 30, 15, 7]
word_list = ['python', 'ruby', 'perl', 'ruby', 'perl', 'python', 'ruby', 'perl']
'''
num_list = [10, 2, 30, 100, 10, 50, 11, 30, 15, 7]
word_list = ['python', 'ruby', 'perl', 'ruby', 'perl', 'python', 'ruby', 'perl']
|
7eb2fa92a03e55a225218424f582c6b3a08f2fba
|
hy299792458/LeetCode
|
/python/92-reverseLinkedList.py
| 672 | 3.71875 | 4 |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
m, n = min(m, n), max(m, n)
res = ListNode(0)
res.next = head
tail = res
for _ in range(m - 1):
tail = tail.next
ent = tail
l = []
for _ in range(n - m + 1):
tail = tail.next
l.append(tail)
ext = l[-1].next
for i in range(1, n - m + 1):
l[- i].next = l[- i - 1]
l[0].next = ext
ent.next = l[-1]
return res.next
|
5b055dfac45a11c88fa356137410d80bc5db5aac
|
pguiffr62/Engineering_4_Notebook
|
/Python/stringsnloops.py
| 160 | 4.03125 | 4 |
print("Write a simple sentence")
sentence = input(" ")
print(sentence.split('-'))
for letter in sentence:
print(letter)
|
5f7e810f56fb142f6d1ad68799dc8d4ef294785c
|
haripriya2703/KNN_Using_SmallWorldGraphs
|
/KNN_Classifier.py
| 1,155 | 3.71875 | 4 |
from KNN_Search import knn_search
def knn_classifier(knn_graph, distance_metric, d, m, k):
"""
:param knn_graph: existing graph
:param distance_metric: metric using which the nearest neighbors should be determined
:param d: new data point
:param m: number of searches to be performed
:param k: number of neighbors to be searched for
:return: predicted label for the data point based on k-nearest neighbors
"""
species_labels = ['Iris-setosa', 'Iris-virginica', 'Iris-versicolor']
labels_count = [0, 0, 0]
# if data point is a vertex in the graph, get its neighbors from the adjacency list representation of the graph
if d in knn_graph:
return knn_graph[d].label
# if data point is not a vertex, invoke knn_search to get neighbors
neighbors = knn_search(knn_graph, distance_metric, d, m, k)
for neighbor in neighbors:
for i in range(3):
if neighbor.label == species_labels[i]:
labels_count[i] += 1
break
label_index = labels_count.index(max(labels_count))
label = species_labels[label_index]
return label_index, label
|
7c3251a556bc23ba25291ab119a0499c25cc1c09
|
karenwsit/ToyProblems
|
/linked_lists/sum_lists.py
| 2,427 | 3.859375 | 4 |
#Exercise 2.5 of Cracking the Coding Interview
#You have 2 numbers represented by a linked list where each node contains a single digit. The digits are stored in reverse order such that the 1's digit is at the head of the list. Write a function that adds the 2 numbers and returns the sum as a linked list
#################################################################################
#Time = O(n)
#Space = O(1)
from linked_list import *
def sum_lists(node1, node2):
"""
>>> from linked_list import *
>>> ll = LinkedList()
>>> ll.data_to_list([7,1,6])
>>> ll2 = LinkedList()
>>> ll2.data_to_list([5,9,2])
>>> sum_lists(ll, ll2)
LinkedList([2, 1, 9])
"""
current1 = node1.head
current2 = node2.head
result_ll = LinkedList() # result node
tens_place = 0
while current1 is not None and current2 is not None:
sum1 = tens_place
if current1 is not None:
sum1 += current1.data
current1 = current1.next
if current2 is not None:
sum1 += current2.data
current2 = current2.next
digit = sum1 % 10
result_ll.addNode(digits)
tens_place = sum1/10
# sum1 % 10
return result_ll
#################################################################################
#Recursive Solution
#Time: O(n)
#Space: O(n)
# def sum_lists2(node1, node2, carry=0):
# """
# >>> from linked_list import *
# >>> ll = LinkedList()
# >>> ll.data_to_list([7,1,6])
# >>> ll2 = LinkedList()
# >>> ll2.data_to_list([5,9,2])
# >>> sum_lists2(ll, ll2)
# LinkedList([2, 1, 9])
# """
# if node1 is None and node2 is None and carry == 0:
# return None
# result = LinkedList() # new node
# value = carry
# if node1 is not None:
# value += node1.data
# if node2 is not None:
# value += node2.data
# result.data = value % 10 # gets the ones' place digit
# if node1 is not None or node2 is not None and value >= 10:
# more = sum_lists2(node1.next, node2.next, carry == 1)
# elif node1 is not None or node2 is not None and value < 10:
# more = sum_lists2(node1.next, node2.next, carry == 0)
# result.next = more
# return result
#################################################################################
if __name__ == "__main__":
import doctest
doctest.testmod()
|
18ada1559c701e475ef0a50983a8eb6a977b97d7
|
danielkim107/Codeforces_Practice
|
/CodeForces/Petya_And_Strings.py
| 238 | 3.734375 | 4 |
import sys
inf = sys.stdin
first_word = str(inf.readline()).lower().strip()
second_word = str(inf.readline()).lower().strip()
if first_word == second_word:
print(0)
elif first_word > second_word:
print(1)
else:
print(-1)
|
450968994c45e916935c317e24c3ab4f9bfa6a5d
|
LONG990122/PYTHON
|
/第一阶段/4. Python03/day04/day03_exercise/02_zhiyinshu.py
| 1,142 | 4.28125 | 4 |
# 2. 分解质因数,输入一个正整数,分解质因数:
# 如:
# 输入: 90
# 打印:
# 90=2*3*3*5
# (质因数是指最小能被原数整数的素数(不包括1))
def is_prime(x):
'''判断 x是否为素数'''
if x <= 1:
return False
for i in range(2, x):
if x % i == 0:
return False
return True
def get_prime_list(n):
'''此函数根据给定一个整数,返回此整数所有因数的列表'''
# 如何用n求出所有的因数
L = [] # 用来存放所有因数(素数)
# 如果n不是素数,我们就拆出因数出来
while not is_prime(n):
# 把n拆出来一个素数因数,然后继续循环
# 找n的一个因数:
for x in range(2, n):
if is_prime(x) and n % x == 0:
# x一定是n的因数
L.append(x)
n /= x # 下次再求n的因数
n = int(n) # 转为整数
break
else:
L.append(n)
return L
if __name__ == '__main__':
n = int(input("请输入整数: "))
print(get_prime_list(n))
|
32eaff1bfbf19a7d5216b2fcc8d590b7ba45f61f
|
keshavvinayak01/alorithms_cse
|
/numberToDecimal.py
| 327 | 3.609375 | 4 |
def toDecimal(n,b):
res = 0
multiplier = 1
while(n>0):
res += (n%10)*multiplier
multiplier *= b
n = n/10
return res
n,b = raw_input("enter the number and base to be converted to decimal").strip().split(' ')
n,b = [int(n),int(b)]
result = toDecimal(n,b)
print(result)
|
f07a7cce8fc23ab14958ea7d5c8d48820b6b70e7
|
erickgust/python-exercises
|
/mundo-01/ex028.py
| 318 | 3.859375 | 4 |
from random import randint
from time import sleep
print('Pensando... Um número entre 0 e 5...')
r = randint(0, 5)
p = int(input('Em qual número eu pensei? '))
print('PROCESSANDO...')
sleep(2)
if p == r:
print('PARABÉNS! Você acertou!')
else:
print('Não foi dessa vez! O número correto era {}!'.format(r))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.