blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
0d1b34813f44c9e8945e2683244b403e8ccf7902 | junha6316/Algorithm | /0714_Goldbach.py | 1,323 | 3.625 | 4 | # import sys
def primelist(N):
isPrime =[True] *N
for i in range(2,N+1):
if i *i > N: break
if isPrime[i]:
for j in range(i+i, N , i):
isPrime[j] = False
return isPrime
prime = primelist(1000000)
#
# while(True):
# N= int(sys.stdin.readline())
# if N ==0:... |
cb534a6bd00da96f43f99ddd02dc5a62985b8172 | junha6316/Algorithm | /0613_bf_2_Pn.py | 1,808 | 3.5625 | 4 | '''
문제 설명
한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
제한사항
numbers는 길이 1 이상 7 이하인 문자열입니다.
numbers는 0~9까지 숫자만으로 이루어져 있습니다.
013은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.
'''
import itertools
import itert... |
c44459367634b98c394802eef3982a0f93c5d4ec | junha6316/Algorithm | /0805_LockKey_Programmers.py | 1,266 | 3.78125 | 4 | def MoveRight(key):
N = len(key)
M = len(key[0])
for i in range(N):
key[i]=('0 '+' '.join(map(str, key[i]))).split()[:-1]
return key
def MoveLeft(key):
N = len(key)
M = len(key[0])
for i in range(N):
key[i] = (' '.join(map(str, key[i]))+' 0').split()[1:]
return key
def ... |
8a370e27c34d07d4d7d0c20b323166ae967f403c | benxiao/pythonit | /algos/suffix_tree/compress.py | 419 | 3.515625 | 4 | a = "googol$"
def compress(text):
prev = text[0]
l = len(text)
count = 1
temp = []
for i in range(1, l):
cur = text[i]
if cur != prev:
temp.append(prev)
temp.append(str(count))
count = 1
prev = cur
else:
count += 1... |
e931f218c9c202db5e08b37cd34a8b651c50a76e | benxiao/pythonit | /algos/myheapdict.py | 4,451 | 3.5 | 4 | class KeyAlreadyExists(Exception):
"""
"""
pass
KEY = 0
PRIORITY = 1
class MyHeapDict:
"""
"""
def __init__(self):
"""
"""
self._heap = [(None, None)]
self._dict = {}
def __len__(self):
"""
:return:
"""
return len(self._he... |
2d4efd85a9ecd1e597c7a554f31bd1ec771cf4a1 | benxiao/pythonit | /algos/tree/rbtree.py | 3,074 | 4.09375 | 4 | from binarytree import BinarySearchTree, Node
"""
A more relaxed balanced binary search tree
Invariants
Every node has a color either red or black
Root of tree is always black
There are no two adjacent red nodes(A red node cannot have a red parent or red child)
Every path from root to a NULL node has same number of ... |
969cda7e8cec87a5f7f03753255d9e2913e01a9d | benxiao/pythonit | /algos/dynamic programming/rabin_karp.py | 1,179 | 3.6875 | 4 | R = 256
Q = 10262821 # prime
def hash(s):
H = 0
for ch in s:
H = (H * R) % Q
H = (H + ord(ch))
return H
def rabin_karp(src, pat):
h_pat = hash(pat)
h_src = hash(src[:len(pat)])
rm = pow(R, len(pat)-1, Q)
i = 0
n = len(src) - len(pat)
while i <= n:
if (h_pat... |
439aed8669d75a54b4c87018353dd820b43d4aef | villakid95/Programming-task | /q3.py | 399 | 3.953125 | 4 | def perfectSquare(number):
number1 = number
while True:
if number1**2 <= number:
return number1**2
else:
number1 -= 1
#Pseudocode
#FUNCTION sqrRoot (x)
# integer -> x
# WHILE TRUE
# IF integer POWER OF 2 >-> x
# RETURN integer POWER ... |
7c1c0b3021281c64d6b15b51407dcde3473bdf6b | bmackenty/studentPythonStuff | /uno.py | 2,697 | 3.953125 | 4 | import random
class Card:
def __init__(self, color, value):
self.color = color
self.value = value
def __str__(self):
return f"{self.color} {self.value} card"
class UnoGame:
def __init__(self):
self.deck = [Card(color, value) for color in ["red", "green", "blue", "yellow"]
... |
972baa95875c1812c7badbed65b8a4a27b299c52 | bmackenty/studentPythonStuff | /deal_cards.py | 744 | 4 | 4 | # This code was generated by chatGPT
import random
# Define the ranks, suits, and values of cards
ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = {'Ace': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, ... |
230e3570978215e62d9a420cfc9aa2f385810821 | bmackenty/studentPythonStuff | /geneticAlgo.py | 1,973 | 3.921875 | 4 | # this code was written by chatGPT
import random
# Define the parameters of the genetic algorithm
POPULATION_SIZE = 100
GENE_LENGTH = 10
MUTATION_RATE = 0.1
# Define the fitness function that the algorithm will try to optimize
def fitness_function(gene):
# In this example, the fitness function simply counts the n... |
cd090672a75acbf3290799d3b205b37031cd9c51 | agustinprieto50/my_docker | /misc/employee.py | 776 | 3.53125 | 4 | class Employee():
def __init__(self, name=None, surname=None, pay=None):
self._name = name
self._surname = surname
self._pay = pay
self._email = self._name + "." + self._surname + "" + "@email.com"
self._fullname = "%s %s" % (self._name, self._surname)
@property
de... |
cd7ef5b3e29febcc89b482986515e12a638fa7bf | karanchawda95/codingbat | /string-2/count_hi.py | 391 | 3.921875 | 4 | # Return the number of times that the string "hi" appears anywhere in the
# given string.
def count_hi(str):
count = 0
for i in range(len(str)-1):
if str[i:i+2] == "hi":
count += 1
return count
#or
def count_hi(str):
count=0
for i in range(len(str)-1):
... |
55f189165b6003bf48b74a9e99dfa41f9b237e83 | Nickedude/Codejam | /2021/test_reversort.py | 666 | 3.609375 | 4 | import unittest
import random
from reversort import calculate_cost
class TestGenerateList(unittest.TestCase):
def test_reversort_example_1(self):
self.assertEqual(6, calculate_cost([4, 2, 1, 3]))
def test_reversort_example_2(self):
self.assertEqual(1, calculate_cost([1, 2]))
def test_re... |
8ff7e379b9a79d6c8094165e0ab6a9fb089d753a | jtwray/Intro-Python-I | /src/07_slices.py | 1,789 | 4.625 | 5 | """
Python exposes a terse and intuitive syntax for performing
slicing on lists and strings. This makes it easy to reference
only a portion of a list or string.
This Stack Overflow answer provides a brief but thorough
overview: https://stackoverflow.com/a/509295
Use Python's slice syntax to achieve the following:
"... |
63e6a1e3a7eb26e9b64902716f093cf5fa48fbf4 | fate7902/2DGP | /assignment_3/py_01_03_2018180048_2.py | 478 | 3.921875 | 4 | import turtle as t
def turtle_move(x,y): ## 위치 이동
t.penup()
t.goto(x,y)
t.pendown()
t.title('거북이로 격자그리기!!')
t.shape('turtle')
t.pensize(3)
t.speed(0)
## 결과가 잘 보이도록 시작점 이동
turtle_move(-300,-300)
(x,y) = t.position()
for i in range(0,6):
turtle_move(x,y+100*i)
t.setheading(0)
... |
410f14e8e974d64102fc3c8067265052fa29840f | rezeq1/Codes | /Python/High-order functions2/lab_5_solutions.py | 1,957 | 4.03125 | 4 | #Q1
print ("start of lambda functions")
var=lambda x: x+2
print (var(4)) #6
var = lambda x: x**2+3*x-2
print (var(3))#16
var=lambda x,y: (x+y)/(x-y)
print (var(8,4))#3
print ("end of lambda functions")
print()
#Q2
def summ(a,b,f,nextt):
total=0
while a<b:
total+=f(a)
a=nextt(a)
return total... |
cfd6887e7350f88afd72f151373696465e4accc3 | xiaoCarl/myclass | /algorithm/mc/pi.py | 383 | 3.5 | 4 | import random
def rand(left,right):
return left+(right-left)*random.random()
def getpi():
cnt = 0
max = 100000
x = 0.0
y = 0.0
for i in range(max):
x = rand(-1.0,1.0)
y = rand(-1.0,1.0)
if x*x+y*y <= 1:
cnt = cnt+ 1
return cnt*4.0/max
if __name_... |
1a45f0c4de4369e4ecfeb8b29f4226b537bba99b | b0dah/Python | /FilesFirstIndividual.py | 477 | 3.8125 | 4 |
file = open('TextFile.txt')
letter = input('Enter a letter to seek out for ... \n')
wordsStartingWithTheLetter = 0
assert len(letter) == 1, 'WARNING: ENTER ONLY 1 SYMBOL!'
fileText = file.read()
if fileText[0] == letter:
wordsStartingWithTheLetter += 1
for i in range(1, len(fileText)):
if (fileText[i-1] == ' ' or... |
82a39a489cb17b5f4b52f78bf1b4f6cb89ac03e1 | matski98/Numeryczne | /lab2.py | 2,120 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 11:58:02 2018
@author: mati
"""
def wzgledny(p,p1):
return abs(p-p1)/p
def bezwzgledny(p,p1):
return abs(p-p1)
import math
p = math.pi
p1=22/7
print("p: ",p)
print("p*: ",p1)
print("blad wzgledny: ",wzgledny(p,p1))
print("blad bezwzgledny... |
25edd04b4e9becd2faa0bb9bbdff5a225ac5b006 | Luis-star54/python-cardio | /conversor_de_millas_kilometros/main.py | 1,085 | 3.78125 | 4 | import os
os.system('clear')
menu = """
The best converter
1) Convertir millas a km
2) COnvertir km a millas
"""
def conversor_kilometro(kilometro):
METROS = 1000
MILLAS = 1609
resultado = round((kilometro * METROS) / MILLAS, 2)
return resultado
def conversor_mi... |
a3f8be589ba8bfe4bfced29f3d288b6dc880b790 | TreyHusko/CS362HW4 | /volume.py | 267 | 4 | 4 | def Cube(a,b,c):
if (type(a) == str or type(b) == str or type(c) == str):
raise TypeError("String input invalid")
elif a < 0 or b < 0 or c < 0:
raise ValueError("Tried to compute volume with negative value")
else:
return a * b * c
|
261c960c64387b0dae0b0107d9e53c3065f71608 | xiaochus/LeetCode | /questions/14.py | 600 | 3.625 | 4 | """14. Longest Common Prefix
Write a function to find the longest common prefix string amongst
an array of strings.
"""
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
if len(strs) == ... |
188b4da639d2935e54452072c9f248ccf2e69e05 | xiaochus/LeetCode | /questions/7.py | 767 | 4.09375 | 4 | """7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold
integers within the 32-bit signed integer range. For the pu... |
c47e9c57348762f2611ff3f003432678e9358594 | kjh03160/Likelion_Class | /week2.py | 855 | 3.71875 | 4 | """
파일 입출력으로 입력 받아서 읽어서 해당 문자열이 몇개 연속인지? -> 후 파일 저장
"""
def answer(file_name):
# result = []
with open(file_name + '.txt', 'r', encoding='UTF-8') as file:
with open('result.txt', 'w', encoding='UTF-8') as result_f:
lines = file.read().split('\n')
for line in lines:
... |
3857664e1a9d00272d405a56360ece276846365d | RohanReignz/FruitBasket | /TypingTest.py | 970 | 3.890625 | 4 | #A typracer game!
#This program requires one to have a 'typetest.txt' named file in the same folder as that containing the script.
#The 'typetext.txt' file is expected to have any number of texts seperated by a line for the code to work properly.
import time
import random
def text_generator():
with open('typetest.t... |
e2de65d22bac73781c41a8f6c724c8537298f8b0 | bienvandai/python | /ex13.py | 188 | 3.5 | 4 | x= lambda a: a+10
y = lambda a,b: a + b
print(x(100))
print(y(10,20))
print("------------------------")
def ham_mu(n):
x = lambda x: x ** n
return x
kq = ham_mu(2)
print(kq(3)) |
3f67104a4eba33ecf9479f0434a2246d56f7b40e | Yonezcy/OneDay-OneAlg | /Permutation_algorithm.py | 776 | 4 | 4 | __author__ = 'zcy'
def swap(a, b):
t = a
a = b
b = t
return a, b
def permutation(array, begin, end):
'''get the permutation of array implemented by recursion
:param array: input array
:param begin: begin pointer
:param end: end pointer
:return: null
'''
if begin == end:
... |
033d856a1d16df5c8aa7eec304a85402c0f56673 | Swapnil-ingle/MachineLearning | /PredictionOfCars.py | 2,095 | 3.515625 | 4 | #Data Preprocessing
#importing the libs
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the datasets
dataset = pd.read_csv('Social_Network_Ads.csv')
x = dataset.iloc[:,[2,3]].values
y = dataset.iloc[:,4].values
#Doing the train_test_split for the Datasets
from sklearn.cross_validat... |
7a6b08c52a1f57f07dc3c6be620b3df74620fa64 | wsullivan17/Cashier | /Cashier.py | 1,678 | 4.125 | 4 | #Automated cashier program
#Willard Sullivan, 2020
#total cost of items
total = 0
done = ""
from users import users_dict, pwds_dict
from items import items_dict, cost_dict
print("Welcome to the Automated Cashier Program. ")
go = input("Type the Enter key to continue. ")
while go != "":
go = input("Type the E... |
9ef549fedc7709dbb62b0b338ce9c9e9e8691e20 | CodeInSleep/mcts-tictactoe | /utils.py | 3,806 | 3.84375 | 4 | """
Classes:
- State
- Node
- Board
pseudocode:
At each turn:
Variables
===
current player's move
current state of the
Routine (run in a certain time threshold)
===
1. Selection Phase
select the child node C of the root node that has the
highest UCT score
2. Expansion Phase
Enumerate all the possible ... |
c676a78831f70a583bea0e1fe27f8a4960db9f2a | mahesh122000/Hackerrank-Solutions | /isFibo.py | 254 | 3.78125 | 4 | #!/bin/python3
import math
import sys
t=int(input())
for i in range(t):
n=int(input())
k=int(math.sqrt(5*n*n+4))
kk=int(math.sqrt(5*n*n-4))
if(k*k==5*n*n+4 or kk*kk==5*n*n-4):
print("IsFibo")
else:
print("IsNotFibo") |
94bf43689367a92c1d41eb71d3626ca0c8fd2e62 | alfagama/twitter_sentiment_analysis_based_on_geolocation | /country_visualization/country_visualization_CreateMap.py | 4,180 | 3.546875 | 4 | # https://plotly.com/python/choropleth-maps/
import plotly
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
# LOAD THE CSVs WITH THE TWEETS COUNT PER COUNTRY
#-------------------------------------------------
covidDF = pd.read_csv("covid_Country_vis.csv")
vaccineDF = pd.... |
6c937dd5f534898bbb4528a6699b0d8a4070ff01 | alfagama/twitter_sentiment_analysis_based_on_geolocation | /preprocessing/tweet_location.py | 4,798 | 3.625 | 4 | import geograpy
import re
from FileAlexia.mongodb_scripts.mongo_db import *
#collectionName = 'covidtemp'
def recognizeSpecificCountries(text):
'''
Gets the location if the text contains abbreviations or words like 'britain' 'england' that are not recognized by geograpy
:param text: location text... |
13606f3c940550f8f60af5f5af0f4b36889be8f4 | RoopsBhasima/Python | /function.py | 550 | 3.828125 | 4 |
#Functions
#FirstFunction
def xyz():
print('Printing from a function')
xyz()
#calling function
print(xyz())
#First function with para
def para_func(str):
return str
print(para_func('a'))
#second function with two parameters
def para_func2(first_name,last_name):
print(first_name,last_name)
p... |
f640f032d723a10c397c2bb5d7c60086d3bbf73c | felippeGEC/-BLASTOFF | /ex8.py | 231 | 3.875 | 4 | n = int(input("Entre com o numero para ver se ele é primo"))
div = 0
for c in range (1,n+1):
if n%c == 0:
div +=1
if div ==2:
print("Seu numero é primo")
else:
print("Seu numero nao é primo") |
dbe62ee2e65761c1a375586fb298907b63e22e69 | felippeGEC/-BLASTOFF | /ex14.py | 247 | 4.03125 | 4 | #entrada de dados
pa = str(input("Entre com a sua palavra")).upper()
#manipulação dos dados
inverso = pa[::-1]
#saida de dados
if inverso == pa:
print("A palavra é um palidromo")
else:
print("A palavra não é um palidromo")
|
1e2b7e6f44c7fba2e1aa916481a50a4dc86e5195 | maianhtrnguyen/Assignment-2 | /Assignment/PythonLearningProject1-master/helloWorld.py | 1,675 | 4.1875 | 4 | # Install the package Pillow: pip install pillow
from PIL import Image
# The documentation is here,
# https://pillow.readthedocs.io/en/stable/reference/Image.html#
# please just look at the Image Module and Image Class section
# Read about this module/class and its relevant information, but dont worry about other cl... |
a34d3f141786a6323c9fa4b20d19f434a2228224 | maianhtrnguyen/Assignment-2 | /Python_Tutorial/Class_and_static_methods.py | 1,376 | 3.796875 | 4 | class Employer:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + "." + last + "@company.com"
self.pay = pay
Employer.num_of_emps += 1
def fullname(self):
return "{} {}... |
dc75877f31ed1648650ec71ef388ce4c80e75950 | reyespinosa3/python | /shopping_list.py | 1,265 | 3.9375 | 4 | # Create new shopping list (the new list should have a title)
# Edit list's name
# See all items
# Add new item
# Exit
# shopping list
# Food shopping list+ gift shopping list
import email
class ShoppingList:
def __init__(self):
self.contents = []
def add_item(self, item):
self.contents.append(item)
... |
77b64ff19c218856644bce7e558ba96afe6b35ed | AtieDag/Project-Euler | /Problem5.py | 586 | 3.625 | 4 | # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Done in 232792561 ms...
from numba import jit
@jit(nopython=True)
def divisible(number, number_length):
... |
21939208c9d75a5e10e77f874041e111051d7be2 | AtieDag/Project-Euler | /Problem14.py | 572 | 4.125 | 4 | # The following iterative sequence is defined for the set of positive integers:
from functools import lru_cache
@lru_cache(maxsize=100)
def collatz_sequence(n, terms=0):
terms += 1
if n == 1:
return terms
# n is even
if n % 2 == 0:
return collatz_sequence(n / 2, terms)
# n is odd
... |
334dafa15e911adf2f38abbf5e66b76aec5b0098 | AtieDag/Project-Euler | /Problem67.py | 2,962 | 3.546875 | 4 | # By starting at the top of the triangle below and moving to adjacent numbers on the row below,
# the maximum total from top to bottom is 23.
class Node:
botton_max_node = None
botton_max_value = 0
exist = {}
@classmethod
def set_children(cls):
for key, node in cls.exist.items():
... |
2fa57f2f3a05c4338b7c8256e3798ceaa96f3f49 | 2019Shun/atcoder_submission | /ABC/abc077/abc077_b_7787511.py | 159 | 3.5625 | 4 | import math
N = int(input())
ans = 0
for i in range(1, int(math.sqrt(N))+1):
if(i == int(math.sqrt(i))*int(math.sqrt(i))):
ans = i
print(i*i) |
e32dd619deb73f3a1d69e5711efaf768bef4dafc | 2019Shun/atcoder_submission | /ABC/abc155/abc155_a_10560679.py | 134 | 3.71875 | 4 | A, B, C = map(int, input().split())
if (A==B and B!=C) or (A==C and C!=B) or (C==B and B!=A):
print('Yes')
else:
print('No') |
d3c36c280719f0c225002a78e43b4cc0cb3783b8 | frankenbeanies/Summer | /Parrot/parrot.py | 201 | 3.625 | 4 | def game():
phrase = raw_input("Please enter a phrase: ")
output = "*SQUACK* " + phrase + " *SQUACK*"
print output
if phrase == "quit":
return
else:
game()
if __name__ == "__main__":
game()
|
afb36bdc95816ee5d4103a02acd136f95bf4361d | RohitRanga12/Resume-Processor | /ResumeProcessor/src/scorer.py | 2,711 | 3.515625 | 4 | """
Rohit Rangarajan
29.3.2019
Abstraction for scoring logic
"""
import json
# abstract class
class ResumeScorer:
def __init__(self):
# let us assume some default sections to be considered
self._sections_for_scoring = ["Skills", "Companies worked at", "Designation", "College Name", "Degree",
... |
aaf34aecc44fa611e2779c1ca99187544f1efb01 | jinyanliu/advent_of_code_2019 | /days/day_16/day_16_part_2_with_recursive.py | 2,410 | 3.671875 | 4 | """
Created at 2019-12-17 14:30
@author: jinyanliu
"""
import numpy as np
def get_original_string():
with open("day_16_input") as lines:
original_string = lines.readline()
return original_string
# def get_multiply_int_list(row, target_len):
# new_list = []
# list_1 = [0, 1, 0, -1]
# lis... |
54db56dc6e32c934181bddf74c564bf07a9e1258 | Jakub21/mpplugs | /Scripts/_scriptUtils.py | 757 | 3.71875 | 4 | from os import mkdir, path
def ifnmkdir(d):
try: mkdir(d)
except FileExistsError: pass
def fexit():
print('Failure')
exit()
def validate(val):
digits = [chr(l) for l in range(ord('0'), ord('9'))]
lower = [chr(l) for l in range(ord('a'), ord('z'))]
upper = [chr(l) for l in range(ord('A'), ord('Z'))]
f... |
ba87bd696e44f8ff14e7fea38b1ec691c3ec7c36 | nigredon1991/TimusOJ | /some_practice/functional_p.py | 1,349 | 3.90625 | 4 | def zero(operator=None):
return _digit(0, operator)
def one(operator=None):
return _digit(1, operator)
def two(operator=None):
return _digit(2, operator)
def three(operator=None):
return _digit(3, operator)
def four(operator=None):
return _digit(4, operator)
def five(operator=None):
re... |
97ffe577f9234bb9b40ac4e6b04f25daac9940e3 | legend-shiang/pythonhomework | /Qu2.py | 534 | 4 | 4 | class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
return self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def size(self):
return len(self.items)
Queue = [] #usin... |
90978f43bef7385dd54ab07eb2ac7883f2104370 | KostadinovShalon/curso-de-python-2020 | /dia 1/ejercicios/ejercicio_6.py | 889 | 3.8125 | 4 | # 6. El Teorema Fundamental de la Aritmetica establece que todos los numeros se pueden descomponer en factores
# primos. Escribe un programa que encuentre todos los factores primos de un numero.
# OJO: el 1 no es primo! (y mucho menos el 0)
x = 2
print(f"Factores primos de {x}: ")
for factor in range(2, x // 2 + 1): ... |
18f31e559b7c838ff226b6dad3bc0f25665930cc | KostadinovShalon/curso-de-python-2020 | /dia 1/ejercicios/ejercicio_15.py | 683 | 4.1875 | 4 | # 15. Pidele al usuario que ingrese una lista de palabras y le digas cual fue la mas larga. Recuerda que deben de ser
# palabras, por lo que frases no cuentan!
palabra_mas_larga = ""
while True:
palabra = input("Introduzca una palabra [O introduzca * para salir]: ")
if palabra == "*":
break
palabr... |
c1c8f82791350528b909e84ee02931be090f4ad6 | KostadinovShalon/curso-de-python-2020 | /dia 1/ejemplos/calculando_pi.py | 1,429 | 3.546875 | 4 | # Pi se puede aproximar por medio de la siguiente serie
# π = 4 - 4/3 + 4/5 - 4/7 = 4/9 - 4/11 + ...
# Escribiremos un programa para calcularlo
# Definimos n como el numero de elementos de la sumatoria
n = 100
pi = 0
for i in range(n): # i va a ir de 0 a n - 1
# Nos podemos dar cuenta que cada elemento de la se... |
be191e85c65d7bd30ec15263b83af6e614e179d2 | RisingLight/Python_Practice | /Cycle1/1.py | 102 | 3.5 | 4 | lis=[6,5,2,1,6,4]
m=max(lis)
full=0
for i in lis:
if(i>full and i!=m):
full=i
print(full)
|
e2e3884345256a114aa8fe57fd10fd8ce388e679 | RisingLight/Python_Practice | /Challenge questions/TejaSreeChand/wordscramb challenge3 .py | 1,349 | 4.25 | 4 | import random
import os
def shuf(string):
ltemp=string[1:len(string)-1] # taking only the mid part { change it into string[0:len(string)] for a full words shuffle
ltemp=list(ltemp) # convert the word into alphabet list eg: "hey" -> ["h","e","y"]
random.shuffle(ltemp) # ... |
cad90a25902bfc3833ffadb60a1a8bbb09fd7974 | MauroOliveira/Python-Projects | /Python Projects/PythonWorks/Find_MaxMinAver_Values.py | 804 | 3.90625 | 4 | #!/usr/bin/env python
#-*- coding: utf8 -*-
'''
Created on 23 de ago de 2016
@author: Mauro Cesar de Oliveira
'''
'''
This program find the highest value,
lower value and the average value on a list.
'''
L = []
#input the value on a list
while True:
n = int(input("Type Number | 0 to exit: "))#the input exit can... |
0232e6dc40982ba14500628d44168fdc10763043 | tovmasYANk/tetris-auto-player | /tetris_algo.py | 5,517 | 3.78125 | 4 | '''
Created on Nov 9, 2014
@author: BrianTruong
'''
import random
import math
import collections
# Abstract class: an RLAlgorithm performs reinforcement learning. All it needs
# to know is the set of available actions to take. The simulator (see
# simulate()) will call getAction() to get an action, perform the acti... |
d6240bd59fcb726bf5a6b4dfcac9ee5a48ac3b7f | razrow/Excel-Column-Number | /main.py | 595 | 3.96875 | 4 | #Given a column title as appears in an Excel sheet, return its corresponding column number.
#Examples:
#
#A -> 1
#
#B -> 2
#
#C -> 3
#
# ...
#
#Z -> 26
#
#AA -> 27
#
#AB -> 28
def excel_column_to_number(column):
val = 0
val2 = 0
val3 = 0
for n in range (0,len(column)):
if n==0:
... |
801c960f543630563b9d1bf2f740d36786012121 | asyed9394/Election_Analysis | /PyPoll.py | 3,608 | 4.21875 | 4 | #Process election results data file and gather following data
#1. Total number of voter casts
#2. A complete list of candiddates who receives vote(s)
#3. The percentage of votes each candidate received
#4. The total number of votes each candidate receieved
#5. The winner of the election based on popular vote
import cs... |
bec4b792796d49c578b19763bf9d16091e6a2c15 | Minard-NG/Face_recognittion_for_Video | /moneyheist.py | 4,412 | 3.71875 | 4 | #module and library required to build Face recognition System
import face_recognition
import cv2
#objective: this code will help you in running face
#recognition on a video file and saving the results to a new
#video file
#Open the input movie file
#'VideoCapture' is a class for video capturing from video
#files, im... |
1d6a730da2128c4703b6a067be1158db3b93a426 | reece-sharp/Lexis-Lectoris | /flaskr/db.py | 3,196 | 3.609375 | 4 | import sqlite3
import click
from flask import current_app, g
# g is a special object that is unique for each request.
# It is used to store data that might be accessed by multiple functions during the request.
# The connection is stored and reused instead of creating a new connection
# if get_db is called a second tim... |
04185216ac42a82e6704ab7737c4d2d488f9a6b8 | loosenthedark/CI_python-essentials_love-sandwiches-walkthrough-project | /run.py | 5,357 | 3.546875 | 4 | # Write your code to expect a terminal of 80 characters wide and 24 rows high
import gspread
from google.oauth2.service_account import Credentials
SCOPE = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]
CREDS = C... |
111da507b5d16f84b442d988ade59eff6558d3be | tamycova/Programming-Problems | /Project_Euler/5.py | 696 | 3.8125 | 4 | # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of
# the numbers from 1 to 20?
# My quick thoughts:
# We just need to check that its divisible from 11 to 20
# We know that units must be c... |
31ee3a9e4d9a2d03ef4044a9b2a6f5c380477d9f | tamycova/Programming-Problems | /ACM-ICPC/2389.py | 646 | 3.796875 | 4 | def isPali(n, base):
s = ""
t = ""
while n:
r = n % base
n //= base
if r <= 9:
s = s + "0" + str(r)
t = "0" + str(r) + t
else:
r -= 10
s = s + "a" + str(r)
t = "a" + str(r) + t
return s == t
num = int(input())
w... |
094793d7dec2871ad633d01aff1ea2619f3a2331 | CarbonComputed/neural | /build/lib/neural/utilities.py | 437 | 3.5 | 4 | __author__ = 'Kevin Carbone'
def abstractMethod():
""" This should be called when an abstract method is called that should have been
implemented by a subclass. It should not be called in situations where no implementation
(i.e. a 'pass' behavior) is acceptable. """
raise NotImplementedError('Method not... |
9729a7f0bbd5af56f30aa9a72658f72ee2a16e6e | Futaacm/Team-astro | /Astro_Task1/astrotask1.py | 269 | 3.984375 | 4 | print"The program that print maximum and minimum of set of numbers"
h=input("Enter a set of numbers seperated by comma:")
k=[(h)]
bignum = max(h)
smallnum = min(h)
print "The maximum number is", bignum
print "The minimum number is", smallnum
raw_input("Press<enter>")
|
b4839a749136a1cace5be79885b0e72098fab39f | vansh1999/Python_core_and_advanced | /functions/decorators.py | 2,034 | 4.59375 | 5 | '''
Decorators in Python
A decorator is a design pattern in Python that allows a user to add new functionality
to an existing object without modifying its structure. Decorators are usually called before
the definition of a function you want to decorate.
Functions in Python are first class citizens. This means that t... |
a0b464844198fef899ad6d5f2eb2a743ee56c536 | vansh1999/Python_core_and_advanced | /OOP/firstclass.py | 646 | 4 | 4 |
class Person: # class name
def __init__(self): # initilize/constructor, self - > points to the current object that is being created , p1.name , p1.age etc.
self.name = "vansh"
self.age = 20
self.rich = "yes"
p1 = Person() # class name
print(p1.name) # access method properties
p... |
0e300dc0c38562bc3842ef23b703f79200307577 | vansh1999/Python_core_and_advanced | /main function/mainfun.py | 995 | 4.0625 | 4 | # def main():
# print("hello world")
# print("guru99")
# main()
'''
function "if__name__== "__main__".
When Python interpreter reads a source file, it will execute all the code found in it.
When Python runs the "source file" as the main program, it sets the special variable (__name__) to have a value ("__mai... |
1cb62233bd6389bde2c75652edf8bd3e361ff236 | vansh1999/Python_core_and_advanced | /input_output_function/inputs.py | 173 | 3.953125 | 4 | num = int(input("enetr number "))
# print(num) # error
# read multiple inputs use split()
a,b,c = input().split()
print("a is {} b is {} and c is {}".format(a,b,c))
|
35435a318e2262d5b7fce50deae1fd3fa82aad48 | vansh1999/Python_core_and_advanced | /sequencedatatype/tuples/tuple.py | 715 | 4.125 | 4 | # declare a tuple
colors = ("r" , "b" , "g")
print(colors)
# tuple packaging -
# Python Tuple packing is the term for packing a sequence of values into a tuple without using parentheses.
crl = 1,2,3
print(crl)
# tuble unpackaging -
a,b,c = crl
print(a,b,c)
# Crete tuple with single elements
tupl1 = ('n') #< --... |
cab5a89fd1ff6f9be92cdc7e3669c7ea1cd4d9d5 | ruth9403/testSourceM | /source/etlProcedures.py | 1,577 | 3.546875 | 4 | # from Connection import Connection
# import os
# import numpy as np
# import pandas as pd
# con = Connection(user='DB_USER', password='DB_PASSWORD', database='DB_DATABASE')
# con = con.connect()
# con.close() #no Cierra TT_TT
#print('conection closed')
# with open('files/RAW_recipes.csv','r', newline='') as csvfile:... |
b82d71eb1dc0de047774443a519425cf5bb85605 | yadielc/algorithms | /hackerRank/python/textallignment.py | 1,273 | 4.09375 | 4 | '''
https://www.hackerrank.com/challenges/text-alignment/problem
Author: Yadiel F. Cabrera
textallignment.py
Text Allignment HackerRank Problem Solution in Python
Instructions:
You are given a partial code that is used for generating the HackerRank Logo of variable thickness.
Your task is to replace the blank (_____... |
41f00b7803fc3c00dab03484f88a7ed87c4e2336 | yadielc/algorithms | /hackerRank/python/nestedlists.py | 1,198 | 3.828125 | 4 | '''
nestedlists.py
Nested Lists HackerRank Challenge In Python
The task is to write a program that displays the second
lowest grades that the students received, given a set of students
However, more than 1 student can receive the second lowest grades.
Thus, the output must be a sorted list of the names of the students... |
7eb74afb08d34791556405398ea2105617b79d4b | yadielc/algorithms | /hackerRank/python/whatsyourname.py | 438 | 3.859375 | 4 |
'''
whatsyourname.py
What's Your Name: HackerRank Challenge Problem Solution
https://www.hackerrank.com/challenges/whats-your-name/problem
Instructions:
Input Format
The first line contains the first name, and the second line contains the last name.
Output Format
Print the output as mentioned above.
'''
def print... |
79f68842fcc5b2098074d5d9d3b1d1f19eaf6c98 | jkxruby/fluent_python | /chapter1.py | 7,051 | 4.09375 | 4 | '''
# 1.1 python风格的纸牌
import collections
from random import choice # 内置的随机选元素模块
Card = collections.namedtuple('Card', ['rank', 'suit']) # 一个元组(点数,花色)
class FrenchDeck:
ranks = [str(n) for n in range(2,11) ] + list('JQKA') # list('123')结果就是['1','2','3'],本质上为2个list相加
suits = 'spades diamonds clubs hearts'.... |
02f42d9c69c3ab2b7dec8c56333af234ae75da7a | chenPerach/Open-Vision | /libs/geometry/point.py | 755 | 4.21875 | 4 | import math
class vector:
"""
a simple class representing a vector
"""
def __init__(self,x:float,y:float):
self.x = x
self.y = y
def __add__(self,vec):
return vector(self.x - vec.x,self.y - vec.y)
def size(self):
return math.sqrt(math.pow(self.x,2) + mat... |
4e204edef152793478e4542acf5d1f5b7fa27390 | resturp/admserver | /templates/testTemplate.py | 565 | 3.609375 | 4 | """ TestCase with Methods that invoke the programmed exercise and
assert some state. All methods with leading _ underscores will
not be run autonomic during a test. Test methods are run in
random order so isolate them from each other."""
import unittest
class TestClass(unittest.TestCase):
def setUp... |
3bf0c59b4e8de01aa4e7196ca6ba9a75bf21c2d6 | gbataille/GregsSandbox | /CodeGame/ProjectEuler/44.Pentagon.py | 758 | 3.5 | 4 | #!/usr/local/bin/python3
# Not my solution. I was forcing myself to use iterators and generators but the
# way I coded it, that meant O(n^4) I guess now that I think about it.
# This however is O(n^2) only
def main():
# dSolution()
def pe44():
ps = set()
i = 0
while True:
i... |
14c00a061015e3b37db7def2bd9a93c952c09538 | gbataille/GregsSandbox | /CodeGame/ProjectEuler/56.py | 437 | 3.5625 | 4 | #!/usr/local/bin/python3
from functools import reduce
def maxDigitalSum():
maximum = 0
for a in range(1, 100):
for b in range(1, 100):
num = a ** b
digitalSum = reduce(
lambda x, y: x + y,
map(int, list(str(num))))
maximum = max(maxim... |
cc567424f2f9cc997f18864514044951935a06c7 | gbataille/GregsSandbox | /CodeGame/Hackerrank/2016_Python/arraysAndSorting/quicksort4.py | 1,383 | 3.984375 | 4 | #!/usr/local/bin/python3
#https://www.hackerrank.com/challenges/quicksort4
import sys
qcount = 0
icount = 0
def main(argv = None):
if argv is None:
argv = sys.argv
n = int(input())
ar = list(map(int, input().split(' ')))
global qcount
global icount
iar = ar[:]
quicksort(ar)
... |
aa6ac48319d2bc544574d9f4e20b5964e610cd26 | gbataille/GregsSandbox | /CodeGame/Hackerrank/2016_Python/warmup/manasaAndStones.py | 585 | 3.546875 | 4 | #!/usr/local/bin/python3
import sys
def main(argv = None):
if argv is None:
argv = sys.argv
T = int(input())
for t in range(0,T):
nbStone = int(input())
incA = int(input())
incB = int(input())
solutions = set([0])
for i in range(1, nbStone):
newSolution = set()
... |
7db98d89320026d39aafd770cf9840fca367031d | gbataille/GregsSandbox | /CodeGame/Hackerrank/2016_Python/warmup/LoveLetter.py | 506 | 3.6875 | 4 | #!/usr/local/bin/python3
from math import fabs
def readCase1():
a = input()
return a
def readCase2():
a = input()
b = input()
return a, b
def readCase3():
a = input()
b = input()
c = input()
return a,b,c
T = int(input())
for t in range(0, T):
word = list(readCase1())
moves ... |
ce2732b76243dd79924bc286f8cd726760300750 | evroandrew/python_tasks | /tests/test_task5.py | 4,028 | 3.578125 | 4 | import unittest
import task5
class TestNumberInWords(unittest.TestCase):
"""
This class tests task5.py
"""
def test_representation(self):
self.assertEqual(str(task5.NumberInWords(0)), 'ноль')
self.assertEqual(str(task5.NumberInWords(1)), 'один')
self.assertEqual(str(task5.Numb... |
8b22fc6b4b4f6b3cf28f7c2b3dfc1f03ac301fb4 | evroandrew/python_tasks | /task8.py | 2,322 | 4.21875 | 4 | import argparse
MSG_INFO = 'To output Fibonacci numbers within the specified range, enter range: '
MSG_ERROR = 'Use any numbers, instead of you entered.'
MSG_FIRST_ELEMENT = 'Enter first argument of range: '
MSG_SECOND_ELEMENT = 'Enter second argument of range: '
ERRORS = (argparse.ArgumentError, TypeError, argparse.A... |
1ea533434d5516c65b5392be7ddfabdc125c89f3 | evroandrew/python_tasks | /_numberpairs.py | 449 | 3.890625 | 4 | import argparse
import sys
def make_print_pairs_of(n):
def print_pairs_of(*args):
x = args
for item1 in range(len(x)):
for item2 in range(item1 + 1, len(x)):
if x[item1] + x[item2] == n:
print(f'{x[item1]}+{x[item2]}')
return print_pairs_of
de... |
31620eac34244edac47755a4437bfc204a5a764e | Devejya/AstroPhysics | /A1/q1_4.py | 843 | 3.765625 | 4 | import math
def max_altitude(delta: list, observatory: str) -> float:
''' '''
if observatory == "GN":
beta = 19.8238
if observatory == "GS":
beta = -30.24075
delta_radians = math.radians(delta[0] + delta[1]/60 + delta[2]/(60*60))
beta_radians = math.radians(beta)
return math.deg... |
e22bab6abd3b9fed4538d4903f35eed042518dc0 | luzerochen/MobileNet_pytorch | /mobilenet.py | 4,312 | 3.515625 | 4 | # coding=utf-8
import torch
import torch.nn as nn
class DepthwiseSeparableConv(nn.Module):
"""DepthwiseSeparableConv
Implement of depthwise separable convolution
Args:
in_channels: Number of channels in the input data
out_channels: Number of channels produced by the convolution
... |
2816461ff39b0817fa813e825e7a69d710e0d5c9 | mbwreath/some-pig | /some_pigs.py | 331 | 3.734375 | 4 | from random import randint
def one_round(total, strategy):
round = 0
while True:
value = randint(1,6)
round = round + value
if value == 1:
round = 0
print('your turn is over')
break
#build strategy logic and when to stop/keep rolling
re... |
ea7ff1c884df00744d8b745158b129e81375652d | seemantKaul/AdventOfCode_2020 | /Problem2.py | 1,548 | 3.921875 | 4 | def problem2(list_input_2):
valid_count = 0
for entry in list_input_2:
min_count = 0
max_count = 0
actual_count = 0
char_to_check = ''
password_string = ''
count_str, char_to_check, password_string = entry.split()
min_count, max_count = [int(x) for x in co... |
a43eb0eb665e5e3657983b0afa535755f983678f | seemantKaul/AdventOfCode_2020 | /Problem3.py | 1,994 | 4.0625 | 4 | def problem3_part1(grid, step_right=3, step_down=1):
tree_count = 0
current_point = (0, 0)
# While we are not out of the depth of the grid, keep calling Move to change the current point
# and check if the current point is a tree. if so, increase the tree count.
while current_point != 'Done':
... |
f493557f7a9ecb3393d8ab4c68de61e5fc1f6250 | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /Pratice_python/zero.py | 113 | 4.1875 | 4 | num=int(input("enter the num"))
while num<0 or num>0:
print("infinte loop")
break
else:
print("stop") |
64b18d4c4baed3c93e024b6eb655cfecd9801ab4 | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /funcation_Python/add.py | 151 | 3.765625 | 4 | def add_list(list1,list2):
i=0
while i<len(list1):
print(list1[i]+(list2[i])
i+=1
add_list([2,4,7,9],[4,8,9,9])
|
165847c23fff39b00cccfa066593797fcdfc6dca | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /Python-Recursion/binarysearch.py | 954 | 3.90625 | 4 | def f(n,l):
l.sort()
if len(l) == 0:
return False
elif len(l) == 1:
if n == l[0]:
return True
else:
return False
else:
a = l[:len(l)/2]
b = l[len(l)/2:]
mid = len(b) + (len(a) - len(b))/2
c = l[mid]
if c == n:
... |
91353b7a1deb7599a56262ddcc0a4e8c5373e29d | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /funcation_Python/debuging1.py | 695 | 3.796875 | 4 | # def sum():
# print(12+13)
# sum()
# def welcome():
# print("Welcome to function")
# welcome()
# def isEven():
# if(12%2==0):
# print("Even Number")
# else:
# print("Old Number")
# isEven()
# def calculate_sum(a,b):
# sum = a+b
# print(sum)
# calculate_sum(4,5)
... |
1523565a6a4122ecb89f998ece772228ffd0faef | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /ifelse_python/ifelse.py | 187 | 4.03125 | 4 | lenghth=int(input("enter the lenghth"))
breath=int(input("enter the breath"))
if lenghth==breath:
print("it is squere")
else:
print("it is rectangle")
|
1d09ecbc161cee60e88019b28509c20dfd041b1c | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /funcation_Python/kbc.py | 2,154 | 3.734375 | 4 | # print("*****swagat hai aap ka kon banega karorpati*****")
# print(" ")
# print(".......yeh rha question aapki screen par.........")
def kbc(question,option,i ,t1,lol,count,solution):
i = 0
while i<len(question):
print(question[i])
j=0
k=1
while j<len(option)... |
9c9c562ac2a07f66c4d4202ea003f9ed308c0d5a | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /ifelse_python/char.py | 413 | 4.25 | 4 | char=str(input("enter the char"))
if char>="a" and char<="z" or char<"A" and char<="Z":
print("it is char")
number=float(input("enter the number"))
if number>=0 and number<=200:
print("it is digit")
specialchar=input("enter the specialchar")
if specialchar!=char and specialchar!=number:
... |
aad6088e046f4b4f333441f26ed6a65d50f260a3 | Praveen-Kumar-Bairagi/Python_Logical_Quetions | /ifelse_python/prime.py | 883 | 4.15625 | 4 | # num=int(input("enter the num"))
# if num==1:
# print("it is not prime number")
# if num%2!=0:
# print("it is prime number")
# if num%5!=0:
# print("it is prime number")
# else:
# print("it is prime number")
Sex = input("enter sex M\F")
material_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.