blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
37d07b988d460e91d6d6aaf4f8d93ffcb4446284 | zjmdyd/Web | /04_python/06_面向对象编程/02_访问限制.py | 3,238 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
"""docstring for Student"""
def __init__(self, name, score):
super(Student, self).__init__() # 特殊方法“__init__”前后分别有两个下划线!!!
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
def get_grad... |
af0057033c77a413aa4bd3699e5e2cb58bb87fef | unigranrioTI/LouzadaN4 | /Teste/Exercicio 2.py | 571 | 3.75 | 4 | sexMas = int(input('Digite quantos alunos do sexo masculinos possuem: '))
sexFem = int(input('Digite a quantidade de alunos do sexo feminino: '))
alunosApro = int(input('Digite a quantida de alunos aprovados: '))
totalAlunos = sexMas + sexFem
porcMas = sexMas*100 / totalAlunos
porcFem = sexFem*100 / totalAlunos
porcApr... |
5535fe52383b506d3dd6fa8ca2c14aee46ba9ea1 | MashMaleLLO/LearnSQLDB | /dbManager.py | 456 | 3.75 | 4 | import sqlite3
#ติดต่อกับ file database
connecT = sqlite3.connect('/Users/naraw/Desktop/sqlite/chinook.db')
print("HI")
#เรียกใช้คำสั่งใน ภาษา sql
cur = connecT.execute("SELECT CustomerId,FirstName,LastName FROM customers WHERE CustomerId <= 10 ORDER BY CustomerId DESC;")
for row in cur:
print("Customer ID : ", row... |
277af3432dc7938e01abd1a9a41470e70af7ca90 | rafaelperazzo/programacao-web | /moodledata/vpl_data/13/usersdata/137/5747/submittedfiles/flipper.py | 243 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
P=input('digite a posição da porta P:')
R=input('digite a posição da porta R:')
if P==0:
print('C')
elif P==1 and R==0:
print('B')
else:
print('A') |
1fc160a80479e125b845d84a4cc87d027ca8aede | mygithello/python_test | /pythonbase/15python的类定义及内容.py | 9,811 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class Employee:
'所有员工的基类'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmploy... |
84fc7efbcd1b64c26d8caeb00c88c1382542fc6b | SirFreud/learn-python | /python-basics/number-game.py | 880 | 4.125 | 4 | import random
def game():
# generate a random number between 1-10
secret_num = random.randint(1, 10)
guess_count = 0
while True:
# get a number guess from player
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("That's not a number, try again!")
continue
if gu... |
3d17a6e7efc3d1435286b7e0da76f72d97676075 | guillermedev75/tp1-python | /questão01.py | 471 | 4.0625 | 4 | #Aplicação para somar ímpares
#Função responsável por somar os termos ímpares
def somaTermos(termos):
#Variavel
soma = 0
#Laço que soma os termos
for termo in range(1, termos, 2):
soma += termo
#Onde é impresso o resultado da função
print(f'\nA soma dos termos ímpares é {... |
a4bcb20a78e023bff5abf4bd5393e0a37eefdeff | SanjanaSawant1234/python | /bday user1.py | 256 | 3.59375 | 4 | def bday(ab):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday ,dear !"+ab+".")
print("Happy Birthday to you!")
def main():
username=input("Enter name:")
bday(username)
main()
|
aa3c97fe4d17e410aa1b0af7f222b591205d7e10 | saquibherman/Solutions_Python_Crash_Course | /Part_1/chapter_6/6-1_person.py | 197 | 3.609375 | 4 | person = {
'first_name' : 'noor',
'last_name' : 'khan',
'age' : '6',
'city' : 'stockholm',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
|
d3c6203df34a0a09175df819f8d4de9fdd8556c1 | cailiaoniubi/TUM_2021Results | /3rd Exercise Supervised Learning.py | 7,716 | 3.59375 | 4 | # Jian Hu is writing the code here
# ''' Day3 Exercise for Supervised Machine Learning '''
# import the methods and packages we need
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_boston
from sklearn.preprocessing import PolynomialFeatures... |
4dab26960702bfd6932255cd668bc48a35f847de | ubuntunux/WorkSpace | /Codes/PrimaryArithmetic/PrimaryArithmetic.py | 241 | 3.53125 | 4 | while True:
A, B = input("Input 2 numsbers or 0 0 for quit : ").split()
if A != "0" or B != "0":
print("%d carry operation." % len([i for i in range(1, min(len(A), len(B))+1) if (int(A[-i:])+int(B[-i:])) >= 10**i]))
else:
break |
d7872ed613d3b9f9326c28089b27907de14e5086 | naldridge/python2 | /lists2.py | 784 | 4.25 | 4 | # Sum the Numbers
# Create a list of numbers
# Print the sum
# Lists numbers to work with
list_of_numbers = [-1,3,4,6,-7,8]
# Shortcuts
#print(sum(list_of_numbers))
#print(min(list_of_numbers))
#print(max(list_of_numbers))
#Starting value
total = 0
# Prints each number in list_of_numbers
#for number in list_of_num... |
b84559587472babce3f0f5cc1b65d94045377451 | CzerniawskiHugo/CDV-Python-WeekTwo | /Zadanie4.py | 522 | 3.96875 | 4 | import numpy as np
print('This app calculates the average and standard deviation')
while 1==1:
n = int(input('Please insert the amount of numbers: '))
r = []
for i in range(n):
r.append(int(input('Type the value of r: ')))
mean = np.mean(r)
standard = np.std(r)
print(... |
3a4e614505ba996ccadf7638f1230d8d4edb9770 | brycereynolds/practice | /data_structures/Trees_IsBinarySearchTree_2.py | 607 | 3.78125 | 4 | def check_binary_search_tree_(root, lower=None, upper=None):
if root is None or root.data is None:
return False
if lower is not None and root.data < lower:
return False
if upper is not None and root.data > upper:
return False
if root.left is not None:
if root.left.data... |
21608792d9074eaf744db4c9455fab6a6a49fd37 | julianakcm1/Minicurso-de-Python_Katie | /2.py | 138 | 3.921875 | 4 | #print("Metros: ")
metros = int(input("Digite a quantidade de metros:\n"))
centimetros = metros * 100
print(centimetros, "centímetros")
|
0257161a34362d29091d636a554b4f0bb2034437 | cheyunping77/learingnote | /基础代码/Python练习题 037:毕达哥拉斯三元组之乘积.py | 801 | 3.59375 | 4 | '''
这题若是想清楚了,其实是相当简单,无非是找出各种 a+b+c=1000 的组合,然后验证 a**2 + b**2 = c**2 就行了。
遍历范围方面,因为 a<b<c,最小的 a 最大也就是 332,所以取值范围可设为 range(1, 1000//3)。
b 肯定比 a 大,而且撑死了也超不过 500,所以取为 range(a+1, 1000//2)。而一旦 a, b 都确定,c 自然也就确定了。
话说、什么“毕达哥拉斯三元组”啊?不就是“勾股定律”里的“勾三股四弦五”吗……
果然古代中国人都不怎么外交的,所以西方人都不知道,这定律早就被中国人发现了……
'''
for a in range(1,100... |
737a7ea458b6e31a3cf819e958b6e2c41f3071dd | Mrquoc2409/Pham-Quoc-Anh-C4T8 | /Session9/eg40.py | 1,459 | 4 | 4 | points = 0
Questions = {
'1':'Who is Spiderman ?',
'Answers' :{
'A':'Tom Holland',
'B':'Steve Job',
'C':'You'
},
'Correct answer':'A'
}
print ('1',Questions['1'])
for i in Questions['Answers']:
print (i,'.', Questions['Answers'][i])
a = input("What's your answer ?").upper()
... |
d1b88598c3d0416926cf81d98d10a907cc19bb18 | prossellob/CodeWars | /Fizz_Buzz.py | 722 | 4.21875 | 4 | '''Return an array containing the numbers from 1 to N, where N is the parametered value. N will never be less than 1.
Replace certain values however if any of the following conditions are met:
If the value is a multiple of 3: use the value 'Fizz' instead
If the value is a multiple of 5: use the value 'Buzz' i... |
74bcfc187e93a5400fc008128e2ada59e97a3c83 | wwtang/code02 | /fibcache.py | 872 | 4.125 | 4 | """fibonacci numbers: cache the intermediate result"""
import time
#Cached method
def fib1(n):
cache_dict = {0:0,1:1}
if n == 0: return 0
if n == 1: return 1
if n in cache_dict:
return cache_dict[n]
cache_dict[n] = fib1(n-1) + fib1(n-2)
return cache_dict[n]
#Non Cached method
def fib... |
8efeb39d390eb120e6b3b564235106fcb5ef80af | blackplusy/0504 | /例子-0511-01.python的输出.py | 514 | 3.734375 | 4 | #coding=utf-8
#字符集相当于翻译官,解析不同语言进行显示
#中国的字符集GBK2312
#1.直接输出
#直接输出是通过
print("天气不错!!!")
print(100)
#2.
a=100
print(a)
a='hello'
print(a)
a=10
b=20
print(a+b)
a='hello'
b='python'
print(a+b)
#3.
print(abs(-10))
a='memeda'
print(len(a))
#4.
name='heygor'
age=18
print('黑哥的年龄是18')
print('%s的年龄是%d'%(n... |
6db90e6de92dc5a3ca12f22a6e94577abd42a6c1 | gungorefecetin/CS-BRIDGE-2020 | /Day3PM - Lecture 3.1/khansole_academy.py | 1,021 | 4.375 | 4 | """
File: khansole_academy.py
-------------------
This program generates random addition problems for the user to solve, and gives
them feedback on whether their answer is right or wrong. It keeps giving them
practice problems until they answer correctly 3 times in a row.
"""
# This is needed to generate random numb... |
5dd2fcb097b04e1746f23ed3d9cba0c27a462725 | ornichola/learning-new | /pythontutor-ru/01_inout_and_arithmetic_operations/05_hello_harry.py | 354 | 4.21875 | 4 | '''
http://pythontutor.ru/lessons/inout_and_arithmetic_operations/problems/hello_harry/
Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу:
'''
name = input()
print('Hello, ' + name + '!')
|
ce468202768636304ced89e55d16a905f7c847e6 | eflagg/Accounting-Scripts | /melon_info.py | 898 | 4.0625 | 4 | """
Prints out all the melons in our inventory
"""
from melons import melon_names, melon_seedlessness, melon_prices
"""
def print_melon(name, seedless, price):
have_or_have_not = 'have'
if seedless:
have_or_have_not = 'do not have'
print "{}s {} seeds and are ${:.2f}".format(name, have_or_hav... |
fb9ca0dede77d9fd75b967141e8b8bad02cf08d5 | ncheungg/EQWorks | /questions1-3.py | 2,034 | 3.53125 | 4 | import pandas as pd
from math import pi
class EQWorks:
def __init__(self):
self.poi = pd.read_csv("data/POIList.csv")
self.data = pd.read_csv("data/DataSample.csv")
def findPOI(self, latitude, longitude):
distance = 2 ** 31 - 1 # purposely set high so first hypotenuse is always lower... |
f011e84fcb065e08bf95df58d113a438a3a9a13a | Jorgefebres/python-tut-pildoras | /condicionales5.py | 692 | 4.0625 | 4 | salario_presidente = int(input("INTRODUCE SALARIO PRESIDENTE: "))
print("SALARIO DEL PRESIDENTE: ", salario_presidente)
salario_director = int(input("INTRODUCE SALARIO DIRECTOR: "))
print("SALARIO DEL DIRECTOR: ", salario_director)
salario_lider_proyecto = int(input("INTRODUCE SALARIO LIDER DE PROYECTO: "))
print("SA... |
c6dad18005b6b80cfb46f9175fce2b54cdaa94d0 | gabriellaec/desoft-analise-exercicios | /backup/user_372/ch19_2020_03_09_19_50_54_372540.py | 412 | 3.734375 | 4 | def classifica_triangulo(x, y, z):
if x==y and y==z:
return 'equilatero'
elif x==y and x!=z or x==z and x!=y or y==z and z!=x:
return 'isósceles'
else x!=y and x!=z and y!=z:
return 'escaleno'
print(classifica_triangulo(5, 5, 5).format(x, y, z))
print(classifica_triangulo(5, 5, 7).fo... |
b3b9aeb7e84979950e940b78e2398bfa3c9f40e7 | TopZeraProductions/linguagem-de-programacao-II | /exercicios/09-24-2018/Professor.py | 1,226 | 3.609375 | 4 | #João Vitor Paulino - 1801021 - paulino.joaovitor@yahoo.com.br
#Daniel Roberto - 1800479 - bruce-irom@hotmail.com
#Tiago Beneteli - 1800804 - tiagobeneteli@hotmail.com
#Ramon C. Pires - 1800260 - ramoncavpires@gmail.com
class Professor:
def __init__(self):
self.__email = None
self.__nome = None
... |
3d169db232ecfc0a3a3f535319f40adc85c2f90f | bybel/Python-projects | /facto.py | 251 | 4.03125 | 4 | while True:
nb = int(input("what factorial do you want?"))
prod = 1
for i in range(0, nb):
prod = prod * (i+1)
print(prod)
reponse = input("recommencer?")
if reponse == 'n' or reponse == 'N':
break
|
0fe623a2f1469421161084a29540aaa47ff45810 | GreenMarch/datasciencecoursera | /algo/hash_table/continuous-subarray-sum.py | 1,237 | 3.65625 | 4 | class Solution(object):
def checkSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
my_hashmap = {0: -1}
su = 0
for idx, num in enumerate(nums):
su += num
if k != 0:
su = su % k
... |
a8d4bd47b47aebcdf9bdc492d1d34dcd25cfe3ad | ravichalla/wallbreaker | /week3/pow_xn.py | 750 | 3.875 | 4 | '''
QUESTION:
50. Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
'''
class Solution(object):
def myPow... |
936da96713d6caa28a287aae33f9fb2fbf74e9ad | neitpam/pythonForEveryoneCoursera | /count.py | 137 | 3.75 | 4 | count = 0
print('Before', count)
for thing in [9, 41, 12, 3, 74, 15]:
count = count + 1
print(count, thing)
print('After',count)
|
d0c6c97c71faaa21f45e40125255f088eb15ed7d | andreafresco/Project-Euler | /p003.py | 1,097 | 4.03125 | 4 | #
# Solution to Project Euler problem 3
# Copyright (c) Andrea Fresco. All rights reserved.
#
# https://projecteuler.net/problem=3
# https://github.com/andreafresco/Project-Euler
#
def smallest_prime(n): # return the smallest prime of n or n itself
# if it is prime
assert n > 0
i = 2
... |
151085f1cfcd29b4eca6237935a8a18c01b7839c | RonaldZhao/NowCoder | /7.8.py | 572 | 3.796875 | 4 | """
有一棵二叉树,请设计一个算法判断这棵二叉树是否为平衡二叉树。
给定二叉树的根结点root,请返回一个bool值,代表这棵树是否为平衡二叉树。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class CheckBalance:
def check(self, root):
if root is None:
return True
def chk(root):
... |
b302836efba52cebf2eee925d1caa664e6a6cc93 | csimps04/NPU_NeuralProcessingNetwork | /python_interface/pyexample.py | 835 | 3.890625 | 4 | import NeuralProgrammingUint as NPU
# number of inputs
inputs = 3
# number of outputs
outputs = 3
# number of hidden layers
hlayers = 2
# number of nodes in each hidden layer
hlayer_ vals = [4, 4]
# specify size of training batch
tr_batch_size = 1000
# specify size of testing batch
tst_batch_size = 50
# establish con... |
5ec397de4ac21f84123071ac1d331c5864ce3678 | alex-tarkhov/DataScience | /module_0/numberPredict.py | 676 | 3.546875 | 4 | import numpy as np
def numberPredict(minimum=1, maximum=1000):
'''Использую алгоритм бинарного поиска для минимализации количества попыток (count) поиска
рандомного числа в диапазоне от 'minimum' до 'maximum' '''
count = 1
predict = np.random.randint( minimum, maximum+1 )
start = minimum
e... |
3221f8a9d3e17d3e8fba4a1b9c9b719c2f36c033 | SahilShikalgar/Python-Tkinter-MySql | /ese.py | 3,566 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 18:55:24 2018
@author: SaHiL
"""
from tkinter import *
import tkinter.messagebox as MessageBox
import mysql.connector as mysql
def insert():
id = e_id.get()
name = e_name.get()
phone = e_phone.get()
if(id=="" or name=="" or phone==""):
M... |
e4a824336689f2c519c5d9a407d9d6f266d30b30 | viktor02/Hildr | /Hildr/Database.py | 1,387 | 3.75 | 4 | import sqlite3
import time
class Connector:
def __init__(self, database_name):
"""Initialize db class variables"""
self.connection = sqlite3.connect(database_name)
self.cur = self.connection.cursor()
def __exit__(self, ext_type, exc_value, traceback):
self.cur.close()
... |
61b134aac1c1e4c371f3d5f99a61ea2089866796 | msps9341012/leetcode | /string/removeDuplicates2.py | 441 | 3.703125 | 4 | def removeDuplicates2(S):
"""
:type S: str
:rtype: str
"""
stack=[]
for i in S:
if stack and i==stack[-1]:
stack.pop()
else:
stack.append(i)
return ''.join(stack)
def removeDuplicates2(S):
res=[]
for i in S:
res=res+[i]
if len(... |
cedfdff3a3e3ba1a645ebb609f896ca5cc87f0b1 | interuss/dss | /interfaces/openapi-to-go-server/operations.py | 8,738 | 3.640625 | 4 | import dataclasses
from typing import Dict, List, Tuple
import data_types
import formatting
@dataclasses.dataclass
class StringParameter:
"""Single parameter to an operation found in the path used to invoke the operation"""
name: str
"""Name of this parameter"""
description: str
"""Documentatio... |
0b48a2d0ed692e371a0d7a40d942c10f4f89702e | takumiw/AtCoder | /ABC057/C.py | 522 | 3.609375 | 4 | import sys
readline = sys.stdin.readline
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
def main():
N = int(readline())
... |
02ed14d7cee928f54efb768c56915cf3e669e4a2 | tobyatgithub/LeetCode | /876_Middle_of_the_Linked_List.py | 663 | 3.890625 | 4 | # 876. Middle of the Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
mid_finder, end_finder = head, head
# while end_finder.next and e... |
7b1513625d85a5a513744e604b85a9cb0ec18c21 | rameshtarini/blackjack | /cards.py | 3,072 | 4 | 4 | # Cards Module
# Basic classes for a game with playing cards
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit, value, face_up = True):
self.ra... |
20c168a490ee027720ec8e92b282a14f915e1476 | hpanushan/Tigo_Call_Center_Voice_Intent_Matching | /Get_File_Names.py | 325 | 3.53125 | 4 | from os import listdir
from os.path import isfile, join
def get_file_names(my_path):
# Getting files name in current dir
only_files = [f for f in listdir(my_path) if isfile(join(my_path, f))]
return only_files
#my_path = 'C:/Users/Anushan/Desktop/Car_Music/Music/English_Songs'
#print(get_file_name(my_pat... |
dc02ec2600792e819448c5aa3e0947e4a1f94488 | chirateep/algorithm-coursera-course1 | /week3_greedy_algorithms/1_money_change/change.py | 545 | 3.8125 | 4 | # Uses python3
import sys
def get_change(m):
total_coin = 0
coin_list = [10, 5, 1]
coin_index = 0
while (m > 0):
value_size = coin_list[coin_index]
# print(m, value_size)
if (m - value_size) >= 0:
m -= value_size
total_coin += 1
else:
... |
f06ecf434e44ae2bb776d25142d11039a6601531 | ashwinpunj/python-challenge | /main.py | 1,171 | 3.640625 | 4 | import csv
import os
import pandas as pd
csvpath = os.path.join('..', '..', 'HOMEWORK02', '02-Python',
'Instructions', 'PyBank', 'Resources', 'budget_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# print(csvreader)
csvrep = list(csvreade... |
8bacf187998cc3f6b114d751e6734955ea60c65e | Priyankasharma181/game | /lenghthfunction/len.py | 232 | 3.859375 | 4 | def user_string(user):
count=0
for i in user:
count+=1
return count
user_str=input("enter the name")
print(user_string(user_str))
# list1="priyanka"
# count=0
# for i in list1:
# count+=1
# print(count)
|
908403e7c401e913af726aa591796d56924683cb | dhtmdwo/edutem | /gector/json_to_text.py | 3,267 | 3.71875 | 4 | import sys, json, os
# HOW TO USE
# python3 json_to_text.py [filename1] [filename2] ...
# or python3 json_to_text.py folder [foldername]
# make if checklist do not exist
def make_checklist():
if not os.path.isfile('checklist.txt'):
with open('checklist.txt', 'w') as file:
pass
# check if alre... |
092af652e3d16d418895b2ad378bf05e3a588b56 | Izekor-Eric/Database | /add.py | 1,290 | 4.40625 | 4 | import sqlite3
#connect to database. You can connect without create the database file.
# when you save and run the connection, the database file will be created automatically.
connection = sqlite3.connect('books.db')
# creates a cursor.
connect = connection.cursor()
#createing the database table.
# note the data type ... |
d0672836fe96932f82412e0c1ce73103910c2ac2 | JBAhire/JuliaEconomics | /IntroStructuralEstimation/consump_leisure_python.py | 1,589 | 3.625 | 4 |
#############################################################################
###### Lecture: Introduction to Structural Econometrics in Julia ############
###### 3. Data generation, management, and regression visualization #########
###### Bradley Setzler, Department of Economics, University of Chicago ######
#######... |
fd9dc4a3318cce4211f40c0b6a5bb7b554f3773e | Dasmitrich/PythonLabs | /lab1/num2.py | 369 | 3.515625 | 4 | import math;
def f12(x):
if x < 99:
return 90 * x ** 6 + x ** 4 / 28 - 12
elif 99 <= x < 191:
return x ** 2 + x ** 4 + 41
elif 191 <= x < 228:
return 94 * x - 25 * x ** 8
elif 228 <= x < 268:
return 23 * x ** 6 + x ** 5 / 72 + math.log()
elif x >= 268:
retur... |
c35e023eca4325a2771dd81fde7b192f6821f5ec | August1s/LeetCode | /Tree/No863二叉树中所有距离为 K 的结点.py | 1,405 | 3.671875 | 4 |
# 如果能够为树中的所有节点添加一个指向父节点的指针,那么求距离问题就可以转化为BFS求距离问题
# 不过需要注意的就是需要控制访问
# 这里我们使用一个DFS统计父节点,顺便初始化节点访问列表
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
parent = {} # 使用一个hashmap保存节点的父节点
visted = {} # 使用一个hashmap记录节点是否访问
def DFS(head):
if not head:
return
... |
cb9b33e1a0a27e0c28d1e9bdf697de8b1dc079d6 | jimlyas/Project_python | /DASAR/gametebakangka.py | 805 | 3.765625 | 4 | from random import randint
class TebakAngka:
def tebak():
acak = randint(1, 100)
chance = 7
win = False
while chance!=0:
print('Kesempatan anda masih %d ' % chance+' lagi.')
tebak = int(input('Masukkan angka tebakan anda :'))
if teba... |
11567247870429d69d78ef56ea8d7d061513ca11 | jonXue92/PythonGit | /Algorithm/chapter3/twoSum.py | 256 | 3.671875 | 4 | # -*- coding: utf-8 -*-
def twoSum(numbers, target):
hash_set = set()
for i in range(len(numbers)):
if target-numbers[i] in hash_set:
return (numbers[i], target-numbers[i])
hash_set.add(numbers[i])
return None |
a1faef458f4b204e70d4a81837f100d5cad3024c | Flagman2015/projekt | /les2_task_6.py | 1,970 | 3.578125 | 4 | goods, order = [], 1
title, price, amount = None, None, None
while True:
if title is None:
tmp = input('Введите название товара: ')
if not tmp.isalnum():
print('Вы не ввели название товара')
continue
title = tmp
if price is None:
tmp = input('Введите ст... |
2f1d2211f4c259999c4c523350348a82e060b695 | KoushikBose2019/PYTHON-CODES | /dict.py | 1,937 | 4.40625 | 4 | # dictionarie
# its unorder collection of data in key: value pairs
# how to create dictionaries
#user={'name':'koushik','age':27}
#print(user)
#print(type(user))
# second method to create dictionary
#user1=dict(name='koushik',age=27)
#print(user1)
# how to access data from dictionary
# there is no indexing me... |
b13ac877e15fa7bbbcc6749527bd18f036929b02 | abhi8893/Intensive-python | /exercises/similar_authors.py | 1,641 | 3.96875 | 4 | def get_similar(author_dict, author, method='A'):
""" Return a list of similar authors
authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
'Kurt Vonnegut': ['Te... |
940e9e81d272e1a020b1b29053ab9bb48a856ecf | mabrenu/phyton_basico_2_2019 | /Tareas/Tarea_2.py | 669 | 3.90625 | 4 | #Promedio de los valores de la lista
mis_valores = [5, 6, 10, 13, 3, 4]
promedio = 0
for i in mis_valores:
promedio += i
print('El promedio de la lista es:', promedio / len(mis_valores) )
#Escriba un código en python que determine cual grupo de personas contiene la mayor de todas las alturas de todas las ... |
b891cf069a5f7386f21fa8d8dfa19e21f3f3665e | ajwake97/Week-8-Assignment | /main.py | 1,149 | 3.96875 | 4 | import os
filePath = input('Where would you like to save the file? \n')
fileName = input('What would you like to name the file? ')
userName = input('What is your name? ')
userAddress = input('What is your address? ')
userPhone = input('What is your phone number ')
completePath = filePath+fileName
if os.path.isfile(... |
014c5970823b525eeaa289ac563161aa4772a8b6 | Piton2306/Study | /Calculate m,p ,V.py | 839 | 4.15625 | 4 | """Расчитать массу плотность или обём"""
result = None
while True:
a = input('введите:масса, объем, плотность:')
if a == 'Масса' or a == 'масса':
p = float(input('Плотность = '))
v = float(input('объем = '))
m = p * v
print('Масса = %.1f' % (m))
elif a == 'объем' or a == 'Об... |
8f18940e9479c86a392fd9f228793b5936b4b15b | shaon0000/csv-converter | /csv_converter_test.py | 4,147 | 3.5 | 4 | import unittest
from csv_converter import CSVdata
class CSVdataTest(unittest.TestCase):
def setUp(self):
self.files = []
self.new_data = CSVdata(['january', 'february', 'march'])
""" first data source is a typical ideal case.
All of the mandatory columns are in perfect ... |
78433e5a63911e328884f5b5507d9106be43b647 | xiewenwenxie/168206 | /168206120/快速排序.py | 508 | 3.53125 | 4 | def quick_sort(alist, l, r):
if l < r:
q = partition(alist, l, r)
return quick_sort(alist, l, q - 1)
return quick_sort(alist, q + 1, r)
return alist
def partition(alist, l, r):
x = alist[r]
i = l - 1
for j in range(l, r):
if alist[j] <= x:
i += 1
a... |
e624c0e58d8b8720f4bcfc09401b45478634cffb | allbackoff/test_data_generation_with_PDG | /evaluation/find_max.py | 438 | 3.859375 | 4 | # find_max
def main():
x = int(input())
y = int(input())
z = int(input())
if x > y:
if y > z:
print(x)
else:
if x > z:
print(x)
else:
print(z)
else:
if x > z:
print(y)
else:
... |
d84d2b2b8048c3219f72eb46829b728504a1843d | smtamh/oop_python_ex | /student_result/2018/01_number_baseball/baseball_04.py | 2,063 | 3.59375 | 4 | import random
num = list(range(10)) # 랜덤 수 리스트
print("Welcome to number baseball game!")
print("Here 3digits, and you will guess it.")
print("If you had a correct digit in the right place, you will have a 1S.")
print("If you had a correct digit but in the wrong place, you will have a 1b.")
print("Either of them, you... |
764dddaea716b08372448fd74b3e6065a274bfd5 | Anju-PT/pythonfilesproject | /exam/pallindrom.py | 461 | 3.828125 | 4 | string=input("enter the string")
ls=list(string)
#print(ls)
#l=len(ls)
ls2=ls[::-1]
#print(ls2)
c=0
if(ls==ls2):
print("pallindrome")
else:
print("not pallindrome")
#o/p
#amma
#pallindrome
#helo
#not pallindrome
#ls=["a","d","b","b","d","a"]
# for i in ls:
# for j in ls2:
# if(i==j):
# ... |
1404cabb82989a88af9afcc23c7809efcbd84240 | Aasthaengg/IBMdataset | /Python_codes/p00001/s706380784.py | 138 | 3.53125 | 4 | mnts = []
for t in xrange(0, 10):
mnts.append(int(raw_input()))
tops = sorted(mnts, reverse = True)
for i in xrange(0, 3):
print tops[i] |
7f64d47b27371bb308281a53bec34ba352eb8837 | JhymerMartinez/Proyectos_PYTHON_JAVA | /serie_python/main/Main.py | 1,040 | 3.71875 | 4 | #encoding:utf-8
limite = int(raw_input("Ingrese el limite: "))
multiplic = 1.0
aux=0.0
contador = 1.0
numero = 2.0
divisor = 2.0
while contador <= (limite-1):
if (numero % divisor) == 0:
if numero == divisor:
for i in range(1,int(contador+1)):
multiplic = multiplic * i
... |
71902de1b91d4a1aec370330e6634e98084549c0 | nuha-jawi/code | /Day29.py | 224 | 4.0625 | 4 | l=['banana','cherry','apple']
for x in l:
print(x)
s='banana'
for a in s:
print(a)
for b in l:
print(b)
if b=='cherry':
break
for m in l:
print(m)
if m=='banana':
continue |
295254eaf88892cebe5450fa8b3ca8f096839a12 | coconetlero/algoritmos_clase | /Prac09/diamond.py | 850 | 3.96875 | 4 | # definicion de la funcion print_diamond
def print_diamond(size):
upper_half = int((size + 1) / 2)
lower_half = int(upper_half - 1)
# print upper half diamond
for i in range(upper_half+1):
spaces = upper_half - i
for j in range(spaces, 0, -1):
print(" ", end="")
... |
1c36f5bf5a686c7fe074bf882ef11d16051a18ba | nveenverma1/Dataquest | /Practice/20_Linear_Regression_for_ML/The Linear Regression Model-235.py | 2,059 | 3.65625 | 4 | ## 2. Introduction To The Data ##
import pandas as pd
data = pd.read_csv('AmesHousing.txt', '\t')
train = data[:1460]
test = data[1460:]
print(train.info())
print(test.info())
target = 'SalePrice'
## 3. Simple Linear Regression ##
import matplotlib.pyplot as plt
# For prettier plots.
import seaborn as sns
fig =... |
3be3547c1d16e7bcb12ffaa46f255c7320c8aa3c | patcoet/Advent-of-Code | /2019/10/2.py | 2,638 | 3.515625 | 4 | # Day 10: Monitoring Station
# Determine which asteroid will be the 200th to be vaporized by a rotating laser.
# Idea: Get a list of asteroids in line of sight of the station, and compute a list of them in clockwise order from 12. Iterate through and repopulate the list until reaching the target number.
import math
de... |
bc30f49b899ed52228506152fa360c7d161a2148 | yottabytt/atlas | /atlas/foundations_events/src/foundations_events/consumers/jobs/mixins/listing.py | 938 | 3.53125 | 4 |
class Listing(object):
"""Saves the a value to a set listing
Arguments:
redis {redis.Redis} -- A Redis connection object
"""
def __init__(self, redis):
self._redis = redis
def call(self, message, timestamp, meta_data):
"""See above
Arguments:
... |
f0fa9af9ba20618e232b903a69c0d469bb2471de | voicezyxzyx/python | /Exercise/PYTHON/yx_10_随机数.py | 186 | 3.546875 | 4 | # coding:utf-8
import random
a = random.randint(0, 99)
b = int(input("请输入你猜的数:"))
print(a)
if a == b:
print("猜对了")
else:
print("猜错了")
print(a)
|
40ba9b8d6915a8acb75df46def280dac825cad91 | shuyirt/Leetcode | /[00263-E]Ugly Number/iteration.py | 645 | 3.90625 | 4 | class Solution:
def isUgly(self, num: int) -> bool:
if num == 0:
return False
while (num):
print(num)
if num % 2 == 0:
num = num // 2
elif num % 3 == 0:
num = num // 3
elif num % 5 == 0:
num ... |
e9f90270e1b161b45f301354a0cf031eec33fe49 | tlian25/edabit_solutions | /stand_in_line.py | 130 | 3.515625 | 4 | def next_in_line(lst, num):
if lst == []:
return "No list has been selected"
else:
return lst[1:] + [num]
|
759cccd32b822bb319a519f3d4abbab9d133ea75 | rjrobert/daily_coding_problems | /daily13.py | 1,284 | 3.921875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "b... |
7c5d20db99b30e8c31ae609e4d84acb36d42adfb | Hamng/hamnguyen-sources | /python/LeetCode/roman_to_integer.py | 3,941 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 19:46:00 2021
@author: Ham
LeetCode #13: Roman to Integer
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we su... |
38ee487bc5766da0135f3be61e2090721573937e | Aasthaengg/IBMdataset | /Python_codes/p03605/s632232677.py | 97 | 3.828125 | 4 | s = str(input())
l = len(s)
if s[0]=='9' or s[-1]=='9':
print("Yes")
else:
print("No")
|
5021a0f3d355979b1b0c0d7ae15aba7030c0987f | huytng/GuessingGame | /GuessingGame.py | 2,203 | 4.25 | 4 | """Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
(Hint: remember to use the user input lessons from the very first exercise)
Extras:
Keep the game going until the user types “exit”
Keep tr... |
f6f1a3ed4161a17dc97ea295ced17569feb54952 | vvhiteboard/algorithm | /ccw/main.py | 614 | 3.953125 | 4 | def isCcw(point1, point2, point3):
x1 = int(point1[0])
y1 = int(point1[1])
x2 = int(point2[0])
y2 = int(point2[1])
x3 = int(point3[0])
y3 = int(point3[1])
vector1_x = x2 - x1
vector1_y = y2 - y1
vector2_x = x3 - x2
vector2_y = y3 - y2
vector_z = vector1_x * vector2_y - vec... |
03235b9985677750a0d6af51091675529989130b | Okle/interview_prep | /Graph/MeshMessage.py | 2,272 | 4 | 4 | from queue import *
# BFS without path
def isConnected(network, sender, recipient):
nodes_to_visit = Queue()
nodes_to_visit.put(sender)
already_visited = set()
while not nodes_to_visit.empty():
node = nodes_to_visit.get()
if node == recipient:
return print('Found!!')
... |
67babda4cd3b8d0a49514bba4689c6b3608b8a2a | alexjmedina/DataCamp | /pandas_DataFrames/PandasScatterPlots.py | 961 | 4.34375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# In this exercise, you're going to plot fuel efficiency (miles-per-gallon) versus horse-power for 392 automobiles manufactured from 1970 to 1982 from the UCI Machine Learning Repository.
# The size of each circle is provided as a NumPy array called sizes. This array... |
c3d29921efc6540b76ed625058acf0c9bbfc8a63 | jeffbahns/Horoscope-Finder | /changereturn.py | 735 | 3.703125 | 4 | # python 2.7
from collections import OrderedDict as od
def change_return(cost, payment):
cashback = payment - cost
bills = cashback // 1
change = (cashback % 1) * 100
quarters = 0
coin_return ={ "Quarters" : 0,
"Dimes" : 0,
"Nickels" : 0,
... |
eeb331ad0834c494a7e8d5ba4b691f6a0a95ff40 | alussana/python-programming-alessandro-lussana | /exam/mid-term/parsing_fasta.py | 2,762 | 4.1875 | 4 | # parsing_fasta.py
# For this exercise the pseudo-code is required (in this same file)
# Write a script that:
# a) Reads sprot_prot.fasta line by line
# b) Copies to a new file ONLY the record(s) that are not from Homo sapiens
# b) And prints their source organism and sequence lenght
# Use separate functions for the ... |
f677a57e2ff6c590136a7c734f9131b83343ae54 | Israelgd85/Pycharm | /excript/app-comerciais-kivy/Int.Ciencia_da Computacao_Python/semana-7/teste.py | 648 | 4 | 4 | # def desenha(linha):
# while linha > 0:
# coluna = 1
# while coluna <= linha:
# print('*', end = "")
# coluna = coluna + 1
# print()
# linha = linha - 1
#
# desenha(5)
altura = 5
linha = 1
while linha <= altura:
print("*", end ="")
coluna = 2
... |
6b6132ca1a45ca88af7a230df7f1769efa7e6641 | WichoEguia/TSOProject | /nearestNeighbor.py | 3,032 | 3.59375 | 4 | import random
from operator import itemgetter
class NearestNeighbor():
def __init__(self, nodes, k=1, alpha=0, method=1):
self.nodes = nodes
self.tour = []
self.k = k
self.alpha = alpha
self.method = method
"""
description: Run the algorithm and get the tour
ret... |
3b0352542f9b6090ac022c8082e2a0daaedfbe40 | charlesezra/Game-of-Life | /gameoflife.py | 5,441 | 4.1875 | 4 | """
Conway's Game of Life Visualization Project
Charles Ezra Cabauatan
Description: This project focuses on creating a way to visualize the game of life problem which
is structured around overpopulation. This algorithm will attempt to show how the populations will
move which depends on the amount of... |
27df2fedd5f3d2c26366302df58b012f7af61d57 | ricaportela/happy_numbers | /happynumber.py | 327 | 3.671875 | 4 | def sum_of_squares(number):
digits = [int(char) ** 2 for char in str(number)]
return sum(digits)
def happy(number):
box = []
n = number
if number < 0:
return True
while True and n not in box:
box.append(n)
n = sum_of_squares(n)
return n ... |
0d8fde8ac71b0f9aa31494fe609d831e701effb9 | lorenzosimpson/Computer-Architecture | /ls8/cpu.py | 4,911 | 3.5 | 4 | """CPU functionality."""
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.reg = [0] * 8
self.pc = 0
self.reg[7] = 0xf4
self.sp = self.reg[7]
self.instructions = {
0b10000010... |
975aa164eaad7c949df77ef52ab8fd146a0ec8c5 | hongxchen/algorithm007-class01 | /Week_01/G20200343040025/LeetCode_1_0025.py | 857 | 3.828125 | 4 | """
1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
... |
a0c260509465deace78ebccd5bbe768350a315c6 | junaidabdool/python | /list.py | 873 | 4.15625 | 4 | Tv_Shows = ["Dark", "Breaking Bad", "Mr Robot", "Lucifer", "Elite", "Blacklist", "Mindhunter"]
print(Tv_Shows)
print(Tv_Shows[0]) # access element based on the index
print(Tv_Shows[-1]) # access back of the list
print(Tv_Shows[1:]) # starting with index 1
print(Tv_Shows[3:5])
Tv_Shows[4] = "The Vampire Diaries" # u... |
2297c0f4500a866cc61cfcb7cce7f6a1b2b75571 | LKlemens/university | /python/7zestaw/rectangle_test.py | 1,883 | 3.640625 | 4 | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
import unittest
from point import Point
from rectangle import Rectangle
class TestRectangle(unittest.TestCase):
def test_init_rectangle(self):
point1 = Point(1, 2)
point2 = Point(3, 4)
rec = Rectangle(1, 2, 3, 4)
self.assertEqual(rec.p... |
4b495c930bf5f5bb2269979d28ec1b8bc79590db | AnkitM18-tech/Key-Logger | /basic.py | 933 | 3.625 | 4 | from pynput.keyboard import Key,Listener
count = 0
keys = []
#defines what happens after hitting the keys
def on_press(key):
global keys,count
keys.append(key) # saving in the text file
count += 1
print(f'{key} is pressed')
if count >= 10 : # resetting values in inte... |
1a90c5f59918ebf8ce264eefa87df8e035a61bd6 | girishkumaral/leet | /[217]Contains Duplicate.py | 711 | 3.546875 | 4 | # Given an integer array nums, return true if any value appears at least twice
# in the array, and return false if every element is distinct.
#
#
# Example 1:
# Input: nums = [1,2,3,1]
# Output: true
# Example 2:
# Input: nums = [1,2,3,4]
# Output: false
# Example 3:
# Input: nums = [1,1,1,3,3,4,3,2,4,2]
... |
fda0c44ba87fe049c2c0eaa8fad7e7365b58a529 | devparkk01/Tkinter | /Frame/ttk/2entry.py | 1,445 | 4.40625 | 4 | # Learn how to create an entry box
# we'll use Entry() to create an entry box
import tkinter as tk
from tkinter import ttk
win = tk.Tk()
# win.geometry("400x400")
# win.resizable(0 ,0 )
# Creating a label
name = ttk.Label(win , text = "Enter your name : " ,width = 16)
name.grid(row = 0 , column = 0 , sticky = tk.W ... |
6a3e5e0c939ff6e22fe310e8a847f62a5d1cfd3a | MARV1S/QuadEQ | /Code/Main.py | 460 | 3.9375 | 4 | import math
print("Hello User!")
print("This program helps you to solve:")
print("Quadratic equations")
print("Lets start")
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = int(input("Enter c:"))
D = b**2 - 4 * a * c
def Disc(a,b,c,D):
print("Discriminant:")
print(D)
def Main(a,b,c,D):
x1 = (-b - math.s... |
d356a4960535759ba86958398b8e42b8d9e5b524 | hujianli94/Python-code | /11.python实现高效编程/14.使用描述符对实例属性做类型检查/example1.py | 377 | 3.796875 | 4 | #!/usr/bin/env python
#-*- coding:utf8 -*-
class Descriptor(object):
def __get__(self, instance, owner):
print("in __get__",instance,owner)
return instance
def __set__(self, instance, value):
print("in __set__")
def __delete__(self, instance):
print("in __del__")
class A(o... |
a00a0b0dc2c2bcdf9f76885b3f9fbfc98bce5167 | AndraPop29/Faculty | /Graph Algorithms/practical work no3 - Dijkstra/domain/DirectedGraphs.py | 6,309 | 3.78125 | 4 | '''
Created on 7 mar. 2016
@author: Pop Andra
'''
class Directed_Graph:
"""
Class Directed_Graph contains :
dictOut - dictionary, where key: the origin vertex
value: all the target vertices associated to the key
dictIn - dictionary, where key: the target verti... |
96db31f2afb43d423fd4354afc73d06cd945f8ac | jackwener/leetcode | /14.最长公共前缀.py | 797 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=14 lang=python3
#
# [14] 最长公共前缀
#
# @lc code=start
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0 :
return ""
str_common = strs[0]
for str_in in strs :
str_common = self.common(str_in, str_common)
... |
492e8f6fe35c45d966f68fb1712447e175fdc672 | Aasthaengg/IBMdataset | /Python_codes/p02401/s282728832.py | 290 | 3.515625 | 4 | import sys
for v in iter(sys.stdin.readline,""):
a,op,b = v.split()
a = int(a)
b = int(b)
if op == '+':
print(a+b)
elif op == '-':
print(a-b)
elif op == '*':
print(a*b)
elif op == '/':
print(a/b)
elif op == '?':
break |
250c73c01c85836668478f94010c5b46fe2ada19 | zzz136454872/leetcode | /outerTrees.py | 1,318 | 3.609375 | 4 | from typing import List
class Solution:
def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
trees.sort()
stack = []
n = len(trees)
used = [True] * n
def product(a, b):
return a[0] * b[1] - a[1] * b[0]
def anti_clock(a, b, c):
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.