blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4f51b32921083c2e8aae08a54e635391a8f07da4 | carlos2020Lp/progra-utfsm | /guias/2014-1/marzo-24/digitos/pauta.py | 87 | 3.703125 | 4 | n = int(raw_input('n: '))
c = 0
while n > 0:
c += 1
n /= 10
print c, 'digitos'
|
841c8dffe714ccf436a0e75f7093a371d2ad055d | carlos2020Lp/progra-utfsm | /certamenes/2012-1-certamen-1/edad/solucion3.py | 413 | 3.703125 | 4 | ano = int(raw_input('Ano: '))
mes = int(raw_input('Mes: '))
dia = int(raw_input('Dia: '))
ya_tuvo_cumpleanos = mes < 5 or (mes == 5 and dia <= 10)
ya_tuvo_cumplemes = dia <= 10
edad_anos = 2012 - ano - (not ya_tuvo_cumpleanos)
edad_meses = ( 5 - mes - (not ya_tuvo_cumplemes)) % 12
edad_dias = (10 - dia) % 30
pri... |
3201b8dc5539c849280f71592c7bef4e4e3d8200 | carlos2020Lp/progra-utfsm | /diapos/programas/promedio-n-numeros.py | 172 | 3.75 | 4 | n = int(raw_input('Cuantos numeros? '))
suma = 0.0
for i in range(n):
x = float(raw_input())
suma = suma + x
promedio = suma / n
print 'El promedio es', promedio
|
e6248f1bb2f01c9e9e2f70ec55f744c03df4e290 | carlos2020Lp/progra-utfsm | /certamenes/2012-1-certamen-1/basquet-2/solucion.py | 486 | 3.59375 | 4 | anotaciones = raw_input('Anotaciones: ')
n = len(anotaciones)
puntos = 0
total = 0
periodo = 1
for i in range(n):
a = anotaciones[i]
if a == 'T':
puntos += 3
elif a == 'D':
puntos += 2
elif a == 'L':
puntos += 1
elif a == ' ':
print puntos, 'puntos en el periodo', per... |
1f00f3d5df2fb3a21ab62cd1e6ad2d91caea27f1 | carlos2020Lp/progra-utfsm | /certamenes/2011-1-certamen-1/rango/pauta3.py | 300 | 3.78125 | 4 | n = int(raw_input('Cuantos valores ingresara? '))
minimo = float('inf')
maximo = -float('inf')
for i in range(n):
x = float(raw_input('Valor ' + str(i + 1) + ': '))
if x < minimo:
minimo = x
if x > maximo:
maximo = x
rango = maximo - minimo
print 'El rango es', rango
|
8a576ccf595e3825cf4dbd111900148f3887f670 | carlos2020Lp/progra-utfsm | /_static/programas/conversion_unidades.py | 1,038 | 3.6875 | 4 | km_por_milla = 1.609344
cm_por_pulgada = 2.54
def millas_a_km(mi):
return mi * km_por_milla
def km_a_millas(km):
return km / km_por_milla
def pulgadas_a_cm(p):
return p * cm_por_pulgada
def cm_a_pulgadas(cm):
return cm / cm_por_pulgada
if __name__ == '__main__':
print 'Que conversion desea hace... |
537155b62c3fa9902709fea9ed6580639b01e627 | carlos2020Lp/progra-utfsm | /certamenes/2011-1-certamen-1/alfil-torre/pauta2.py | 309 | 3.8125 | 4 | fa = int(raw_input('Fila alfil: '))
ca = int(raw_input('Columna alfil: '))
ft = int(raw_input('Fila torre: '))
ct = int(raw_input('Columna torre: '))
if fa == ft or ca == ct:
print 'Torre captura'
elif fa + ca == ft + ct or fa - ca == ft - ct:
print 'Alfil captura'
else:
print 'Ninguno captura'
|
62deddbbf7b223634f5e9ebcfb7d3acd9e75d805 | carlos2020Lp/progra-utfsm | /controles/2012-1-presencial-1/miercoles-1-2.py | 416 | 3.8125 | 4 | print 'Jugador X'
x1 = int(raw_input('Carta 1: '))
x2 = int(raw_input('Carta 2: '))
print 'Jugador Y'
y1 = int(raw_input('Carta 1: '))
y2 = int(raw_input('Carta 2: '))
if x1 == x2 and y1 == y2:
print 'Empate'
elif x1 == x2:
print 'Gana X'
elif y1 == y2:
print 'Gana Y'
elif abs(x1 - x2) < abs(y1 - y2):
... |
136f0423ffcc5142249b96d6880970ecceeeafcd | carlos2020Lp/progra-utfsm | /controles/2011-1-control-en-linea-3/b_pauta.py | 231 | 3.515625 | 4 | def suma_digitos(n):
s = 0
while n > 0:
ultimo = n % 10
s += ultimo
n /= 10
return s
def reducir_a_digito(n):
s = suma_digitos(n)
while s >= 10:
s = suma_digitos(s)
return s
|
863f8334490bd206e927c75bbc643e46188c2de8 | carlos2020Lp/progra-utfsm | /guias/2014-1/abril-16/binomial/binomial.py | 274 | 3.890625 | 4 | def factorial(n):
producto = 1
for i in range(1, n + 1):
producto *= i
return producto
def binomial(n, k):
return factorial(n) / (factorial(n - k) * factorial(k))
n = int(raw_input('n: '))
k = int(raw_input('k: '))
print '(n k) =', binomial(n, k)
|
4af46f54ab1939214c53b3375e8426b07b85540b | carlos2020Lp/progra-utfsm | /diapos/programas/rima2.py | 228 | 3.703125 | 4 | p = raw_input('Palabra 1: ')
q = raw_input('Palabra 2: ')
iguales1 = p[-1] == q[-1]
iguales2 = p[-2] == q[-2]
iguales3 = p[-3] == q[-3]
iguales4 = p[-4] == q[-4]
print (iguales1 and iguales2 and
iguales3 and iguales4)
|
a7ba8d2f0fff7ac1d1d38b0d4d9410f8db44ded6 | shashwatc12/Python-Projects | /Python_Basic_Projects/RockPaperScissor.py | 2,315 | 4.25 | 4 | # RockPaperScissors.py
# Purpose: Use random module, and loop
# Program: RockPaperScissor Game
#Pseudocode
""" Get initial Wins, Losses Ties
Assign the value of Rock,Paper and Scissor
Give option to quit
Let user give the input
Generate Rock Paper Scissor for opponent
Compare the input with the given variable a... |
1203da498ed04f28bc3dbbaf1ba14d090a36e1bb | stefan1123/newcoder | /左旋转字符串.py | 1,479 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指
令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=
”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
代码情况:accepted
"""
class Solution:
def LeftRotateString(self, s, n):
# write code here
# # 方法一: 数组
# ... |
35890f4e530de0b2a29a04e544d6e7434746fd41 | stefan1123/newcoder | /机器人的运动范围.py | 2,140 | 3.546875 | 4 | """
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个
方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够
进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
请问该机器人能够达到多少个格子?
代码情况:accepted
"""
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
... |
7e1508ec5df018a317b271c7b896d2937d3d7a3d | stefan1123/newcoder | /平衡二叉树.py | 2,009 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
代码情况:accepted
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# def IsBalanced_Solution(self, pRoot):
# # write code here
# # 方法一: 判断某一节点上的左右子树的平衡因子。按此法逐个判... |
085371b0923f82774ff80f3a974a96e10d8e0e81 | stefan1123/newcoder | /52_两个链表的第一个公共结点.py | 1,935 | 3.765625 | 4 | """
题目描述(acc)
输入两个链表,找出它们的第一个公共结点。
"""
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
# # 方法一: 使用hashmap的思想,把链表1的节点放入list,再遍历链表2,看是否含有相同节点
# if pHead1 == None or pHead2 ==None:
# return None
# nodelist = []
# p = pHead1
# while... |
65f4f09f99777c896fc0fa930b07aff809baef7a | zefaradi/Coding-Challenges-from-codewars.com | /Replace with alphabet position.py | 862 | 4.4375 | 4 | # Replace With Alphabet Position
# In this kata you are required to, given a string, replace every letter with its
# position in the alphabet.
# If anything in the text isn't a letter, ignore it and don't return it.
# "a" = 1, "b" = 2, etc.
# Example
# alphabet_position("The sunset sets at twelve o' clock."... |
16d3064f4918207532254bb8086ba8d6994a9509 | kooruhana/Othello | /othello.py | 8,540 | 3.78125 | 4 | # Yuchen Rong ID:75819508
BLACK = 1
WHITE = 2
NONE = 0
def new_game_board(COLUMNS:int,ROWS:int,top_left:str)->[[int]]:
"""Get the initial board of the game.
"""
board = []
for col in range(COLUMNS):
board.append([])
for row in range(ROWS):
board[-1].append(NO... |
363aecbcee3eb835a1ae1b45a325168ceddc69c6 | hkh0105/python-study-8th | /허태정(예시)/Assignment1-2.py | 430 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# 맨위의 한 줄은 한글이 깨지는 문제가 발생해서 추가했습니다.
i, j = input("숫자 두개를 입력해주세요 : ").split()
i = int(i)
j = int(j)
print(f"더하기: i + j = {i + j}")
print(f"빼기: i - j = {i - j}")
print(f"곱하기: i * j = {i * j}")
print(f"나누기: i / j = {i / j}")
print(f"나머지없이: i // j = {i // j}")
print(f"나머지만: i % j = {i % j}")
|
7b9e11d138512152db66805cbc5d1f8f13b0f9bb | yorabl/python3_course | /humanGuessingGame.py | 449 | 4.125 | 4 | p1_num = 0
p2_num = 0
while p1_num < 1 or p1_num > 100:
p1_num = int(input("Please enter a number between 1 - 100: "))
print("\n" * 100)
while True:
p2_num = int(input("Please guess a number, between 1-100: "))
if p2_num < p1_num:
print("Your guess, {}, is too low!".format(p2_num))
elif p2_nu... |
5f84fd32d16f8e6a652bb09e13b8e94cebd89205 | yorabl/python3_course | /calculatedMedian.py | 803 | 3.921875 | 4 | def median(data):
length = len(data)
if (length % 2):
tmp = (length // 2 )
middle = sorted(data)[tmp]
else:
tmp = length // 2
middle = (sorted(data)[tmp] + sorted(data)[tmp - 1]) / 2
return middle
def calc_median():
l = []
while True:
tmp = input('> ')... |
f17f6b4e6280a81995825b6dc9622a1abeca5f68 | yorabl/python3_course | /father.py | 465 | 4.28125 | 4 | # father1.py
name = "joe"
sons = 2
daughters = 3
# ----- ENTER YOUR CODE HERE --------
s = "{} has {} kids.".format(name.capitalize(), sons + daughters)
# -----------------------------------
print(s)
assert s == "Joe has 5 kids."
print("OK")
name = input("What is your name? ")
sons = int(input("How many sons do you ... |
01458536eb92e0331a9ee02e04169360fa2c7e7e | Shalom91/Practice-Python-Exercises | /rock_paper_scissors.py | 964 | 4.03125 | 4 | """Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input),
compare them, print out a message of congratulations to the winner, and ask if the players
want to start a new game)"""
# define variables
r = 'rock'
p = 'paper'
s = 'scissor'
# initialize the game
while True:
start_new_ga... |
2c7504268318705c7f8305cd60912c6604bded87 | LanQikun/Udacity-CS212 | /Problem Set 2/floor_puzzle.py | 910 | 3.984375 | 4 | #------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a higher... |
0ada4e908257e3665940f22c2d498d4b4703c5b1 | agude/insight-project | /website/app/distance.py | 451 | 3.6875 | 4 | from math import sin, cos, sqrt, atan2, radians
def delta_r(lat1, lon1, lat2, lon2):
# approximate radius of earth in km
R = 6373.0
lat1r = radians(lat1)
lon1r = radians(lon1)
lat2r = radians(lat2)
lon2r = radians(lon2)
dlon = lon2r - lon1r
dlat = lat2r - lat1r
a = sin(dlat / 2)*... |
c68f895d927ab759da3e38d921fd68faced3cbb3 | caddycarine/wtm_buea_codes_2020 | /strings/robot_name.py | 549 | 3.75 | 4 | import random
from string import ascii_uppercase, digits
class Robot:
existingBots = []
def __init__(self):
self.newName()
self.__class__.existingBots.append(self)
def newName(self):
while True:
newName = ''.join(random.choices(ascii_uppercase, k=2)) + ... |
61f1571cacb89ca270bc9d595474add78b040827 | EthanWhang/crimtechcomp | /assignments/000/Ethanwhang/000-code/assignment.py | 1,052 | 3.71875 | 4 | def say_hello():
print("Hello, world!")
# Color: Blue
def echo_me(msg):
print(msg)
def string_or_not(d):
exec(d)
def append_msg(msg):
print("Your message should have been: {}!".format(msg))
class QuickMaths():
def add(self, x, y):
return x + y
def subtract(self, x, y):
retu... |
515792e79d8b448976a6c7869064a7e1fa33b294 | luoming1224/algorithm | /sort/merge_sort.py | 1,619 | 3.9375 | 4 | #coding=utf8
def merge(left, right):
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
resu... |
b9a81c53141436e83376feb6809f1da6c71f4b1b | ParkGiyoun/companyInfoPy | /CorpWithGUI/Process/Monetary.py | 451 | 3.765625 | 4 | # 영미식 단위로 끊어주는 함수
def money(mon):
a = mon
result = str(mon)
finalresult = ""
count = 0
while (a > 0):
a = a//1000
if(a != 0):
count += 1
for i in range(count):
info = -3*count
index = info+i*3
result = result[:index] + ',' + result[index:]
... |
f87819857558003b0fba9d906152c03d8f337379 | jiangsir/PythonBasic | /五福專區/5-5.py | 148 | 3.609375 | 4 | s = input()
s2 = s[len(s)//2:]
if len(s)%2==0 and s[:len(s)//2] == s2[::-1]:
print('Yes')
print(s[:len(s)//2])
else:
print('No') |
f999428c0a52fc7ece1948bd9942a2e506f9d438 | jiangsir/PythonBasic | /五福專區/期末考P1.py | 182 | 3.671875 | 4 | n = int(input())
for i in range(n):
p1, p2, p3 = [int(x) for x in input().split()]
if p1!=p2 and p2!=p3 and p1!=p3:
print('YES')
else:
print('NO')
|
a241fa374816e5dcf168de49aeecb018d50d0bc5 | MariosRichards/BES_analysis_code | /pgmpy-dev/pgmpy/factors/continuous/LinearGaussianCPD.py | 4,457 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from scipy.stats import multivariate_normal
from pgmpy.factors.base import BaseFactor
class LinearGaussianCPD(BaseFactor):
u"""
For, X -> Y the Linear Gaussian model assumes that the mean
of Y is a linear function of mean of X a... |
2ece6ebb6dff5c9eeb71e20068a053315d20aa1b | MariosRichards/BES_analysis_code | /bayesian-belief-networks-master/bayesian/examples/factor_graphs/monty_hall.py | 1,929 | 3.703125 | 4 | '''The Monty Hall Problem Modelled as a Bayesian Belief Network'''
from bayesian.factor_graph import *
'''
As BBN:
GuestDoor ActualDoor
\ /
MontyDoor
p(M|G,A)
As Factor Graph:
fGuestDoor fActualDoor
| ... |
8b7f918905ca63d8d5d0c51fd880a936b840e9fb | kinetickansra/algorithms-in-C-Cplusplus-Java-Python-JavaScript | /Algorithms/Recursion/Python/towerOfHanoi.py | 301 | 3.703125 | 4 | def moveTower(height,source, destination, helper):
if height >= 1:
moveTower(height-1,source,helper,destination)
moveDisk(source,destination)
moveTower(height-1,helper,destination,source)
def moveDisk(s,d):
print("Moving disk from",s,"to",d)
moveTower(4,"A","B","C")
|
81f649ae24879765da37c0e7b5e3e65f3efbe782 | shirleymramirez/ProblemSet1_PayingOffCreditCardDebt | /ProblemSet1_PayingOffCreditCardDebt.py | 1,000 | 4.15625 | 4 | outstandingBalance = float(raw_input('Enter the outstanding balance on your credit card: '))
annualInterestRate = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
minMonthlyPaymentRate = float(raw_input('Enter the minimum monthly payment rate as a decimal: '))
totalAmountPaid = 0
for month... |
31aafda238ce087957eac248316499a98b3d6689 | msalameh83/Algorithms | /sorting/practice.py | 3,211 | 3.9375 | 4 | __author__ = 'Mohammad'
from random import randint
from random import shuffle
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def is_sorted(arr):
for i in range(1, len(arr)):
if arr[i-1] > arr[i]:
print('Not Sorted')
return
print('TRUE')
def less(... |
feff5ff1501a7831465caad619b3bd892cd17b31 | msalameh83/Algorithms | /BinarySearchTree/problems/same_bst.py | 1,654 | 4.03125 | 4 | __author__ = 'Mohammad'
"""
http://www.ideserve.co.in/learn/check-if-identical-binary-search-trees-without-building-them-set-1
Given two arrays which would be used to construct two different binary search trees(BSTs),
write a program to identify if the BSTs constructed from these would be identical.
The condition is t... |
1cc7e1bf42b23e0bebaeb62170f1f5663e61c25c | msalameh83/Algorithms | /BinarySearchTree/problems/all_paths.py | 785 | 4.1875 | 4 | __author__ = 'Mohammad'
"""
Given a binary tree, print all the root to leaf paths of the tree.
1
2 3
4 5
7 8
[1, 2, 4]
[1, 2, 5, 7]
[1, 2, 5, 8]
[1, 3]
Time Complexity is O(n)
Space Complexity is O(1)
"""
from BinarySearchTree.problems.Node import Node
from coll... |
980aa8bd33836a278f9dd2561113239c0aa01ea0 | msalameh83/Algorithms | /BinarySearchTree/problems/minimum_depth.py | 1,462 | 4.09375 | 4 | __author__ = 'Mohammad'
"""
Given a binary tree, find the minimum depth of the tree.
Minimum depth of a binary tree is the length of the shortest path of all paths from root to any leaf.
http://www.ideserve.co.in/learn/minimum-depth-of-a-binary-tree
Time Complexity is O(n)
"""
class Node(object):
def __init__(self... |
52129473eb537cb184513d240afeb377e7b41134 | msalameh83/Algorithms | /DataStructures/testing.py | 3,077 | 3.78125 | 4 | from scipy.optimize.anneal import fast_sa
__author__ = 'Mohammad'
class Node():
def __init__(self, val, next = None):
self.value = val
self.next = next
class SinglyLinkedList():
def __init__(self):
self.head = None
self.tail = None
def add_to_front(self,val):
n= N... |
ae9661eab3d65882e24348cef3e5fe08bb6f5644 | Miagarciaru/BasicPython | /print1.py | 833 | 4.28125 | 4 | print ("Hello Python") #Poner para escribir lo que se quiere decir
print ("He was a man called John")
print ("He had 70 years old until he died")
character_name = "John"
character_age = 50
print ("He was a man called " + character_name)
#print ("He had " + character_age +" years old until he died") had an error
pri... |
9b17e116e640a3d11aa6bbc1e9f7233ac934d93d | tamador1963/assignment-1 | /4_1.py | 1,020 | 3.703125 | 4 | class hous:
def __init__(self,area=0,num_of_room=0):
self._area=area
self._num_of_room=num_of_room
def getarea(self):
return self._area
def getnum_of_room(self):
return self._num_of_room
def setarea(self,area):
self._area=area
def setnum_of_room(self... |
774ea9a513a930495f83e24739686cfb8c8a18f5 | henrybudden/CS-NEA | /Code Practices/Examples/Object Orientated Programming/Programming/Crop Simulator/crop_class.py | 2,569 | 3.96875 | 4 | import random
class Crop:
"""A generic food crop"""
#constructor
def __init__(self, growth_rate, light_need, water_need):
#set attributes with initial values. Underscore prefix denotes protected attribute
self._growth = 0
self._days_growing = 0
self._growth_... |
7dd4eb47517ebe9e0862cdc9c40ce992b1826fc0 | henrybudden/CS-NEA | /Code Practices/Database/databaseClass.py | 7,853 | 4.0625 | 4 | import sqlite3
import datetime
class Database: #Create class for all database functions.
def __init__(self): #No class variables needed
pass
def execute(self, sql, values):
with sqlite3.connect("warehouse.db") as db:
cursor = db.cursor()
... |
4bc230ce5c61656d9e122db86bcab8a2c288d09a | vincentwenxuan/playgroud | /Python_Crash_Course/alien_invasion_refactored/ship.py | 3,038 | 3.671875 | 4 | import pygame
from bullet import Bullet
class Ship(object):
"""docstring for Ship"""
def __init__(self, screen, settings):
self.screen = screen
self.settings = settings
#Load the ship image
self.image = pygame.image.load('images/player.bmp')
self.resize_ship(... |
2f374505de4d534ddf9d4671c4104fd06ceecc8b | UMBC-AI/AIProject1 | /SamLeung95/Search.py | 3,100 | 3.921875 | 4 |
# coding: utf-8
# In[23]:
class Graph:
graph={}
def addnode(self, nodeName, connectedNode, weight):
if(nodeName in self.graph):
self.graph[nodeName][connectedNode]=weight
else:
self.graph[nodeName]={connectedNode:weight}
... |
83fab8746a1d861dc66ca8caf2ad17dc04e76f48 | UMBC-AI/AIProject1 | /tbry1/Search.py | 2,761 | 3.546875 | 4 | import sys
import queue
class Search:
def readFile(self, inFile):
graph = {}
with open (inFile) as file:
for lines in file:
s, f, w = lines.split()
graph.setdefault(s, []).append((f))
#print (graph)
return graph
def readFileWe... |
e1f261057a3f8c96f9b1d99903ab4b7337b79298 | UMBC-AI/AIProject1 | /csidell1/SearchStructure.py | 5,154 | 3.921875 | 4 | """
SearchStructure.py - Search structures for Search algorithms
CMSC 471 - Spring 2016
Author: Christopher Sidell (csidell1@umbc.edu)
ID: JZ28610
Abstract Search structure, queue(FIFO), stack(FILO), and a priority queue
"""
from abc import ABCMeta, abstractmethod
from SearchNode import SearchNode
from typing import L... |
32f4de9b871cd4b541396a7fedb5339762489964 | UMBC-AI/AIProject1 | /adamwe1/Search.py | 8,057 | 3.640625 | 4 | #Search.py
#Adam Wendler
#2/5/16
#CMSC471
import sys
#Holds a series of nodes and the weights of movement between them
class Graph:
#constructor
def __init__(self):
self.Nodes = {} #Nodes are held in a Dictionary
#Adds a node
def AddNode(self, name):
#nodes are dictionarie... |
00f6913b6f6d7685458cb58b6cb0f56d4de626fa | Frangconge/GeneralaZP19 | /registro_usuarios.py | 1,880 | 3.578125 | 4 | #import sqlite3
from tabulate import tabulate
# la idea es crear un menu para consultar instrucciones del juego o iniciar un juego directamente.
#import turtle
window = Tk()
menu = Menu(window)
window.config(menu = menu)
filemenu = Menu(menu)
menu.add_cascade(label = "juego nuevo", menu = filemenu)
#se crea la funcion... |
d1afec8729bb8e614d8c86d4611359b2e49717d9 | yezixigua/homeTE | /test.py | 1,742 | 3.5 | 4 | # def tt(a = [], b = 1):
# a.append(1)
# b += 1
# print(a, id(a), b ,id(b))
#
#
#
#
# tt()
#
#
# class Fab(object):
# def __init__(self, max):
# self.max = max
# self.n, self.a, self.b = 0, 0, 1
#
# def __iter__(self):
# return self
#
# def __next__(self):
# if se... |
0fb162f271f14febca99866283223e433f8a1d90 | psengupta1973/MachineLearning_py | /UniLinReg.py | 2,946 | 4 | 4 | # Given two data sets with test scores vs hours of study
# We can run a linear regression to predict test score for a given hour and see the graph
import numpy as np
import matplotlib.pyplot as plt
# the checkError method goes over the list of data once and returns a sum of errors
def checkError(x, y, theta):
... |
9cedd7e8936d88bb396b3fbf149e9d2fd0c7d367 | Hachirota/Coursework2017 | /encrypter.py | 513 | 3.96875 | 4 | plaintext = input("Please enter a phase to be encrypted: ")
cyphertext = ""
while len(plaintext) > 0:
char = plaintext[-1]
cypherchar = chr(ord(char) + 1)
cyphertext = cyphertext + cypherchar
plaintext = plaintext[:-1]
print(cyphertext)
cyphertext = input("Please enter a phrase to be decrypted: ")
p... |
56349371ea6d93b4223e37ff8e561c000f96ffad | Rich-Wu/wallbreakers | /week1/binaryGap.py | 482 | 3.59375 | 4 | class Solution:
def binaryGap(self, N: int) -> int:
max_dist = 0
current_dist = 0
started = False
N = "{0:b}".format(N)
for digit in N[::-1]:
if started:
current_dist += 1
if digit == "1":
max_dist = max(max_dist... |
66dab23d497788d58620d77ad76e4cefa276e8f7 | Rich-Wu/wallbreakers | /week1/reverseWords.py | 210 | 3.703125 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
reverse = ""
for _ in reversed(s):
reverse += _
reverse = reverse.split(" ")
return " ".join(reverse[::-1]) |
8e4ee6a77cddf5291ad673b6c4866f750220836d | Rich-Wu/wallbreakers | /week1/selfDividingNumbers.py | 502 | 3.71875 | 4 | from typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
nums = []
for num in range(left, right + 1):
if check_digits(self, num):
nums.append(num)
return nums
def check_digits(self, number: int) -> bool:
... |
6883c292ce9d00c1d8e9a4706d79458063544aa8 | mzanaj/Data-Camp | /Data Manipulation with Pandas/Vizualizations.py | 1,281 | 3.84375 | 4 | # Import matplotlib.pyplot with alias plt
import matplotlib.pyplot as plt
# Look at the first few rows of data
print(avocados.head())
# Get the total number of avocados sold of each size
nb_sold_by_size = avocados.groupby('size')['nb_sold'].sum()
# Create a bar plot of the number of avocados sold by size
n... |
9c38b8caf810afac5de4560eceac5bbd1f7993bb | mzanaj/Data-Camp | /Merging DataFrames with Pandas/MultiIndex-Concat.py | 1,759 | 3.578125 | 4 | for medal in medal_types:
file_name = "%s_top5.csv" % medal
# Read file_name into a DataFrame: medal_df
medal_df = pd.read_csv(file_name, header= 0, index_col='Country')
# Append medal_df to medals
medals.append(medal_df)
# Concatenate medals: medals
medals = pd.concat(med... |
5776f25b3d1bab49111f13a43f20149c73a9573d | mzanaj/Data-Camp | /Viz with Matplotlib/Histogram.py | 792 | 3.859375 | 4 | fig, ax = plt.subplots()
# Plot a histogram of "Weight" for mens_rowing
ax.hist(mens_rowing['Weight'])
# Compare to histogram of "Weight" for mens_gymnastics
ax.hist(mens_gymnastics['Weight'])
# Set the x-axis label to "Weight (kg)"
ax.set_xlabel('Weight (kg)')
# Set the y-axis label to "# of observations"... |
5649fadd0911a7873024fc9078c80905378c9f09 | mzanaj/Data-Camp | /Viz with Matplotlib/Error Bar - Boxplot.py | 1,155 | 3.75 | 4 | fig, ax = plt.subplots()
# Add a bar for the rowing "Height" column mean/std
ax.bar("Rowing", mens_rowing['Height'].mean(), yerr=mens_rowing['Height'].std())
# Add a bar for the gymnastics "Height" column mean/std
ax.bar("Gymnastics", mens_gymnastics['Height'].mean(), yerr=mens_gymnastics['Height'].std())
... |
938a03a00a99bf9488c7968479c6fa1509f19456 | mzanaj/Data-Camp | /Stats Thinking/Corr Plot and Cov.py | 1,027 | 3.5625 | 4 | # Make a scatter plot
_=plt.plot(versicolor_petal_length,versicolor_petal_width, marker="o", linestyle='none')
# Label the axes
_=plt.xlabel('Petal Length')
_=plt.ylabel('Petal Width')
# Show the result
plt.show()
# Compute the covariance matrix: covariance_matrix
covariance_matrix = np.cov(versicolor_pet... |
a284a1346975cbe8b3a26c2f1091ddd6d848008a | VladCincean/homework | /farmacii-virtuale/Library/IDGenerator.py | 585 | 3.609375 | 4 | '''
Created on 21 nov. 2015
@author: Vlad
'''
class IDGenerator(object):
'''
Manages the allocation of unique IDs for objects
'''
def __init__(self, firstID):
'''
Constructor for IDGenerator class
Input: firstID (integer) - The first valid ID. The following IDs are increased ... |
ec1776a19a23d613a0611d5e9bcfa5e2043c55f5 | VladCincean/homework | /Computational Logic/domain/conversions.py | 2,283 | 3.953125 | 4 | '''
Created on 7 dec. 2015
@author: Vlad Cincean
'''
from domain.operations import add, mul, div
def substitution_method(n, s, d):
'''
Performs a conversion from base s to base d using the substitution method
It is recommended if s < d ! Raises ValueError if s >= d or s,d not in {2, 3, ..., 10, 16}
In... |
f81e32aba887bcaa0a303d993e469c707fd6fa2f | giulianadowd/trivia-refactoring | /trivia_test.py | 4,588 | 3.796875 | 4 | #!/usr/bin/env python3
class Game:
def __init__(self):
self.players = []
self.places = [0] * 6
self.purses = [0] * 6
self.in_penalty_box = [0] * 6
self.pop_questions = []
self.science_questions = []
self.sports_questions = []
self.rock_questions = []
... |
c03422d0e8b7f87e105bbe162891d9acefd7e028 | urbeck/pyaton | /test.py | 171 | 3.8125 | 4 | print("Да, здесь!")
if 1 == 1:
print("1 = 1")
a = input("1 + 1 = ?")
if a == 2:
print("Правильно!")
else:
print("Неправильно!")
print(1)
|
0e6bae10c8ee97e36c288539e140724031374ae6 | MuflahNasir/basic-concepts-of-python-in-codes | /Check Plindorme.py | 307 | 4.21875 | 4 | integer = eval(input("Enter three-digit integer: "))
digit1 = integer % 10
Rem_integer = integer // 10
digit2 = Rem_integer % 10
digit3 = Rem_integer //10
print("The integer is ",integer)
if digit1 == digit3:
print("The integer is palindrome")
else:
print("The integer is not palindrome")
|
4b1ee348435479c840c18becf56ad545e9932cde | MuflahNasir/basic-concepts-of-python-in-codes | /InputOutputRedirection.py | 208 | 4.21875 | 4 | number = eval(input("Enter an integer: "))
max = number
while number != 0:
number = eval(input("Enter an integer: "))
if number > max:
max = number
print("max is", max)
print("number", number
|
c3ebaee49484f9a2c5d4deed46805af93a02b9b9 | MuflahNasir/basic-concepts-of-python-in-codes | /Lottery.py | 569 | 3.796875 | 4 | import random
number = random.randint(0, 99)
guess = eval(input("Enter you lottery guess of two digit number: "))
digit1 = guess % 10
digit2 = guess //10
number1 = number % 10
number2 = number // 10
print("Lotter number is ",number)
if guess == number:
print("You win $10,000")
elif (digit1 == number1 or dig... |
5a4561aa0fc342a50f197c5ef2ad2a3d7b653270 | MuflahNasir/basic-concepts-of-python-in-codes | /Locate point in a rectangle.py | 997 | 4.1875 | 4 | import turtle
import math
x, y = 0, 0
h, w = 60, 100
x1, y1 = eval(input("Enter two coordinates of a point: "))
s = turtle.Screen()
turtle.penup()
# start at the center
turtle.goto(x,y)
# head east
turtle.setheading(0)
# go to the middle of the right side
turtle.forward(w / 2)
# turn south, put the pen down, start d... |
972b350a8f2c2fb5aa95a83b58ab95ee8310f08b | temirbayeva/sql_python | /task.py | 284 | 3.734375 | 4 | import tkinter as tk
def changtext():
edit.delete(0, 'end')
window = tk.Tk()
t1 = tk.Label(window, text='Enter your text',fg='red')
t1.pack()
edit=tk.Entry(window, width=30, bg='pink')
edit.pack()
but=tk.Button(window, text='Puch', command=changtext)
but.pack()
window.mainloop()
|
7a9e58336a0a587dac7a1f251b4467184ec133d7 | Eminem-ant/Leet-Code | /SinglyLL.py | 1,190 | 4.34375 | 4 | # Python3 program to check if linked
# list is palindrome using stack
class Node:
def __init__(self,data):
self.data = data
self.ptr = None
# Function to check if the linked list
# is palindrome or not
def ispalindrome(head):
# Temp pointer
slow = head
# Declare a stack
stack = []
ispalin = True
... |
23c4e71c3acf26108a65a979c77206b96034231f | Eminem-ant/Leet-Code | /anagram.py | 753 | 3.515625 | 4 | NO_OF_CHARS = 256
file1 = open("input.txt","r")
file2 = open("input1.txt","r")
str1 = file1.readline().rstrip()
str2 = file2.readline().rstrip()
file1.close()
file2.close()
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
for i in str1:
count1[ord(i)]+= 1
for i in str2:
count2[ord(i)]+= 1
flag = True
i... |
18439586fb9ed308face48d35e79323a0f7b3ee6 | ricrogz/Wordhunter | /formatting.py | 245 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def embolden(s):
return f'\002{s}\002'
def listtostr(iterable, conj="and"):
lst = list(iterable)
if len(lst) == 1:
return lst[0]
else:
return ', '.join(lst[:-1]) + f' {conj} {lst[-1]}'
|
6848be90205e5f79370ff1c4b01dff6f3edfef14 | MD6338/Python | /ex2.py | 625 | 4.03125 | 4 | # Faulty Calculator
# 45 * 3 = 555, 56 + 9 = 77, 56 / 6 = 4
print("Enter first number :")
inp = int(input())
print("Enter Operator :")
op = input()
print("Enter second number")
inp2 = int(input())
if inp == 45 and inp2 == 3 and op == "*":
print("Answer - 555")
elif inp == 56 and inp2 == 9 and op == "+":
print("... |
8d10544590583db722487035621e7f8b02b6c3b1 | MD6338/Python | /tut12.py | 105 | 3.890625 | 4 | # if 5>9: print("5 is greater than 9")
print("5 is greater than 9") if 5>9 else print("9 greater than 5") |
934400d10cf1801bdccc964e52622effbb46001c | SevcanDogramaci/bioinformatics-algorithms | /LloydAlgorithm.py | 3,666 | 3.640625 | 4 |
from math import sqrt
from random import randrange
# constant definitions
COMPARISON_THRESHOLD = 0.00001
MATRIX_DIM = 10
K = 3
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def find_distance_to(self, other_point):
squared_distance = (self.x - other_point.x)**2 + (... |
c404578f27952d3b91725f3c1ff113f4a60593ac | d4ngermana/python | /runnerUp.py | 123 | 3.671875 | 4 | n = int(input())
my_list = []
while n :
num = int(input())
my_list = my_list.append(num)
n = n-1
print(my_list) |
7e0e05e60918238b55683521024652c7c20bc3a9 | d4ngermana/python | /password_checker.py | 229 | 3.9375 | 4 | username = input('Your Username?')
password = input('Enter Your Password')
password_length = len(password)
password_string = '*' * password_length
print(f'Hey {username}, Your password {password_string} is {password_length} letters long') |
5ba3eb7393c317878389f6de841e03e0570bdc09 | d4ngermana/python | /rotation.py | 199 | 3.5625 | 4 | ar = [1,2,3,4,5,6,7]
rotate = int(input("How many rotation?"))
n = len(ar)
while rotate:
temp = ar[0]
for i in range(n-1):
ar[i] = ar[i+1]
ar[n-1] = temp
rotate-=1
print(ar)
|
251bdb6cb09a1d60d9e9e5edb7517efb025d9e42 | Samriddhakc/Animal-guessing-game | /main_file.py | 3,439 | 3.59375 | 4 | from tkinter import *
from Object_A16 import *
class Animal_guessing_GUI:
def __init__(self, master):
self.master = master
self.object_file=animal_guessing_implementation()
def update_text_box_yes(self,display_lab):
self.object_file.yes_button()
display_lab['text']=self.obje... |
cbd868ad03b24cc1cbe82099b91b289bf492d1c1 | NishaUSK/pythontraining | /ex12.py | 1,068 | 4.4375 | 4 | #converting list to tuple
print(tuple(['hi', 'hello','how are you', 'well']))
print("-------------------------------------")
sea = ['starfish','shark','octopus','crocodial']
print(tuple(sea))
print("-------------------------------------")
print(tuple("nisha"))
print("-------------------------------------")
... |
4216452265d44c62f8233e6b84928e6a1071e782 | NishaUSK/pythontraining | /ex19.py | 124 | 4 | 4 | #Using Formatters to Organize Data
for i in range(2,13):
print(i,i*i,i*i*i)
print("----------------------------")
|
e42edfb10dfe5f99c4f34bec6185e472f8c2eacd | NishaUSK/pythontraining | /ex17.py | 245 | 3.921875 | 4 | #assigning single value to multiple variables
a=b=c=d=15
print(a)
print(b)
print(c)
print(d)
print("--------------------------------")
#assigning multiple values to multiple variables
s,n,v="nisha",26,18.0
print(s)
print(n)
print(v)
|
20970fc7b629b7656bb9fc1e4af9a4459995ba72 | HiAwesome/python-leetcode | /leetcode/q0232-implement-queue-using-stacks/solution.py | 817 | 3.921875 | 4 | """
https://leetcode-cn.com/problems/implement-queue-using-stacks/
https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode/
https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/bzhan-tu-jie-leetcode-232-yong-zhan-mo-ni-dui-lie-/
"""
class MyQueue... |
0955fe5c453272140cc92845b250b32234dd5847 | HiAwesome/python-leetcode | /leetcode/q0133-clone-graph/solution.py | 831 | 3.5 | 4 | """
https://leetcode-cn.com/problems/clone-graph/
https://leetcode-cn.com/problems/clone-graph/solution/ke-long-tu-by-leetcode/
https://leetcode-cn.com/problems/clone-graph/solution/dfs-he-bfs-by-powcai/
"""
class Node:
def __init__(self, val=0, neighbors=None):
if neighbors is None:
neighbors... |
b6f79f17050c36a4420297277e4d7282a6aefc25 | HiAwesome/python-leetcode | /leetcode/q0912-sort-an-array/solution.py | 1,067 | 3.78125 | 4 | """
https://leetcode-cn.com/problems/sort-an-array/
https://leetcode-cn.com/problems/sort-an-array/solution/pai-xu-shu-zu-by-leetcode-solution/
"""
from random import random
from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
self.randomized_quicksort(nums, 0, len(n... |
85e28d768c64aa0f2038764aed52a10d9899440a | mattycoles/alien_invasion | /settings.py | 1,488 | 3.71875 | 4 | class Settings():
""" Class to save settings for alien invasion """
def __init__(self):
""" Initialise the game settings """
self.screen_width = 1200
self.screen_height = 800
self.bg_colour = (230,230,230)
# Ship Settings.
self.ship_speed_factor = 1.5
self.ship_limit = 3
# Bullet setting... |
718a43bcfbcfc0efa66914d6b2c546b813633024 | EnthusiasticTeslim/MIT6.00.1x | /other/guess_my_number.py | 760 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 00:02:25 2019
@author: olayi
"""
print("Please think of a number between 0 and 100!")
minim = 0
maxim = 100
diff = 0
guess = (minim + maxim)/2
while True:
print("Is your secret number {}".format(guess))
indicator = input("Enter 'h' to indicate ... |
9d18a54c03e37a7456b655ddd1edc8c1692da917 | EnthusiasticTeslim/MIT6.00.1x | /other/IsIn_search.py | 862 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 00:54:31 2019
@author: olayi
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
low = 0
high = len(aStr)
mid = (low + high)//2
... |
d7a0b7973c717fd8641482205a7c0b372f7bc98d | EnthusiasticTeslim/MIT6.00.1x | /other/vowel_count.py | 257 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 18:40:11 2019
@author: olayi
"""
count = 0
s = 'azcbobobegghakl'
for let in s:
if let == 'a' or let == 'e' or let == 'i' or let == 'o' or let == 'u':
count += 1
print(count) |
842dd52f79f31ef0a8d35fe571ca2b6278b3a7d9 | EnthusiasticTeslim/MIT6.00.1x | /week6/codewars/shortest_steps_to_num.py | 382 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 18:38:51 2019
@author: olayi
"""
def shortest_steps_to_num(num):
# Good Luck!
if num < 1 or num > 10000:
raise ValueError("Verify your input")
trans = 1
count = 0
while trans < num:
trans += trans
co... |
3ec766fd7f738dc86b2cc7f5102007f8aeef9e26 | EnthusiasticTeslim/MIT6.00.1x | /week6/codewars/DNA_Strand.py | 369 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 13:52:21 2019
@author: olayi
"""
def DNA_strand(dna):
DNA = ''
for char in dna:
if char == 'A':
DNA += 'T'
elif char == 'T':
DNA += 'A'
elif char == 'G':
DNA += 'C'
else:
... |
25897e6c15688593d5ce37566d3907cb233517aa | EnthusiasticTeslim/MIT6.00.1x | /week4/Hackerrank/hckrank_v3.py | 369 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 10:57:32 2019
@author: olayi
"""
def getCount(inputStr):
num_vowels = 0
# your code here
vowels = ['a','e','i','o','u']
for alpha in inputStr:
if alpha in vowels:
num_vowels += 1
return num_vowels
inpu... |
5b4de14834648e18a734e95e005d8e0575ebee23 | mariedos/test | /test_git.py | 180 | 3.734375 | 4 | import time
n = 0
continuer = 'o'
while continuer == 'o':
print("Le compteur est maintenant à {}".format(n))
continuer = input("Voulez-vous continuer ? o/n")
n += 1
|
88afc8f8d86a6e030dc9c84c1d3aff7a268be2d6 | VictorZ94/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 194 | 3.515625 | 4 | #!/usr/bin/env python3
""" type-annotated function to recieve float and return a str
"""
def to_str(n: float) -> str:
""" take an arg type float and return a str
"""
return str(n)
|
83294754de033d98696f8eb6348b6ef210a25d82 | VictorZ94/holbertonschool-web_back_end | /0x00-python_variable_annotations/miscellaneous/annotations.py | 628 | 4.09375 | 4 | #!/usr/bin/python3
def greetings(name: str) -> str:
return f"Hello {name}!"
print(greetings("Víctor"))
def new_greetings(name: str) -> None:
print(f"Hello {name}!")
new_greetings("Mom")
# type annotation int typed
a: int = 20 # annotation to variable
print(a)
def add(a: int, b: int) -> int:
return a... |
3b137a6c564b7b21811f9777b794356aea841637 | VictorZ94/holbertonschool-web_back_end | /0x01-python_async_function/2-measure_runtime.py | 529 | 3.515625 | 4 | #!/usr/bin/env python3
"""function that measures the total execution time for wait_n(n, max_delay)
"""
import asyncio
import time
wait_n = __import__('1-concurrent_coroutines').wait_n
def measure_time(n: int, max_delay: int) -> float:
"""
Args:
n (int): [initial value]
max_delay (int): [time... |
53b3cbc969e3b2465faf22ce7a0e4c921f2bb4da | wainstead/programming-challenges-sept-2019 | /pieces/queen.py | 792 | 3.828125 | 4 | from .piece import Piece
class Queen(Piece):
name = 'Queen'
def moves_algorithm(self, coordinates):
moves_coordinates = self._determine_horizontal_and_vertical_moves(coordinates)
(row, col) = coordinates
directions = (
(1, 1),
(1, -1),
(-1, 1),
... |
0cb9c291522d34f08a912f8a730c166e1cd9a6a3 | tshradheya/ai-projects | /8-puzzle-search/8-puzzle-IDS.py | 7,136 | 3.53125 | 4 | import os
import sys
class Puzzle(object):
explored = 0
num_nodes = []
def __init__(self, init_state, goal_state, visited):
# you may add more attributes if you think is useful
self.init_state = init_state
self.goal_state = goal_state
self.actions = list()
self.visi... |
6d0d09667b7d02bbb98909947defe379a77332f1 | mohanrajendran/ProjectEuler | /20.py | 156 | 3.75 | 4 | # Problem 20
# Factorial digit sum
#
from math import factorial
def sum_digit(n):
return sum(int(x) for x in str(n))
print sum_digit(factorial(100))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.