blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
54d13bef355f59710b0b6f7a314d86a6daf8af68 | TroyJJeffery/troyjjeffery.github.io | /Computer Science/Data Structures/Week 4/CH5_EX3.py | 2,347 | 4.5 | 4 | """
Modify the recursive tree program using one or all of the following ideas:
Modify the thickness of the branches so that as the branchLen gets smaller, the line gets thinner.
Modify the color of the branches so that as the branchLen gets very short it is colored like a leaf.
Modify the angle used in turnin... |
952a66e0dcde2ef1da5214ba50f443b355df9d4e | PythonPostgreSQLDeveloperCourse/Section13 | /2_queue/linkedlist.py | 3,011 | 4.3125 | 4 | from node import Node
class LinkedList:
"""
You should implement the methods of this class which are currently
raising a NotImplementedError!
Don't change the name of the class or any of the methods.
"""
def __init__(self):
self.__root = None
def get_root(self):
return sel... |
21f0ba5e725f4dcde7406db8a215105e4402e383 | gitcardoso/Pyquest | /Pyquest 1/ex_3.py | 698 | 4.0625 | 4 | """Faça um programa para solicitar o nome e as duas notas de um aluno.
Calcular sua média e informá-la.
Se ela for inferior a 7, escrever "Reprovado”; caso contrário escrever "Aprovado"."""
aluno = str(input('Digite o nome do aluno:'))
nota1 = float(input('Digite a primeira nota do aluno {}:'.format(aluno)))
nota2 = f... |
d787c39a40fb55aff1e6eb34259254def303f9c4 | walkoncross/mxnet-test-zyf | /lr_scheduler/advanced_lr_schedulers.py | 15,438 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Advanced Learning Rate Schedules
#
# Given the importance of learning rate and the learning rate schedule for training neural networks, there have been a number of research papers published recently on the subject. Although many practitioners are using simple learning rate sc... |
ea6bae24ae2729aaf178c6be03102f6d6ab8b5d1 | ovravindra/SentimentAnalysis | /word_embeddings.py | 10,339 | 3.75 | 4 |
# word embeddings are the vector representations of a word in the context.
# similar words have similar embeddings, in the sence that they have similar cosine score
#
# %%
import pandas as pd
import numpy as np
import nltk
import matplotlib.pyplot as plt
import re
twitter_df = pd.read_csv('twitter_train.csv')
twitt... |
a11978bb1c6f16924822da8859b245108fe65de0 | Wattanajit/Python | /week3/work3.py | 4,026 | 3.578125 | 4 | #แบบฝึกหัดที่ 3.1
"""print("\tเลือกเมนูเพื่อทำรายการ")
print("#"*50)
print("\tกด 1 เลือกจ่ายเพิ่ม")
print("\tกด 2 เลือกเหมาจ่าย")
choose = int(input(" ")) #เลือกจ่ายเพิ่มหรือเหมาจ่าย
km = int(input("กรุณากรอกระยะทาง กิโลเมตร\n")) #กรอกระยะทาง
if choose == 1 : #เลือกแบบจ่ายเพิ่ม
if km <= 25: #ถ้าไม่ถึง 25 km จ่าย 2... |
4a2ebd50aeeb20316d67ac7e3262c492d97dceb4 | pddpp/alogrithm-practice | /Kth-Largest-Element/solution.py | 1,671 | 3.859375 | 4 | class Solution:
# @param k & A a integer and an array
# @return ans a integer
def kthLargestElement(self, k, A):
# Bubble sort is time consuming, use two pointer and quick sort
# This question needs review, it is a two pointer question and use the module of quick sort from "partition array"
... |
b7a7a03ef0b5849bf80ebc548ae178e371a1f79b | leonardolginfo/Exercicios_python_org | /Coursera/semana_3/desafio_raiz.py | 756 | 3.828125 | 4 | import math
a = int(input("Digite o valor de a:"))
b = int(input("Digite o valor de b:"))
c = int(input("Digite o valor de c:"))
delta = (b**2)-4*a*c
if(delta >= 0):
delta_teste = math.sqrt(delta)
#print("Delta =", delta_teste)
if (delta < 0):
print("Não existe raiz, pois o delta é menor qu... |
bcaadd4ef1abe91fdbd9bb9a2c0bf906b58dd825 | leonardolginfo/Exercicios_python_org | /EstruturaSequencial/calcula_salario_base_horas.py | 423 | 3.875 | 4 | # Faça um Programa que pergunte quanto você ganha por hora e o
# número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
print()
valorhora = float(input('Qual o valor da hora trabalhada? '))
qtd_horas_trabalhadas = float(input('Quantas horas trabalhou esse mês? '))
salario = valorh... |
20e673cfe85c66080f258e1aca0ddc0fff6b5380 | leonardolginfo/Exercicios_python_org | /EstruturaSequencial/exerc_16_latas_tintas.py | 640 | 3.9375 | 4 | # Faça um programa para uma loja de tintas. O programa deverá pedir o
# tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta
# é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00.
# Informe ao usuário a quantidades de latas de tin... |
d51b87217e551bafae041a03411606f6c89d5f9b | leonardolginfo/Exercicios_python_org | /EstruturaDeDecisao/exerc_3_veri_F_ou_M.py | 357 | 4.09375 | 4 | # Faça um Programa que verifique se uma letra digitada
# é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
print()
sexo = input('Digite uma letra em caixa alta para ientificar o sexo: ')
if sexo == 'F':
print(f'{sexo} - Feminino')
elif sexo == 'M':
print(f'{sexo} - Masculino')... |
08639865633197e713d1d89bb5ffa8a721898a4f | leonardolginfo/Exercicios_python_org | /EstruturaSequencial/exer_12_calc_peso_ideal.py | 287 | 3.8125 | 4 | #Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que
#calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58
print()
altura = float(input('Qual sua altura? '))
peso_ideal = (72.7 * altura) - 58
print()
print(f'O seu peso ideal é {peso_ideal}')
|
829fb6b015d406292e9bebfc73817be1e3c8f7ce | vpelletier/python-prepy | /prepy.py | 5,281 | 3.671875 | 4 | r"""
Simple python preprocessor.
All keywords are on a new line beginning with "##", followed by any number of
whitespace chars and the keyword, optionally followed by arguments.
Names
Definitions can be anything the regular expression "\w+" can match.
Expressions
Expressions are evaluated in python with current def... |
c8e6fd0ff21b2b52effc3948ff6472ee2c0c9db0 | koteswaracse/Pycharm-Prac | /Practice1.py | 772 | 4.03125 | 4 | #!/usr/bin/python
var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
print ("My name is %s and ... |
85c26afa478691ad15a99435f734a79453178c54 | damianmc88/python-challenge | /PyBank/main.py | 1,199 | 3.5625 | 4 | import os
import csv
data = []
with open('C:/Users/damia/Desktop/UDEN201811DATA3/Week3/HW/Instructions/PyBank/Resources/budget_data.csv') as f:
reader = csv.reader(f)
next(reader)
months=0
total=0
for row in reader:
months+=1
data.append(row)
total+=int(row[1])
pairs ... |
9d9bb277ecea40850906449755bc6de5f39826a1 | tanureuyo/uyovbievbo_story | /m/python_functions/mathfunctions.py | 289 | 4.09375 | 4 | """
Math Functions
"""
a = 27
b = 4
c = 3
# Addition / Subtraction
print (a+b)
print (a-b)
# Multiplication / Division
print (a*b)
print (a/b)
# Exponents
print (a**b)
print (b**a)
# Roots
print (b**(1/2))
print (a**(1/3))
# Modulus -- Only returns the remainder after division
print (a%c) |
9929886a03e43fa46190c72e5f13766c4e0d39f6 | wise-bit/g3po | /Fractals and NCBI api (Stray functions)/cantor1.py | 476 | 3.828125 | 4 | import turtle
t = turtle.Turtle()
def cantor_loop(length, current_loop_number):
t.penup()
t.setposition(0, current_loop_number)
t.pendown()
for i in range(int(current_loop_number*3/10)):
t.forward(length)
if t.isdown():
t.penup()
else:
t.pendown()
if current_loop_number == 1:
current_loop_number ... |
c27137e5ecbc98f3eb1ce9461b964f4b4664b455 | RohithKalvakota/Cybersecurity-Algorithms | /Vernam Cipher.py | 2,103 | 3.90625 | 4 | print("Kalvakota Rohith")
choice = input("Encryption(E/e) or Deceyption(D/d)?")
if ord(choice.upper()) == 69:
plaintext = input("Enter Plain Text:")
key = input("Enter key:")
if(len(key) == len(plaintext)):
def split(pt):
return list(pt)
ptlist = []
for... |
a0bef2e102937c13953f0aee0e0838c536572646 | joshey-bit/Short_Codes | /number_series.py | 505 | 3.609375 | 4 | def meth_1(n):
diff = 1
a0 = 1
li = []
while n > 0:
a_num = a0 + (n - 1)*diff
n = n - 1
li.insert(0, str(a_num))
k = "".join(li)
print(k)
def meth_2(n):
diff = 1
a0 = 1
li = []
num = 1
while num <= n:
a_num = a0 + (num - 1)*diff
num = num + 1
li.append(str(a_num))
k = ... |
8a00f9a865c069cf0946932a8ee0859ffc4a7d15 | vinicius-hora/python_udemy | /intermeriario/aula71.py | 143 | 3.59375 | 4 | from itertools import count
contador = count(start = 5, step = 2)
for valor in contador:
print(valor)
if valor >=100:
break
|
1d2f84f2f3a4a22172a30392f5ac8a146555cd0d | lopezjronald/Python-Crash-Course | /part-1-basics/Ch_2/name_cases.py | 1,968 | 4.625 | 5 | """
2-3. Personal Message: Use a variable to represent a person’s name, and print a message to
that person. Your message should be simple, such as, “Hello Eric, would you like to learn some
Python today?”
2-4. Name Cases: Use a variable to represent a person’s name, and then print that person’s
name in lowercase, uppe... |
e5a1bced0363cbd95e114b1de2d2ffafee0514fe | lopezjronald/Python-Crash-Course | /part-1-basics/ch_6/exercises.py | 5,758 | 4.53125 | 5 | # exercise 6-1
person = {
'first_name': 'ronald',
'last_name': 'lopez',
'age': 34,
'city': 'honolulu',
}
for key, value in person.items():
print(f'{key.title()}: {value}')
# exercise 6-2
print()
favorite_numbers = {
'joyce': 9,
'ronald': 3,
'Boo': 33,
'Stew': 22,
'Clue': 100,
}... |
c352da9c2cc16ce099d93750c680d18d4c138011 | lopezjronald/Python-Crash-Course | /part-1-basics/ch_9/practice.py | 1,383 | 3.859375 | 4 | class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(f'{self.name} is now sitting')
def roll(self):
print(f'{self.name} rolled over!!!')
my_dog = Dog("Willie", 6)
print(f"Dog's Name: {my_dog.name}")
print(f"Dog's Age: {my_dog.age}... |
fb2aff5e37a9e9d061c9e0e5fc3e7119c7248b4b | namannimmo10/AdventOfCode | /Day1-2.py | 153 | 3.734375 | 4 | tot = 0
with open("Day1-input", "r") as f:
for line in f:
num = int(line)
while (int(num/3)-2)>0:
num = int(num/3)-2
tot += num
print(tot)
|
d90474d7db36960d29059509886edf769a8e4a19 | galizar/6001x | /Week2/polysum.py | 369 | 3.8125 | 4 | from math import tan, pi
def polysum(n, s):
""" Calculates the sum of the area and the square of the
perimeter of the polygon.
n: int, number of sides of the polygon
s: int, length of each side of the polygon
"""
boundary_length = n*s
area = (1/4 * n * pow(s, 2) / (tan( pi/n ))... |
15a166cbb0763ae5131d0e568b0d9535056df434 | AbhishekGit-hash/Customer-Churn-Prediction-Model-with-XGBoost | /Customer Churn Prediction Model with XGBoost.py | 46,577 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# <br>
# <br>
# In this project based the dataset used is of an electricity power company that supplies electricity utility to coorporates, SME and residential customers. <br>A significant amount of churn in customers is happening in the SME customer segments which is decreasing t... |
5e9432e2699b1cb36af225e17ecddc93106aee41 | lackhoa/kara | /server.py | 538 | 3.59375 | 4 | from math import factorial
def mm1_avg(lam, mu):
rho = lam/mu
return rho/(1-rho)
def C(rho, s):
tmp0 = sum([(((s*rho)**k)/factorial(k)) for k in range(s)])
tmp1 = tmp0*(factorial(s)/((s*rho)**s))
tmp2 = tmp1*(1-rho)
tmp3 = tmp2+1
return 1/tmp3
def mms_avg(lam, mu, s):
rho = lam/(mu*s)... |
483ea8da418c872b647da5d004054f590052f568 | srohit619/Assignments_LetsUpgrade | /Day_2/Assignment_1.py | 1,667 | 4.53125 | 5 | # Assignment of Python for LetsUpgrade Python Course
##### Question 1
# Experiment with Five list's Built in Function
students = ["Rohit Shetty","Ram Mishra", "Pari Yadav","Shubam Mishra", "Kanta Bhai", "Urvi Kanade"]
print(students)
students.append("Raakhi Singh") #1 Adds a value to the end of the List
... |
b370f355c82e724ab3c66691aa6099d89f5a5a97 | Sammie86/My-Homework-3 | /1127.py | 2,017 | 3.8125 | 4 | print('Iyai Bassey 1937369') # This is my name ans PSID
dictionary = {}
for i in range(5):
jersey = int(input("Enter player %s's jersey number:\n" % str(i + 1)))
rating = int(input("Enter player %s's rating:\n" % str(i + 1)))
if jersey not in dictionary:
dictionary[jersey] = rating
print(... |
634e82400d7a132b599a4d3b8172b6de32dc4b7b | rebeccawmx/python3_test | /day4.py | 534 | 3.515625 | 4 | #!/usr/bin/env python
# encoding: utf-8
# date:2018/9/13
# comment:输入某年某月某日,判断这一天是这一年的第几天?
# 第一步:输入年月日
# 第二步:调用time函数的的tm_yday显示天数
# 第三步:输出天数
import time
# 第一步:输入年月日
Date = input("请输入年月日,格式为YYYYMMDD:")
# 第二步:调用time函数的的tm_yday显示天数
days = time.strptime(Date, '%Y%m%d').tm_yday
# 第三步:输出天数
print("这一天在这一年的 {}".format... |
5810545da76d2c4ca5ba2af08833cd5353f0bb3e | rhys-simpson/assignment2 | /test_place.py | 1,188 | 3.921875 | 4 | """
Assignment 2 - Place Class test
Rhys Simpson
"""
from place import Place
def run_tests():
"""Test Place class"""
# Test empty place (defaults)
print("Test empty place:")
default_place = Place("", "", 0, False)
print(default_place)
assert default_place.name == ""
assert default_place.... |
97858f535d9217878a0b36a2ad612d443027a750 | NitinSingh1071/DS | /Practical3d.py | 793 | 4.21875 | 4 | def factorial(num):
fact = 1
while (num>0):
fact = fact * num
num = num - 1
return fact
def factorial_recursion(num):
if num == 1:
return num
else :
return num*factorial_recursion(num-1)
def factors_num(num):
for i in range(1,num+1):
if ... |
203ac1b04734ccd27fc1edd2fd2a7d7700fad4a1 | dasankit1411/IQpython | /IQ3.py | 255 | 3.828125 | 4 | #Write a Python program to convert the Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.
import json
p_str={'4': 5, '6': 7, '1': 3, '2': 4}
j_dict=json.dumps(p_str,sort_keys=True,indent=4)
print(j_dict) |
93906d4f1277f013a5847b30eb94dc0d15a1f8bd | rambo3300/Olympic--Data-Analysis-web-app | /preprocessor.py | 436 | 3.5625 | 4 |
import pandas as pd
def preprocess(df, region_df):
# filtering the summer olympics
df = df[df['Season'] == 'Summer']
# left joining the two dataframes based on NOC
df = df.merge(region_df, on = 'NOC', how = 'left')
# dropping the duplicates
df.drop_duplicates(inplace = True)
# concatinat... |
0303554bdee7176fd7fea1654a8d37e266972247 | hermes-jr/adventofcode2017-in-python | /level_23/level_23b.py | 1,113 | 3.90625 | 4 | #!/usr/bin/env python
""" run as `python -O level_23b.py` to disable debug garbage """
b = 108400 # 100000 + 84 * 100
c = 125400 # 100000 + 84 * 100 + 17000
step = 17 # line 31
result2 = 0
for rng in range(b, c + 1, step):
for i in range(2, rng):
if rng % i == 0:
result2 += 1
br... |
e7f092bc6f80c4d3818552ad27ec6c75343edf27 | Alegarse/Python-Exercises | /Ejercicio1_1.py | 513 | 3.75 | 4 | #! /usr/bin/python3
# Ejercicio 1. Escriba un programa que pida una cantidad de segundos menor a 1 millón y que retorne cuántos días, horas, minutos y segundos son.
segundos=int(input("Cantidad de segundos menor a 1 millon: "))
if segundos>1000000:
print("El numero debe ser menor a 1 millon")
segundos=int(input("Ca... |
ad352e5ef77e961e39356333fc2e6808b27481ad | Alegarse/Python-Exercises | /Ejercicio4_1.py | 917 | 4.3125 | 4 | #! /usr/bin/python3
# Ejercicio 4_1. Pig Latin es un lenguaje creado en el que se toma la primera letra de una palabra
# y se pone al final de la misma y se le agrega también el sonido vocálico “ei”. Por ejemplo, la
# palabra perro sería "erropei". ¿Cuáles pasos debemos seguir?
# Pedir al usuario que ingrese una pa... |
8c384ed7883af590b02e00adcec98390d4462458 | Alegarse/Python-Exercises | /Ejercicio7_1.py | 542 | 4.15625 | 4 | #! /usr/bin/python3
# Ejercicio 7_1. Escribir un programa que guarde en una variable el diccionario
# {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}, pregunte al usuario por una divisa y
# muestre su símbolo o un mensaje de aviso si la divisa no está en el diccionario.
divisas = {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}
divP = ... |
bc60019b0405e20006ce7e73a4e44910818d3bab | Alegarse/Python-Exercises | /EjemploRecusividad-Factorial.py | 401 | 4.21875 | 4 | #! /usr/bin/python3
# Ejercicio Recursividad. Resulver el factorial de un número.
print("Resolucion del factorial de un número.")
print("======================================")
n = int(input("Introduzca el número al que calcular el factorial: "))
resultado = 0
def factN(n):
if (n == 0 or n == 1):
return 1... |
70c3d0a8e954924ebdd5818b3e4a03dc44c0fb89 | arnaudperalta/hex-engine | /hex_engine/common.py | 4,163 | 3.78125 | 4 | from hex_game import hex
from math import inf
def board_evaluation(board: hex.Board):
""""
Return the substraction between blue and red score.
If the heuristic evaluation return a positive value, blue player has
an advantage on the board, else red has an advantage.
"""
return get_s... |
72b730b83db79e0bef6ccd97734d1c16b4fb07cd | baharaysel/python-study-from-giraffeAcademy | /dictionaries.py | 832 | 3.59375 | 4 | monthConversions = {
"Jan" : "January",
"Feb" : "Febuary",
"Mar" : "March",
"Apr" : "April",
"May" : "May",
"Jun" : "June",
"Jul" : "July",
"Aug" : "August",
"Sep" : "September",
"Oct" : "October",
"Nov" : "November",
"Dec" : "December",
}
print(monthConversions["Nov"])
#November
print(mo... |
26d4c7b0708fab0a34f64a0446a488ca6aafc6b4 | baharaysel/python-study-from-giraffeAcademy | /tryexcept.py | 719 | 4.1875 | 4 |
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid Input")
# trying to catch different type of errors
try:
value = 10 / 0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Divide by zero")
except ValueError:
print("Invalid ... |
2929641de43ee29ccaa86d1f5864203c6ec8e5c9 | baharaysel/python-study-from-giraffeAcademy | /for_Loops.py | 693 | 4.1875 | 4 | for letter in "Giraffe Academy":
print(letter)
friends = ["Figen", "Birgul", "Esra"]
for friend in friends:
print(friend)
# Figen
# Birgul
# Esra
friends = ["Figen", "Birgul", "Esra"]
for index in range(10): # 10 is not included
print(index)
#0
#1
#2
#3
#4
#5
#6
#7
#8
#9
friends = ["Fi... |
d3ca722ba429ba67ab48a281f8a20b7c3ddaeaf1 | awosikaola/guess-the-number | /module.py | 548 | 3.8125 | 4 | import random
secretno = random.randint(1, 20)
print('There is a number in my mind now between 1-20')
for guesstaken in range(1, 7):
guess = int(input('Take a quick guess: '))
if guess<secretno:
print('your guess is a bit low, keep trying')
elif guess>secretno:
print('your guess is high, ke... |
44e718b875751abd5c58ad19a9fec3532a72533d | TimurKukharskiy/tictactoe | /viewtictac.py | 464 | 3.59375 | 4 | import sys
def view(list):
for yy in range(0,3):
if yy==0: sys.stdout.write(" 0 1 2\n")
sys.stdout.write(str(yy)+" ")
for xx in range (0,3):
if list[yy][xx]==0: sys.stdout.write(" ")
if list[yy][xx]==1: sys.stdout.write("X")
if list[yy][xx]==2: ... |
f6dc235df0027aeb109e3a36be65cb9ab170a5a7 | BenjaminLange/work_log | /work_log.py | 12,987 | 3.5 | 4 | import csv
import re
import os
import sys
from datetime import datetime
from datetime import timedelta
WORK_LOG_FILENAME = 'work_log.csv'
TEMP_WORK_LOG_FILENAME = 'temp_work_log.csv'
FMT_MONTH_DAY_YEAR = '%m/%d/%y'
FMT_HOUR_MINUTE = '%H:%M'
FIELDNAMES = ['id', 'name', 'date', 'time_spent', 'notes']
def initialize(... |
fc831d3a4869ab1084622ec1cdee10b43d11203d | Diamoon18/grafika | /burning_flower.py | 1,106 | 4.1875 | 4 | import turtle
from turtle import Turtle, Screen
ANGLE = 2
color = 'blue'
color1 = 'black'
color2 = 'red'
color3 = 'yellow'
def circles(t, size, small):
for i in range(10):
t.circle(size)
size=size-small
def circle_direction(t, size, repeat, small):
for i in range (repeat):
... |
2016cae12f56a04bff23c155448a76a09c595005 | xiangling1991/xiangling | /Python/自定义模块.py | 299 | 3.875 | 4 | '''
为了使参数的合法化,需要将参数初始化,或者定义参数的类型
'''
#例如:
#i=0
#j=0
int i
int j
def mul(i,j):
k = i*j
return k
z = mul(i,j)
print z
#dir函数,显示该模块的功能函数,还能查看任意指定的函数列表
|
5d0371c886729ffd8070088321fe21381c2d3487 | xiaowuc2/Code-in-Place-2021-Assignment-Solution | /Assignment-2/4. Random Numbers.py | 864 | 4.59375 | 5 | """
Write a program in the file random_numbers.py that prints 10 random integers (each random integer should have a value between 0 and 100, inclusive).
Your program should use a constant named NUM_RANDOM, which determines the number of random numbers to print (with a value of 10).
It should also use constants named ... |
cf695905d4d217da034247bf4bd9d5b4ab3b0c76 | xiaowuc2/Code-in-Place-2021-Assignment-Solution | /Assignment-3/2. Finding Forest Flames.py | 1,630 | 4.1875 | 4 | """
This program highlights fires in an image by identifying pixels
whose red intensity is more than INTENSITY_THRESHOLD times the
average of the red, green, and blue values at a pixel. Those
"sufficiently red" pixels are then highlighted in the image
and other pixels are turned grey, by setting the pixel red,
green, a... |
4cb2c3538140b1b4f49d29ae713d5129da8f8e20 | CordThomas/census_2020 | /src/insert_census_data.py | 4,233 | 3.796875 | 4 | """
Inserts the geo heading and p1 data from the legacy file format
into the census sqlite database created by create_database.
"""
import os
import sqlite3
from sqlite3 import Error
census_file = '../data/census_2020.db'
geo_heading_table = 'geo_heading'
p1_table = 'p1'
geo_heading_file = '../data/ca2020.pl/cageo2020... |
1a482e608f7624ff133116bfe2646b6f0f437e4c | RmanKarimi/CodeWarsFundamental | /longest.py | 173 | 3.671875 | 4 | """
. Return a new sorted string, the longest possible, containing distinct letters,
"""
@staticmethod
def longest(self, s1, s2):
return "".join(sorted(set(s1 + s2)))
|
93a8fada3a2bac48d3ac31333b48fdfac7b36e26 | RmanKarimi/CodeWarsFundamental | /make_readable.py | 311 | 3.921875 | 4 | """
returns the time in a human-readable format (HH:MM:SS) from none-negative integer value
"""
def make_readable(sec):
hours, rem = divmod(sec, 3600)
minutes, seconds = divmod(rem, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
# return strftime("%I:%M:%S", gmtime(sec))
|
cab0b90aac273c28cf2626d72ee2d2c19f16d69a | RmanKarimi/CodeWarsFundamental | /even_or_odd.py | 73 | 3.640625 | 4 | def even_or_odd(number):
return "Odd" if number % 2 == 0 else "Even"
|
36753ba049d88aae9ea04173bf2de03a86bc8c7b | willerhehehe/audio_mixer | /audio_mixer/common_tools/fft_data_divide.py | 412 | 3.65625 | 4 | # -*- coding:utf-8 -*-
def fft_data_divide(fft_data):
n = len(fft_data)
if n % 2 == 0:
part1 = fft_data[0:int(n / 2)]
part2 = fft_data[int(n / 2):]
elif n % 2 == 1:
part1 = fft_data[0:int((n + 1) / 2)]
part2 = fft_data[int((n + 1) / 2):]
else:
raise RuntimeError... |
cef37285f99e97d1d3e7a371e32c451478c768c6 | nickmachnik/AoC-solutions | /2020/python/day11/solution.py | 3,273 | 3.765625 | 4 | #!/usr/bin/env python
DIRECTIONS = [
(0, 1), # right
(0, -1), # left
(1, 0), # down
(-1, 0), # up
(1, 1), # down right
(1, -1), # down left
(-1, -1), # up left
(-1, 1) # up left
]
def main():
print("Answer part one:", part_one("puzzleinput.txt"))
print("Answer part tw... |
3e8ff20769491123d24fc8fe8212878172baaebd | nickmachnik/AoC-solutions | /2020/python/day21/solution.py | 2,232 | 3.671875 | 4 | #!/usr/bin/env python
def main():
data = load_data('puzzleinput.txt')
print("Answer part one: ", part_one(data))
print("Answer part two: ", part_two(data))
def part_one(data):
alg_to_ingr = {}
ingr_counts = {}
for ingredients, allergens in data:
for allergen in allergens:
... |
18668038ffcb6355fd642ba6fb3151648ef0ff85 | nickmachnik/AoC-solutions | /2020/python/day17/solution.py | 2,191 | 3.53125 | 4 | #!/usr/bin/env python
from itertools import product
class PocketDimension:
def __init__(self, path, dimensionality):
self.ndim = dimensionality
self.load_initial_state(path)
def load_initial_state(self, path):
self.active_cubes = set()
with open(path, 'r') as fin:
... |
0016b75282b5d0355ac2ab3fc9b7b755a1aee667 | p506/PyThon-ProGrammIng | /python_prob_5.py | 972 | 3.875 | 4 | '''
Author: Aditya Mangal
Date: 12 september,2020
Purpose: python practise problem
'''
def next_palindrome(number):
number += 1
while not is_palindrome(number):
number += 1
return number
def is_palindrome(number):
return str(number) == str(number)[::-1]
if __name__ == '__main__':
pr... |
8161f21c556e806ff076ad44a4639abe971418d5 | p506/PyThon-ProGrammIng | /adding_matrixes.py | 994 | 3.921875 | 4 | '''
Author: Aditya Mangal
Date: 20 september,2020
Purpose: python practise problem
'''
def input_matrixes(m, n):
output = []
for i in range(m):
row = []
for j in range(n):
user_matrixes = int(input(f'Enter number on [{i}][{j}]\n'))
row.append(user_matrixes)
... |
eac81f4aa11e96b8479a9ae071be9b3631dbdb19 | p506/PyThon-ProGrammIng | /Itertools.permutations.py | 373 | 3.921875 | 4 |
'''
Author: Aditya Mangal
Date: 5 october,2020
Purpose: python practise problem
'''
from itertools import permutations
x = word, num = input().split()
a = list(permutations(word, int(num)))
b = list(map(list, a))
final_list = []
for i in range(len(b)):
final_list.append(''.join(b[i]))
a = sorted(final_list)... |
a904abefad2dd40aed7e41d1e06b71c7cbcd3043 | MeryemsCode/PyhtonBasicProjects | /05_Projects/FactorialCalculation_Function_For.py | 144 | 3.65625 | 4 | def factorial(sayi):
factorial = 1
for i in range(1,sayi+1):
factorial *= i
return factorial
print(factorial(5))
|
17247024e0cf48881a077727816ff7aa7eb94bf3 | MeryemsCode/PyhtonBasicProjects | /20_Project/ManavFiyatListesi_Dict.py | 2,036 | 4 | 4 | meyveler={} #meyveler isminde bir sözlük
giris=-1 #kullanıcıdan aldıgım secenek
while giris!="0":
#kullanıcının seçenekleri
print("Yapacağınız işlemin numarasını seçiniz: ")
giris=input("1- Kayıt Ekle \n 2- Kayıt Düzelt \n 3- Kayıt Ara\n 4- Tümünü Listele\n 5- KAyıt Sil\n 6-Tümünü Sil\n 0-Çıkış\n")
... |
2201f654d9bb424efbb07d46f015dc38971f72f0 | hesajs/Timer | /timer-console.py | 681 | 3.78125 | 4 | import time
import os
os.system("clear")
minutes = int(input("Enter the minutes: "))
sec = minutes*60
min = minutes
elapsed_min=0
for i in range(1, minutes*60+1):
time.sleep(1)
sec-=1
os.system("clear")
if(i%60==0):
elapsed_min+=1
min-=1
print(f"Number of miutes: {minutes}\n")... |
41e98e7c943f2f6b36eb00ae60338ea6170ac588 | tomatolike/MyLittleGame | /main.py | 8,090 | 3.703125 | 4 | from GameClass import *
from Game import *
import socket
import _thread
from multiprocessing import Lock
import time
# Initialize the world!
Game = Game()
Game.initialization()
f = open('log.txt','w')
print("世界建立完成!")
f.writelines("世界建立完成!\n")
# This is the server class
# The logic of communication with client is h... |
2e2999ea776e5f8d449f697e4555d9415e5a2d99 | arkssss/alien_invasion | /bullet.py | 1,139 | 3.65625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_setting, screen, ship):
super().__init__()
self.screen_rect = screen.get_rect()
self.screen = screen
# 创建一个新矩形 在0,0处
self.rect = pygame.Rect(0, 0, ai_setting.bullet_width, ai_setting.... |
3683a953acb651128dd00cf7a90df96486c2a986 | jakezachariahnixon/rosalind-py3 | /REVC/main.py | 270 | 3.5 | 4 | # title: Complementing a Strand of DNA
# id: REVC
dataset = ['A','A','A','A','C','C','C','G','G','T']
comp = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
def main():
for char in dataset:
print(comp[char], end='')
print()
if __name__ == '__main__':
main()
|
c5bd3fd0107db4a2c013626ad75718af8ae2ab34 | tourloukisg/Streamlit_Prophet_TSeriesWebApp | /tseriesforecast_streamlit_webapp.py | 5,923 | 3.640625 | 4 | # STREAMLIT --- PYTHON --- MACHINE LEARNING --- Time Series Forecasting
# In this example, the use of the FB Prophet model for time series forecasting
# with respect to four stocks(Netflix, Amazon, Google & Microsoft ) is
# demonstrated. In addition, there is use of the Streamlit open-source Python
# library t... |
25fc000fae0441b45308ed3d314033beced52e88 | Graey/pythoncharmers | /Genetic Algorithm/Population.py | 4,620 | 3.59375 | 4 | from Individual import Individual
import random
class Population:
def __init__(self, id, size, lower_inps, upper_inps):
# id : (int) population's id
# size : (int) how many individual objects in this population
# lower_inps : (list) list of lower-boundary inputs
# upper_inps : (list... |
9948289046b823a7888eea9afb42f43f2b2724ed | Graey/pythoncharmers | /hcfof2num.py | 333 | 3.890625 | 4 | #using loops
# define a function
def compute_hcf(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
print("The H.C.F. is", compute_hcf(... |
1a5aac856bd8a19833ccc0f21fb78c7646050d29 | Graey/pythoncharmers | /koch curve.py | 553 | 3.5 | 4 | import turtle
def snowflake(lengthSide, levels):
if levels == 0:
t.forward(lengthSide)
return
lengthSide /= 3.0
snowflake(lengthSide, levels - 1)
t.left(60)
snowflake(lengthSide, levels - 1)
t.right(120)
snowflake(lengthSide, levels - 1)
t.left(60)
snowflake(lengthS... |
5df0cbe40e62d5efec6fb39ad48c2f90d5fd280b | Graey/pythoncharmers | /dijaktra.py | 1,257 | 3.9375 | 4 | import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
# Nodes can get added to the pr... |
a883747d2028159815103ad67d11f73a8a1fcda3 | Graey/pythoncharmers | /calccompoundinterest.py | 301 | 3.671875 | 4 |
# interest for given values.
def compound_interest(principle, rate, time):
# Calculates compound interest
Amount = principle * (pow((1 + rate / 100), time))
CI = Amount - principle
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)
|
0e60cf785fa491656c8b87b5a42777db14048a4e | Graey/pythoncharmers | /palindromes.py | 224 | 3.71875 | 4 | def palindrome(s):
s = s.replace(' ','') # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces)
return s == s[::-1] # Check through slicing
palindrome('nurses run')
|
13b15323e2cca29ee326a58a7b7a74bf997f3ecd | Graey/pythoncharmers | /Die_Roller.py | 322 | 4.1875 | 4 | #Using Random Number Generator
import random
min_value = 1
max_value = 6
again = True
while again:
print(random.randint(min_value, max_value))
another_roll = input('Want to roll the dice again? ')
if another_roll == 'yes' or another_roll == 'y':
again = True
else:
again = Fals... |
0d885c684061825f0c657a9d4a98e416cfa41200 | Graey/pythoncharmers | /complexconversion.py | 761 | 4.03125 | 4 | import math
print("Enter your input format:")
print("1. a+ib")
print("2. r*e^(i*theta)")
print("3. rCis(theta)")
choice=int(input())
print("Enter number:")
if choice==1:
print("Enter a:")
a=float(input())
print("Enter b:")
b=float(input())
r=math.sqrt(a*a+b*b)
theta=math.ata... |
ebd0bee6b3e9189c04add38a2d4290123d838f6c | Graey/pythoncharmers | /binarytree.py | 440 | 4.09375 | 4 | from binarytree import Node
root = Node(3)
root.left = Node(6)
root.right = Node(8)
# Getting binary tree
print('Binary tree:', root)
#Getting list of nodes
print('List of nodes:', list(root))
#Getting inorder of nodes
print('Inorder of nodes:', root.inorder)
#checking tree properties
print('Size of tree:', root.si... |
fab253da275ab591be5002f7e17ea826a4c4cd43 | Graey/pythoncharmers | /electricalf.py | 323 | 4.03125 | 4 | # calculate gravitational force
import math
print("enter the charge of the first body in C")
q1=float(input())
print("enter the charge of the second body in C")
q2=float(input())
print("enter the distance between them in m")
d=float(input())
force=(9*math.pow(10,9)*q1*q2/(d*d))
print("Force=",force,"N"... |
cf94c48b12db2f1bc4ee69a8a82b85de13dc2149 | Graey/pythoncharmers | /stack.py | 698 | 3.875 | 4 | s=[]
ch='y'
while (ch=='y'):
print("1.Push")
print("2.Pop")
print("3.Display")
choice=int(input("Enter your choice:"))
if (choice==1):
a=input("Enter any number:")
b=input("name")
c=(a,b)
s.append(c)
elif (choice==2):
if (s==[]):
... |
6fc58e11d2549dc50f66e4b2107424a40071a32e | Graey/pythoncharmers | /arrayrotation.py | 532 | 4.125 | 4 | #Function to left rotate arr[] of size n by d*/
def leftRotate(arr, d, n):
for i in range(d):
leftRotatebyOne(arr, n)
#Function to left Rotate arr[] of size n by 1*/
def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
# utility function to print an ar... |
54fe3a05f78b6724e0167776103d1d58bcc46d4c | lizalexandrita/kyd-scraper | /test_scrap.py | 6,316 | 3.5 | 4 |
import unittest
import scraps
class TestScrap(unittest.TestCase):
def test_Scrap(self):
"""it should create and instanciate a Scrap class"""
class MyScrap(scraps.Scrap):
a1 = scraps.Attribute()
myScrap = MyScrap()
self.assertEquals(myScrap.a1, None)
myScrap.a1 = 1
self.assertEquals(myScrap.a1, 1... |
e80a517f6eda1a019bf898bfa0d1721187563e6c | chrislucas/hackerrank-10-days-of-statistics | /python/BinomialDistribuitionII/solution/BinomialDistribution.py | 1,224 | 3.625 | 4 | '''
https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem
DONE
'''
def fast_exp(b, e):
if e == 0:
return 1
elif e == 1:
return b
elif e < 0:
b, e = 1 / b, -e
acc = 1
while e > 0:
if e & 1 == 1:
acc *= b
b *= b
e >>= 1
... |
f69dafe7e3cd2bba8f46924f56fc36ccaeb49bb1 | chrislucas/hackerrank-10-days-of-statistics | /python/PoissonDistribuition/solution/PoissonDistribII.py | 536 | 4 | 4 | '''
https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem
'''
from math import e as E
def factorial(n):
acc = 1
for i in range(n, 1, -1):
acc *= i
return acc
def poisson_distribution(success, avg):
return ((avg ** success) * (E ** (-avg))) / factorial(success)
'''
a = 0... |
da9fb9e3090ffcffb8c94215776fad7a2749b80f | chrislucas/hackerrank-10-days-of-statistics | /python/BinomialDistribuitionI/solution/OKNCR.py | 579 | 3.640625 | 4 | '''
https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
'''
'''
C(n, k) = n! / (n-k)! * k!
ou
C(M, k) = n * ... (n-k+1) / (k * k-1 * k-2 ... * 1)
ou
C(n, k) = C(n, n-k) =
(n * n-1 ... * n-k+1) / (k * k-1 * ... * 1)
'''
def ok_ncr(n, k):
if k > n - k:
k = n - k
res = 1
... |
19152fb52ea0155fa395061589dfb6cdb03c1f00 | chrislucas/hackerrank-10-days-of-statistics | /python/Quartiles/sol/Quartiles.py | 1,505 | 3.796875 | 4 | '''
https://www.hackerrank.com/challenges/s10-quartiles/problem
https://en.wikipedia.org/wiki/Quartile
https://en.wikipedia.org/wiki/Quantile
DONE
'''
def calc_q1(n, nums):
half = (n // 2)
if n > 4:
# se ao cortar o array na metade temos 2 metades impares
if (half & 1) == 1:
# di... |
85e741e34dcd26f4bffea551cbf9d6cc74fba3ce | alok-chandra/Python | /Proj013_Except.py | 329 | 3.84375 | 4 | while True:
try:
iData = int(input("Enter the number Buddy:\n"))
print(100/iData)
break
except ValueError:
print("Enter proper data \n")
except ZeroDivisionError:
print("Don't enter 0\n")
except :
print("Ufff")
break
finally:
print("Bye... |
fbc7c914d0a9dc983e82f2bb3f604cbc5c794b0f | DanielJWagener/automate-the-boring-stuff-with-python | /regex/phoneNumbers.py | 258 | 3.796875 | 4 | import re
message = "Call me 123-123-1234 because that's totes a real phone number. Otherwise, 432-432-4321"
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search(message)
print(mo.group())
print(phoneNumRegex.findall(message))
|
6b8ecdfb0306cf32d25814cbdba7d06de21a1af9 | PalRob/rdp | /int/dp_348_int.py | 2,536 | 3.9375 | 4 | def pins_knocked_in_frame(frame):
"""Get number of knocked pins in given frame
Args:
frame(str): string containing information about throws
in the frame formatted by "bowling rules"
Returns:
pins_knocked(int): number of knocked pins in given frame
"""
pins_knocked = 0
... |
480d5d5cc49249179f48f1f81faa59a2cc36fffb | PalRob/rdp | /easy/dp_344_easy.py | 1,011 | 4.0625 | 4 | def have_odd_zeros(num):
"""
Returns True if binary representation of a num contains block of
consecutive 0s of odd length. False otherwise."""
# [2:] to slice out starting 0b from a binary number
bin_num = bin(num)[2:]
odd_zeros = False
num_of_zeros = 0
for i in bin_num:
if i ==... |
7f4e9bac7c1223c0baa8d90cf603dec2d6b11446 | IsraMejia/CodeInterview | /1_TwoSum_Microsoft/Python/two_sum.py | 821 | 3.875 | 4 | """Given an array of integers nums and an integer target,
return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
You can return the answer in any order.
Input: nums = [2,7,11,15], target = 9
Output... |
6ffcbf8b2dfd97191c106928be8b77a75655fbd2 | Asmitadhikari/python_project | /Remove_user_input.py | 180 | 3.921875 | 4 | a = [1, 2, 4, 5, 6, 1, 3, 1, 8, 10, 1]
num = int(input("Enter a number you want to remove from list:"))
print(a)
for i in a:
if num == i:
a.remove(num)
print(a)
|
4c4aadd140193a4507ba1c4f5f6dc0635ce4b546 | ektogamut/battleship | /battleship_scratch.py | 3,566 | 4.21875 | 4 | from random import randint
from random import choice
# This function adds individual dictionaries to a specified square board (edge by edge). Cannot use the * function
# as with the original example because calling to one member of a list alters everything in that lists row.
def place_board(edge):
board = []
f... |
7b7327d61d90ab6266a8db9d4a45c82e81c1b432 | qiushenjie/myLeetcode | /29_两数相除.py | 1,304 | 3.78125 | 4 | # 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
# 返回被除数 dividend 除以除数 divisor 得到的商。
# 示例 1:
# 输入: dividend = 10, divisor = 3
# 输出: 3
# 示例 2:
# 输入: dividend = 7, divisor = -3
# 输出: -2
# 说明:
# 被除数和除数均为 32 位有符号整数。
# 除数不为 0。
# 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
clas... |
52a6f941a820f1050f183831550010d6734d51d5 | qiushenjie/myLeetcode | /62_不同路径.py | 1,696 | 3.515625 | 4 | # 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
# 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
# 问总共有多少条不同的路径?
# 输入: m = 3, n = 2
# 输出: 3
# 解释:
# 从左上角开始,总共有 3 条路径可以到达右下角。
# 1. 向右 -> 向右 -> 向下
# 2. 向右 -> 向下 -> 向右
# 3. 向下 -> 向右 -> 向右
class Solution:
def uniquePaths(self, m, n):
grid = [[0] * n for i in ran... |
e555401276ae7e25dd052dc6a686a4d4555648d0 | qiushenjie/myLeetcode | /26_删除排序数组中的重复项.py | 1,776 | 3.75 | 4 | # 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
# 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
# 示例 1:
# 给定数组 nums = [1,1,2],
# 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
# 你不需要考虑数组中超出新长度后面的元素。
# 示例 2:
# 给定 nums = [0,0,1,1,1,2,2,3,3,4],
# 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
# 你不需要考虑数组中超出新长度... |
2e01179c5f5d1a7c1f80fbd9030bcbf430b2728c | qiushenjie/myLeetcode | /55_跳跃游戏.py | 1,283 | 3.703125 | 4 | # 给定一个非负整数数组,你最初位于数组的第一个位置。
# 数组中的每个元素代表你在该位置可以跳跃的最大长度。
# 判断你是否能够到达最后一个位置。
# 示例 1:
# 输入: [2,3,1,1,4]
# 输出: true
# 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
# 示例 2:
# 输入: [3,2,1,0,4]
# 输出: false
# 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置
#贪心算法
class Solution:
def canJump(self, nums):
n = l... |
225f71f198f337eb1468c9525a579ee6e8364888 | qiushenjie/myLeetcode | /96_不同的二叉搜索树.py | 2,069 | 3.578125 | 4 | # 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
# 示例:
# 输入: 3
# 输出: 5
# 解释:
# 给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# / / \ \
# 2 1 2 3
'''
解题思路:
这道题实际上是 Cat... |
f99d1cf51c8505b82e17d11709a82f40fb1ab6a4 | qiushenjie/myLeetcode | /2_两数相加.py | 1,690 | 3.953125 | 4 | # 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
# 你可以假设除了数字 0 之外,这两个数字都不会以零开头。
# 示例:
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#链表具有递归性,所... |
62ed5fcef461fc03b01b99815c7e5787ab271fc2 | qiushenjie/myLeetcode | /1_两数之和.py | 649 | 3.6875 | 4 | '''
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
'''
class Solution:
def twoSum(self, nums, target):
dic = {}
for i in range(len(nums)):
el1 = nums[i]
if (el1 in dic)... |
ea1dfb54388799367e88108cb50c74f800ff5589 | qiushenjie/myLeetcode | /38_报数.py | 950 | 3.625 | 4 | # 报数序列是指一个整照其中的整数的顺序进数序列,按行报数,得到下一个数。其前五项如下:
# 1. 1
# 2. 11
# 3. 21
# 4. 1211
# 5. 111221
# 1 被读作 "one 1" ("一个一") , 即 11。
# 11 被读作 "two 1s" ("两个一"), 即 21。
# 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
# 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
# 注意:整数顺序将表示为一个字符串。
class Solution:
def coun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.