blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4e8d81e831111b9ba0024a049a9746fec7a5aeb9 | thsmcoding/P_Projects | /Miscellaneous/Python/Challenges.py | 3,022 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 10:48:42 2019
@author: HTT
@task: training
"""
''' GOOGLE CHALLENGE : Find the longest word in a dictionary that is a subsequence of a given string'''
def dictString(word):
dict = {}
for index, w in enumerate(word):
if(w in dict):
dict[w... |
28673d40fc45a3d8790b62e902424c97e9b4ac94 | Pnickolas1/Code-Reps | /AlgoExpert/Recursion/getNthFib.py | 844 | 3.703125 | 4 |
"""
memoized version
time: O(n)
space: O(n)
iterative approach
time: O(n)
space: O(1)
fibs =>
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393,
196418, 317811,
"""
#memoize versions
def getNthFib_memoize(n, memoize = {1: 0, 2: ... |
bdd90025509fda03f0288de05550daa05f4cd81e | Pkpallaw16/Tree-level-2 | /19 vertical order traversal.py | 2,058 | 3.890625 | 4 | # User function Template for python3
from _collections import deque
class pair:
def __init__(self, node=None, vlevel=0):
self.node = node
self.vlevel = vlevel
class Solution:
# Function to find the vertical order traversal of Binary Tree.
def verticalOrder(self, root):
# Your code... |
2fad853fa3f0eb619dbd9a13980317513bc80129 | antonylu/leetcode2 | /Python/606_construct-string-from-binary-tree.py | 2,262 | 3.890625 | 4 | """
https://leetcode.com/problems/construct-string-from-binary-tree/description/
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis... |
26f7265ec60e184425e4d98fc4c8093c25a6f520 | sigridjb/adventofcode2019 | /day01.py | 418 | 3.546875 | 4 | import pandas as pd
import numpy as np
d = pd.read_csv("input",header=None)
d["fuel1"] = np.floor(d/3)-2
print("Day 1 - part 1: "+str(int(d.fuel1.sum())))
def getfuel(val):
fuelneeded = 0
while (np.floor(val/3)-2)>0:
fuelneeded += np.floor(val/3)-2
val = np.floor(val/3)-2
return(fuelneeded... |
2c56a3b04fc375ff2d78fdd163ad230f67cb55af | JFerRG/MySQL_Py | /GitHub/ComprobacionDeCuadrados.py | 643 | 4 | 4 | def validacion():
while True:
try:
num = int(input('Ingresa el valor: '))
if num > 0:
return num
break
else:
print('El número ha de ser mayor que cero')
except Exception as e:
print('Error al obtener el n... |
a1c9dce40b93c0011c070577332314be1616ac75 | yakann/Algorithms | /Searching Algorithms/Binary Search/Python/binary_search.py | 468 | 3.890625 | 4 | def binarySearch(seq,f):
left = 0
right = len(seq)-1
while left <= right:
mid = round((left + right)/2)
if seq[mid] == f:
return seq[mid]
elif seq[mid] < f:
left = mid + 1
else:
right = mid - 1
seq = [1,2,5,6,7,8,9,44,46,71,79,88]
p... |
34a7e10a55c4d3d1ceaf93236ebfa311be3e6c66 | ryannhanna/DC-Class-Sept-17 | /wk 1 python/py-exercises day 2/vowelsreal.py | 63 | 3.609375 | 4 |
word = 'boo'
word = word.replace('oo', 'ooooo')
print(word)
|
dc8afd61482f947b5cde950a91f3429ebf665df5 | Richiewong07/Python-Exercises | /python-assignments/functions/degree_conversion_plot.py | 323 | 4.34375 | 4 | # 7. Degree Conversion
# Write a function that takes a temperature in Celcius and converts it Fahrenheit. Plot it on a graph.
import matplotlib.pyplot as plot
def f(x):
return x * 1.8 + 32
xs = list(range(0, 38))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.axis([0, 37.8, 30, 100])
plot.show... |
e7701b826a79e7587d0e85bbc12e7c60208af055 | richardOlson/Data-Structures | /data_structures/singly_linked_list/singly_linked_list.py | 3,247 | 4.3125 | 4 | # This the place where the Node and the single linked list
class Node:
def __init__(self, value=None, next_node=None):
self.next_node = next_node
self.value = value
# The linked list will use the nodes and then will make the linked list
class LinkedList():
def __init__(self):
# Gett... |
a1de304530dfb08aa2be1609cb9e951cc93878ef | AvikramS/Python-Projects | /Data Cosistency.py | 168 | 4.34375 | 4 | name = input("What is your name? ")
country = input("What country do you live in? ")
country = country.upper()
print('Hello ' + name + ". You live in "+ country)
|
a598a79ef45a3bc1b939b2d9c88d179690bffa90 | adqz/interview_practice | /pathrise/16_paint_house.py | 3,370 | 4 | 4 | '''
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green.
The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color i... |
8480d2ef230d868ebee247ca1c7d78b6032419fb | guilhermeagostinho22/exercicios-e-exemplos | /exercicio11.11/exercicio2.2.py | 538 | 3.921875 | 4 | def leiaint():
try:
c = float(input("Digite um valor real: "))
d = float(input("Digite um valor real: "))
t = c/d
print("O resultado foi: ", t)
except(ValueError, TypeError):
print("Infelizmente tivemos um problema com o valor digitado :( ")
except(ZeroDivisionError)... |
0b21e38a0fb84bae1ad70e345bf6afac02a72207 | iiinjoy/algorithms_python_lessons | /level1/test_lesson5.py | 509 | 3.640625 | 4 | #!/usr/bin/env
import unittest
from lesson5 import *
class TestQueue(unittest.TestCase):
def test_queue(self):
Q = Queue()
self.assertEqual(Q.size(), 0)
Q.enqueue(1)
Q.enqueue(2)
self.assertEqual(Q.size(), 2)
item1 = Q.dequeue()
item2 = Q.dequeue()
... |
6697f40f3afbeeadf4750341596aca4b942b43ac | jonstrutz11/AdventOfCode2020 | /05.py | 2,182 | 3.5625 | 4 | """Advent of Code - Problem 5"""
class BoardingPass():
"""Store boarding pass code and parsed seat location information."""
def __init__(self, seat_code):
self.seat_code = seat_code
self.row, self.col = self._parse_seat_code()
self.id = self._calculate_id()
def _parse_seat_code(s... |
d4325344433397aacfcba40c08f5bf6363fb41c0 | TrellixVulnTeam/Demo_933I | /Demo/tkinter编程/messagebox.py | 323 | 3.78125 | 4 | from tkinter import *
import tkinter.messagebox as messagebox
root = Tk()
def callback():
# 消息窗体提醒
if messagebox.askyesno('Wang', 'Hi sjaf'):
print("Yes")
else:
print("No")
button = Button(root, text='Button1', command=callback)
button.pack()
root.mainloop()
|
3bb7b3747e7b6b5551dd8e8b62f7f6ad93c7f8f5 | m-fahad-r/python-scripts | /Script sample.py | 11,239 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The Ship Rendezvous Problem
This code will:
1. Read a problem instance (data) from a CSV file;
2. Run the greedy heuristic against the problem instance to obtain a solution.
3. Output the resulting path to a CSV file.
4. Output key performance indicators of... |
cb2f2c0cfee7a4a4ed1f9f41309f5fd6bf08a409 | Shulamith/csci127-assignments | /hw_08/hw_08.py | 1,602 | 4.1875 | 4 | filename = "moby-small.txt"
filenameTwo = "moby-medium.txt"
filenameThree = "moby-large.txt"
s = 'one two three four five four six three seven three two three eight nine'
def build_word_counts(words):
d={}
for word in words.split():
d.setdefault(word,0)
d[word]=d[word]+1
return d
def clean_... |
18e12dd100296ebf2b189f91ee84c75e54ebcac8 | kodurivamshi/data-science | /linear reg with scklearn.py | 1,076 | 3.75 | 4 | #importing all libraries..
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#importing libraries from sklearn..
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import os
os.chdir("C:/Users/user... |
8de59040316f2b00f1dc4cc544b2a5683d39b440 | wendeel-lima/Logica-de-Programacao | /02-07/ex0207.py | 1,115 | 3.859375 | 4 | class Netflix:
def __init__(self, nome, ano):
self.__nome = nome.title()
self.ano = ano
self.__like = 0
@property
def nome(self):
return self.__nome
@nome.setter
def nome(self, nome):
self.__nome = nome
@property
def like(self):
return self.... |
877e23af9cfe9100afcdaf8fa9c7e194804e33d1 | shivamagrawal3900/pythonTutorial | /day3_string/rotate_word_via_slicing.py | 97 | 3.78125 | 4 | a1 = input("Enter a word:\n")
for i in range(1, len(a1) + 1):
print(a1[i:], a1[:i], sep="")
|
0791e438601d204dffa890a13bb18532d976f1b4 | liuminzhao/eulerproject | /euler41.py | 522 | 3.546875 | 4 | __author__ = 'liuminzhao'
import math
def isprime(x):
return not [t for t in range(2,int(math.sqrt(x))+1) if not x%t]
import itertools
x = list(itertools.permutations("87654321"))
for num in x:
tmp = ""
for i in range(8):
tmp += num[i]
tmp = int(tmp)
if isprime(tmp):
print tmp
... |
9e3e988c1f265f0b060d6e80d8e59ec2871abaed | simonhoch/python_basics | /04_working_with_list/4_15_code_review.py | 436 | 3.890625 | 4 | rectangles = [(80, 50), (40,50), (30,40)]
print ('Rectangles:\n')
for rectangle in rectangles:
print ('the dimention of the rectangle n' + str(rectangles.index(rectangle)+1) + ' is ' + str(rectangle[0]) + '*' + str(rectangle[1]))
arrays = [rectangle[0] * rectangle[1] for rectangle in rectangles]
print ('\n')... |
e95f9370fe7225885ea7b9722c3b2cdb6bc15f31 | mxmaria/coursera_python_course | /week1/Сумма цифр трехзначного числа.py | 174 | 3.671875 | 4 | # Дано трехзначное число. Найдите сумму его цифр.
n = int(input())
a = n // 100
b = (n // 10) % 10
c = n % 10
print(a + b + c)
|
a3a3987d53a110b622d2db5370f90958f82a6fa6 | Jimmyjtc001/assignment1 | /a1_t6_2.py | 187 | 3.65625 | 4 |
from collections import defaultdict
d = defaultdict(int)
for i in [1, 1, 2, 3, 3, 3, 4, 5]:
d[i] += 1
for item, count in d.items():
print('Mode: {} Count: {}'.format(item, count))
|
a744cd5b6d3a9219368f73cf011699dbf381b18d | jvautrain/FEDREPO | /businessstarts.py | 1,868 | 3.515625 | 4 | class BusStarts:
def __init__(self):
self.date = ""
self.measure = 0
self.FIPS = ""
def set_FIPS(self, inval):
self.FIPS = inval
def get_FIPS(self):
return self.FIPS
def set_measure(self, inval):
self.measure = inval
def get_measure(... |
00a635bfb9999ba8b5c62d65163caa69a9d039a5 | mayakota/KOTA_MAYA | /Semester_1/Lesson_04/Circle.py | 187 | 4.03125 | 4 | r = float(input("The radius of the circle is: "))
def calcArea(r):
a = 3.14159 * (r * r)
return(a)
print("The area of a circle with a radius of" , r , "is" , calcArea(r))
|
b9f9600fc4528089ddae44597e060964fae5c297 | novayo/LeetCode | /0022_Generate_Parentheses/try_4.py | 705 | 3.75 | 4 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def recursive(left, right):
if left == right == 0:
return [""]
if 0 <= left <= right:
left_list = recursive(left-1, right)
for i in range(len(lef... |
e52459733af61b7cd0563529317d91bd5f384a8b | GarryG6/PyProject | /13.py | 598 | 3.796875 | 4 | # Дано натуральное число. Определить: номер минимальной цифры числа при счете слева направо (известно, что такая цифра – одна)
n = int(input('Введите натуралное число: '))
count = 0
n1 = n
while n1 > 0:
n1 = n1 // 10
count = count + 1
print(count)
min = n // 10 ** (count - 1)
pos = 1
res = pos
while pos < co... |
f57a57cff7e3bd0b9e9dddcf632662559f4126be | orlandosaraivajr/dojo | /2018_OUT_15/dojo.py | 664 | 3.75 | 4 | def abnt(nome):
nomes = nome.split(" ")
sobr = ['JUNIOR', 'FILHO', 'FILHA', 'NETO', 'NETA']
dos = ['do']
tam = len(nomes)
result = nomes[-1].upper()
if result in sobr :
result = nomes[-2].upper() + " " + result
tam -= 1
result += ","
for x in range(tam - 1):
result += " "
if
result += nomes[x].cap... |
d7991f4e7a4634c587609d53c76005e4da6185b9 | maxnovak/ConnQuest | /Direction.py | 4,110 | 3.984375 | 4 | #Movement method
#By Max Novak
#4/19/10
#This class will control all movements around the game world
class Direction():
def __init__(self, location):
"""sets up the location variable"""
self.location=location
def printLocation(self):
"""will display the current location"""
pr... |
cf13cc67e3be9eb78d62c68e748d41160e8134d4 | KaylaBaum/astr-119-hw-1 | /if_else_control.py | 481 | 3.96875 | 4 | #define a function
def flow_control(k):
#define a string based on the value of k
if(k==0):
s = "Variable k = %d equals 0." % k
elif(k==1):
s = "Variable k = %d equals 1." % k
else:
s = "Variable k = %d does not equal 0 or 1." % k
#print the variable (the string s)
print(s)
#define a... |
14183da3776e239e3659399136eb39fb75c210ed | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/demo03.py | 1,254 | 3.828125 | 4 | """
属性各种写法
"""
# 写法1:读写属性
"""
# 适用性:有一个实例变量,但是需要在读取和写入过程中进行限制
# 快捷键:props + 回车
class MyClass:
def __init__(self, data=0):
self.data = data
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
self.__data = value
m01 = MyClass(10)
print(m01.... |
1181234e659e137e825a6abbf3892f5cfc5d49f4 | c109156126/h | /62.py | 261 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 9 20:29:58 2021
@author: 曾睿恩
"""
a={"蘋果":"紅色","香蕉":"黃色","葡萄":"紫色","藍莓":"藍色","橘子":"橘色"}
print(a.keys())
fruit=input("請輸入水果")
print(fruit,"是",a.get(fruit)) |
e07eb2819e34b36938666852655b39e2811bb1ef | MikhailChernetsov/python_basics_task_1 | /Hometask5/ex2/main.py | 641 | 4.03125 | 4 | '''
2. Создать текстовый файл (не программно), сохранить в нем
несколько строк, выполнить подсчет количества строк, количества
слов в каждой строке.
'''
with open('text_2.txt', 'r', encoding='utf-8') as my_file:
number_of_strings = 0
for line in my_file:
line = line.split()
print(f'Количество с... |
749128f2cbefbd69eee3507b7836355553845b91 | gil9red/SimplePyScripts | /tkinter_examples/center_window.py | 672 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def center_window(root, width=300, height=200):
# get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# calculate position x and y coordinates
x = (screen_width / 2) -... |
c3f377adfd05f5235afec1709e31913d65adc1b7 | Nate8888/programming-contest-practice | /programming-team/First Semester/Learn Problems/IntroProblems/trip.py | 173 | 3.53125 | 4 | cases = int(input())
for i in range(cases):
line = input().rstrip().split(" ")
total = float(line[0]) * int(line[2]) + float(line[1]) * int(line[3])
print(round(total,2)) |
de76c74c8697465dd100fbe9a088f62d64b4da4d | insoPL/PythonHomework | /python11/11.3.py | 848 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import random
def random_list(n):
re_list = range(n)
random.shuffle(re_list)
return re_list
def swap(L, left, right):
"""Zamiana miejscami dwóch elementów."""
# L[left], L[right] = L[right], L[left]
item = L[left]
L[left] = L[right]
L[right] = item
def quick... |
1f9653bfe59d629527d231e2e360e0b0192b9ce7 | harpolea/AOC19 | /day6.py | 1,534 | 3.78125 | 4 | import numpy as np
import sys
def count_orbits(input_file):
orbits = {'COM': None}
satellites = set()
# read file and make a dictionary of orbits
with open(input_file, 'r') as infile:
for line in infile:
inner, outer = line.replace('\n', '').split(')')
orbits[outer] ... |
31f08aa56d0d69151f39a7928b1bc0c9c5432c31 | lidongdongbuaa/leetcode2.0 | /数据结构与算法基础/leetcode周赛/200329/Count Number of Teams.py | 2,737 | 3.9375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/29 12:21
# @Author : LI Dongdong
# @FileName: Count Number of Teams.py
''''''
'''
题目概述:
题目考点:
解决方案:
方法及方法分析:
time complexity order:
space complexity order:
如何考
'''
'''
from head to end, choose arr which is ascedning or descending with 3 elem, soldier are... |
c7000099e13df771a687b4e9ee32dada6ea55e40 | judy2k/python_and_mongodb | /src/main.py | 8,001 | 3.515625 | 4 | from datetime import datetime
import os
# Import the `pprint` function to print nested data:
from pprint import pprint
from dotenv import load_dotenv
import bson
import pymongo
from pymongo import MongoClient
def print_title(title, underline_char="="):
"""
Utility function to print a title with an underlin... |
acd90374fa435eba71ad75bffa19f1e4b5fcecb0 | constklimenko/PY | /6 week/boots.py | 1,365 | 4.125 | 4 | """В обувном магазине продается обувь разного размера.
Известно, что одну пару обуви можно надеть на другую,
если она хотя бы на три размера больше. В магазин
пришел покупатель.Требуется определить,
какое наибольшее количество пар обуви сможет
предложить ему продавец так, чтобы он смог
надеть их все одновременно... |
ca7a132da5fa1faa4445cc191b906829c8cc0dd7 | pedal-edu/pedal | /examples/submissions/student_code.py | 153 | 3.84375 | 4 | print("Hello", 1+input("What is your name? "))
def add(a, b):
return a + b
def bad_add(a, b):
return a - b
x = 0
add
bad_add
x
#print(x + "")
|
e51927913300fb437e4e71079b9ee2877a9f1fc1 | cs-learning-2019/python1contsat | /Lessons/Week12/Animations/Animations.pyde | 4,077 | 4.65625 | 5 | # Focus Learning: Python Level 1 Cont
# Animations
# Kavan Lam
# Dec 12, 2020
# Contents
# 1) Simple animation of a ball moving to the right
# 2) Animation of a ball moving up and down (bouncing off walls)
# 3) Same as 2 but with a square
# 4) Be able to switch the direction of animation with mouse pressed
... |
e320d11929e87fcba8dc84c1fa4966af364b4701 | oscar-oneill/RockPaperScissors | /rock.py | 517 | 3.9375 | 4 | import random
def play():
user = input("What's your choice? Select 'r' for Rock, 'p' for Paper, 's' for scissors: ")
computer = random.choice(['r', 'p', 's'])
if user == computer:
return "Tie Game..."
if is_winner(user, computer):
return "You win!"
return "You lose!"
def is... |
2d0cae4e44c62316876916fbe1250b1f82f00e6e | VargheseVibin/dabble-with-python | /Day24(SnakeGameHighScore)/main.py | 1,432 | 3.78125 | 4 | from turtle import Screen, Turtle
import time
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
def draw_border():
border = Turtle()
border.hideturtle()
b... |
0ee00e912ded3d5b339a97e80a5d555739427c30 | chamulovidio/clases | /ejercicios.py | 3,514 | 3.96875 | 4 | # En este ejemplo se solicitara la introduccion de datos
dato = input('Digite su Nombre: ')
dato1 = input('Diguite su apellido: ')
print(dato, dato1)
# Crear una variable, una lista, luego digitar un dato, verificar si
# en la lista y mostrar el dato introducido
var = input('Ingrese un Dato: ')
lista = ["Hola", "Mundo... |
9ebbbbfd7d867c295c79682de4db902abaa4cd09 | taaeyoon/Ace_todolist | /search.py | 2,371 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# todo table에 존재하는 todo 항목을 검색하여 찾는 함수...
import sqlite3
import list_todo as printer
def search(option=None):
conn = sqlite3.connect("ace.db")
cur = conn.cursor()
# 검색한 항목을 담은 list
search_list = []
search_answer_list = ["i", "d", "t", "c"]
# 어떤 방법으로 찾고 싶은 지에 대한 inpu... |
9f46b703dcbfcf9d178cffd754acc4360d6dd877 | FefAzvdo/Python-Training | /Exercicios/Aula 13/054.py | 728 | 3.8125 | 4 | mulheres_com_menos_de_20 = []
soma_idade = 0
nome_homem_mais_velho = ""
idade_homem_mais_velho = 0
for c in range(0, 4):
nome = input("Digite o seu nome: ")
idade = int(input("Digite a sua idade: "))
sexo = input("Digite o seu sexo: 'M' ou 'F' : ")
soma_idade = soma_idade + idade
if(sexo == 'F'):... |
3857d9d475081ff0e2d775e8d86f7ca6d958f2a0 | venkatram64/python_ml | /my_graphs/g_histo_gram_4.py | 556 | 3.796875 | 4 | import matplotlib.pyplot as plt
population_ages = [22, 44, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65, 54, 44, 43, 42,48]
"""ids = [x for x in range(len(population_ages))]
plt.bar(ids, population_ages, label="BARS1") """
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 10... |
2abef8ae1622397d73ea39194ee45cd06c770cc2 | jacopodisi/mru_securitygame | /mru/test/testfunctions.py | 630 | 3.71875 | 4 | import numpy as np
def compare_row_mat(x_mat, y_mat):
""" Compare rows of 2, unordered, matrices
Parameter
---------
x_mat: 1st matrix to compare
y_mat: 2nd matrix to compare
Return
------
boolean: True if the 2 matrices contains the same rows
(also in different order), F... |
88fe417718946be243638b7b0b45e1e70d48a210 | ashwinitangade/PythonProgramming | /PythonAss1/14.py | 1,969 | 4.125 | 4 | #Write a program to create two list A & B such that List A contains Employee Id, List B contain Employee name (minimum 10 entries in each list) & perform following operation
a) Print all names on to screen
b) Read the index from the user and print the corresponding name from both list.
c) Print the name... |
ec5b632bdd243f7b68c4223354cb27e8a418ac15 | 1987617587/lsh_py | /basics/day11/lzt/single_test.py | 2,129 | 3.609375 | 4 | # author:lzt
# date: 2019/11/20 15:44
# file_name: single_test
from typing import Any
class Book:
def __new__(cls, name) -> Any:
print("类的构造执行了 对象就会出生")
return super().__new__(cls)
def __init__(self, name) -> None:
super().__init__()
print("初始化方法执行了")
self.name = name... |
43dde6a93adc53e43becae46d8821a97b9468298 | Simran-Sahni/LeetCode-Solutions | /Python/baseK.py | 517 | 4.0625 | 4 | def sumBase(n: int, k: int) :
"""
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
TC : O(N)
SC : O(1)
n : int (integer base 10... |
93e375e270504890db29cc68dec14ff88053d16e | usamah13/Python-games- | /CMPUT 175/parcheck.py | 1,006 | 3.90625 | 4 | from Stack import Stack
#an example of abstraction
def parcheck(symbolString):
index = 0
aStack = Stack()
balanced = True
open_brackets = ['(','[','{']
while index < len(symbolString) and balanced:
if symbolString[index] in open_brackets:
aStack.push(symbolString)
else:
... |
8344bbf55bab18d971ccc068e453a99cbbe7cb0b | DuongTuan3008/duongquoctuan-fundamentals-c4e26 | /lab1/crawl_data.py | 897 | 3.515625 | 4 | #1. Creat connection
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pyexcel
url = "https://dantri.com.vn"
conn = urlopen(url)
#2. Download content
raw_data= conn.read()
page_content = raw_data.decode("utf8")
with open("dantri.html","wb") as f:
f.write(raw_data)
# # print(page_content)
# ... |
33fd170874d95a599842f18f35e2cba1e5a08cdb | SaFed23/helper | /3/2.py | 239 | 3.921875 | 4 | arr_of_days = ["Среда", "Четверг", "Пятница", "Суббота", "Воскресенье", "Понедельник", "Вторник"]
number = int(input("Введите чило: "))
print(arr_of_days[(number % 7) - 1])
|
3a47db15df8b70c5f810a1022d7637ae5b8b8182 | cademccu/cs152 | /programs/A10.py | 3,035 | 4.3125 | 4 | # Your program should count the number of word occurrences contained in a file and
# output a table showing the top 20 frequently used words in decreasing order of use.
def extract_words(string):
"""
Returns a list containing each word in the string, ignoring punctuation, numbers, etc.
DO NOT CHANGE THIS ... |
1dad3b765ae627f18d43a233e6e15faafcd8e41d | Varsha1230/python-programs | /ch7_loops.py/ch7_prob_04.py | 273 | 4.15625 | 4 | num = int(input("please enter a number of which you want to check whether it is prime or not: "))
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
break
if prime:
print("This no. is prime")
else:
print("This no. is not prime") |
27e7bbc22cdc282b500d85bc0e2ef12f3b8fec7d | Zarwlad/coursera_python_hse | /week5/task14.py | 174 | 3.65625 | 4 | string = str(input())
s = string.split()
evens = []
for sas in s:
sas = int(sas)
if sas % 2 == 0:
evens.append(sas)
for e in evens:
print(e, end=" ")
|
ed92a77ef364c98353312cbc9279bce4b828c52c | Awesome94/Algorithms | /insertion_Sort.py | 422 | 4.25 | 4 | def insertion_sort(nums):
for i in range(len(nums)):
j = 1
while j>0 and nums[j-1] > nums[j]:
swap(nums, j, j-1)
j = j-1
return nums
def swap(nums, i, j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == "__main__":
nums = [1,5,3,2,429,12... |
6cee67f5b3a578a7c8e8126f033f61321d5445c4 | klhoab/leetcode | /python/array and string/reverse-string.py | 313 | 3.75 | 4 | #https://leetcode.com/problems/reverse-string/
class Solution:
def reverseString(self, s: List[str], i = 0) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if i < len(s) //2:
s[i], s[-i-1] = s[-i-1], s[i]
self.reverseString(s, i+1) |
7e2102d40c76b12d2e592cb842e4024fad88d179 | 2226171237/Algorithmpractice | /chapter02_stack_queue_hash/t2.5.py | 2,004 | 4.125 | 4 | #-*-coding=utf-8-*-
'''
如何用O(1)的时间复杂度求栈中最小的元素
'''
class LNode:
def __init__(self, x, next=None):
self._data = x
self.next = next
class MyStack:
def __init__(self):
self.head = None # 栈顶
self._length = 0
def is_empty(self):
return self.head is None
def push(s... |
4b275a04c0313edf4b5831eb4a2fc7593a504643 | sudiq/leetcode | /search-a-2d-matrix-ii.py | 1,168 | 4.03125 | 4 | # https://leetcode.com/problems/search-a-2d-matrix-ii/
# Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
# Integers in each row are sorted in ascending from left to right.
# Integers in each column are sorted in ascending from top to b... |
9691a7fea3fa65ab4d5c2fe7744824d762a8dbc4 | SilverWin/HackerRankPython | /set_intersection_operation.py | 287 | 3.734375 | 4 | #!/usr/bin/env python
"""Solution for: https://www.hackerrank.com/challenges/py-set-intersection-operation/problem"""
__author__ = "Filip Jankowski"
n = int(input())
ns = set(input().split(" "))
b = int(input())
bs = set(input().split(" "))
com = ns.intersection(bs).__len__()
print(str(com)) |
5b11dea2e0a90cea12dbe5a4440b6b2e33065eb3 | rodrigograca31/Sprint-Challenge--Hash | /hashtables/ex4/ex4.py | 437 | 4.125 | 4 | def has_negatives(a):
"""
YOUR CODE HERE
"""
hashtable = {}
result = []
for index, number in enumerate(a):
# opposite = -number
if -number in hashtable:
result.append(abs(number))
hashtable[number] = number
return result
if __name__ == "__main__":
... |
9851c88515b9638af79a1e5b99486f4240a975de | willmead/intro_to_python | /src/Day1/rocket_builder.py | 768 | 3.734375 | 4 | """
Rocket Builder
Author: Will M
Date: 18.06.20
Use variables to store information about a new rocket.
"""
height = 60
width = 10
weight = 1000
power = 10
name = "Explorer"
destination = "Jupiter"
material = "Metal"
fuel = "Hydrogen"
is_manned = False
has_experiments = True
will_return = False
is_due = True
print... |
0652c2cdda9e7eab1566b0ba04ba24b1dd42a1ba | CAdummyaccount/fishtank | /project2.py | 1,929 | 4.0625 | 4 |
#change initial tank size input
#change calculations to look up contents of dictionary
#add calculations for water change amounts
#add round function to Alkalinity "needs" to prevent floats
#find a way to add a dictionary, while & for loops
print ("please enter length")
L=input()
print ("please enter width")
W=input(... |
c82de7ba37660963b0b29d9112a9d5af5e3ece68 | TaoCurry/Basic_Python3 | /递归例子/递归表示Fibo.py | 244 | 3.765625 | 4 | def fibo(n):
if n < 1:
print('输入有误')
return -1
elif n ==1 or n ==2:
return 1
else:
return fibo(n-1) + fibo(n-2)
result = fibo(35)
if result != -1:
print('一共有%d小兔崽子'% result)
|
5d8481aa452e1d923f9fa5fe5100a35237969fc2 | hugovk/twitter-tools | /bot_authorise.py | 1,512 | 3.640625 | 4 | #!/usr/bin/env python
"""
Authorise a Twitter bot account against a Twitter bot application.
It works by giving you a URL to authorise with, you paste that into a browser
that's logged in as the given (bot) user. You'll get a PIN back, which the app
is now waiting for -- from there you get your access key and secret.
... |
97e031dea3086caae21ec15114a5a39caa46a413 | neumann-mlucas/belousov-zhabotinsky | /belousov_zhabotinsky/render.py | 6,742 | 3.515625 | 4 | #!/usr/bin/python
import curses
import argparse
from .functions import *
def parse_args():
COEFFICIENTS = (1.0, 1.0, 1.0)
COLORS = np.random.choice(6, 10) + 1 # valid range is 1-7
ASCIIS = list(map(lambda x: " .:?!@~¨*&+"[x], np.random.choice(10, 10)))
# ASCIIS = (" ", ".", " ", ":", "*", "*", "#... |
c9b50baf2b37e1b2be26bd22227f51d084b2ce5e | hojin-shin/AnalyticswithPython | /analytics/chap1.py | 1,121 | 3.84375 | 4 | #!/usr/bin/env python3
'''
Foundation for analytics with Python
Lesson1))
'''
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
string1_list2 = string1.split(" ", 2)
print("Output #21 : {0}".format(string1_list1))
print("Output #22 : FIRST PIECE : {0} SECOND PIECE : {1} THIRD PI... |
5b4c25340d1f97fefc18550f617ea44997cfd568 | daniel-reich/ubiquitous-fiesta | /YSJjPdkwrhQCfnkcZ_24.py | 117 | 3.890625 | 4 |
def repeat_string(txt, n):
x=str(txt)*n
if type(txt) is str:
return x
else:
return "Not A String !!"
|
f8ffc08448fc769fbf237ae0f72bc5bf7880ddcd | MysteriousSonOfGod/python-workshop-demos-june-27 | /src/loops.py | 445 | 3.890625 | 4 |
numbers = [2, 3, 5, 7, 11, 13]
for n in numbers:
print(n)
print(n*n)
print()
# greeting = input("Say something: ")
#
# while greeting != "bye":
# print("You said " + greeting)
# greeting = input("Say something: ")
while True:
greeting = input("Say something: ")
if greeting == 'shh':
... |
5a4af2c9fe869252b7c7a0978f45a8e1d18d95ff | Angie-0901/AngieDeLaCruzRamos-AlvaroRojasOliva | /verificador16.py | 618 | 3.96875 | 4 | print("EJERCICIO N°16")
#Este programa calculara la energia cinetica de un X cuerpo
#INPUT
masa=float(input("la masa es: "))
velocidad_1=float(input("la velocidad 1 es: "))
velocidad_2=float(input("la velicidad 2 es:"))
#PROCESSING
Ec= (masa*velocidad_1 * velocidad_2)/2
#VERIFICADOR
Ec_verificado =(Ec >=... |
b504e13544af2c59f60b8c473d3afd1c5a2144c3 | malaikact/Number-Guessing-Game- | /guessing_game.py | 1,689 | 3.953125 | 4 | import random
def start_game():
scores = [100]
name = input("Hi there \U0001F44B, welcome to the Number Guessing Game! \U0001F3AE What is your name? ")
print("The highscore is {}, let's see if you can beat it.".format(min(scores)))
print("Let's get started {}!".format(name))
number... |
76f8ac4d0c14217cc3a60754784c47d35db09a7b | Mrzhaohan/python-one | /lei/neisuanfuchongzu.py | 474 | 3.828125 | 4 | class list_new():
def __init__(self,*agrs):
self.__mylist=[i for i in agrs]
def __add__(self,x):
return [i+x for i in self.__mylist]
def __sub__(self,x):
return [i-x for i in self.__mylist]
def __mul__(self,x):
return [i*x for i in self.__mylist]
def __di... |
83a9dd7a55b62c372938197d276eac77abb17702 | wanqiangliu/python | /parrot.py | 121 | 3.578125 | 4 | #input学习,编写交互式程序
message = input("Tell me somthing,and I will repeat it back to you:")
print(message) |
a993451a2c693d20231689c5c95b5a96240d0580 | duongnt52/ngotungduong-fundamentals-c4e25 | /Fundamentals/Session1/age_cale.py | 72 | 3.5 | 4 | yob = int(input("Your year of birth? "))
print("Your age: ", 2018 - yob) |
292e7b9b70e41bf9d878b8d2b635c4cfc979ccbf | kirigaikabuto/Python19Lessons | /lesson23/1.py | 338 | 3.515625 | 4 | from cat import Cat
from dog import Dog
cat1 = Cat(name="cat1", age=10)
cat2 = Cat(name="cat2", age=12)
cat3 = Cat(name="cat3", age=1)
cat4 = Cat(name="cat4", age=13)
cats = [cat1, cat2, cat3, cat4]
maxi = cats[0].age
maxi_cat = cats[0]
for i in cats:
if i.age > maxi:
maxi = i.age
maxi_cat = i
max... |
31b0f58fff7b31d0c2c0036f101cc82b279feccb | abi-oluwade/engineering-48-open-close-improved | /test_unittest_simple_calc.py | 732 | 3.640625 | 4 | import unittest # unittest is a LIBRARY
from simple_calc import SimpleCalc # we do not currently have this {file} or this {class}.
class Calctest(unittest.TestCase):
calc = SimpleCalc()
def test_add(self):
self.assertEqual(self.calc.add(2, 4), 6)
self.assertEqual(self.calc.add(4, 4), 8)
... |
78717c6e3930f1e65eec08d5f13d3ea5f2797986 | websvey1/TIL | /algorithm/algorithm_week/week5/problem_2(준석).py | 1,427 | 3.765625 | 4 | import sys
sys.stdin = open("problem_2.txt")
def iswall(x, y, n):
if x < 0 or x >= n: return True
if y < 0 or y >= n: return True
return False
def start(x):
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
return [i, j]
def finder(x, y):
globa... |
ed98a735591c71d72997fe2047f6274a8d9ac9c1 | thanh-falis/Python | /bai__75+76+77+78+79+80+81+82/PhuongThucThuongDung/Sort.py | 438 | 3.796875 | 4 | """Python hỗ trợ hàm sort để sắp xếp list"""
from random import randrange
lst = [0]*10
for i in range(len(lst)):
lst[i] = randrange(100)
print(lst)
lst.sort()
print(lst)
print("*"*20)
lst = [4, 2, 10, 8]
print(lst)
#sorted ko làm thay đổi bản chất của chuỗi
lst1 = sorted(lst)
print(lst1)
print(lst)
print("*"*20... |
d552099536526c6cc26c85fabd10da818b69ef48 | osmium18452/dmt-fig | /histogram.py | 452 | 3.578125 | 4 | import matplotlib.pyplot as pyplot
import numpy as np
def calHistogram(img):
if len(img.shape) != 2:
print("wrong image size")
return None
histogram=np.zeros(256)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
histogram[img[i][j]] += 1
return histogram
def drawHistoGram(histogram):
pyplot.... |
48b234f98df84f1725c47d2f07b9b84535d95031 | CameronHG/PythonProject | /CameronHG_1_3_6.py | 496 | 3.65625 | 4 | import random
#a = (6, 7, 9)
some_values = ('a', 'b', 3)
#print(some_values[0:2])
a = 10
tup = (9, a, 11)
print(tup[1] == 10)
print(tup[1])
values = [1, 2, 3]
print(values[1:])
values2 = ['a','b','c']
values2[2] = '3'
print(values[2] == 3)
values += [4, 5]
print(values)
values.append([6,7])
print(values)
... |
a72c38f21869d4941b128f95219e3264e9d67bec | alisson-fs/POO-II | /Exercício VPL - Herança e Classes Abstratas/animal.py | 433 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, tamanho_passo: int):
self.__tamanho_passo = tamanho_passo
@property
def tamanho_passo(self):
return self.__tamanho_passo
@tamanho_passo.setter
def tamanho_passo(self, tamanho_passo):
self.__tamanho_passo = tamanho_passo
def mover... |
e3ab9b8724d2ef8726efb237fa197fe88c5d1099 | pandapranav2k20/Python-Programs | /Lab 5/ENGR102_504_23_bisection.py | 1,962 | 4.15625 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Names: Damon Tran
# Benson Nguyen
# Matt Knauth
# Pranav Veerubh... |
97575b0b14abe6c020188b640500683c53e39a05 | dahyeeeon/Python | /Hello/test/Step15_random.py | 854 | 3.578125 | 4 | #-*-coding:utf-8 -*-
'''
random package 사용하기
'''
import random as ran #import 된 random의 별칭ㅂ여
ranNum=ran.random() #0이상 1미만의 무작위 실수
ranNum2=int(ran.random()*10) #0이상 10미만
ranNum3=int(ran.random()*10)+10 # 10이상 20미만
ranNum4=int(ran.random()*45)+1 # 1이상 45미만
#로또번호
nums=set() #로또번호를 담을 set객체
while True:... |
31ac06150e3850733cf2de74b6e70fa88c5819b9 | longfight123/17-CoffeeMachineProjectOOP | /oop-coffee-machine-start/main.py | 962 | 3.515625 | 4 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
coffee_maker_object = CoffeeMaker()
money_machine_object = MoneyMachine()
def make_a_drink():
a_menu_object = Menu()
print(a_menu_object.get_items())
user_drink = input('What would you like?')
... |
2fcc42c9b1246db1cfdc17097385ad8cdd98ea85 | DongHyukShin93/BigData | /pandas/pandas03/Pandas03_03_ClassEx03_신동혁.py | 674 | 3.640625 | 4 | #Pandas03_03_ClassEx03_신동혁
class FourCal() :
def setdata(self, first, second) :
self.first = first
self.second = second
def sum(self) :
result = self.first + self.second
return result
def sub(self) :
result = self.first - self.second
return result
def mul(self) :
result = self.first... |
bc55e21af2f1b4417a941c14f4519aae8e93a90b | chrislarabee/kivy-studio | /kivy-studio/scripts/new_app/lib.py | 1,904 | 3.515625 | 4 | from pathlib import Path
from kivyhelper import lib
def setup_kivy_app_py(app_name: str) -> str:
"""
Generates a file string for the *App python file in the root kivy
app.
Args:
app_name: A string, the name of the app.
Returns: A string, the python code to save to the App.py file.
... |
cf59c7e17dfbb4d5abfc2cff7f4a0135c2cd17ed | cascam07/csf | /unique_column.py | 967 | 3.8125 | 4 | def unique_column_values(rows, column_name):
"""
Given a list of rows and the name of a column (a string), returns a set
containing all values in that column.
"""
result = set()
for poll in rows:
result.add(poll[column_name])
return result
poll_rows1 = [{"ID":1, "State":... |
6aac6c9eea7524b25c751a7931e76a30dd2acc0f | mjnorona/codingDojo | /Python/python_fundamentals/typeList.py | 899 | 4.03125 | 4 |
def printList(list):
elType = type(list[0])
mixed = False
text = ""
sum = 0;
for i in range(0, len(list)):
if type(list[i]) is not elType:
mixed = True
if type(list[i]) is float or type(list[i]) is int:
sum += list[i]
elif type(list[i]) is str:
... |
2ceafb364ae0863085962f5f4dcefc060de2c47a | SriVasudhaKilaru/Datascience-Projects | /LinearReg/linearReg.py | 1,418 | 3.9375 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the dataset
dataset = pd.read_csv('C://Users/Prani/Desktop/python/salary.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#Taking care of missing data
"""from sklear... |
af69e62b41b7748153d31567b61260cedec5d73f | Z-App-Xpert/project0 | /test/loops1.py | 65 | 3.5 | 4 | names = ["Alice", "Bob", "Charlie"]
for x in names:
print(x)
|
9763beacdc255af2bfd6d1ddebfd98495e336cb7 | azarrias/udacity-nd256-problems | /src/min_operations.py | 1,772 | 4.375 | 4 | """
Min Operations
Starting from the number 0, find the minimum number of operations required to reach
a given positive target number. You can only use the following two operations:
1. Add 1
2. Double the number
Example:
1. For Target = 18, output = 6, because it takes at least 6 steps shown below to reach the t... |
7d7e00ac11748cbff75e84f0b6fd87c8e6b1c816 | akuchlous/leetcode | /168.py | 672 | 3.5 | 4 | import pdb
import string
import string
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
allS = string.ascii_uppercase
# base 26
buf = ""
remainders = []
#pdb.set_trace()
while (n >0):
print ( " ", n)... |
e29c67b7024824419a42abee383426187150c969 | royalbhati/ComputerVision | /smiledetector.py | 2,176 | 3.609375 | 4 | import cv2
#We need two classifiers one to detect frontal face and one to detect eye
face_clf=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile=cv2.CascadeClassifier('haarcascade_smile.xml')
# we define a detect function which takes a gray scale image to processs and a normal
# image to return after... |
7482289d1dec29b72c75477a647089d168be1ed5 | dumin199101/PythonLearning | /python3/016闭包/001.py | 416 | 3.96875 | 4 | #coding=utf-8
#闭包:如果一个函数内部定义了一个函数,并且用到了外部函数的变量,那么这个内部函数可以称之为闭包!
#在未调用内部函数之前,外部函数的变量不会释放!!!
def test(num):
print("-----1------")
def test1(num2):
print("----2------")
print(num+num2)
print("------3-----")
return test1
a = test(100)
a(200) |
b304734735544e2c4050ba1df34c0d7f542b9576 | LouiGi9/pace_giver | /speed_and_pitch_change.py | 1,607 | 3.546875 | 4 | from pydub import AudioSegment
class PaceGiver:
def speed_change(sound, speed=1.0):
# This is a copy-paste of a solution posted by a stackoverflow user here:
# https://stackoverflow.com/questions/43408833/how-to-increase-decrease-playback-speed-on-wav-file
# This method alters the p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.