blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
66b8c6815a588d9c9c1bfac47ce0e22d3ebb20f0 | cytoly/data_structures | /implementations/LinkedList.py | 2,755 | 4.125 | 4 | from typing import Union
class Node:
def __init__(self, data=None):
self.data = data
self.next: Union[Node, ()] = None
def has_next(self) -> bool:
return self.next is not None
class LinkedList:
def __init__(self):
self.head: Union[Node, ()] = None
self.length = 0... |
8d600e3a5ca852a4f986c929b7a9b538237361cd | yeo040294/cz1003 | /FunctionList.py | 3,623 | 3.71875 | 4 | from tkinter import *
def tick():
import time
time1 = ''
time2 = time.strftime('%a, %d %b %y %H:%M:%S') # get the current local time from the PC
if time2 != time1: # if time string has changed, update it
time1 = time2
clock.config(text=time2)
# calls itself every 200 milliseconds
... |
522385d08ccd855e401d141f9f4e8ccf1535f926 | purwokang/learn-python-the-hard-way | /ex6.py | 971 | 4.15625 | 4 | # creating variable x that contains format character
x = "There are %d types of people." % 10
# creating variable binary
binary = "binary"
# creating variable do_not
do_not = "don't"
# creating variable y, contains format character
y = "Those who know %s and those who %s." % (binary, do_not)
# printing content of v... |
73fde459583226d6bdd2dc97c3bb7be80d5bd206 | patidarrohit/us-state-guess-game | /main.py | 931 | 3.828125 | 4 | import turtle
import pandas as pd
screen = turtle.Screen()
screen.title('U.S. States Game')
image = "blank_states_img.gif"
turtle.addshape(image)
turtle.shape(image)
guessed_state = []
data = pd.read_csv("50_states.csv")
states = data.state.to_list()
while len(guessed_state) < 50:
answer = turtle.textinput(title... |
5211bb145600460c72b911168a3917b2d2086e56 | cyberandrei/time_tailored_string_exercise | /calculate_total_minutes_in.py | 3,457 | 3.859375 | 4 | import re
from math import ceil
from decimal import Decimal
import unittest
string_example="all I did today; i 20m, 35m, 2.5h, 2h40m v 40m 35m 1.2h e 30, 60m "
class MinutesTest(unittest.TestCase):
def test_calculate_total_minutes_in(self):
self.assertEqual(calculate_total_minutes_in(), 602)
# ch... |
ea1e981b9a899e15fddce5b28d20ea97c05b5ccd | lovingstudy/Molecule-process | /point2Plane.py | 1,296 | 4.15625 | 4 | #---------------------------------------------------------------------------------------------------
# Name: point2Plane.py
# Author: Yolanda
# Instruction: To calculate the distance of a point to a plane, which is defined by 3 other points,
# user should input the coordinates of 3 points in the plane into (x1,y1,z1... |
19e10f2d86501c35eacca1775d2717e4c27a52a1 | chrisadbr/Python-Tutorial | /employee.py | 665 | 3.953125 | 4 | class Employee:
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.emp_count += 1
"""def display_count(self):
print(f"Total number of employees: {Employee.emp_count}")"""
def display_employee(self):
print("Name: ", ... |
eaf7562051ed60068967a4d5e5f0cdf2fb0f428f | liu-yuxin98/Python | /chapter3/3.8.py | 134 | 3.65625 | 4 | import math
number=(input("input a number:"))
number_new=number[::-1]
number_result=int(number_new.lstrip("0"))
print(number_result)
|
849b8d7b506850e4c17a06336311474482d0304e | liu-yuxin98/Python | /myOwnfunc/isPalindrom.py | 141 | 3.53125 | 4 | from myOwnfunc import Reverse
def isPalindrom(number):
if number==Reverse.reverse(number):
return 1
else:
return 0
|
8322a7426daf57e6aa802952ca4a7680db6531b2 | liu-yuxin98/Python | /myOwnfunc/IsLeapYear.py | 1,373 | 3.796875 | 4 | def IsLeapYear(year):
if year%4==0 and year%100!=0:
return 1
elif year%400==0:
return 1
else:
return 0
monthLeap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def NumberOfDaysOftheMonth(year,month):
if IsLeap... |
3cafe63251f472829b0defa73519a2ec9e3a5aee | liu-yuxin98/Python | /chapter13/13-1.py | 1,042 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# 2020-02-19
# author Liu,Yuxin
# check whether President.txt exists
'''
import os.path
if os.path.isfile('President.txt'):
print("President.txt exists")
'''
outfile = open("President.txt","w")
outfile.write('Bill Clinton\n')
outfile.write("George Bush\n")
outfile.write('Barack Obama\n')
o... |
f2b1f3bd3c6fc0dbfbd1ec1174374dba2ed53c31 | liu-yuxin98/Python | /PythonClass/week6/lab-6.py | 1,775 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# 2020-04-01
# author Liu,Yuxin
print(chr(1))
'''
def containsDuplicate(lst):
s = set(lst) # without set
if len(s)==len(lst):
print('NO')
return 0
else:
print('YES')
return 1
n = int(input())
lst = input().split()
lst = [ int(x) for x in lst]
contai... |
d1556d9eacb878908fc9ebb2393ee47a09b93022 | liu-yuxin98/Python | /myOwnfunc/Reverse.py | 411 | 3.875 | 4 |
def reverse(number):
rnumber=0
if number<0:
number=-1*number
while number != 0:
rnumber = 10 * rnumber + number % 10
number = (number - number % 10) / 10
rnumber=-1*rnumber
else:
while number != 0:
rnumber = 10 * rnumber + number % 10
... |
193cb4ae9de57fdd0f44e672e6d7884aae0af1a0 | liu-yuxin98/Python | /PythonClass/week5/5-7-4.py | 324 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# 2020-03-23
# author Liu,Yuxin
def f(n):
sum = 1
if n == 0:
return 1
elif n ==1:
return 1
else:
for i in range(1,n+1):
sum *= i
return sum
n = int(input())
lst = [ f(i) for i in range(1,n+1,2)]
s = sum(lst)
print('n='+str(n)+',s='+str(... |
b3e654fb7d302437c7d13d06d3abc6b7c83a28ef | liu-yuxin98/Python | /PythonClass/week5/5-7-1.py | 329 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# 2020-03-23
# author Liu,Yuxin
def f(n):
sum = 1
if n == 0:
return 1
elif n ==1:
return 1
else:
for i in range(1,n+1):
sum *= i
return sum
n = int(input())
lst = [1/f(i) for i in range(0,n+1)]
result = sum(lst)
print("{:.8f}".format(r... |
8f06c97a2061ed6cdd62c6230d8bf5857210ea84 | liu-yuxin98/Python | /chapter7/shape.py | 1,033 | 4.125 | 4 | #-*- coding=utf-8-*-
import math
class Circle:
def __init__(self,radius=1):
self.radius=radius
def getPerimeter(self):
return self.radius*2*math.pi
def getArea(self):
return self.radius*self.radius*math.pi
def setRadius(self,radius):
self.radius=radius
class Rectangular:... |
913a343cf8aeeba68780700d8529c4cc3ebc82ad | liu-yuxin98/Python | /chapter5/5.1.py | 229 | 3.890625 | 4 | num = eval(input(" enter a number, except 0:"))
sum=num
count=0
while num!=0:
num = eval(input(" enter a number, except 0:"))
sum+=num
count+=1
print("sum={}".format(sum/count,"5.2f"))
print(format(sum/count,"5.2f"))# |
571dd80f1fd7f2a70f1e7dbb9245829cc4b6eb6b | liu-yuxin98/Python | /chapter3/3.6.py | 97 | 3.75 | 4 | ch=input("enter a letter:")
print(ord(ch))
nu=eval(input("enter an ascii code:"))
print( chr(nu)) |
7d7d941bdfd9d5daf281f20613f6a975e9c6748a | liu-yuxin98/Python | /PythonClass/week4/4-7-1.py | 375 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# 2020-03-16
# author Liu,Yuxin
n = int(input())
if n == 0:
print('average = '+str(0.0))
print('count = ' + str(0))
else:
gradelst = list(map(int, input().split()))
avg = sum(gradelst) / n
avg = round(avg, 1)
count = len([k for k in gradelst if k >= 60])
print('averag... |
7d38432729304ddf772e5bcdb0f9e52ab8aa40ad | liu-yuxin98/Python | /myOwnfunc/isReversePrime.py | 273 | 3.65625 | 4 | from myOwnfunc import IsPrime
from myOwnfunc import Reverse
def isReversePrime(number):
if number<10:
return 0
else:
if IsPrime.IsPrime(number) and IsPrime.IsPrime(Reverse.reverse(number)):
return 1
else:
return 0
|
728b4d353e7f9413c02c942701be5a63b89b3687 | liu-yuxin98/Python | /PythonClass/week3/3-lab.py | 1,871 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# 2020-03-11
# author Liu,Yuxin
'''
def sumlst(n):
if n == 1:
lst = [1]
elif n == 2:
lst = [1,-2/3]
else:
lst = [-i/(2*i-1) if i%2==0 else i/(2*i-1) for i in range(2, n+1)]
lst.insert(0,1)
return sum(lst)
n = eval(input())
print("{:.3f}".format( su... |
fae798cbf978a8219c737399647ff1dbc8309772 | liu-yuxin98/Python | /chapter9/9-11.py | 1,512 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# 2020-02-04
# author Liu,Yuxin
from tkinter import *
import math
class LoacCalculator:
def __init__(self):
# window and two frame
window = Tk()
window.title('Loan Calculator')
# left 5 labels
Label(window, text='Annual Interest Rate:').grid(row=1, co... |
e5719292794e7507606d3c952730bd9d02352656 | tushushu/artificial-intelligence | /bfs and dfs.py | 5,198 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
@Author: liu
@Date: 2018-05-07 20:40:47
@Last Modified by: liu
@Last Modified time: 2018-05-07 20:40:47
"""
class Node():
def __init__(self):
self.next = set()
self.color = "white"
class graph(object):
def __init__(self):
"""[summary]
e.g.
... |
ad50e57b62467400f9ff978a0bbc5135033b3200 | kutoga/learning2cluster | /core/nn/misc/uncertainity.py | 1,251 | 4.09375 | 4 | import numpy as np
def uncertainity_measure(dist):
"""
The uncertainity measure is just the normalized entropy of the input distribution.
If the value is 0, then one single value is selected. If the value is 1 then the
distribution is uniform
This measure may be used for a neural netwo... |
93c378525593aef72ea35ed3a740b1988ea22bf6 | kutoga/learning2cluster | /playground/creepy_network.py | 4,449 | 3.78125 | 4 | # This test is independent of the MT;-)
# This code is really just to play around. It is a try to implement some neural network like thing that only operates
# on boolean values (which is much faster than working with floats).
import numpy as np
np.random.seed(1)
# The complete network only works with 1d data.... |
bda693f3f07c052185858531f01c619432908c7a | igorgbr/intro-python-CDD | /curso_python_coisadedev/aula01.py | 378 | 3.53125 | 4 | # Variaveis
# Crie um programa que receba pelo menos 3 variaveis
# (nome, idade e sobrenome)
# Leia essas variaveis e imprima na tela uma frase
# mostrando quantos anos o usuario tera daqui 20 anos
# "Olá Usuario daqui 20 anos voce ter x anos."
nome = 'Carlos'
sobrenome = 'Alberto'
idade = 45
print(f'Olá {nome} {s... |
dc3e1ef98f938de7f58315adb99b398394fc93ad | niektuytel/Machine_Learning | /Deep_Learning/_deprecated/network/_scratch.py | 5,918 | 3.75 | 4 | # https://github.com/pangolulu/rnn-from-scratch
import numpy as np
import matplotlib.pyplot as plt
import sys, os, keras
from network.LSTM import LSTM
sys.path.insert(1, os.getcwd() + "/../")
import data
class Model:
def __init__(self, seq_length, seq_step, chars, char2idx, idx2char, n_neurons=100):
"""
... |
eb8330a70b7872267bb928151ee6b5ec969311db | niektuytel/Machine_Learning | /Unsupervised_Learning(UL)/Clustering/Gaussian_Mixture/gaussian_mixture_scratch.py | 5,139 | 3.703125 | 4 | import numpy as np # for the math
import pandas as pd # for read csv file
import matplotlib.pyplot as plt # for visualizing data
import math # for math
class GaussianMixture():
"""
Parameters:
-----------
k: int
The number of clusters the algorithm will form.
max_iterations: int
The... |
215e07a4c2197dac235dca63f0b3bdcf5f0e1a32 | Ayseguldeniz/python--project | /assignment-primenumbers.py | 189 | 3.65625 | 4 | p = []
n = 100
for i in range(2,n+1):
prime = True
for j in range(2,i) :
if i % j == 0:
prime = False
if prime:
p.append(i)
print("Prime list = ", p) |
3fbe66368cb280a796554f56110e25a893122f23 | shobithkalal/Data_Structures | /Recursion (Linked List) /LinkedList.py | 5,288 | 4.3125 | 4 | """
PROJECT 2 - Linked List Recursion
Name:
PID:
"""
class LinkedNode:
# DO NOT MODIFY THIS CLASS #
__slots__ = 'value', 'next'
def __init__(self, value, next=None):
"""
DO NOT EDIT
Initialize a node
:param value: value of the node
:param next: pointer to the next ... |
d846912ba458d7a7620fdb44776c396d65075450 | pkdism/misc-programs | /missing-number.py | 250 | 3.953125 | 4 | def missing_number(array):
n = len(array) + 1
total_sum = n * (n + 1) // 2
array_sum = sum(array)
missing_value = total_sum - array_sum
return missing_value
print(missing_number([1, 2, 4]))
print(missing_number([1, 2, 3, 4, 6]))
|
ec7fc736bea025f1ebb21c4d47a4d290925152f8 | jmarin4777/algos | /python/uniqueBST.py | 850 | 3.96875 | 4 | # Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
# Example:
# Input: 3
# Output: 5
# Explanation:
# Given n = 3, there are a total of 5 unique BST's:
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# /... |
2303e2f97cbfd56e99aea1ad1b2adcabd3dc0618 | Vetrix/obstacle_avoidance | /source/sudoku.py | 4,543 | 4.375 | 4 | #!/usr/bin/env python
'''
SELEKSI CALON KRU PROGRAMMING DAGOZILLA 2018
Take Home Test
File name: sudoku.py
Problem 2: Code Comprehension
'''
import sys
import numpy as np
def read_from_file(filename, board):
with open(filename) as f:
data = f.readlines()
for i in range(9):
for j in range(9):... |
10d9e5f8376e60f0d9cbc4144662e7b03f43a460 | drunkinlove/data-structures | /binary-search-tree.py | 8,884 | 4.4375 | 4 | class Node:
"""
The node class, which we will spawn the tree with.
The key principle of binary trees is that, at any given moment,
the right child of a node is larger than it, and the left child is
always smaller.
(This is only true if tree's order relation is a total order.
Which it ... |
3c1219e7c7c57db39fc61e7551c9e3e8808fadb7 | league-python-student/level1-module2-ezgi-b | /_01_writing_classes/_b_intro_to_writing_classes.py | 2,725 | 4.3125 | 4 | """
Introduction to writing classes
"""
import unittest
# TODO Create a class called student with the member variables and
# methods used in the test class below to make all the tests pass
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.homework_d... |
86d62162df8024d7a2fe9891eb9dcb719a6744c6 | kudiXPR/6_password_strength | /password_strength.py | 2,392 | 3.546875 | 4 | import string
import os
def check_pass_is_date_or_digits(password):
return not set(password).difference(set(string.digits), set(string.punctuation))
def check_pass_is_letters(password):
return not set(password).difference(set(string.ascii_letters))
def check_pass_is_punctuation(password):
return not s... |
e392968fe946f5627af9e3caa28c7a3bed3c0ae6 | 0t3b2017/CursoemVideo1 | /desafio #019.py | 451 | 4.03125 | 4 | """
desafio #019
Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um
programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido
"""
from random import choice
n1=str(input("Primeiro aluno: "))
n2=str(input("Segundo aluno: "))
n3=str(input("Terceiro aluno: "))
n4=str(input(... |
10b98f23aed7717f9648ea95aa78e7ab2790cb52 | 0t3b2017/CursoemVideo1 | /aula06b.py | 477 | 4.3125 | 4 | """
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
"""
x=input("Digite algo: ")
print("O tipo do valor é {}".format(type(x)))
print("O valor digitado é decimal? ",x.isdecimal())
print("O valor digitado é alfanum? ",x.isalnum())
print("O ... |
4bfba7c91923794a62b17e796ea043d8f8afa543 | 0t3b2017/CursoemVideo1 | /desafio #037.py | 2,039 | 4.125 | 4 | """
desafio #037
Escreva um programa que leia um número inteiro (em decimal) e peça para o usuário escolher qual será a base de conversão:
1 para binário
2 para octal
3 para hexadecimal
"""
"""
num = int(input("Digite um número: "))
opc = int(input(\"""Selecione uma das base de conversão desejada:
... |
35f07132ed792e76da0ca01799f2679206571ad7 | 0t3b2017/CursoemVideo1 | /desafio #012.py | 355 | 3.734375 | 4 | """
desafio #012
Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto.
"""
preco=float(input("Qual o preço original? R$ "))
desc=float(input("Qual o desconto a ser aplicado em porcentagem? "))
new_preco=(preco - ((preco * desc) / 100))
print("O valor com desconto de {}% é R$ {:.2... |
d219c316c3a67a940a8d0c369a2cdec1cb882d36 | 0t3b2017/CursoemVideo1 | /desafio #041.py | 749 | 4.09375 | 4 | """
desafio #041
A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua
categoria, de acordo com a idade:
- Até 9 anos: Mirim
- Até 14 anos: Infantil
- Até 19 anos: Junior
- Até 25 anos: Senior
- Acima: Master
"""
from datetime import date
ano_nasc = int(inp... |
1866eaa566cf7da42fad880204300044ed994fa4 | 0t3b2017/CursoemVideo1 | /desafio #022.py | 1,004 | 4.375 | 4 | """
Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas
- O nome com todas as letras minusculas
- Quantas letras ao todo (sem considerar espaços)
- Quantas letras tem o primeiro nome.
"""
name = str(input("Type your name: ")).strip()
print("Seu nome em letras maiú... |
30cd643809fbb92f2842d5cc1bc5f2b3206dd494 | LydiaZhou/LeetCode | /P1-300/P2.py | 1,617 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addNumberCarry(self, l: ListNode, carry: int) -> ListNode:
result = ListNode(-1)
ptr = result
while l != None:
ptr.next = ListNode((c... |
3b29d593b0f91621cd38e616b833f1c4a5ec7b46 | LydiaZhou/LeetCode | /P601-/P981.py | 1,320 | 3.6875 | 4 | import collections
class TimeMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = collections.defaultdict(list)
def set(self, key, value, timestamp):
"""
:type key: str
:type value: str
:type timestamp: int
... |
f8224e641379496e2a79e71426bb23a09f3ef3dd | LydiaZhou/LeetCode | /P301-P600/P314.py | 2,771 | 3.875 | 4 | # 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 verticalOrder(self, root):
if not root:
return []
newDict = {}
curPos = 0
queue = [... |
d2463ea58310ac43303cc67962199cf0c693cca0 | LydiaZhou/LeetCode | /P1-300/P5.py | 1,230 | 3.6875 | 4 | class Solution(object):
def __init__(self):
self.data = None
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
self.data = s
palindrome = ""
for i in range(len(s)):
# Even situation
currentVal = self.helper(s... |
f3a8be529229afb1dc8aae55029cc6c62186acc9 | LydiaZhou/LeetCode | /P1-300/P62.py | 573 | 3.671875 | 4 | class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 1 or n == 1:
return 1
if n > m:
return self.fractorial(n, m + n - 1) // self.fractorial(1, m)
else:
return se... |
fc1bb8f29a9dc8a85f6e88784a66e432149866da | LydiaZhou/LeetCode | /P1-300/P21.py | 929 | 3.96875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
new = ListNod... |
e83f86e15aecd6eb0009ea838026ebb57c85d06a | wesleyramos/Chatbot | /PatternMatching/main1.py | 470 | 4.0625 | 4 | """
In this example only content starting with hi or hello or hey with 0 or more spaces and letters will be matched
"""
import re
r = "(hi|hello|hey)[ ]*([a-z]*)"
print(re.match(r, 'Hello Rosa', flags=re.IGNORECASE))
print(re.match(r, "ho ho, hi ho, it's off to work ...", flags=re.IGNORECASE))
print(re.match(r, "hey,... |
3fac10e5c9ccf3814be608c7e6fe35db55759d6f | willian-pessoa/My-codes-in-CS-learning-journey | /Intro CS/Mit 6.0001/ps1b.py | 944 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 21 19:17:51 2021
@author: willi
"""
portion_down_payment = 0.25
current_saving = 0.0
r = 0.04
annual_salary = float(input("Enter your annual salary:"))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal:"))
total_cost = floa... |
098749d838c1a502871f3e98afb6c69de278cb0d | rtaguma01/Python_Exercises | /list.py | 393 | 4.0625 | 4 | #Practice List
list = ["apple", "banana", "pear", "orange", "strawberry"]
length = len(list)
print length
print ("\n")
list.append("grapes")
print list
list.insert(2,"cantaloupe")
print list
list.remove("orange")
print list
list2 = ["peas", "carrots", "lettuce", "beets"]
list.extend(list2)
prin... |
65dd73e46b023df5c03a32f0a7b10459e8b076c7 | rtaguma01/Python_Exercises | /range.py | 218 | 3.796875 | 4 | #Practice Range
a = range(1, 10)
for i in a:
print i
print ("\n")
for b in range(0,28, 2):
print b
print ("\n")
for c in range (40, 0, -4):
print c
print ("\n")
for d in range(20):
print d |
45d5f2d08f9b31aee0ae71aead411e1d3f9e6fdd | NihalAnand/Python6B | /wm.py | 477 | 3.578125 | 4 | def weighted_mean(values: list, weights: list) -> float:
sum_weighted_values = 0
sum_weights = 0
for i in range(len(values)):
for j in range(len(weights)):
value = values[i]
weight = weights[i]
sum_weighted_values += value * weight
sum_weights += weight
result = sum_weighted_values / sum_weig... |
ee2be7243780a0c8c35d7d680a7e98b6ad011a4f | JacobMason83/my_atm | /my_machine.py | 20,594 | 3.734375 | 4 | import tkinter as tk # importing tkinter as the gui for the app
from tkinter import font as tkfont #importing all the tkinter functionality
from tkinter import *
account_balance = 1000
class My_Atm(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
... |
4cb649d8a71138ca487b0e6a7eda8edfe1245a83 | jmnunezd/NaiveBayes | /nb.py | 4,417 | 4.09375 | 4 | import numpy as np
import operator
def suit(book):
"""
suit cleans the 'words' that are found in a book, this helps to count every single word just once. e.g.
'kiss,' and 'kiss' content actually the same word, so we remove the ',' and makes everything simple.
:param book: it's the book we want to clea... |
1c2e9a4f7d93dfcce5b74087ed6e6cbd51337f27 | Highstaker/Dropbox-Photo-Uploader | /tests/thread_with_lock_test001.py | 836 | 3.6875 | 4 | #!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
import threading
from time import sleep
class A(object):
"""docstring for A"""
def __init__(self):
super(A, self).__init__()
self.mutex = threading.Lock()
def func(self,a,Sleep=False):
print(a + " called func()")
with self.mutex:
print(a + " entered mutex")
... |
aee5132cf7fdd9e2c4bfbacdf5362de64c50882e | ivanulb/luracoin-python | /luracoin/helpers.py | 1,351 | 3.796875 | 4 | import binascii
import hashlib
from typing import Union
def sha256d(s: Union[str, bytes]) -> str:
"""A double SHA-256 hash."""
if not isinstance(s, bytes):
s = s.encode()
return hashlib.sha256(hashlib.sha256(s).digest()).hexdigest()
def little_endian(num_bytes: int, data: int) -> str:
retur... |
b5cf2fc7f42367eb826ba6e59021f5465b040bcd | sorokotyaha/TicTacToe_simulation_using_binary_trees | /game_tree.py | 4,366 | 4.03125 | 4 |
from board import Board
from linked_binary_tree import LinkedBinaryTree
import random
class GameSimulator:
"""
This class represents a tic tac toe game simulator, where
computer plays with 0 and the player plays with X
"""
MAXSTEPS = 9
WON = 0
LAST_PLAYER = None
def ... |
36a04e409a3ea79e336b56ca7989aaa91c55f9b3 | Mohamed-Taha-Essa/AI_algorithms_by_python | /algorithms_ai/BFS.py | 1,114 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
#creating by "Mohamed Abdallah "
from queue import Queue
adj_list = {"A" :["B" , "D"] ,
"B" : ["C" ,"A"],
"C" :["B" ] ,
"D" : ["B","F" ,"A"],
"E" : ["D","F" ,"G"],
"F" :["D","E" ,"H" ] ,
"G" : ["E"... |
0da29fef733652c8a03c4aabecb1fef8374ee1dd | HUSSAMFAEZALTARAJI/Python | /open function.py | 556 | 3.71875 | 4 | # def name(first_name, Last_name):
# return f"Hi {first_name} {Last_name} welcom with us in our lesson"
# print(name(str(input("Enter your first name :")),str(input("Enter your Last name :"))))
# message=name(str(input("Enter your first name :")),str(input("Enter your Last name :")))
# file = open('C:/User... |
8deeb1d4276520dbea5b0014bce480d58ec45861 | Prabhjyot2/workshop-python | /L2/P4.py | 131 | 3.5 | 4 | #wapp to convert fare to degree
n = float(input("Enter "))
r = (n - 32) * 5 / 9
print("%.2f \u0046 --> %.2f \u0043" %(n , r))
|
6a793cfc990f511cce72216830fd7c443e9e04c6 | Prabhjyot2/workshop-python | /L4/p5.py | 683 | 3.640625 | 4 | # wamdpp for queue implementation
import array
queue = array.array('i',[])
while True:
op = int(input("1.insert, 2.remove, 3.peek, 4.display and 5.exit "))
if op == 1:
ele = int(input("enter the element to insert "))
queue.append(ele)
print(ele, "is inserted in queue ")
elif op == 2:
if len(queue) == 0:
... |
f742a6010866badbb9f77203c6f6b4e69cd6c56f | Prabhjyot2/workshop-python | /L3/p4.py | 196 | 3.765625 | 4 | # wapp to generate
num = int(input("enter the number "))
if num < 0:
print("b +ve")
else:
n = 0
for i in range(1 , num+1):
for j in range(1, i+1):
print(n, end="")
n = n + 1
print()
|
3d18f0eb26f85178c2f3c6b6f009e6f00b94c3af | Prabhjyot2/workshop-python | /L9/p5.py | 149 | 4 | 4 | # wapp to o/p yess if user enters integer else else o/p no
try:
num = int(input("enter an integers"))
print("yes")
execpt ValueError:
print("no") |
cf3c05d28b1c3fbdb58d966e308f6b0a1d0a64df | Prabhjyot2/workshop-python | /L2/p8.py | 254 | 3.84375 | 4 | #wapp to read marks & find the grades
mark = int(input("enter the marks "))
if (mark>=70):
g="dist."
elif(mark>=60):
g="FIRST CLASS"
elif(mark>=50):
g="SECOND CLASS"
elif(mark>=40):
g="PASS"
else:
g="fail"
print("marks =", mark,"GRADES = ",g)
|
d2181a4d79b5f40ce98e852f429bc7881cda34aa | Prabhjyot2/workshop-python | /L5/p6.py | 288 | 3.953125 | 4 | '''
wapp tp read a sentence and sort every word of sentence
i/p Kamal sir rocks
o/p aaklm irs ckors'''
def mysort(s):
ls = sorted(s)
ns = ''.join(ls)
return ns
s1= input("enter a string ")
l1= s1.split(" ")
ns1 =" "
for m in l1:
m = mysort(m)
ns1 = ns1 + " " + m
print("", ns1) |
e897af19e5fdf1f6ab3568b14ae124c5971a2a57 | Prabhjyot2/workshop-python | /L2/P2.py | 235 | 4.40625 | 4 | #wapp to read radius of circle & find the area & circumference
r = float(input("Enter the radius "))
pi = 3.14
area = pi * r** 2
print("area=%.2f" %area)
cir = 2 * pi * r
print("cir=%.4f" %cir)
print("area=", area, "cir=", cir )
|
b794e6fa42a47d23f44792945a330e57b2f45412 | Prabhjyot2/workshop-python | /L2/p7.py | 223 | 4 | 4 | # wapp to read year & find if its a leap year
year = int(input("Enter the year"))
b1 = (year%100 == 0) and (year%400 == 0)
b2 = (year%100 != 0) and (year%4 == 0)
if b1 or b2:
print("yessssssss")
else:
print("naaaaaaa") |
63896d5b332d30ed57338c3277fd9dc4cfaf8bfb | prabhugs/scripts | /duplicate.py | 297 | 3.75 | 4 | a = [1,1,2,2,2,3,4,5]
c=[]
d=[]
for entry in a:
if entry not in c:
c.append(entry)
d.append(entry)
print "----"
print c
print d
print "----"
pass
if entry in c and entry in d:
print d
d.remove(entry)
print c
print d
|
51dc7d36233782cfb7481e5a29b6061d99983669 | alexcarlos06/CEV_Python | /Mundo 2/Desafio 036.py | 2,886 | 3.921875 | 4 | # Escreva um programa para aprovar o empréstimo bancário para comprar uma casa.
# O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# Calcule o valor da prestação mensal sabendo que ele nao pode exceder 30% do salário ou então o empréstimo será negado.
# Importando o mét... |
44f9c71e161a2fddd66975520ca4b0444be0fefa | alexcarlos06/CEV_Python | /Mundo 2/Desafio 069.py | 2,095 | 4.15625 | 4 | '''Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou nao continuar. No final, mostre:
a) Quantas pessoas tem mais de 18 anos. b) Qantos homens foram cadastrados. c)Quantas mulheres tem mais de 20 anos .'''
print('\n{:^100}\n'.format... |
ab830dfe0aa7c1006ddc12c332194fe546dc8724 | alexcarlos06/CEV_Python | /Mundo 1/Desafio 013.py | 352 | 3.890625 | 4 | #Faça um algoritimo que leia o salário de um funcionário e mostre seu novo salario com almento de 15%
# Fazendo a leitura do salario atual
s = float(input('Iinforme o salário atual: '))
#Informando na tela o valor obtido através da soma do salario atual mais 15%
print('O novo salário será {} reais '.format(s+(s*0.15)... |
c748ec48187e940398cda28db426de3c0ce6c219 | alexcarlos06/CEV_Python | /Mundo 1/Desafio 011.py | 1,085 | 3.9375 | 4 | #Faça um programa que leia a largura e a altura de uma parede em metros e cacule sua área e a quantidade de tinta necessária para pinta-la. sabendo que cada litro de tinta pinta uma área de 2m²
# Lendo o rendimento da embalagem de tinta a ser comprada
rend = int(input('Informe o rendimento da embalagem de tinta: '))
... |
337341d300ebe5397368e6ca19dcf2ae8c895d3e | alexcarlos06/CEV_Python | /Mundo 2/Desafio 071.py | 2,201 | 4.15625 | 4 | '''Crie um programa que simule o funcionamento de um caixa eletônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro)
e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1'''
print('\n{}{:^^100}{}\n'.f... |
2bd2b887faf5433b01e8f743c54186d801442691 | alexcarlos06/CEV_Python | /Mundo 2/Desafio 058.py | 2,752 | 4 | 4 | '''Melhore o jogo do desafio 028 onde o computador vai "pensar" em um número entre 0 e 10. só que agora o jogador vai tentar adivinhar
até acertar, mostrando no final quantos palpites foram necessários para vencer. '''
from random import randint
''' Paleta de cores'''
cores = {'azul' : '\033[34m',
'amare... |
7adc48dd7da8cea5d02cbdc83ea6524f924fc037 | alexcarlos06/CEV_Python | /Mundo 1/desafio 008.py | 341 | 4.21875 | 4 | #Escreva um programa que leia um valor em metros e o exiba convertido em centimentros e milimetros
m=int(input('Informe a quantidade de metros que desja converter: '))
mm=int(1000)
cm=int(100)
mmconverte=m*mm
cmconverte=m*cm
print(' Em {} metros existem {} centimetros e {} milimetros.'.format(m, cmconverte, mmconverte)... |
7366faebfd176414ff1bf491adaefe7030557187 | alexcarlos06/CEV_Python | /Mundo 2/Desafio 038.py | 577 | 3.9375 | 4 | #Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem:
#O primeiro valor é maior, O segundo valor é menor , Não existe valor maior, os dois são iguais.
# Fazendo a leitura de dois números
n1 = float(input('Digite o primeiro valor: '))
n2 = float(input('Digite o segundo valor:... |
02fc4d0883508b8ed4ef03cc15856e5308538050 | alexcarlos06/CEV_Python | /Mundo 2/Desafio 070.py | 1,743 | 4.09375 | 4 | '''Crie um programa que leia o nome e o peço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre:
a) Qual é o total gasto na compra. b) Quantos produtos custam mais de R$ 1000. c) Qual é o nome do produto mais barato. '''
print('\n\033[1;32m{:~^100}\033[m'.format(' \033[1;4;33m... |
1d8edc6e0ad9f240115c16793e369cf63b73cefb | alexcarlos06/CEV_Python | /Mundo 1/Desafio 032.py | 846 | 3.96875 | 4 | #Faça um programa que leia um ano qualquer e mostre se ele é BISSEXTO.
# Mensagem inicial do programa
print('xxxxxX Verificador de Ano Bissexto Xxxxxx')
print('========'*10)
#Colhendo a informação do ano consultado
ano = int(input('Informe qual ano deseja verificar: '))
#Montando a condição, se o resto da divisão p... |
d4888e3a514d852c58b30b04a38a3066a12fb6ab | alexcarlos06/CEV_Python | /Mundo 2/Desafio 042.py | 2,293 | 4 | 4 | #Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado.
#Equilátero: todos os lados iguais ; Isóceles: dois lados iguais ; Escaleno: todos os lados diferentes.
#Se os 3 seguimentos de retas formarem o triângulo o programa precisa responder qual o tipo de triangulo mo... |
532793eb6901f35e2184ab5b510aea233c5a484b | Sher-Chowdhury/CentOS7-Python | /files/python_by_examples/loops/iterations/p02_generator.py | 845 | 4.34375 | 4 | # functions can return multiple values by using the:
# return var1,var2....etc
# syntax.
# you can also do a similar thing using the 'yield' keyword.
fruits = ['apple', 'oranges', 'banana', 'plum']
fruits_iterator = iter(fruits)
# we now use the 'next' builtin function
# https://docs.python.org/3.3/l... |
51ef16e584f74ddbfa5d23412847e88fd8f4cf27 | rodrigocms/python | /Scripting_ErrorsAndExceptions.py | 509 | 3.609375 | 4 | #Errors And Exceptions
#Syntax errors occur when Python can’t interpret our code, since we didn’t follow the correct syntax
# for Python. These are errors you’re likely to get when you make a typo, or you’re first starting
# to learn Python.
# Exceptions occur when unexpected things happen during execution of a prog... |
8ee8bfee53f3b666a3cddd35bb85ddae2c52e6b8 | tntterri615/Pdx-Code-Guild | /Python/lab10unitconverter.py | 587 | 4.125 | 4 | '''
convert feet to meters
'''
x = int(input('What distance do you want to convert?'))
y = input('What are the input units?')
z = input('What are the output units?')
if y == 'ft':
output = x * 0.3048
elif y == 'km':
output = x * 1000
elif y == 'mi':
output = x * 1609.34
elif y == 'yd':
output = x * ... |
f1497ee3c556984b0c9034b07687c2353046edb5 | tntterri615/Pdx-Code-Guild | /Python/lab31atm.py | 1,398 | 4.125 | 4 | '''
atm lab
'''
class Atm:
transaction_list = []
def __init__(self, balance = 0, interest_rate = 0.1):
self.balance = balance
self.interest_rate = interest_rate
def check_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
sel... |
59802ababfc3db1657ac9227b618e583df6aac14 | tntterri615/Pdx-Code-Guild | /Python/lab25countwords.py | 2,382 | 3.75 | 4 | # unicode count words
punctuation = ";,.?!'\"-()*:[]$#"
other_punctuation = '":;#*()[]\'/$#,-\n'
word_count = {}
# Version 1
# with open('leviathan.txt', 'r') as f:
# contents = f.read()
# contents = contents.lower()
# for char in punctuation:
# contents = contents.replace(char, "")
# contents... |
bae3bd82fed925785023d6270207ad175da884b1 | tntterri615/Pdx-Code-Guild | /Python/lab09makechange.py | 816 | 4.03125 | 4 | '''
making change out of a dollar amount
'''
# get input(dollar amount) from user
x = int(input("Let's convert your money from dollars into change. How much money do you have, without using the decimal point?"))
# determine how many quarters can be used
quarters = float(x//25)
# get remainder
q_remainder = x%25
# d... |
a6bbf085e34878cf47623fef38c77da3b7ef8d4c | djamrozik/CS411-VegeCheck | /scripts/cheating_detection/detect_utils_copy.py | 2,766 | 3.546875 | 4 | from fetch_score import score_data
import re
from collections import defaultdict
def split_answers(input):
groups = re.match(r"(\d*):[\d],(\d*):[\d],(\d*):[\d],(\d*):[\d],(\d*):[\d],", input)
return (groups.group(1), groups.group(2), groups.group(3), groups.group(4), groups.group(5))
""" a and b should both ... |
4faf66595614f1e6342d12d115b62b927a503030 | sunjuyoung/coding-test | /ch06/6-5.py | 181 | 3.796875 | 4 | array = [5,7,9,0,3,1,6,2,4,8]
def quick_sort(array):
pivot = array[0]
tail = array[1:] # 피벗을 제외한 리스트
left_side = [x for x in tail if x<= pivot]
|
b6dbb2ce166a364aba1d21cef86ce8e16211eff4 | lyjeff/Machine-Learning-Class | /hw1-Perceptron/hw1-1.py | 1,593 | 3.71875 | 4 | import numpy as np
from utils import (
PLA, build_data,
verification, plt_proc
)
def PLA_3_times_with_30_data(m, b, num, times):
# build 2D data
x, y = build_data(m, b, num)
#initial weight w = (0, 0, 0)
w = np.zeros([1,3])
# count the iteration total numbers
iteration_count = 0
... |
042aea68e1f50e022a82004118433c410336b7be | YEJINLONGxy/shiyanlou-code | /investment.py | 715 | 4 | 4 | #!/usr/bin/env python3
#
#amount = float(input('Enter amount: ')) #输入数额
#inrate = float(input('Enter Interest rate: ')) #输入利率
#period = int(input('Enter period: ')) #输入期限
#value = 0
#year = 1
def investment():
amount = float(input('Enter amount: ')) #输入数额
inrate = float(input('Enter Interest rate: ')) #输入利率
per... |
9cae7dd953a102a146fe23105b85c64746c2f834 | YEJINLONGxy/shiyanlou-code | /matrixmul.py | 1,735 | 4.25 | 4 | #!/usr/bin/env python3
#这个例子里我们计算两个矩阵的 Hadamard 乘积。
#要求输入矩阵的行/列数(在这里假设我们使用的是 n × n 的矩阵)。
n = int(input("Enter the value of n: "))
print("Enter value for the Matrix A")
a = []
for i in range(n):
a.append([int(x) for x in input().split()])
#print(a)
print("Enter value for the Matrix B")
b = []
for i in range(n):
b.ap... |
f6cf5dd18f276acb2e83a3f7b2fb701a3b4528f3 | YEJINLONGxy/shiyanlou-code | /palindrome_check.py | 668 | 4.25 | 4 | #!/usr/bin/env python3
#回文检查
#回文是一种无论从左还是从右读都一样的字符序列。比如 “madam”
#在这个例子中,我们检查用户输入的字符串是否是回文,并输出结果
s = input("Please enter a string: ")
z = s[::-1] #把输入的字符串 s 进行倒叙处理形成新的字符串 z
if s == z:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
#运行程序
#[root@dev1 python_code]# ./palindrome_che... |
7693472e4e9e0e294f95e89eca7ee7df6bb8acf7 | rajiv786/turtle-library-in-python | /4.py | 293 | 3.625 | 4 | import turtle
t = turtle.Turtle()
turtle.title("Heart Shape")
w = turtle.Screen()
w.bgcolor("black")
t.color("red")
t.begin_fill()
t.fillcolor("red")
t.left(140)
t.forward(180)
t.circle(-90, 200)
t.setheading(60)
t.circle(-90, 200)
t.forward(180)
t.end_fill()
t.hideturtle()
|
25e5e995ce64c0953a463eb92ba9b294e909f67c | soukalli/jetbrain-accademy | /Topics/Nested lists/Word list/main.py | 360 | 3.796875 | 4 | text = [["Glitch", "is", "a", "minor", "problem", "that", "causes", "a", "temporary", "setback"],
["Ephemeral", "lasts", "one", "day", "only"],
["Accolade", "is", "an", "expression", "of", "praise"]]
length = int(input())
print([word for word in [word_in_sentence for sentence in text for word_in_sentenc... |
0f7add96fea2633342d15e577bd3363a614385e6 | soukalli/jetbrain-accademy | /Topics/Algorithms in Python/Last index of max/main.py | 199 | 3.890625 | 4 | def last_indexof_max(numbers):
# write the modified algorithm here
index = 0
for i in range(len(numbers)):
if numbers[i] >= numbers[index]:
index = i
return index
|
72ded11a309eb690440c7f9c3e7a8e02c12d316f | davruk/mojevje-be- | /guess the secret number.py | 217 | 4.0625 | 4 | secret = "22"
guess = int(input("Guess the secret number (between 1 and 30): "))
if guess == 22:
print("You got it - It is the number 22")
else:
print("Sorry, your guess is not correct")
|
2ddb1a6ff62f577e06a8102ca42dd46710f22cbd | BigFav/Project-Euler | /p_33.py | 1,046 | 3.65625 | 4 | from fractions import Fraction
from operator import mul
""" Find the denominator for the product of digit cancelling fractions. """
digit_cancel_fracs = []
for numerator in xrange(10, 99):
if numerator % 10 == 0 or numerator % 11 == 0: # trivial cases
continue
for denominator in xrange(numerator + 1... |
b265460fc33d63e632d20275ca7b56137ad961c9 | BigFav/Project-Euler | /p_56.py | 240 | 3.84375 | 4 | ''' For a^b, where a, b < 100, what is the maximum digital sum? '''
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n / 10
return r
print max(max(sum_digits(a**b) for b in xrange(1, 100)) for a in xrange(1, 100))
|
52f91fbb66db692a1136d6fc61b11c1e40cab9e5 | UPstartDeveloper/zip_file_maker | /zip_test.py | 559 | 3.859375 | 4 | import os
import zipfile
def zipdir(path, ziph):
"""ziph is zipfile handle"""
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
if __name__ == '__main__':
file_name = input("Enter a name for your new ZIP folder " +
"... |
b7104c88bf95201fb455f5dd1f0a918b78a682b0 | ankush1717/2048 | /gui2048.py | 3,712 | 4.125 | 4 | from class2048 import *
from tkinter import *
class Square:
'''Objects of this class represent a square
on a tkinter canvas.'''
def __init__(self, canvas, center, size, color, order, value):
(x, y) = center
x1 = x - size / 2
y1 = y - size/2
x2 = x + size/2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.