blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
863b67f297862f0f51ed0065fff66861e79684dc | rcarrasco3652/PythonParaPrincipiantes | /tiposVariables.py | 1,090 | 4.1875 | 4 | #Variables
#Una variable es un nombre simbolico para un valor
nombre = "Roberto Carrasco" #Forma mas comun de declarar una varibale
book = "Libro genial"
print(nombre)
#En una variable puedes guardar cualquier tipo de datos
nombre2, numBook = "Rosa Jaramillo", 19 #Otra manera de declarar variables
print(n... |
6299ae3438ab1ff9c2ca1831ad9aa9d762371c1e | EstherOA/PythonNDataScience | /files/q1.py | 387 | 3.6875 | 4 |
user_in = input('Enter some text and END to quit:')
try:
f = open('userInput.txt', 'a')
while user_in != 'END':
f.write(user_in + '\n')
user_in = input('Enter some text and END to quit:')
finally:
f.close()
try:
fr = open('userInput.txt', 'r')
i = 0
for line in fr:
... |
060e6f73a5fe3c47bf19284bad2a664f216e5a7a | aroraakshit/coding_prep | /reverse_words_string_2.py | 924 | 3.515625 | 4 | class Solution: # 228ms
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if s == [] or ' ' not in s:
return
for j in range(len(s)//2):
s[j], s[len(s)-j-1] = s[len(s)-j-1], s[j]
pr... |
4e78bb6e62beeeda164c6d1a9df12951485beca0 | krsatyam20/pythonApr | /FirstDayQ2.py | 499 | 3.78125 | 4 | a=input ("Roll No.")
b= raw_input ("Student Name")
c=input ("Marks in Maths")
d=input ("Marks in Science")
e=input ("Marks in English")
f=input ("Marks in Hindi")
g=input ("Marks in SST")
print ("==================")
print ("Roll No %d"%(a))
print ("Roll No %s"%(b))
print ("Roll No %d"%(c))
print ("Roll ... |
c8f1c4ef75718a50296f6d7ea7b0b3779e8a6a20 | arshadumrethi/Python_practice | /list_comprehension.py | 1,272 | 4.71875 | 5 | #List Comprehension syntax is used to build lists easily
#Example 1
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print even_squares
#Example 2
cubes_by_four = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0]
print cubes_by_four
#Example 3
threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or... |
d9fa529280e41fe064c7df4f58abd41e93ba325a | lostsquirrel/python_test | /checkio/elementary/pangram.py | 1,962 | 4 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015-03-17
@author: lisong
pangram:字母表所有的字母都出现(最好只出现一次)的句子
A pangram (Greek:παν γράμμα, pan gramma,
"every letter") or holoalphabetic sentence for a given
alphabet is a sentence using every letter of the alphabet
at least once. Perhaps you are familiar with the well
known pang... |
693e69f8d1d1414147c30b6e738b70993ced0c87 | Klaus-Analyst/Python-Programs | /SQLITE3/002.py | 392 | 3.953125 | 4 | import sqlite3 as sql
conn=sql.connect("PWG.sqlite3")
curs=conn.cursor()
idno=int(input("Enter id no"))
name=input("Enter name")
salary=float(input("Enter the salary"))
try:
curs.execute("insert into employee values(?,?,?)",(idno,name,salary))
conn.commit()
print("Data Stored Successfully")
except sql.Integ... |
6265ba1033c3c6b6aacf6f0b9c90fef1eaef6242 | prateek1404/AlgoPractice | /Strings/allspace.py | 192 | 3.796875 | 4 | def allspace(word,i):
if i==len(word)-1:
print word
return
aword = word[:i+1]+" "+word[i+1:]
allspace(aword,i+2)
allspace(word,i+1)
word = raw_input()
allspace(word,0)
|
07b66aa28faa4c26de29487e2e8cc5e1476779ca | dan-mcm/python-practicals | /P14/p14p4.py | 753 | 4.09375 | 4 | # Psuedocode
# for number in range (2,20)
# let the variable x = 1 // this will act as a semaphore
# for i in range (2,number):
# if number has no remainder:
# print number equal to number 1 by number 2
# let x = 0 //switch semaphore state - forces program to run though entire range ... |
e2600edcdf2213c3495a2b63148c339fbcfec8eb | mihailruskevich/rosalind | /bioinformatics_stronghold/signed_permutation/permutations.py | 935 | 3.578125 | 4 | def permutations(a, index, res):
if index < len(a):
i = index
while i < len(a):
b = a.copy()
b[index], b[i] = b[i], b[index]
i = i + 1
permutations(b, index + 1, res)
else:
res.append(a)
def signed_combinations(p, index, res):
if inde... |
2096b01a725336df0eb8a8fd54ca2e124f5f480d | rublaman/Python-Course | /exercices/ej62.py | 211 | 3.84375 | 4 |
# Crea un programa que imprima "Hola". Cada iteración va a aumentar
# en un segundo el tiempo de espera para volver a imprimir
import time
i = 2
while 1 < 2:
print("Hola")
time.sleep(i)
i += 1
|
43a95259a2cf5e5e7bd87da80875f3dc87f1658e | chanheum/Practice-Python- | /자료구조/해시테이블/close_hash.py | 2,080 | 3.640625 | 4 | # close hashing
class CloseHash:
def __init__(self, table_size):
self.size = table_size
self.hash_table = [0 for a in range(self.size)]
def getKey(self, data):
self.key = ord(data[0])
return self.key
def hashFunction(self, key):
return key % self.size
def getAd... |
f9032cbdb7f46eeb5f9a1eb2b8417c76f6e5eb73 | THUZLB/leetcode_python | /048_Retate_Image.py | 889 | 3.875 | 4 | # -*- coding: utf-8 -*-
# author: THUZLB
# GitHub: https://github.com/THUZLB
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n):
for j in ra... |
6a29d30ce126ffbae27a3e6e74b5538e614ba589 | JustinLee32/cai_niao_shua_ti | /按题号/1161 最大层内元素和.py | 1,822 | 3.625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
from collections import defaultdict
self.level_sum_dict = defaultdict(int)
a... |
7c2e45ec864f2257bc40f34c1b51d996991fa025 | PengZhang2018/LeetCode | /algorithms/python/BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.py | 920 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# recursive
class Solution1:
def preorderTraversal(self, root: TreeNode):
if not root:
return []
result = []
result.append(root.v... |
13abb7c305e92b959ca13470cf65630a28240c2a | georgegoglodze/python | /stock_trading/get_monthly_data.py | 406 | 3.515625 | 4 | import sqlite3
# Function to get stock trading data
def get_monthly_data(month):
connection = sqlite3.connect("stock.db")
cursor = connection.cursor()
#cursor.execute("SELECT * FROM stock")
#cursor.execute("select * from stock where trade_date < date('now','-0 days')")
cursor.execute(f"SELECT * FR... |
c4ff84c39a7a1aab9cb70411f497b2e68eac4886 | acehu970601/Motors-Temperature-Prediction | /src/util.py | 2,172 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def add_intercept(x):
"""Add intercept to matrix x.
Args:
x: 2D NumPy array.
Returns:
New matrix same as x with 1's in the 0th column.
"""
new_x = np.zeros((x.shape[0], x.shape[1] + 1), dtype=x.dtype)
new_x[:, 0] = 1
new_x[... |
ae83ddacb88098fb1db1447ae0bb97af0dbe9b09 | gmauricio/game-of-life | /tests.py | 2,636 | 3.5625 | 4 | import unittest
from game import World, Cell
class WorldTest(unittest.TestCase):
def test_counting_0_corner_cell_neighbours(self):
world = World(2, 2)
world.set([
[Cell(0), Cell(0)],
[Cell(0), Cell(0)]
])
self.assertEqual(0, world.get_neighbourhoods()[0][0])
def test_counting_3_corner_cell_neighbour... |
4628cb33312da7e7024301c5fdef2c367470c542 | marcos-mpc/CursoEmVideo-Mundo-2 | /ex061.py | 146 | 3.78125 | 4 | termo = int(input('TERMO: '))
razao = int(input('RAZÃO: '))
cont = 0
while cont < 10:
print(termo, end=' ')
termo += razao
cont += 1
|
dbb78a2c764277eef5797c29e67b57017d9e1e3c | ColorfulCodes/Algo-Grind | /Random/newspiral.py | 1,350 | 3.546875 | 4 | #
# def printSpiral(matrix):
# result = []
# rows = len(matrix)
# topRow = 0
# btmRow = rows -1
# leftCol = 0
# rightCol = len(matrix[0]) -1
#
# if rows == 0:
# return result
#
# while (topRow <= btmRow and leftCol <= rightCol):
# for i in range(leftCol, rightCol +1):
# result.append(ma... |
08b9736de5ded403a6f41e0a8bd019729b8dcfea | mikebentley15/sandbox | /python/multiplicative-permanence/multperm.py | 6,620 | 4.25 | 4 | #!/usr/bin/env python3
import argparse
import sys
import itertools
def populate_parser(parser=None):
if not parser:
parser = argparse.ArgumentParser()
parser.description = 'Calculate multiplicative permanence'
group = parser.add_mutually_exclusive_group()
group.add_argument('num', type=int, de... |
6b72d449b6da8c8d94e2fd10f1e22bb44f677d9a | hamburgcodingschool/L2CX-January_new | /lesson 6/homework_7.py | 263 | 4.03125 | 4 | # 7 - Write a program that prints the names on odd positions in an array of names.
l2cClass = ["Helder", "Fabia", "Leonie", "Carina", "Lexie"]
for i in range(0, len(l2cClass)):
name = l2cClass[i]
if i % 2 != 0:
print("{}: {}".format(i, name))
|
01f47b93c0902270904803a7e9d1e180743ccc4a | Ivan-yyq/livePython-2018 | /day9/demon8.py | 723 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/20 20:06
# @Author : yangyuanqiang
# @File : demon8.py
# 阶乘的和
class JinCinCount(object):
def __init__(self, n):
self.n = n
def jc(self, n):
result = 1
if n == 0:
return result
else:
f... |
52a69fc9e91c94f9dfebaeb5ad6024f955150e41 | s1td1kov/Basics-in-Python | /Week2/Утренняя пробежка.py | 96 | 3.5 | 4 | x, y = int(input()), int(input())
k = 0
while x < y:
x = x * 1.1
k = k + 1
print(k + 1)
|
52c4bd26be8b0ea375966e187462c7945b60caaf | parthjoshi09/ner | /nerv1.py | 867 | 4.46875 | 4 | #Identify person names in a given piece of text, using dictionaries.
import re
regex = "[a-zA-Z]+" #Defining regex for tokenizer.
with open("female.txt") as f:
female_names = f.readlines() #Read names line by line and store them in a list.
female_names = [w.strip() for w in female_nam... |
da52d941e3fb1025e2cb2cd72dfdcda0b4b1f6bf | thaistlsantos/Python-FIT | /1º Semestre/Aula 12 - 05_11/Aula_11_lista_range.py | 200 | 3.609375 | 4 | lista = [1, 5, 7, 6, 9]
for x in lista:
print(x)
lista.append(x**2)
if cont == 10:
break
cont += 1
n = len(lista)
for i in range(len(lista)):
lista.append(lista[i] ** 2)
|
e8e881cece87d6937f1cd5bf4a5dbdc7913de454 | brandonhumphries/week-1-python-exercises | /blastoff4.py | 443 | 3.9375 | 4 | starting_number = int(raw_input("Number under 21 to start counting from? "))
counter = 0
while starting_number > 20:
starting_number = int(raw_input("Number under 21 to start counting from? "))
numbers = range(0, starting_number + 1)
while abs(counter) < len(numbers):
print numbers[counter - 1]
counter -= 1... |
583860109443f4a61026711896d8fe132973bbdd | jiushibushuaxie/my_leetcode_path | /python/9回文数.py | 809 | 4.03125 | 4 | """
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
输入: 121
输出: true
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
所以负数肯定不是回文数
注意事项:'int' object has no attribute 'copy' int不能用copy()
暂时存储x的值
"""
class Solution:
def isPalindrome(self, x):
if x < 0:
... |
ab7fbb0138a26f4f0ba3979df5c008289263b258 | Rohit-83/TODO | /dbhelper.py | 1,251 | 4.0625 | 4 | import sqlite3
#for creation of data base
conn = sqlite3.connect('test.db')
#creation of table if not exists
conn.execute(''' CREATE TABLE IF NOT EXISTS todo(
id INTEGER PRIMARY KEY,
task TEXT NOT NULL
)
''')
#DATA INSERTION
#query = "INSERT INTO todo(task) VALUES('Reecord');"
#conn.execute(query)
#conn.commit()
def... |
4a377c66981ff01dc8afe447b591f9681c955b35 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC257.py | 830 | 3.8125 | 4 | # O(n*log(n))
# n = numberOfNodes(root)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res... |
40e47a034eb1eafaf5d5ee7cf97165a0b375a447 | ivenn/ready | /basics/sorting/merge_sort.py | 810 | 3.8125 | 4 | def merge(arr, l, m, r):
big_int = 100
size_l = m - l + 1
size_r = r - m
larr = [0] * size_l
rarr = [0] * size_r
for i in range(size_l):
larr[i] = arr[l + i]
for j in range(size_r):
rarr[j] = arr[m + j + 1]
larr.append(big_int)
rarr.append(big_int)
i = 0
... |
d0f9a755e18f163ac4ea71a841604069caa1c1c9 | javargas510-bit/Python_stack | /_python/python_fundamentals/basic_functions.py | 1,368 | 3.875 | 4 | #1 prints number 5
def a():
return 5
print(a())
#2 prints number 10
def a():
return 5
print(a()+a())
#3 prints number 5
def a():
return 5
return 10
print(a())
#4 prints 5
def a():
return 5
print(10)
print(a())
#5 prints 5
def a():
print(5)
x = a()
print(x)
#6 print 3 , 5 and error
def a(b,... |
df88a4dbe442d59b1c4454b4b6152b54730c9a9c | DaianeFeliciano/python-fatec | /ATV78.py | 2,290 | 4 | 4 | n1 = int(input("Digite o primeiro número inteiro: "))
n2 = int(input("Digite o segundo número inteiro: "))
n3 = int(input("Digite o terceiro número inteiro: "))
n4 = int(input("Digite o quarto número inteiro: "))
if (n1 > n2 and n2 > n3 and n3 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".form... |
f5fd210cebe5e234e437235a999d31aecfac23ab | PropertyOfMan/WebServer-API-Project | /diction.py | 1,061 | 3.546875 | 4 | dictionary = {1: ('В золотом окне востока лик свой солнце показало.', 'Ромео и Джульетта'), 2: ('— Через столько лет? — Всегда.', 'Северус Снегг (Северус Снейп)'), 3: ('Ни одного правителя не поддерживают все до единого.', 'Игра престолов'), 4: ('Он коснулся пальцами ее волос, она ощутила, что к ней прикоснулась любовь... |
350d8b79396dcd705f2adb64e72db917ebed3963 | Skillicious/PythonJunk | /futval.py | 862 | 3.78125 | 4 | from graphics import*
def main():
principal = eval(input("Enter the intial principal: "))
apr = eval(input("Enter the annualized unterest rate: "))
win = GraphWin("Investment Growth Chart", 320,240)
win.setBackground("white")
Text(Point(20,230), " 0.0K").draw(win)
Text(Point(20,180), " 2.5K").draw(win)
Text... |
bc84fc11a51c42b9747e70d23a5dd7321b13d5c4 | smtamh/oop_python_ex | /student_result/2019/01_number_baseball/baseball [2-1 김A].py | 6,184 | 3.578125 | 4 | import random
# 똑바로 입력했나 판단
def fin_check(a):
# if (a == 'y' or a == 'n'):
if a in 'yn':
return True
return False
# 입력값에 따라 게임 지속 여부 판단
# 게임을 끝내겠습니까?
def which_func(a):
if a == 'y':
# 아뇨
return False
else:
# 네
return True
def make_func():
# 랜덤하게 0~9 ... |
9917e44fbc0fc3f37018739d2858e289e8675e7a | arparker95/Learn-to-Program-Activities | /directory.py | 1,238 | 4.03125 | 4 | import csv
def menu():
print "A) Add to Directory"
print "B) Diplay Directory"
print "X) Exit Directory Program"
selection = raw_input()
if selection == "A":
addToDirectory()
elif selection == "B":
displayDirectory()
elif selection == "X":
quit()
els... |
c79141e6c0c99141fd38b5368d47f6b0981124a5 | alvindrakes/python-crashcourse-code | /Chapter 4/foods.py | 809 | 4.4375 | 4 | # copying list in python
my_food = ['veggies', 'tomatoes', 'apple']
friend_food = my_food[:] # just omit the indexes to copy the entire list
print('This is my food')
print(my_food)
print('\n')
print('This is my friend''s food')
print(friend_food)
my_food.append('cheese')
friend_food.append('nugget') ... |
ba0748f72652df6dddcb7180d4fb5dfe587de720 | addtheletters/laddersnakes | /graphs/bellmanford.py | 956 | 3.765625 | 4 | # Bellman-Ford algorithm.
# Find shortest paths from a source to elsewhere in a graph.
# Slower than Dijkstras, but works with negative edge weights.
# https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
import testgraph as tg
def bellmanford(graph, src):
edges = tg.edgeList(graph)
dist = {}
pat... |
b95d390fe5fc34cac1a79275684bb64d415ef83b | Solvi/statsmodels | /examples/example_interaction_categorial.py | 779 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""Plot Interaction of Categorical Factors
"""
#In this example, we will vizualize the interaction between
#categorical factors. First, categorical data are initialized
#and then plotted using the interaction_plot function.
#
#Author: Denis A. Engemann
print __doc__
import numpy as np
from s... |
faef581455d52a27a5e405e2192229a8b2a12dd9 | Muslum10cel/HackerRankPY | /com/mathematics/fundamentals/HalloweenParty.py | 183 | 3.578125 | 4 | import math
T = int(input())
for _ in range(T):
K = int(input())
if K % 2 == 0:
print(K // 2 * K // 2)
else:
print((math.ceil(K / 2) * math.floor(K / 2))) |
649f9722c554371994007ca67553e0297970ad59 | zhouyuhangnju/freshLeetcode | /3SumClosest.py | 1,055 | 3.765625 | 4 | def threeSumClosest(nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
maxdiff = 2**31-1
nums = sorted(nums)
print nums
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l <... |
7d10db3f652923241d5779ba250d7e6c28334b38 | Android-Ale/PracticePython | /mundo2/lerNomePreçoDoProdutoComWhile.py | 941 | 3.671875 | 4 | print('-'*20)
print('LOJA BARATÃO')
print('-'*20)
fim = 'a'
totalpreço = contadorpreço = menor = contador = 0
menorproduto = ''
while True:
produto = str(input('Nome do produto:'))
preço = float(input('Preço: R$'))
totalpreço += preço
contador += 1
if preço > 1000:
contadorpreço += 1
if ... |
b85a99807f08dc7e96a64151026e10594f8ff60e | severinkrystyan/CIS2348-Fall-2020 | /Homework 1/1.20 zyLab_Krystyan Severin_CIS2348.py | 392 | 3.859375 | 4 | """Name: Krystyan Severin
PSID: 1916594"""
user_num1 = int(input('Enter integer:\n'))
print('You entered:', user_num1)
print(user_num1, 'squared is', user_num1**2)
print(f'And {user_num1} cubed is {user_num1**3} !!')
user_num2 = int(input('Enter another integer:\n'))
print(f'{user_num1} + {user_num2} is {user... |
80dc46160aa39078add57d1b0de9614bb1033f55 | chaozc/leetcode | /python/p110.py | 613 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def height(self, root):
if root == None:
return True, 0
bl, hl = self.height(root.left)
... |
74255c438de37d22da51070c23c7a7ee876a5135 | zxl-python/- | /day5/new的认识.py | 280 | 3.65625 | 4 | #__new__ 魔术方法
# 实例对象的时候触发,负责对象的创建与否
class Human:
def __new__(cls,limit):
if isinstance(limit,int):
return super().__new__(cls)
def __init__(self,limit):
print("哈哈哈哈")
a = Human('he')
print(a)
|
d49200c51c1b0d3b41b756c2f4f5615945a72883 | jjcenturion/ej21 | /main.py | 279 | 3.84375 | 4 | cont_letra = 0
cont_palabra = 0
cadena = None
while cadena !='.':
cadena = input('Ingresar letra, termina con"."')
cont_letra += 1
if cadena == '' or cadena == '.':
if cont_letra > 1:
cont_palabra +=1
cont_letra = 0
print('Cantidad de palabras:', cont_palabra ) |
a90b203e64385c2f1b09cb96069e50a05bf0b4dd | edu-sense-com/OSE-Python-Course | /SP/Modul_07/funkcje_python.py | 1,346 | 3.859375 | 4 | # przykłady definiowania i wywoływania funkcji w Python
def just_print():
print("Just printing some text.")
def just_return():
return "Just returning some text"
def parameter_print(some_value):
print(f"You pass value: {some_value}")
def parameter_return(some_value):
return f"You pass value: {some_va... |
a5f2c62d0ad6a52f6c084eca308dab633042ac11 | honwenle/pygit | /fibs.py | 286 | 3.78125 | 4 | def fib1(n):
result=[0,1]
for i in range(n-2):
result.append(result[-2]+result[-1])
return result
def fib2(n):
a, b = 0, 1
result=[]
while b < n:
result.append(b)
a, b = b, a+b
return result
a1 = fib1(10)
a2 = fib2(100)
print(a1,a2) |
92b76e85bd05d4c0da375aaa98ae6da54d45a1a1 | ovch-antonina/tokenizer | /test_tokenizer.py | 2,394 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import unittest
from tokenizer import Token, Tokenizer
class TokenizerTest(unittest.TestCase):
'''tests for tokenizer.py'''
def test_regular(self):
'''
tests a string with mixed alphabetical symbols, numbers, and whitespaces
'''
tokens = T... |
29fcfa072bd8a12d022ec0ea963a2ecd033c81d8 | Jaraiz91/Javier_Araiz_TheBridge | /ML_Project/src/utils/mining_data_tb.py | 5,521 | 4 | 4 | import pandas as pd
import numpy as np
import os, sys
def merge_csv(base_name, range_number, column_name, file_name, path, start_number= 0):
"""" The function saves a csv file with all the csv files you want to join
arguments:
base_name: base name that share all the files in order to make the loop insid... |
aefbbb52913be3b602cbfda29debc69bd7612ac8 | suilin0432/DataStructurePratice | /树/BinarySearchTree.py | 5,227 | 3.921875 | 4 | import collections
class BinarySearchTree(object):
def __init__(self):
self.root = None
def clear(self):
self.root = None
def insert(self, node):
if not self.root:
self.root = node
return
root = self.root
while True:
if node.val >... |
67c83d04cc00e3d9acb024ace11f211e080c11ef | microainick/high_low_game2 | /MyBBcomGuess.py | 4,240 | 4.15625 | 4 | #import
import random
#make ran be a random integer between 1 and 128)
ran = random.randint(1, 128)
int(ran)
#it probably was an integer but that was to ensure it.
#Print eplanation
#spacing for readability
#i like the formatting this way with spaces
print(" ")
print("If the computer has 7 chances to calculate the Se... |
e7f2b44f135a6bc488adc96c27b0686b522c4b62 | wow01022634/udemy_python_quickstart | /6_Class/6-1_class.py | 171 | 3.578125 | 4 | class Customer:
def __init__(self, name, city):
self.name = name
self.city = city
p1 = Customer("peter","Austin")
print(p1.name)
print(p1.city) |
ac1eaa54f645a7b2d5fee018d5b6720fb7e8b9a7 | xinshuoyang/algorithm | /src/86_BinarySearchTreeIterator/solution.py | 1,325 | 3.890625 | 4 | #!/usr/bin/python
################################################################################
# NAME : solution.py
#
# DESC :
#
# AUTH : Xinshuo Yang
#
# DATE : 20181229
#
################################################################################
"""
Definition of TreeNode:
"""
class TreeNode:
def __i... |
c3c1feafa7e3962240985ded734dd3a6192ee4ab | slavamirovsky/The-tasks-Python- | /task_8.py | 890 | 4.65625 | 5 | ## 8. Volume of a Spherical Shell
## The volume of a spherical shell is the difference between the enclosed volume
## of the outer sphere and the enclosed volume of the inner sphere:
##
## Create a function that takes r1 and r2 as arguments and returns the volume of
## a spherical shell rounded to the nearest tho... |
05a17191a8f890f24811ef6ab7d2128fce7a96d4 | humachine/AlgoLearning | /leetcode/Done/416_PartitionEqualSubsetSum.py | 2,698 | 3.53125 | 4 | #https://leetcode.com/problems/partition-equal-subset-sum/
# There also exists a bitset solution which uses O(max possible sum of all numbers) space and O(N) time
"""
Inp: [1, 5, 11, 5]
Out: True (can be partitioned into 11 and the rest)
Inp: [1, 2, 3, 5]
Out: False (no equal partition of the array p... |
812682b6cb8efc47ba3eddab3eba16234bc46927 | mayrazan/exercicios-python-unoesc | /comparação/1.py | 317 | 4.15625 | 4 | numero1 = input("Informe um número: ")
numero2 = input("Informe um número: ")
if numero1 > numero2:
print("O maior numero é %s." % numero1)
elif numero1 < numero2:
print("O maior numero é %s." % numero2)
elif numero1 == numero2:
print("O numero %s e o numero %s são iguais." % (numero1, numero2)) |
979c8644423e6650c10f19eae1ec31589f251ecf | poornachandrakashi/OOPs-in-Python | /Employee.py | 579 | 3.796875 | 4 | class Employess():
#Definiing the initializers
def __init__(self,ID=None,salary=None,department=None):
self.ID=ID
self.salary=salary
self.department=department
def tax(self):
return(self.salary*0.2)
def salaryperday(self):
return(self.salary/30)
#Initializing ... |
4209dae8f28831a9b2f8a1a90971830c7ec3d161 | Quantanalyst/SoftwareEngineeringNotes | /Data Structure and Algorithms/Popular Questions/toptal test.py | 2,851 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 7 16:46:47 2020
@author: saeed
"""
def solution(N,K):
if N < 2:
return 0
else:
if K == 0:
return N - 1
elif (K !=0) & ((N // (2**K)) > 0):
X = N // (2**K)
res = N % (2**K)
... |
700ee9093a2dbd55ebf6fb1028ca1c44eee76a9f | Ldarrah/edX-Python | /PythonII/3.3.3 Coding Problem sumloop.py | 947 | 4.125 | 4 | mystery_int = 7
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Use a loop to find the sum of all numbers between 0 and
#mystery_int, including bounds (meaning that if
#mystery_int = 7, you add 0 + 1 + 2 ... |
029a2b40b859a6282eef809474756486f8ef2ec9 | JDHProjects/AOC-2020 | /day3/day3.py | 452 | 3.515625 | 4 | def getTreeCount(inData, x, y):
treeCount = 0
xOffset = 0
for i in range(0,len(inData),y):
if(xOffset >= len(inData[i])):
xOffset -= len(inData[i])
if(inData[i][xOffset] == "#"):
treeCount += 1
xOffset += x
return treeCount
def multiSlope(inData, s... |
1f3cb8e812212b5bf2d29ae765db38b553691436 | Kent1004/Python_1try | /Krivykh_Mikhail_dz_3/task3_5.py | 1,996 | 3.671875 | 4 |
from random import choice,choices,shuffle, randint, sample
nouns = ["автомобиль", "лес", "огонь", "город", "дом"]
adverbs = ["сегодня", "вчера", "завтра", "позавчера", "ночью"]
adjectives = ["веселый", "яркий", "зеленый", "утопичный", "мягкий"]
"""Функция - генератор шуток из заданных списков"""
def get_jokes(numbe... |
cc48b26bdd1934e2407c91cf227b0d1c63492a9a | boboalex/LeetcodeExercise | /leetcode_105.py | 1,089 | 3.875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, preorder, inorder) -> TreeNode:
def myBuildTree(preLeft, preRight, inLeft, inRight):
... |
91e6486cc3ed3f523f2c72bba9ee34f278176da0 | nmanley03/final_project | /Python.py | 891 | 3.703125 | 4 | import pandas as pd
import numpy as np
#import csv file
data = pd.read_csv(r"/Users/niallmanley/Downloads/Final_Project/202021Football1.csv")
avgage = data['age'].mean()
print(avgage)
#Some players ages appearing as 0, as well as birthday field. Clean data and replace 0 in age with avg age of 23
data.loc[data['birthda... |
a10dbaba77a40d21bab0182a3dfadeaed29bbbff | mittsahl/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 378 | 3.828125 | 4 | #!/usr/bin/python3
"""MyInt class"""
class MyInt(int):
""" Canging equality attributes of int class"""
def __eq__(self, other):
"""Chagnes equality artributes form equal to not equal"""
return int.__ne__(self, other)
def __ne__(self, other):
"""changes equality attributes from not... |
ff0b73331098958831e435fdef6b67432f6efb39 | mischief901/nyt_unscrambler | /unscramble.py | 672 | 3.53125 | 4 | import sys
import getopt
import bisect
def main(letters, center) :
words = open("/usr/share/dict/american-english", "r")
for word in words :
word = word.lower().strip()
if center not in word :
continue
if len(word) < 4 :
continue
lets = "".join(sorted(set(word)))
valid = ... |
be1c8e737259555b7e78550e1097609e01c4badf | chitreshd/puzzles | /hackerrank/findPossibleSentences.py | 1,314 | 4.03125 | 4 | # For a given string and dictionary, how many sentences can you make from the string, such that all the words are contained in the dictionary.
# // eg: for given string -> "appletablet"
# // "apple", "tablet"
# // "applet", "able", "t"
# // "apple", "table", "t"
# // "app", "let", "able", "t"
# // "applet", {ap... |
328b17bc68ccbe85cc8e5125c1a6edc5e7c1b2a3 | jackHorwell/automatedChessBoard | /main.py | 13,828 | 3.5 | 4 | # Imports modules to control raspberry pi GPIO
import RPi.GPIO as GPIO
import time
import charlieplexing
# Sets up Stockfish engine
from stockfish import Stockfish
stockfish = Stockfish("/home/pi/Downloads/a-stockf")
stockfish = Stockfish(parameters={"Threads": 2, "Minimum Thinking Time": 30})
stockfish.set_skill_lev... |
9ae8aeb122efb8a83f9004157b5a62d684a35b07 | ShamiliS/Java_Backup | /SimplePython/callFunction.py | 462 | 3.609375 | 4 | '''
Created on 4 Apr 2018
@author: SHSRINIV
'''
import math
import SampleFunction
import var_len_arg
# module1
var_len_arg.printinfo(56, 20, 10)
# module2
prntval = SampleFunction.samplefun("Shamili")
for val in prntval:
print(val)
content = dir(math)
print(content)
def sum(a, b):
"Adding the two v... |
12c54f72446d434e9cb8a9f758e0b1955d378568 | Joelciomatias/programming-logic-python | /3-if-elif.py | 913 | 3.875 | 4 | """
Escreva um programa que leia um nome e idade
e no final escrever no terminal,
se for igual ou maior que 18: é obrigatório o voto,
se for igual ou menor que 16: ainda não tem idade para votar,
se for igual ou maior que 16 e menor que 18: voto é facultativo.
Exemplo 1:
Entradas:
> José
> 20
Saída:
... |
fd679b56155868bd0dbfc3bc2bbb28d98d477d08 | gschen/where2go-python-test | /1906101009肖文星/ago/实验5.2.py | 234 | 3.75 | 4 | def isPrime(q):
if type(q)==int:
for i in range(2,q):
if q%i==0:
print("False")
break
else:
print("Ture")
else:
print("你输入的不是整数")
|
5c00e3e6e4c3385d79b8c82c53a23e02a6949758 | gozelalmazovna/Caesar-Cipher-Code-in-Python | /caesar-code.py | 1,646 | 3.796875 | 4 | def num_offset(num):
"""Checking offset number to be in range of A to Z code values
Preconditions:
num = int
Result:
boolean
"""
if 90 >= num >= 65: #Conditions for offset from A = 65 to Z = 90
return True
else:
return False
def turn_around(num):
""" To ... |
7ccc1dd6c4921265a1ef958836dec8a2ba52e260 | danicon/MD2-Curso_Python | /Aula13/ex14.py | 352 | 3.765625 | 4 | maior = 0
menor = 0
for p in range(1,6):
peso = float(input(f'Peso da {p+1}ª pessoa: '))
if p == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print(f'O maior peso lido foi de {maior}Kg')
print(f'O men... |
2ab1814bcc20c3bd07306af940aeab246b22fa26 | Ovilia/ProjectEuler | /014.py | 251 | 3.703125 | 4 | def collatz_step(n):
i = 1
while n != 1:
n = n / 2 if n % 2 == 0 else 3 * n + 1
i += 1
return i
steps = 1
n = 1
for i in range(1, 1000000):
c = collatz_step(i)
if c > steps:
steps = c
n = i
print n
|
6499201c407f5ab70911c2555df8bdebed725bce | richardbowden/pyhelpers | /tests/test_date_tools.py | 1,473 | 3.515625 | 4 | import unittest
from datetime import datetime
import pyhelpers.date_tools as date_tools
class LengthOfTimeCalc(unittest.TestCase):
def test_should_return_1_year_and_0_months(self):
start_date = datetime(2001,1,1)
end_date = datetime(2002,1,1)
years, months = date_tools.get_length_of_time... |
9ba2a0957d65a59b659cb5084cabbdb2da90cf4e | gengwg/Python | /extract_emails.py | 202 | 3.890625 | 4 | # find all email addresses between <>
st = "Anurag Gupa <AGupta10@example.com>; Fezal Miza <FMirza@example.com>; Donld Slvia Jr. <Donad.Sivia@xyz.com>; Lar Gln <lary.glnn@jht.com>"
import re
emails = re.findall("\<(.*?)\>", st)
for email in emails:
print email
|
5504541c2672295a644f211b0056710c34ee9b6a | joyonto51/Programming_Practice | /Python/Old/Python Basic/Problem/22-08-17/Problem-1.1.3.py | 408 | 3.921875 | 4 | inp=input("Please Enter an year:")
n=int(inp)
if n%4==0 and (n%400==0 or n%100!=0):
print(str(n)+" is a Leap year")
print("The next Leap year is:"+str(n+4))
else:
print(str(n)+" is not leap year")
a=n+(4-n%4)
b=a+(4-a%4)
if(a%4==0 and (a%400==0 or a%100!=0)):
print("The next Leap year is:"+s... |
bd71f0d44308bf49741559bb2ed1dcee4214a7b4 | zainul45/Rangkuman-Materi-PBO | /Rangkuman Materi/Tugas Praktikum/Tugas Praktikum/no_4.py | 570 | 3.6875 | 4 | class mahasiswa:
def __init__(self):
self.nama = input("Nama :")
self.npm = input("NPM :")
class matakuliah:
def __init__(self):
self.kode = input("Kode :")
self.namamatkul = input("Nama Mata Kuliah :")
class pengambilanmatkul(mahasiswa,matakuliah):
def __init__(self):
... |
06ba8b7f6637cd9e4d8121cebd673eb8cd823d99 | udaykumarbpatel/HackerRankKit | /FileRead.py | 495 | 3.96875 | 4 | import sys
def num_of_words_in_file(filename):
file_obj = open(filename, 'r')
count = 0
max_w = -sys.maxint
max_word = ""
for line in file_obj:
words = line.split()
for w in words:
if len(w) > 1 and w[0] == w[-1]:
if len(w) > max_w:
... |
11ba5e49e0f10e028060a65dcb41f1f21d2460b1 | aruimk/ud_pyintro | /lesson18.py | 554 | 3.78125 | 4 | i = [1, 2, 3, 4, 5]
j = i
j[0] = 100
print(i)
print(j)
# 上記の様にリストを = でコピーすると、C言語での参照渡しの様なイメージで実態が②つあるわけではなくなる。
# 同じものを二種類の名前で見ているだけ。
# 以下の様に実態を別として二つにしたい場合はcopy メソッドを使用したり、スライスで最初から最後までをコピーしたりする必要がある
x = [1, 2, 3, 4, 5]
y = x.copy()
# y = x[:]
y[0] = 100
print('X = ', x)
print('y = ', y)
|
c64afeb0fc3f49603966b25a711bfd099e1cba88 | vladlemos/lets-code-python | /Aula_5/01.py | 570 | 4.0625 | 4 | '''
crie um dicionario cujas chaves
sao os meses do ano e os valores sao a duracao em dias de cada mes
'''
dicionario = {
'janeiro':31,
'fevereiro':28,
'marco': 30,
'abril': 31,
'maio': 30,
'junho': 30,
'julho': 31,
'agosto': 31,
'setembro': 30,
'outubro': 30,
'novembro': ... |
ed60d64e3958bf86537d5c965a21e4b164f303af | NNishkala/PESU-IO-SUMMER | /coding_assignment_module1/w1q5.py | 107 | 4.0625 | 4 | a=input("Enter string")
if a.isnumeric():
print("String is numeric")
else:
print("String is not numeric") |
6aa461004bb2293047fa2c6459cba2c9e21bfb4f | KBerUX/OODPy | /customer.py | 406 | 3.75 | 4 | class Customer:
#__init__ is constructor/initializer
# self is like this.
def __init__(self, name, membership_type):
self.name = name
self.membership_type = membership_type
customers = [Customer("Caleb", "Gold"), Customer("Brad", "Bronze")]
# finish tomorrow 9:47 https://www.youtube.com/w... |
79ad57ed8bff6f2f7616dd32ef6fa75e1057108c | AnastasiiaDm/Python_Hillel_Nickisaev | /06-mydict.py | 582 | 3.5 | 4 | from pprint import pprint
team = dict(
Colorado='Rockies',
Boston='Red Sox',
Minnesota='Twins',
Milwaukee='Brewers',
Seattle='Mariners'
)
print(team)
print(team['Colorado'])
team['Colorado'] = 'Spartak'
print(team)
team['Kiev'] = 'Dinamo'
pprint(team)
P = {
1: 'one',
2: 'two',
3: 'thr... |
851634ba29c99a5086d6b254078d21203df41c21 | PeterChain/simpleorgs | /apps/members/utils.py | 537 | 3.625 | 4 |
class NumberRange(object):
"""
Number range operations
"""
FILL_LENGTH = 5
def __init__(self, number):
"""
Constructor which receives the original number
"""
self.old_number = number
def next(self, step):
"""
Increase the original number (s... |
0fa19d36567502e1d6ce2fc6e6af7cd3e839ea2f | prattaysanyal/Assign3 | /Assign10.py | 1,720 | 4 | 4 | #question1
class animal():
def attribute(self):
print("carnivore animal")
class tiger(animal):
pass
obj=tiger()
obj.attribute()
#question2
#print a.f(),b.()->A,B
#print a.g(),b.g()->A,B
#question3
class Cop():
def __init__(self,n,a,w,e,z):
self.name=n
self.age=a
self.work=... |
68613423fb66781998bd48b4b2d8f60964d4f67b | Mr-BYK/Python1 | /generators/generators.py | 532 | 4.09375 | 4 | def cube():
for i in range(5000):
yield i ** 10 #bellek üzerinde yer kaplamadan işlem yaptırırız.İkinci kez ulasılmaz bir kereye masustur
for i in cube():
print(i)
##mesela bellek üstüned nasıl yer kaplar
#def cube():
# result=[]
# for i in range(5):
# result.append(i**3)
# ... |
8b28b40a52bad250743a0ad54520f464bc511a89 | umairkhan1154/Machine-Learning | /polynomial_regression.py | 835 | 3.921875 | 4 | #import the libraries
import numpy as py
import matplotlib.pyplot as plt
import pandas as pd
#Import the data set from Desktop
dataset = pd.read_csv('M_Regression.csv')
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,3].values
#Training and Testing Data (divide the data into two part)
from sklearn.model_sele... |
aa39dcbab4800749fa260e8a2b057336cc644c6d | YXRSs/myrepo | /2017_final_mangled_code.py | 2,133 | 3.953125 | 4 | def build_marks_dict(input_file):
student_to_marks = {}
input_line = input_file.readline()
while(not input_line.startswith("---")):
course_to_grade = {}
input_line = input_line.strip()
(student, course, grade) = input_line.split(',')
if(student in student_to_marks):
... |
b775df43bf988a866f9633821770b289e39c5adb | AdmiralGallade/GUI-file-explorer-python | /test.py | 245 | 3.53125 | 4 | input_string="Name1: Han Age: 23 Guns: 2"
print(list(map(str,input_string.split())))
print('\n',list(map(str,input_string.split(':'))))
print('\n',list(map(str,input_string.strip())))
print('\n',list(map(str,input_string.strip().split()))) |
9a2dd61443207a5c8e033175318e177101760701 | mottaquikarim/pydev-psets | /pset_pandas_ext/101problems/p73.py | 288 | 3.640625 | 4 | """
74. How to get the frequency of unique values in the entire dataframe?
"""
"""
Difficulty Level: L2
"""
"""
Get the frequency of unique values in the entire dataframe df.
"""
"""
Input
"""
"""
df = pd.DataFrame(np.random.randint(1, 10, 20).reshape(-1, 4), columns = list('abcd'))
"""
|
4070e1709cd1f689878bd718e7af3d586a77704c | git-mih/Learning | /python/04_OOP/polymorphism/08__format__.py | 1,678 | 4.65625 | 5 | # __format__ method
# is just yet another representation... We know we can use the format() function
# to precisely format certain types like: floats, dates, etc.
format(0.1, '.2f') # 0.10
format(0.1, '.25f') # 0.1000000000000000055511151
from datetime import datetime
datetime.utcnow() ... |
8e701e1d02be276def933cd411e3f9aa0655dedc | marloncalvo/BuggyJavaJML | /Macros/time.py | 6,461 | 3.796875 | 4 | from datetime import date, datetime, timedelta
from util import test_case
def get_time_string(time: datetime, var="time"):
return f"Time {var} = new Time({time.hour}, {time.minute}, {time.second});"
def get_time():
print("getting time...")
second, minute, hour = input("second: "), input("minute: "), inpu... |
57c93992da7f50a1c2e7c9e02eac1204df8d32ce | kira-Developer/python | /107_OOP_Part_5_Class_Attributes.py | 1,437 | 4.0625 | 4 | # -----------------------------------------------------
# -- Object Oriented Programming => Class Attributes --
# -----------------------------------------------------
# Class Attributes: Attributes Defined Outside The Constructor
# -----------------------------------------------------------
class member :
not_all... |
65207cd2c9982587bf76a269221b1f1cc7ece594 | aleuli/PythonPY100 | /Занятие3/Лабораторные_задания/task2_1/main.py | 249 | 3.625 | 4 | def task(str1, str2, k):
if str1[:k + 1] == str2[:k + 1]:
print("Да")
else:
print("Нет")# TODO проверка совпадения строк
return
if __name__ == "__main__":
print(task("Hello", "Herry", 0))
|
8f70dfb3d59b18a4b41c1b67e7cfb4635a06dd3b | Darkxiete/leetcode_python | /107.py | 1,650 | 3.59375 | 4 | from DataStructure.BinaryTree import BinaryTree as TreeNode, create_btree
from typing import List
class Solution:
def levelOrderBottom1(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = [root]
level, ans = [], []
while queue:
level = q... |
7e04eba92c71430cc1b104df4a302130eaf09f37 | WeiNyn/TrieTree | /build_corpus.py | 989 | 3.828125 | 4 | import pandas as pd
df = pd.read_csv("new_merged_csv.csv")
def check_input(words: str) -> str:
texts = words.replace("\r", " ") \
.replace("\n", " ") \
.replace("- ", "-") \
.replace(" -", "-") \
.split(",")
new_texts = []
for text in texts:
if not text.strip().is... |
19433aa6384dd496f808121f8a36c2dd7cd764b6 | blitzwolfz/nextgencoder_cc-35 | /PyChallenge.py | 595 | 3.921875 | 4 | #Made by Samin Q
def Add_Per(number):
first_step = 0
for x in range(len(number)):
first_step += int(number[x])
second_step = int(str(first_step)[0]) + int(str(first_step)[1])
return second_step
def Multi_Per(number):
first_step = 1
for x in range(len(number)):
fir... |
9847109288eb59761847c7597dd81541a87df572 | RaulMyron/URIcodes-in-py-1 | /URI/1073.py | 100 | 3.78125 | 4 | X = int(input())
Z = 0
for i in range(1, X+1):
if i%2 == 0:
print("%d^2 = %d" %(i, pow(i,2))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.