blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d5b50dc98afa6fe56cca90e3a98900be87d558d7 | Aasthaengg/IBMdataset | /Python_codes/p02257/s294042094.py | 490 | 3.9375 | 4 | """素数を求める。
以下の性質を用いる。
合成数 x は p <= sqrt(x) を満たす素因子 pをもつ。
"""
import math
def is_prime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, math.floor(math.sqrt(x)) + 1):
if x % i == 0:
return False
return True
N = int(input())
data =... |
d5ce5fd1c4b75f9d922bde437526e4a02b1ee51b | extra-virgin-olive-eul/pe_solutions | /3/PE-P3_VSX.py | 3,290 | 3.734375 | 4 | #!/usr/bin/env python3
'''
Program: PE-P3_VSX.py
Author: vsx-gh (https://github.com/vsx-gh)
Created: 20171002
Project Euler Problem 2:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
This program approaches the problem from the pe... |
22114982f91f6a8b58e53432b5dec6cf6b45cda3 | gauravyantriks/PythonPractice | /Exercise3.py | 1,131 | 4.5 | 4 | '''
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the
elements of the list that are less than 5.
'''
list_1=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print('first loop approach')
for no in list_1:
if no < 5:
print(no)
#extras
'''... |
174b45a35d01c35adaf2436f9cf14aaa90e6ea63 | uosoul/soul | /力扣题目/206链表逆序.py | 561 | 4.0625 | 4 | def reverselist(head):
cur =head
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
def reverse_list(head):
cur = head
pre = None
while cur:
t... |
537a0bce959fec499626bd41f76e6f7578a4da0c | Dilshodbek23/Python-lessons | /34_2.py | 237 | 3.53125 | 4 | import json
student_json = """{"name":"Hasan","surname":"Husanov","ybirth":2000}"""
student = json.loads(student_json)
print(student['name'], student['surname'])
with open('student.json', 'w') as f:
json.dump(student, f) |
452997b701f784cbe1dfbf51d6358ee4456831e3 | srbrettle/Sandbox-Algorithms | /HackerRank/Tutorials/10 Days of Statistics/Day 0 Mean, Median, and Mode.py | 358 | 3.703125 | 4 | size = int(input())
numbers = list(map(int, input().split(" ")))
numbers.sort()
# mean
mean = sum(numbers)/size
print(mean)
# median
if size%2==1:
# odd size
median = numbers[int(size/2-0.5)]
else:
# even size
median = (numbers[int(size/2-1)]+numbers[int(size/2)])/2
print(median)
# mode
mode = max(nu... |
d75fd4ec35ba613b8698aaf04ffb0a28fb97535d | pedrillogdl/ejemplos_python | /contrasena.py | 241 | 3.859375 | 4 | contrasena=input("Por favor, introduce tu contrasena: ")
valida=True
for i in contrasena:
if i==" ":
valida=False
if len(contrasena)>8 and valida==True:
print("La contrasena es Correcta")
else:
print("La contrasena es Incorrecta")
|
90f7851f88a34a9b0389274d743ea5035aded2b8 | spmvg/evt | /src/evt/methods/peaks_over_threshold.py | 3,478 | 3.828125 | 4 | from numbers import Real
import matplotlib.pyplot as plt
from evt import utils
from evt.dataset import Dataset
from scipy.stats import expon
class PeaksOverThreshold:
"""
The peaks over threshold method is one of the two fundamental approaches in extreme value theory.
The peaks of the ``Dataset`` ``datas... |
c20d449afb6a9517578af89bddb25e12e1b3ff15 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 5.14 - Méthodes Séquences.py | 1,393 | 3.921875 | 4 | """ Auteur = Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Nous pouvons définir la distance entre deux mots de même longueur (c’est-à-dire
ayant le même nombre de lettres) mot_1 et mot_2 comme le nombre minimum de fois où
il faut modifier une let... |
a497a1afb0059dee82a0195a8d372b5fe979e503 | ReshmaRajanChinchu/python-programming | /A16.py | 128 | 3.96875 | 4 | n=int("Enter the number:")
s=int("Enter the number:")
for i in range(n+1,s):
if(n%i == 0):
print(i)
else:
print('invalid')
|
9c3e59e0fd3477f3dd66059f67f0ec6eeeaa5d9f | weiyinfu/learnNumpy | /ndenumerate.py | 142 | 3.515625 | 4 | import numpy as np
a = np.random.random((2, 2, 3))
for index, value in np.ndenumerate(a):
print(index, value, type(index), type(value))
|
b747303e9d95e5ab0c86b0b0c78f48f69f3535dd | hi1rayama/PythonAlgorithm | /Sort/RadixSort.py | 3,901 | 3.859375 | 4 | '''
基数ソート(k=3桁の場合)
1. 10 個の容器(バケツ)を用意(a[0]~a[9])
2. k(3) 番目から 1 番目まで以下を繰り返し(最下位桁(1 の位)から最上位桁(3)まで)
3. 当該要素をキーとして,用意した容器でバケットソート
0~Aの整数値が対象の時
平均計算量:O(nlogA)
最悪計算量:O(nlogA)
内部ソート:×
安定ソート:○
'''
def radixSort(N, INPUT_VALUE):
print("ソート前:", INPUT_VALUE)
bucket = [[] for i in range(10)]
bucket2 = [[] for i in ... |
c50e6313e8f83b81e31462b230f38ca3865768b5 | pychthonic/python-3 | /password_hash.py | 6,854 | 4.28125 | 4 | from hashlib import sha256
from getpass import getpass
import re
class LoginSession:
"""This program demonstrates password hashing, that is, how
computers authenticate users. Instead of keeping databases full of
plaintext passwords, or even encrypted passwords, they often store
hashes of the passwords... |
d16500e000f0208292921659b90472036e9aa0de | sudheemujum/Python-3 | /Print_All_Prime_numbers.py | 319 | 4.09375 | 4 | n=int(input('Please enter the number:'))
if n<=1:
print('entered number is not prime')
else:
n1=2
while n1<=n:
is_prime=True
for i in range(2,n1):
if n1%i==0:
is_prime==False
break
if is_prime==True:
print(n1)
n1+=1
|
42cd57ec608346cf420351e7b1b2339458947f8b | aldob02/York-Summer-Camp-Python | /Python II/oop_isometry.py | 1,639 | 4.125 | 4 | import turtle
import math
turtle.speed(0)
# create and draw Box objects with:
# >>> box1 = Box(0, 0, 0)
# >>> box2 = Box(0, 0, 1)
# >>> box3 = Box(1, 1, 0)
# >>> box1.draw()
# >>> box2.draw()
# >>> box3.draw()
class Box:
def __init__(self, x, y, z):
self.x = x
self.y = y
self... |
88f9c9f08979e1aa3ee2c9969885c93998eb4bba | chriszhangm/Scrap_python | /MyFirstScrapy-.py | 6,192 | 3.546875 | 4 |
# coding: utf-8
# # Make more money by buying lottery?
# ## --- (Python Crawler+Data Analysis)
# ## Introduction
#
# **In this report, I will extract 100 pages of '3d' lottery data from http://www.zhcw.com to see if there is any strategy to make more money by buying the lottery. '3d' lottery is one of the favorite... |
00789e1ed7647672b7557232be77e7db1b9ad5e7 | holim0/Algo_Study | /python/네트워크.py | 544 | 3.546875 | 4 | from collections import deque
def solution(n, computers):
answer = 0
size = len(computers)
check = [False for _ in range(size)]
q = deque([])
for i in range(size):
if not check[i]:
check[i] = True
answer += 1
q.append(i)
while q:
... |
2f3554616019c8e21f1f8ae2bc08758ee44c5cd8 | fernandorssa/CeV_Python_Exercises | /Desafio 25.py | 481 | 3.890625 | 4 | print('Método 3')
nome = str(input('Digite o seu nome completo: ')).lower().strip()
x = str('silva' in nome)
print('Seu nome tem "Silva"?')
print(x)
'''
MÉTODO 1
n = str(input('Digite o seu nome completo: '))
a = int(n.count('Silva'))
print('Vejamos...')
if a >= 1:
print('Seu nome tem Silva')
else:
print('S... |
786f2d3b7bf35f6a0e2d697ec705102532338cbd | idahopotato1/learn-python | /01-Basics/007-Files/Files.py | 753 | 4.3125 | 4 | # Files
# When you're working with Python, you don't need to
# import a library in order to read and write files. ...
# When you use the open function, it returns something called a
# file object. File objects contain methods and attributes that can
# be used to collect information about the file you opened.
file = ... |
7946fd0c2e6364a4600f5fad2e5c22bd017b4156 | PPinto22/LeetCode | /codejam/2022 Qualification Round/a.py | 532 | 3.515625 | 4 | def print_punch_card(rows, columns):
print('..+' + '-+' * (columns - 1))
print('..|' + '.|' * (columns - 1))
print('+-+' + '-+' * (columns - 1))
for _ in range(rows - 1):
print('|.|' + '.|' * (columns - 1))
print('+-+' + '-+' * (columns - 1))
def main():
n_test_cases = int(input()... |
758fdbdd558d0052fd00f71691e728e62fae0abb | vincentliao/euler_project | /largest_palindrome_product.py | 515 | 3.9375 | 4 | #! /usr/bin/env python
# description : Euler project, problem 4: Largest palindrome product
# author : vincentliao
# date : 20140503
from itertools import product
# palindromic number is like 121, 9009, etc....
def is_palindromic(number):
number_str = str(number)
return True if number_str == number_st... |
986294475b2aa78b1864329448c784edaf6d601b | suraphel/RSA-file-encryptor- | /padding&grouping.py | 947 | 3.875 | 4 | # This is the padding and the division part of the code
# taking the user input
def padding ( read, calculate, padd):
read.read()
return len(read)
def odd(x):
if x % 2 == 0:
return("odd")
else:
return ("even")
p_text = input ("what would like to send\n")
p_to_file ... |
6c3191d475a852514339007fa7db66833bb82fce | MohammadRezaHassani/HomeWorks | /HW1/8.py | 143 | 3.953125 | 4 | number = int(input())
for i in range(1,number*2):
if i <=number:
print("*" * i)
else:
print("*" * (number*2 -i))
|
5e67254d5b691ff51a3cc8eb6e01d5ba823b1094 | kwoodson/euler | /python/euler20.py | 237 | 4.0625 | 4 | #!/usr/bin/env python
'''
n! means n x (n - 1) x ... x 3 x 2 x 1
Find the sum of the digits in the number 100!
'''
def fact(x):
return (1 if x==0 else x * fact(x-1))
astring = str(fact(100))
print sum([int(x) for x in astring])
|
2849c314dbcd2b006c995e9fbdefd8eab7d00517 | kaliskamila/zadanie-domowe-ci-g-fibo | /03_python/zadanie1.py | 241 | 3.78125 | 4 | for i in range (1,101):
pass
if i % 15 == 0:
print(i, "FizzBuzz")
if i % 3 == 0:
print(i, "Fizz")
if i % 5 == 0:
print(i, "Buzz")
else:
print(i)
for i in range (1,101):
pass
if i % 15 == 0 and i %5 != 0:
|
1dcc63e47abbd9feaf8502493bbe1324f67579fa | nikitauday/EXERCISM_WORKSPACE | /python/robot-name/robot-name.py | 472 | 4.1875 | 4 | import string
import random
unique=set()
X=input("Generate name? Y/N ")
while True :
if(X=='Y'or X=='y'):
while True:
A=(''.join(random.choice(string.ascii_uppercase) for _ in range(2)))+(''.join(random.choice(string.digits) for _ in range(3)))
if A not in unique:
unique.add(A)
break
print(A)
X=inp... |
edd994acb8281c11f430d85244a8d773315f7ca4 | Ekultek/codecademy | /Introduction To Classes/02 Classes/4.py | 497 | 4.375 | 4 | """
Description:
Calling class member variables
Each class object we create has its own set of member variables. Since we've created an object my_car that is an
instance of the Car class, my_car should already have a member variable named condition. This attribute gets assigned
a value as soon as my_car is created.
... |
089b9fe56c2706b3ea52bf782b27d976e763ffb5 | buptxiaomiao/python | /study_program/guess_num.py | 296 | 3.984375 | 4 | #!/usr/bin/env python2.7
true_num = 88
guess_num = int(raw_input("\nInput the number:"))
if guess_num > true_num:
print "Sorry,It's lower than that... \n"
elif guess_num < true_num:
print "Sorry,It's higher than that...\n"
else:
print "Amazing, You guessed it.\n"
print "Game will exit:)"
|
8109140783f2fed266b5dcccf8b56f3df7fbdbe5 | vijayjag-repo/LeetCode | /Python/LC_Binary_Tree_Level_Order_Traversal.py | 2,574 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Two solutions to this problem
# Solution 1:
# if the length of the list is equal to the level, then create a new [] and append this value... |
16b1cac1abfe5919ba290dca0fc87e5ff931d408 | zabojnikp/study | /Python_Projects/hackathon_Brno/warm-up/6_souhlasky_samohlasky.py | 388 | 3.78125 | 4 | user_input = 'a speech sound that is produced by comparatively open configuration of the vocal tract'
raw_text = user_input.replace(" ", '')
vowels = []
consonants = []
sentence = {}
for i in raw_text:
if i.lower() in "aeiouy":
vowels.append(i)
else:
consonants.append(i)
sentence["vowels"] = ... |
4e9c215ebbb4bfd02859d3e888e307d980b444dc | NMOT/PycharmProjects1 | /python_desafios/ex_14_62.py | 402 | 3.96875 | 4 |
# Permita que o usuário escolha quantos termos da progressão quer mostrar
#saia do programa quando o usuário disser que quer calcular mais 0 termos
i = 1
n = int(input('Introduza o 1º termo da progressão aritmética.'))
r = int(input('Introduza a razão da progressão '))
f = int(input('Quantos termos da progressã... |
e9ffc4b98b05ce7ef499e9c42ec22bc892576f4b | KataBedn/AutomatedTestingExercise | /utilities/dataGenerator.py | 404 | 3.625 | 4 | import random, string
class DataGenerator:
@staticmethod
def generate_random_number_with_n_digits(n) -> int:
lower = 10 ** (n - 1)
upper = 10 ** n - 1
return random.randint(lower, upper)
@staticmethod
def generate_random_string(length=10, chars=string.ascii_uppercase + string... |
c70140b109ebcebb11e256a0d57196d5ae015258 | luiscristerna/PruebaTravis | /Calculadora.py | 1,693 | 3.53125 | 4 | # Luis Manuel Cristerna Gallegos 05/09/2017
# Implementando CI con travis
#pruebas
import math
class Calculadora():
def __init__(self):
self.resultado = 0
def obtener_resultado(self):
return self.resultado
def suma(self, num1, num2):
try:
self.resulta... |
3374d6414eec6480a8803b54ea0b35dd7c2c2b85 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 6/Exercicios 6a/Algoritmo479_fun21.py | 377 | 4 | 4 | # Program: Algoritmo479_fun21.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 09/06/2020 - 16:48
# Updated:
from arranjo import *
number1 = int(input("Entre com o primeiro número: "))
number2 = int(input("Entre com o segundo número: "))
number3 = int(input("Entre com o terceiro número: "))
print(formula2... |
7c0e1edabfe7f36f17df0a35b16edbd87c5e7024 | Seungjin22/TIL | /00_StartCamp/02_Day/00_string_format.py | 805 | 3.671875 | 4 | #1. pyformat
# name = '홍길동'
# english_name = 'hong'
# print('안녕하세요, {}입니다. My name is {}'.format(name, english_name))
# print('안녕하세요, {1}입니다. My name is {0}'.format(name, english_name))
# print('안녕하세요, {1}입니다. My name is {1}'.format(name, english_name))
#2. f-strings
# name = '홍길동'
# print(f'안녕하세요, {name}입니다.')
# p... |
df512b58cf9ab2da0e597aebafe4ab4e616a5487 | pony-ai/PythonDaily | /1.4/list_1.py | 663 | 4.1875 | 4 | #遍历列表
# magicians = ['liu','xue','xiao']
# for magician in magicians:
# # print(magician)
# print(f"{magician.title()},that was a great trick.")
#创建数值列表
# numbers = list(range(1,6))
# print(numbers)
#打印1-10的平方数
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
# 简单运算
#... |
95273e87935d258d72b52bf7ade08a69fd719779 | dreamer-1996/learning-python-total-novice | /hello.py | 251 | 3.9375 | 4 | # My first python program
print ("Welcome to the world of programming")
print ("Please enter your name")
myName = input()
print ('Hello ' + myName)
print ("What is your age?")
myAge = input()
print ("You will be " + str(int(myAge)+1) + " next year")
|
4c666cbb5e26d9faf04e78427dd64e2fa60dfcc3 | nolan-gutierrez/ReinforcementLearning | /MAB/GridVisual.py | 1,574 | 3.640625 | 4 | class GridVisual:
def __init__(self,
gridWorld,
):
self.gridWorld = gridWorld
def getAgentVisual(self):
_,_,o = self.gridWorld.getAgentPose()
if o == 'up': return 'u'
elif o == 'down':return 'd'
elif o == 'left': return 'l'
elif o == 'righ... |
ac1c2b9fb9e8aab19a8a2c1b300799da420df6c3 | Kamilet/learning-coding | /simple-program/check-io-solutions/digits-multiplication.py | 986 | 4.03125 | 4 | '''
You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).
'''
from functools import reduce # for method 2
def checkio(number):
#method 1
... |
454622761e238faca0e199f728d3642192ca36dc | ShaneRich5/fti-programming-training | /solutions/labs/lab8.1/dealership/vehicle.py | 288 | 4 | 4 |
class Vehicle(object):
""" A vehicle for passenger transport """
wheels = 4
def __init__(self, year, make, model):
self.year = year
self.make = make
self.model = model
print("Vehicle: " + str(self.year) + " " + self.make + " " + self.model) |
e6c07258a419f1aec9ef74a063e47aa248d8568a | vanessalb08/learnignPython | /desafio063.py | 216 | 3.9375 | 4 | num = int(input('Quantos elementos quer ver? '))
termo = 0
soma = 1
cont = 1
fib = 0
while cont <= num:
fib = termo + soma
print(termo, end='➔ ')
soma = termo
termo = fib
cont += 1
print('Fim')
|
d8355b4a792a7dfa1638d6d327d560ad955580ca | mrmyothet/ipnd | /ProgrammingBasicWithPython-KCL/Chapter-6/Delete_Dictionary.py | 153 | 3.78125 | 4 | dict = {"Name":"Aung Ko","Age":7}
dict["Age"] = 9
del dict["Name"]
print("NAME:" + dict["Name"]) # you will get error...
print("Age:" + str(dict["Age"]))
|
b01bd3133de9b45e7a619f2ece581e08c01040e9 | fridriks98/Forritunarverkefni | /Python_projects1/Mímir verkefni/mimir_verkefni/strings and/verkefni4.py | 110 | 3.5 | 4 | s = input("Input a float: ")
s_float = float(s)
s_justified = "{:>12.2f}".format(s_float)
print(s_justified) |
db67bd319aee9e36817270c39de8457291a06585 | romanus77/python-course | /03_examples/00_file_read.py | 1,014 | 3.90625 | 4 | # -*- encoding: utf-8 -*-
# Открыть файл на чтение:
f = open("input_file.txt", "rt") #можно также открывать в бинарном режиме: "rb"
# Прочитать первые 10 символов из файла, `first10' --- строка:
first10 = f.read(10)
print "First 10 chars: '{0}'".format(first10)
# all_file = f.read() --- прочитает файл до конца в стр... |
112f3f9d411caed6afea25fe75680fdad584fc59 | cmj123/MultiThreading_in_Python | /multithreading22.py | 1,145 | 3.75 | 4 | """
Name: Esuabom Dijemeni
Date: 22/03/2020
Purpose: Create a program where two consumer threads wait on the producer thread to notify them
"""
# Import key libraries
import threading
import logging
# Logging message for status tracking
logging.basicConfig( level=logging.DEBUG,
format='(%(threadN... |
317df6c3cc587636f61450d331d343ca61278163 | pbednarski/programowanie-obiektowe-1 | /lab2_06.py | 361 | 4.15625 | 4 | def fiboncciGenerator(n):
numberslist = list(range(0, n))
for (i, number) in enumerate(numberslist):
if number > 1:
number = numberslist[i - 1] + numberslist[i - 2]
numberslist[i] = number
yield number
print('Set Fibonacci length:')
obj = fiboncciGenerator(int... |
1a225d15a873c9038e9a037d8165877ac9e069a8 | nestoregon/learn | /advent_code/2020/day9.py | 2,329 | 3.609375 | 4 | import os
import sys
from collections import namedtuple
def part_1():
raw_input = []
with open('input9.txt') as fp:
for line in fp:
line.strip()
number = int(line)
raw_input.append(number)
for i in range(len(raw_input) - 25):
pack_25 = raw_input[i:i+25]
... |
501f20e642042df9c2183603fc46b4f43170227e | dtobin02/assignments | /readwrite-csv.py | 406 | 3.578125 | 4 | import csv
# write csv
with open('testwrite.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['col1', 'col2'])
writer.writerow(['val1', 'val2'])
writer.writerow(['val1', 'val2'])
writer.writerow(['val1', 'val2'])
# read csv
from pprint import pprint
with open('testwrite.csv', 'r') as f:
... |
e43eae51777627410307326bdb8bd4518c21ee77 | vinay279/pythonLearningclasses | /AutomationPython/SortingAutomation.py | 4,287 | 3.78125 | 4 | '''Class for the Sorting Automation'''
import random
from SortingTypes import Bubble, Quick, Selection, Insertion, Radix, Merge
class SortingAutomation:
def __init__(self):
self.elements = []
# Inserting Elements in List
def inserting(self):
for value in range(10):
self.element... |
e552e5b34ef13214380152ee00db7edbbde6013a | MoritzWillig/GenieInAGanzzahlAddierer | /src/datatypes/CreationInfo.py | 881 | 3.546875 | 4 | from enum import Enum
class CreationInfo(Enum):
EXISTING = 0
RESERVE = 1
CREATE = 2
@staticmethod
def from_string(value_str):
value_str = value_str.lower()
if value_str == "existing":
return CreationInfo.EXISTING
elif value_str == "reserve":
return... |
494dda9707c3e2b07c59db1b85e8c6a7757c754d | pvanh80/intro-to-programming | /round01/Smileys.py | 545 | 4.09375 | 4 | smiley = int(input('How do you feel? (1-10) '))
if smiley >= 1 and smiley <= 10:
if smiley == 10: print ("A suitable smiley would be :-D")
else:
if smiley >=8 and smiley<=9 : print("A suitable smiley would be :-)")
else:
if smiley >=3 and smiley <=7: print("A suitable smiley would be... |
d85680620a26c9e54b71f13342654cba4f40e597 | bpbpublications/Advance-Core-Python-Programming | /Chapter 08/Examples_Code/Example1_6.py | 950 | 4.4375 | 4 | #Example 14.6
#Write a program for two buttons one on the left and the other on the right. Try it out and match your results with the output given in the book.
#import Statements
from tkinter import*
import tkinter.messagebox
# Create a function for right button
def message_display_right():
tkinter.mes... |
90628d2a5a1e90bf99cf779d5c5a542f523c402b | hongyesuifeng/python-algorithm | /python-offer/question4.py | 708 | 4.03125 | 4 | def find_in_matrix(matrix,number):
"""二维数组中的查找"""
if matrix:
rows = len(matrix)
columns = len(matrix[0])
row = 0
while(matrix and row<rows and columns>0):
if matrix[row][columns-1] == number:
return number
elif matrix[row][columns-1] > ... |
f30b5662175b3aaec872237a7fbd9cf92ab80b8b | HarryChen1995/data_structure_algorithm | /3Sum.py | 896 | 3.640625 | 4 | def threeSum(nums):
nums.sort()
arr = []
for i in range(0, len(nums)-2):
if (i == 0 or (i> 0 and nums[i] != nums[i-1])):
low = i+1
high = len(nums)-1
sum = 0 - nums[i]
while low < high:
if nums[low]+... |
1aaea78327f56b2bb7707f19a42fa77159ff0090 | RoiSadon/python | /06_Class & instance & constructors/09_oop subclass.py | 394 | 3.890625 | 4 |
class schoolMember:
def __init__(self,name):
self.name=name
def tell(self):
print('hi school member:', self.name,end=" ")
# If subclass does not contain a constructor
# The subclass will have a default call to the base constructor
class Teacher(schoolMember):
def tell(self):
school... |
60d8467b566ad3c2c760242125d7383a0e8eb156 | bermmie1000/lselectric_dtc | /Lotto generator/ball.py | 651 | 3.734375 | 4 | # 로또 번호 제조기 입니다 ㅎㅎ
# 자, 부자가 되어 봅시다.
import random
class ball:
def __init__(self):
number = random.randint(1, 45)
self.number = number
if __name__ == "__main__":
games = 5
for game in enumerate(range(games)):
container = []
first_ball = ball().numb... |
6e98a09967265031b4b8355868a5883613592236 | Chaitanya-NK/ML-MINOT-JUNE | /ML-MINOR-JUNE.py | 8,430 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Problem Statement:
#
# gender : Gender of the student.....
# race/ethnicity : Race of the Student As Group A/B/C......
# parental level of education : What is the education Qualification of Students Parent.......
# lunch ... |
24f4ccb92d21b103b3b90447eae91e0494e73d13 | Hiteshsaai/AlgoExpert-CodingProblems-PythonSolution | /Easy/nonConstructibleChange.py | 551 | 3.59375 | 4 | class Solution:
def nonConstructibleChange(self, coins):
## Time O(n) || Space O(1)
if not coins:
return 1
coins.sort()
currChange = 0
for coin in coins:
if coin > currChange + 1:
return currChange + 1
else:
... |
ea1b4f7c1b0f014f78e5177b65e631fa43b2cbe5 | arodan10/Ejercicios10 | /2ejercicio.py | 167 | 3.78125 | 4 | def tabla():
#Datos de entrada
numero=int(input("Digite un número entero:"))
#Proceso
for X in range(1, 11):
print(f"{X} * {numero} = {X*numero}")
tabla() |
ba3d1bb1c2b1822c9bfbef545b0879b2ef07b663 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2748/40186/320689.py | 222 | 3.6875 | 4 | s = input()
if(s=="(a)())()"):
print("['(a)()()', '(a())()']")
elif(s=="()())()"):
print("['()()()', '(())()']")
elif(s==")("):
print("['']")
elif(s=="[\"23:39\",\"00:00\"]"):
print("21")
else:
print(s) |
94ba4e077c30ad23f28ee70041d0ce0c6aa1d7b4 | xXG4briel/CursoPythonGuanabara | /8 - Módulos/Desafio 019.py | 245 | 3.578125 | 4 | import random
a=random.randint(1,4)
if a==1:
print('Vem apagar a lousa noia')
if a==2:
print('Vem apagar a lousa Larissa')
if a==3:
print('cala a boca marcelo\nvem apagar a lousa')
if a==4:
print('Apaga a lousa porfavor Alice')
|
14cf9f06a52d8d7dd310339607cb727a70f43020 | ErdunE/LanguageLearning-MyImprovement | /Python/01_Python基础/hm_07_超市买苹果增强版.py | 469 | 4.15625 | 4 | # 1. 输入苹果的单价
price_str = input("苹果的单价: ")
# 2. 输入苹果的重量
weight_str = input("苹果的重量: ")
# 3. 计算支付的总金额
# 注意:两个字符串变量之间是不能直接用乘法的
# money = price_str * weight_str
# 4. 将价格和重量转换成小数
price = float(price_str)
weight = float(weight_str)
# 5. 用转换后的小数计算总价格
money = price * weight
print("苹果的总价为: ")
print(money)
|
f872c3a93a3163f92d80970b79819e4dd6d79718 | FlintHill/SUAS-Competition | /UpdatedSyntheticDataset/SyntheticDataset2/ElementsCreator/quarter_circle.py | 1,290 | 3.5 | 4 | from PIL import ImageDraw, Image
from SyntheticDataset2.ElementsCreator import Shape
class QuarterCircle(Shape):
def __init__(self, radius, color, rotation):
"""
Initialize a Quarter Circle shape
:param radius: radius in pixels
:type radius: int
:param color: color of sha... |
a67d995efafec9cc253f5d736efb14dea4421879 | daniel-reich/ubiquitous-fiesta | /BxKT4agPnm9ZNpDru_20.py | 121 | 3.8125 | 4 |
def zip_it(women, men):
if len(women) != len(men):
return "sizes don't match"
return list(zip(women,men))
|
7ce9c58970b6194cfda63cf4d616f95fe34961de | tiennynyle/similarities | /helpers.py | 917 | 3.734375 | 4 | from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
#take in string inputs a, b, split each string into lines, compute a list of all lines that appear in both a and b
lines_a = set(a.split('\n'))
lines_b = set(b.split('\n'))
#return the list
return lines_... |
b8ebc514508647984c0d9cd19279fa27185e7f48 | Incertam7/Infosys-InfyTQ | /Programming-Fundamentals-using-Python/Day-5/Exercises/Exercise-26.py | 667 | 4.03125 | 4 | #PF-Exer-26
def factorial(number):
fact = 1
while number > 0:
fact *= number
number -= 1
return fact
def find_strong_numbers(num_list):
strong_list = []
for num in num_list:
sum = 0
if num == 0:
sum = 1
temp = num
... |
88b19864056385105bb6cd7cca9db24f0d8a6882 | eternaltc/test | /Test/Basis/mypy14_for_else.py | 434 | 3.828125 | 4 | #测试循环中的else语句
staffNum = 4
salaryNum = 0
salarys = []
for i in range(staffNum):
s = input("请输入员工的薪资(Q或q退出):")
if s=="Q" or s=="q":
break
if float(s)<0:
continue
salarys.append(float(s))
salaryNum += float(s)
else:
print("已录入4个员工的薪资")
print("录入薪资{0}".format(salarys))
print("... |
48d1a1648f632c34b7c4483657e9607d79729342 | matheusmcz/Pythonaqui | /Mundo2/ex056.py | 833 | 3.5 | 4 | media = 0
homemmaisvelho = 0
nomehomem = 0
mulhermaisnova = 0
quantidademulheres = 0
for c in range(1, 5):
print('--' * 5, '{}ª PESSOA'.format(c), '--' * 5)
pessoa = str(input('Nome: ')).strip().upper()
idade = int(input('Idade: '))
sexo = (input('Sexo [M/F]: ')).strip().upper()
media = media + idad... |
553c367ab7baa6b6a45d5ec3710366f025aad9f3 | terra888/Python_final | /Semana 1/problemas_diversos.py | 699 | 3.734375 | 4 | #Problemas diversos
#Problema 1
ci = float(input("Ingrese la cantidad inicial: "))
for i in range(1,4,1):
ci = ci*104/100
print(f"El monto para el año {i} será: {round(ci,2)}")
#Problema 2
import math
a = float(input("Ingrese el valor de a: "))
b = float(input("Ingrese el valor de b: "))
c = flo... |
b1399cb56fa2760046055af58895659962038856 | ngocphucdo/ngocphucdo-fundamentals-c4e15 | /session_5/homework/ex5.py | 225 | 3.53125 | 4 | pairs = []
for i in range(5):
if i == 0:
pairs.append(1)
elif i == 1:
pairs.append(2)
else:
pairs.append(p[i-1] + p[i-2])
print("Month {0}: {1} pair(s) of rabbits".format(i,pairs[i]))
|
fd36c8d95364c1f74b00526e61654788425c65d6 | sdozier/code_portfolio | /euler_probs.py | 4,477 | 3.609375 | 4 | #Simone Dozier
#Project Euler problems
from helperMethods import *
import math
#==============#
#Problem 52: Permuted multiples
#==============#
def isPermutation(n,x):
#takes 2 lists, assumes n is already sorted
x.sort()
return n==x
def fitsReq(x):
"""Checks if number fits the requirements of proble... |
1fd842c4b95541096fd160cf26fb6ffac41b527c | WeiyiGeek/Study-Promgram | /Python3/Day3/demo3.0.py | 1,483 | 3.53125 | 4 | #!/usr/bin/python3
#功能:easyGUI简单得功能(更多请看配置文件)
import easygui as g
import sys
import os
# g.msgbox("hello,world")
# g.msgbox("I love study Python")
# while 1:
# msg = "谁是最好得编程语言?"
# title = "语言选择"
# choices = ['PHP','Python','Javascript','node.js']
# choices = g.choicebox(msg,title,choices) #都是字符串,选择Ca... |
493b1ae51fabbf39b5f7c9aea123643aa50b1d95 | ongbe/hedgeit | /hedgeit/feeds/indicator.py | 840 | 3.640625 | 4 | '''
hedgeit.feeds.indicator
An indicator that can be used in a strategy
'''
from abc import ABCMeta, abstractmethod
class Indicator(object):
'''
Indicator is an abstract base class that defines the interface for
the signals that can be used to form trading strategies
'''
def __init__(self, name):... |
149469f468f5b3ff948ffc7b63608938795c8290 | Faizah-Binte-Naquib/Program-List | /Loop/11.py | 1,106 | 4.03125 | 4 | # <b>10. Write a program to calculate how many 5 digit numbers can be created if the following terms apply :
# (i) the leftmost digit is even
# (ii) the second digit is odd
# (iii) the third digit is a non even prime
# (iv) the fourth and fifth are two random digits not used before in the number.</b>
#
# * Summa... |
30e986b92cfffa5009e40c77dce7f02738c52664 | czhnju161220026/LearnPython | /chapter2/GeneratorDemo.py | 194 | 3.515625 | 4 |
if __name__ == '__main__':
colors = ['black', 'white', 'gray']
size = ['S', 'M', 'L', 'XL']
for (color, s) in ((color, s) for color in colors for s in size):
print(color,s)
|
d25b2e542dfa25af3aaa6bc16a97d9a414181256 | bearkillerPT/App-Or-amentos-Fachada | /fachada/calc.py | 1,565 | 3.546875 | 4 | # -*- coding: utf-8 -*-
class Piso:
def __init__(self, pisoName):
self.name = pisoName
self.divs = {}
def getDivs(self):
return self.divs
def getName(self):
return self.name
#Para o csv construir sem saber ponteciaref e alturaref
def buildDiv(self, divname, area, ... |
fc90dceece6c03e5bbe51f2a8ea5ebbf5bcba584 | kevynfg/estudos-geral | /codigofonte-estudos/modulo2/thread3.py | 591 | 3.5625 | 4 | import threading
import time
ls = []
def contador1(n):
for i in range(1, n+1): # valor de 1 até o valor recebido no parâmetro
print(i)
ls.append(i)
time.sleep(0.4)
def contador2(n):
for i in range(6, n+1):
print(i)
ls.append(i)
time.sleep(0.5)
x = threadin... |
640a260a0dc8954b63e19af2ca4842e2d43bdbc4 | MikePolinske/PythonForBeginners | /LearnPython/if-statement.py | 227 | 4.09375 | 4 | a,b = 2,2
if a == b:
print(True)
if a != b:
print(True)
if a < b:
print(True)
if a > b:
print(True)
if a <= b:
print("This is true")
if a >= b:
print(True) # not =>
if a == b and b > 1:
print(True) |
6de3473f348bf28e2f5a18468596e523c6168977 | SerGeRybakov/self_made | /таблица_умножения.py | 665 | 3.890625 | 4 | """Multiplication table"""
x1 = int(input('Input lines first number: '))
x2 = int(input('Input lines last number: '))
y1 = int(input('Input columns first number: '))
y2 = int(input('Input columns last number: '))
# Making Y-headers in the first line of table
field = y1 - 1
while field <= y2:
if field ... |
2c6685966a99426fc8642cb33f950d745bfcfc64 | CodingGearsCourses/Python-OO-Programming-Fundamentals | /Module-02-OOPs-Essentials/oops_basics_09.py | 1,362 | 4.15625 | 4 | # https://www.globaletraining.com/
# Changing Class and Object Variables/Attributes
class Car:
# Class Attributes/Variables
no_of_tires = 4
# Class Constructor/Initializer (Method with a special name)
def __init__(self):
# Object Attributes/Variables
self.make = ""
self.model ... |
1e80d23c7b4ce4d0e78b17f59f5fadf0030d8c9f | dark4igi/atom-python-test | /coursera/Chapter_7.py | 479 | 4.03125 | 4 | ### Data type
##file
# example open file
xfile = open (file.txt)
for line in xfile:
print (line )
## work with strings
#
line.rstrip() # strip whitespaces and newline from the right-hand of the string
line.startswith('some text') # became true if line starts with 'some text'
line.upper() # upper case for line
li... |
4fc7289ca0da3827e58824be28e8a352e10bb821 | yes99/practice2020 | /codingPractice/python/학교 과제/quiz3.py | 199 | 3.671875 | 4 | print("라인 수?", end="")
num=int(input())
for k in range(num):
for j in range (k):
print(" ", end="")
for l in range(num-k):
print("*", end="")
print()
|
df7dcb9483f4be3016645c4579b245ea35284fed | arthurDz/algorithm-studies | /leetcode/consecutive_characters.py | 1,012 | 4.09375 | 4 | # Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
# Return the power of the string.
# Example 1:
# Input: s = "leetcode"
# Output: 2
# Explanation: The substring "ee" is of length 2 with the character 'e' only.
# Example 2:
# Input... |
6138b4b3f0503baecb1d8a61430733d47f60cbe2 | IamConstantine/LeetCodeFiddle | /python/LevelOrderTree.py | 708 | 3.71875 | 4 | import collections
from collections import deque
from typing import Optional, List
from Tree import TreeNode
# https://leetcode.com/problems/binary-tree-level-order-traversal
# Medium - easy for me
# For me, Tree questions seems easier.
# T = O(N) - each node exactly once
# S = O(N) - Width of the tree
def levelOrd... |
1a6255f0f73a3e7a99bac9a9afa576878bb25ac0 | sumeyyadede/algorithm-problems | /trees.py | 1,367 | 4.03125 | 4 | class TreeNode(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
# return "({}, {}, {})".format(self.data, self.left.data if self.left else None, self.right.data if self.right else None)
return "({})".format(self.data)
class Tree(object):
def __ini... |
144f427fde92972ee6293331f3e1ae5fc64ba67d | Philfeiran/Calculator | /src/calculatorTest.py | 2,314 | 3.609375 | 4 | from calculator import calculator
import unittest
import csv
def readFile (file):
csvFile = open(file, "r")
reader = csv.reader(csvFile)
IsThreeVar = True
x=[]
y=[]
result=[]
for item in reader:
if reader.line_num==1:
if item[2]==' ':
IsThreeVar=False
... |
57906cf3bfb4412639715e525e301763411cd9d9 | pwang867/LeetCode-Solutions-Python | /0024. Swap Nodes in Pairs.py | 1,416 | 4.0625 | 4 | # time O(n), space O(1)
class Solution(object):
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
p1 = dummy # we swap the pair after p1
while p1 and p1.next and p1.next.next:
p2 = p1.next
p3 = p2.next
p4 = p3.next
... |
f13eb28b6d856d4911986e016eff09f6524559bf | phil-harmston/hangman | /hangman.py | 8,132 | 3.921875 | 4 | # Imports needed to code the project
from curses import wrapper
import curses
import random
import string
import json
import functools
stdscr = curses.initscr()
"""Use this function to input a custom word then choose option "C" When playing the game"""
def custom_word():
my_word = "UTAH"
return my_word
# Used... |
96f3bb31c887bfd1bae92bb286837bdab36d0579 | AndrewPochapsky/genetic-algorithm | /algorithm.py | 2,442 | 3.671875 | 4 | import random
def generate_population(population_size: int, individual_size: int) -> list:
population = list()
for _ in range(0, population_size):
individual = [0] * individual_size
population.append(individual)
return population
def get_fitness(individual: list) -> int:
fitness = 0
... |
51cb98326912c3c9fdce3a75ceeecbf4ec7fdd5d | pieteradejong/joie-de-code | /strdistanceapp/similarity.py | 1,018 | 3.609375 | 4 | import math
import sys
import unittest
# assumes two points in R^2 (points in 2D-space)
class Similarity():
def euclidian(self, a, b):
return self.minkowski(a, b, 2)
def manhattan(self, a, b):
return self.minkowski(a, b, 1)
def minkowski(self, a, b, p):
p = float(p) # ensure 1/p is accurate when ... |
91616f475693d64af7857fefd456afe6274ae984 | Yashsharma534/Python_Projects | /dice.py | 417 | 3.5625 | 4 | from tkinter import *
import random
root = Tk()
root.geometry('500x500')
root.title("Dice Simulator")
label = Label(root,text ='',font=('Helvetica',260))
def roll_dice():
dice = ['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
label.configure(text=f'{random.choice(dice)}')
label.pack()
button = Button(roo... |
f96d339a1b20e72591c9bc1e64f32dc752727bed | Seeun-Lim/Codeup | /6078.py | 76 | 3.640625 | 4 | while(True):
n=input()
print(n)
if (n == 'q'):
break |
bff98ff95997d1a267aaedbf9d270f19b0ed5bb7 | blegloannec/CodeProblems | /Rosalind/LEXV.py | 629 | 3.578125 | 4 | #!/usr/bin/env python3
from itertools import product
A = input().split()
n = int(input())
## lazy hack over itertools
def main0():
S0 = ' '
for P in product(A,repeat=n):
S = ''.join(P)
d = 0
while d<n and S[d]==S0[d]:
d += 1
for i in range(d+1,n):
pri... |
ce91ce16a97dae37a8f86b7a62d7582a5a85d6cd | SmischenkoB/campus_2018_python | /Yehor_Dzhurynskyi/1/task9.py | 378 | 4.125 | 4 | from string_is_24_hour_time import string_is_24_hour_time
time24 = input('Enter 24-hour time string: ')
if string_is_24_hour_time(time24):
time_parts = time24.partition(':')
hours = int(time_parts[0])
minutes = int(time_parts[2])
noon = 'pm' if hours >= 12 else 'am'
print('%.2d:%.2d %s' % (hours ... |
d2616fb15073b393e522f09f3237253f2cce67a7 | breezeiscool/Python-Learning | /Assignment/3 ways of Fibonacci seq.py | 1,689 | 3.625 | 4 | # Student:Coco
# Assistant:Peter
# Scores:97
# P.S. Done great ! You successfully finish the assignments but three points are deducted because you didn't use an expected function.
# btw, your hard work makes me hang my head in shame.
# Precise:
# As we all know:fibs(0)=0,fibs(1)=1,
# fibs(n)=fibs... |
624d46d50ed5e6961859cdbe42761d2f693a6a0d | harishsakamuri/python-files | /basic python/ramesh5.py | 195 | 3.9375 | 4 | str1=("welcome")
print(str1)
str2=(" to hyderabad")
print(str2)
print(str1+str2)
str3=(str1+str2)
print(str3[1:10])
print(str3[-5:])
print(str3[:-5])
print(str3[-7:])
print(str3[:-7])
|
65364814ba850712390b9e54af7693bbf85587d4 | minzhou1003/intro-to-programming-using-python | /practice10/12_2.py | 1,005 | 4.03125 | 4 | # minzhou@bu.edu
class Location:
def __init__(self, row, column, maxValue,):
self.row = row
self.column = column
self.maxValue = maxValue
def locateLargest(a):
maxValue = a[0][0]
row = 0
col = 0
for i in range(len(a)):
for j in range(len(a[i])):
if a... |
597034f0609230850f3ec2c130e0c0eb24051355 | mstepovanyy/python-training | /course/lesson05/task05/numbers.py | 662 | 4.1875 | 4 | #!/usr/bin/python3
"""
Print a number of numbers in a file; each number shall count only once (e.g.
``1234`` shall count only once, not 4 times).
"""
import re
def count_numbers(file_name):
"""
Count numbers in provided file, and return total amount of it.
Args:
file_name (str): path to a file
... |
1907fb9ce3f2d374767d12baf72a9be27bd5ca92 | WooWooNursat/Python | /lab7/informatics/5/probB.py | 138 | 3.953125 | 4 | a = int(input())
b = int(input())
def power(a,b):
n = a
for i in range(1, b, 1):
n = n * a
return n
print(power(a, b)) |
51a7e112899216269a9aa15816225fb4064d1854 | lcsm29/edx-harvard-cs50 | /week6/mario/mario.py | 257 | 4.03125 | 4 | height = 0
while not (1 <= height <= 8):
try:
height = int(input("Height: "))
except ValueError:
height = 0
for i, line in enumerate([' ' * (height-i) + '#' * i for i in range(1, height + 1)]):
print(line + ' ' + '#' * (i + 1))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.