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 |
|---|---|---|---|---|---|---|
e03f78c339aeb34ea23518d796d20d7148dcf2f1 | ascaniopy/python | /Modulo III/aula018-listasParte2.py | 367 | 3.703125 | 4 | teste = list()
teste.append('Gustavo')
teste.append(40)
galera = list()
galera.append(teste[:])
teste[0] = 'Maria'
teste[1] = 22
galera.append(teste[:])
print(galera)
print()
pessoas = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
print(pessoas)
print(pessoas[0])
print(pessoas[0][0])
print(pessoas[2][1]... |
2af35c6d05e3ad0c1ecb905970a4e4367ee8adb8 | ascaniopy/python | /exerciciosModuloIII/ex072-numeroExtensoTupla.py | 254 | 3.875 | 4 | cont = ('zero', 'um', 'dois', 'três', 'quatro')
while True:
num = int(input('Digite um número entre o e quatro: '))
if 0 <= num <= 4:
break
print('Tente novamente. ', end='')
print('Você digitou o número {}'.format(cont[num]))
|
d00daf6b8c5b196f2f0ad6d1656bfb28645a8d84 | meluzoff97/algorithms | /bfs.py | 386 | 3.71875 | 4 | def bfs(graph, x, y):
queue = [x]
checked = []
while queue:
v = queue.pop(0)
if v == y:
return True
else:
if not v in checked:
queue.extend(graph[v])
checked.append(v)
return False
#simple_graph = {'A' : ['B', 'C'],
# 'B' : ['D', 'C'],
# 'C'... |
3a9375c560290cf76d38ffd6fa38ceaa2d21343f | SynyukV/pythoniasa19fall | /assignment01a.py | 585 | 3.859375 | 4 | """
Assignment 1-A
==============
"""
this = ['house that Jack built.', 'malt', 'rat,', 'cat,', 'dog,',
'cow with the crumpled horn,', 'maiden all forlorn,',
'man all tatter\'d and torn,', 'priest all shaven and shorn,',
'cock that crow\'d in the morn,', 'farmer sowing his corn,']
that = ['lay... |
05127e23c3e2425b9210aba95e87384d1caf8100 | PhilipokTheCat/basic-data-structures | /counted-sort.py | 351 | 3.65625 | 4 | def countedSort(arr):
length = len(arr)
helpArr = [0]*length
for elem in arr: helpArr[elem] += 1
temp = 0
for i in range(length):
if helpArr[i] > 0:
arr[temp:temp + helpArr[i]] = [i]*helpArr[i]
temp += helpArr[i]
return arr
arr = [7, 3, 5, 5, 3, 7, 7, 3, 5, 5]
ar... |
265462e6a06f4b50a87aecb72e05645d2a62d5e1 | danriti/project-euler | /problem019.py | 1,498 | 4.15625 | 4 | """ problem019.py
You are given the following information, but you may prefer to do some research
for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September, April, June and November. All the rest have
thirty-one, Saving February alone, Which has twenty-eight, rain or shine.
And on leap years, twenty-ni... |
c4e1d6502b7a74a38019d7212c742146aedc737c | danriti/project-euler | /problem009.py | 429 | 3.9375 | 4 | #!/usr/bin/python
def find_pythagorean_triplet():
for a in xrange(1, 1000):
for b in xrange(1, 1000):
for c in xrange(1, 1000):
if ((a < b) and (b < c)) and \
((a + b + c) == 1000) and \
((a**2 + b**2) == c**2):
return [a... |
78ea640e7ed26f565f25a4f149a794a6dde41392 | dalek7/Undergrad-707005-2017Fall | /tensorflow/00-4-matmul.py | 456 | 3.625 | 4 | # coding: utf-8
# 717005
# placeholder를 이용한 행렬 연산
import tensorflow as tf
x = tf.placeholder("float", None)
x2 = tf.placeholder(tf.float32, shape=[2, 2])
y1 = x * 2
c1 = tf.constant([[1.0, 1.0], [0.0, 1.0]])
y2 = tf.matmul(x2, c1)
with tf.Session() as session:
result = session.run(y1, feed_dict={x: [1, 2, 3]})
... |
a24a4df5e217ad5b9ced60873a78c746041906ca | MiracleShadow/Comparative-Analysis-of-Network-Novels-and-Traditional-Novels | /天龙八部/tlbb_analysis/analysis_1.py | 930 | 3.671875 | 4 | # 定义字典类型来存储分词的结果,sort_list存放排序后的结果,STOPWORDS是进一步要忽略的词
words_dict = {}
STOPWORDS = []
# 写入要屏蔽的词库STOPWORDS
sort_list = []
fp = open("hanyu2.txt", "r")
for i in fp.readlines():
word = i.strip()
if len(word) > 1:
STOPWORDS.append(word)
fp.close()
# 在jieba分词的结果里,统计每个词出现的情况,如果不在屏蔽词库里,就写入字典里
fp = open("words... |
97f18e64f7642414b53c112f33b4a66d9c840c3f | Schpadel/Text_Based_Browser_Python | /Topics/Stack in Python/Matching brackets/main.py | 354 | 3.796875 | 4 | # put your python code here
import sys
from collections import deque
stack = deque()
text = input()
text.replace(" ", "")
for char in text:
if char == "(":
stack.append(char)
if char == ")":
if not stack:
print("ERROR")
sys.exit()
stack.pop()
if stack:
pri... |
c1d4d6f0b5cc0515d2861c6bb5914f4d7ac87741 | skskdmsdl/python-study | /09. Exception/4. finally.py | 1,379 | 3.65625 | 4 | # finally
# 에러가 발생하든 하지 않든 무조건 실행되는 구문
class BigNumberError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
print("한 자리 숫자 나누기 전용 계산기입니다.")
num1 = int(input("첫 번째 숫자를 입력하세요: "))
num2 = int(input("첫 번째 숫자를 입력하세요: "))
if num1 >= 10 or ... |
6761337f1559f3129efbe58a32e60da934f089f3 | skskdmsdl/python-study | /04. Data Structure/quiz_1.py | 1,318 | 3.59375 | 4 | # 당신의 학교에서는 파이썬 코딩 대회를 주최합니다.
# 참석률을 높이기 위해 댓글 이벤트를 진행하기로 했습니다.
# 댓글 작성자들 중 추첨을 통해 1명은 치킨, 3명은 커피 쿠폰을 받게 됩니다.
# 추첨 프로그램을 작성하시오.
# 조건1 : 편의상 댓글은 20명이 작성하였고 아이디는 1~20 이라고 가정
# 조건2 : 댓글 내용과 상관 없이 무작위로 추첨하되 중복 불가
# 조건3 : random 모듈의 shuffle 과 sample 을 활용
# (출력 예제)
# -- 당첨자 발표 --
# 치킨 당첨자 : 1
# 커피 당첨자 : [2, 3, 4]
# -- 축하합... |
d58ab7520143006e9345212643cb7b6a8781b049 | riley-csp-2019-20/1-1-5-buggy-code-Conor85750 | /115conordycus.py | 730 | 3.71875 | 4 | import turtle as trtl
body = trtl.Turtle()
body.pensize(40)
body.circle(20)
numberlegs = 8
leglong = 90
distance = 369 / numberlegs
body.pensize(5)
loop = 0
while (loop < numberlegs):
body.goto(0,20)
body.setheading(distance*loop)
body.forward(leglong)
loop = loop + 1
body.penup()
body.go... |
fad70892a12c35fd48288c722ec224e7c2b002b1 | YHELDY/jhrbrguo | /tarea2.py | 174 | 3.6875 | 4 | a= int(input("intruduzca la hora: "))
b= int(input("intruduzca el minuto: "))
c= int(input("intruduzca el segundo: "))
x=c+1
print("la hora actual es: ")
print (x)
|
8ebbaad380f8bd22d5c0837b0f5c9c81c7107ee4 | yash1th/hackerrank | /python/Collections/Collections.deque().py | 345 | 3.75 | 4 | from collections import deque
d = deque()
for _ in range(int(input())):
command = input().split()
if 'append' in command:
d.append(int(command[1]))
elif 'appendleft' in command:
d.appendleft(int(command[1]))
elif 'pop' in command:
d.pop()
elif 'popleft' in command:
d.... |
ae99ba05dfed268a96cf36014ece74a6dc8ad58c | yash1th/hackerrank | /python/strings/Capitalize!.py | 418 | 4.125 | 4 | def capitalize(string):
return ' '.join([i.capitalize() for i in string.split(' ')])
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string)
# s = input().split(" ") #if i use default .split() it will strip the whitespace otherwise it will only co... |
92662a366677a1ab6769c3ff7f475f242f4dabd5 | yash1th/hackerrank | /python/strings/String Formatting.py | 417 | 4.09375 | 4 | def print_formatted(number):
# your code goes here
width = len(bin(n).split('b')[1]) #newbies might get an error here, as it should be length
for i in range(1,number+1):
print("%s %s %s %s"%(str(i).rjust(width), oct(i).split('o')[1].rjust(width),hex(i).split('x')[1].upper().rjust(width),bin(i).spli... |
10d5aa766d32346f98c565fb9cb94e235fb41b68 | yash1th/hackerrank | /regex/applications/saying hi.py | 157 | 3.796875 | 4 | import re
n = int(input().strip())
my_regex = r'^[hH][iI]\s[^dD]'
for _ in range(n):
s = input().strip()
if re.search(my_regex, s):
print(s) |
89d361d8c25962d991f4b3898d4c6eed5f316adc | yash1th/hackerrank | /regex/applications/hackerrank tweets.py | 189 | 3.546875 | 4 | import re
n = int(input().strip())
my_regex = r'hackerrank'
total = 0
for _ in range(n):
s = input().strip()
if re.search(my_regex,s,re.IGNORECASE):
total += 1
print(total) |
58e8932f9f57696ee4c1913aa9b287394602c5fe | smaaland/python-sandbox | /adventofcode/2016/day8.py | 1,342 | 3.609375 | 4 | def shift(s, val):
val %= len(s)
return s[-val:] + s[:len(s) - val] if val != 0 else s
def pretty_print(matrix):
for y in range(6):
s = ''
for x in range(50):
if matrix[y][x] == 1:
s += '█'
else:
s += ' '
print(s)
with open(... |
5f8420471184b3574180172a273948bd9cf2f814 | smaaland/python-sandbox | /adventofcode/2016/day10.py | 2,091 | 3.625 | 4 | bots = {}
outputs = {}
instructions = []
stop = False
def execute(instruction):
global stop, outputs
if instruction[2] == 'goes':
if not int(instruction[5]) in bots.keys():
bots[int(instruction[5])] = []
bots[int(instruction[5])].append(int(instruction[1]))
# print('EXECUTE... |
405a9b32fdf117a05b4213b2f839c0c0684996df | smaaland/python-sandbox | /adventofcode/2019/day2.py | 1,058 | 3.53125 | 4 | import copy
from typing import List
def compute(data: List[int]):
index = 0
while data[index] != 99:
if data[index] == 1:
data[data[index+3]] = data[data[index+1]] + data[data[index+2]]
elif data[index] == 2:
data[data[index+3]] = data[data[index+1]] * data[data[index+2... |
145c8d6ed0abaad7e37f7b66f6f0428e4afc4379 | smaaland/python-sandbox | /adventofcode/2022/day8.py | 1,719 | 3.546875 | 4 | lines = [line.strip("\n") for line in open("input8.txt", "r").readlines()]
visible = set()
scenic_scores = []
for y in range(len(lines)):
highest = -1
for x in range(len(lines[y])):
if int(lines[y][x]) > highest:
visible.add((y, x))
highest = int(lines[y][x])
highest = -1
... |
6b8852a62b3016ce923843205d8e9ff98d8f3352 | woodenToaster/1d_wave | /1d_wave.py | 2,742 | 3.515625 | 4 | # The exercise involves solving a discretized wave equation in 1d with absorbing
# boundary layers (known as perfectly matched layers [PML]). The finite-difference
# equation for this example can be found in the attached write up [third equation
# from the top of page 3 in Section 4 "Finite-difference method", right af... |
f769739ee3dee1352cce954888cbeb7c62ca76a9 | shubhamku044/snake-game | /snake.py | 1,275 | 3.828125 | 4 | from turtle import Turtle
POSITIONS = [(0,0), (-20 ,0)]
MOVE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segment = []
self.create_snake()
self.head = self.segment[0]
def create_snake(self):
for i in POSITIONS:
self.add_s... |
4266aa5287f9942306e992d67c1849d013c32aa6 | nurtai00/WebDevPython | /codingbat/string-2/5.py | 206 | 3.703125 | 4 | def twostr(a, b):
la = len(a)
lb = len(b)
if a == b[len(b) - la: len(b)] or b == a[len(a) - lb: len(a)]:
return True
else:
return False
print(twostr('Hiabc', 'abc')) |
491df229094dbed9501b73f19ef2cb0d876317d6 | nurtai00/WebDevPython | /codingbat/logic-2/2.py | 323 | 3.875 | 4 | def summ(a, b, c):
if a != b and a != c and b != c:
return a + b + c
elif a == b and a != c and b != c:
return c
elif a != b and a == c and b != c:
return b
elif a != b and a != c and b == c:
return a
elif a == b == c:
return '0'
print(summ(2, 2, ... |
22143cffcdc06d7cdb1f62bbe40ed95b2e3534a9 | nurtai00/WebDevPython | /codingbat/list-2/2.py | 159 | 3.578125 | 4 | def bigdif(a):
for i in range(len(a)-1):
maximum = max(a)
minimum = min(a)
return maximum - minimum
print(bigdif([10, 3, 5, 6])) |
b73bfc9388ec75ada0728b86304d0f3c9f9c4ba1 | nurtai00/WebDevPython | /codingbat/warmup-2/6.py | 162 | 3.640625 | 4 | def array_count(n):
count = 0
for i in n:
if i == 9:
count = count + 1
return count
print(array_count([5, 8, 9, 5, 9, 7])) |
f02a8bcf8b488c8f486dd1751ce06e43abc63d16 | nurtai00/WebDevPython | /hackerrank/11.py | 88 | 3.71875 | 4 | st = input()
for i in st[:].split():
st = st.replace(i, i.capitalize())
print(st) |
cdf2a238e98bcef9710d1a4c60290c62b587790b | nurtai00/WebDevPython | /codingbat/string-1/5.py | 133 | 3.765625 | 4 | def lasttwo(n):
size = len(n)
if size < 2:
return "incorrect"
return n[size-2:] * 3
print(lasttwo('Nurtay')) |
946f972a2edbea1449a7b1fcada3cbd1b160e33d | welkerCode/MachineLearning-OnlinePerceptron | /stochasticGradientDescent.py | 2,949 | 3.890625 | 4 | '''
Implement the batch gradient descent alg and tune r to find convergence
Convergence can be found by examinging the norm of the weight vector difference ||w_t-w_(t-1)|| at each step t.
If ||w_t-w_(t-1)|| < 1e-6, then converges.
Weight vector is initialized to 0
Start with high r, and decrease by half each time u... |
c0534e0b230f8815c398833c14617b8ea347c6c0 | NABA-OL/DibujoFigurasPy | /Figuras.py | 3,764 | 3.65625 | 4 | import math
from tkinter import*
import tkinter as tk
"""NABA-OL"""
class Figura:
global coordenadas
global coordenadasy
global coordenadasx
def posicion(event):
coordenadasx.append(event.x)
coordenadasy.append(event.y)
ventana.create_oval(event.x-1,event.y... |
49012415276aabc0582600b8a2b2d0d2d544be3f | krj9cr/Hybrid-Prim-Dijkstra-GUI | /Node.py | 429 | 3.59375 | 4 |
import sys
### Node Class ###
# x,y : coordinates in the 2d plane
# i : unique index/identifier
# key : min path or cost of edges so far
# parent : previous Node, used to create output edges
class Node(object):
def __init__(self,x,y,i):
self.x = x
self.y = y
self.idx = i
self.key = sys.maxint
se... |
75fd95c444c62bb23966b81c57a1b4f78e4aba2b | JBarckley/Project-Euler | /Problem_17.py | 2,268 | 3.515625 | 4 |
def tensdigit(n):
ten = 3
twenty = 6
thirty = 6
forty = 5
fifty = 5
sixty = 5
seventy = 7
eighty = 6
ninety = 6
digit = {
1: ten,
2: twenty,
3: thirty,
4: forty,
5: fifty,
6: sixty,
7: seventy,
... |
99b802275a1d87df0e96dc447a50afd7399cc606 | Himanshi-925/Python | /area of square.py | 123 | 4.21875 | 4 | # program for finding area of a square
a = int(input('Side of square= '))
area = a**2
print('Area of square is = ',area) |
d11093f223c4c6c0d62cd213643ee66a25bbf508 | rpassas/python_projects | /scrabble/scrabble.py | 7,247 | 4.03125 | 4 | '''
Robert Passas
CS5001
Lab 11 - Scrabble
given letter and number of outputs command returns highest score scrabble
words (length of words can also be modified)
'''
import string
SCORES = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4,
'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, '... |
baff8f798c16731e41a1aecbd4d2a9fd990bb593 | rpassas/python_projects | /ciphers/substitution.py | 3,082 | 4.34375 | 4 | '''
Robert Passas
CS5001
hw9 - substitution.py
encrypt and decrypt functions implement the substitution cipher or reverse it
respectively as the function names indicate.
'''
import utils
import string
def encrypt(text, key):
'''
Function -- encrypt
encrypts plain text by replacing letters according to the... |
481bd0f56ca501ae763b1d013fdb634b62e624cd | HwiLu/python-player | /按行读取文件并去掉换行符.py | 261 | 3.59375 | 4 | #coding=utf-8
#!/usr/bin/env python
#1
for line in open('/tmp/hello.txt'):
line=line.strip('\n')
print line
print "\n"
#2
fo = open("/tmp/hello.txt", "r")
for line in fo.readlines():
line=line.strip('\n')
print line
fo.close
|
23b10c277a1632f5a41c15ea55f8ca3598cf43c5 | FredericoIsaac/Case-Studies | /Data_Structure_Algorithms/code-exercicies/queue/queue_linked_list.py | 1,696 | 4.28125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
# Attribute to keep track of the first node in the linked list
self.head = None
# Attribute to keep track of the last node in the linked list
self.ta... |
7eeeb7da9d886f806286130d1e2d132a24863965 | FredericoIsaac/Case-Studies | /Data_Structure_Algorithms/code-exercicies/trees/lucid_programming_channel/tree_traversal.py | 9,113 | 4.28125 | 4 | # Source: https://github.com/vprusso/youtube_tutorials/tree/master/data_structures/trees/binary_trees
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
... |
21a6c8ac1b62f8faa8433611edbdb06abdac3ac3 | FredericoIsaac/Case-Studies | /Data_Structure_Algorithms/code-exercicies/queue/queue_array.py | 3,082 | 4.03125 | 4 | class Queue:
def __init__(self, initial_size = 10):
# Create an array of the size predifined
self.arr = [0 for _ in range(initial_size)]
# Indicate the next element in the queueu, the next FREE slot (the first element is 0)
self.next_index = 0
# Indicates the front of the que... |
a3a2d2bedc8c26563125c13f6dec693c28083979 | Chenqiqi0829/PycharmPython | /examples/test_judgeday_base_yearmonthday.py | 1,734 | 3.84375 | 4 | #coding=utf-8
class test_judgeday_base_yearmonthday:
year=""
month=""
day=""
actoryDay=""
def years(self):
print("请输入年份:")
ye=input()
if ye.isdigit():
if int(ye)%4==0:
return 0
else:
return 1
else:
... |
ab94ab7651d9fe7344057a6c1f362579c007b011 | daviespaulwork/Codecademy-Projects | /Pokemon-Master/pokemon.py | 6,534 | 4.03125 | 4 | import math
class Pokemon:
def __init__(self, name, type, level=1):
#Constructor
self.name = name
self.type = type
self.level = level
self.is_knocked_out = False
self.max_health = 10*(self.level**2)
self.health = self.max_health
... |
a5c4ff197e096d038bd635bc8fe50ce353269b07 | Ledicia/Tute | /Baraja.py | 3,782 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 10:40:41 2020
@author: ledicia.diaz
"""
import numpy as np
import random
class Carta:
# Constructor del objeto carta
def __init__(self, palo, numero):
if not 0. < numero < 13.:
raise TypeError('Número de carta incorrecto')
if not p... |
a8d9b9b4bec86e706de198ee2cf8dcf8cd9a23c2 | tiimoS/sma | /centrality/degree_centrality.py | 1,287 | 3.5625 | 4 | import networkx as nx
from collections import defaultdict
graph = nx.Graph()
community_top_users = defaultdict(list)
nr_top_users = 2
def top_users(graph_network, communities):
"""
Returns the n top users (in our case n=2) with the highest old_centrality degree from each community.
:param communities: li... |
ed33b438ba89ede776a04565e7badc4e0a2e9cf8 | Dheeraj-1999/interview-questions-competitve-programming | /python/programs python/classobjdct1.py | 387 | 3.75 | 4 | class vehicle:
def enter(self):
self.number=input("enter vehicle number:")
self.owner=input("enter owner name")
self.phone=input("enter owner phone")
def print(self):
print(self.number)
print(self.owner)
print(self.phone)
a1=vehicle()
a1.enter()
a1.print()
... |
f56f8e18f05ebccfc96c129d7e88fef512b2ec48 | Dheeraj-1999/interview-questions-competitve-programming | /Comp pro qus and sol/gfg/placement series/Arrays/21.1 find duplicates done me.py | 285 | 3.59375 | 4 | def duplicates(arr, n):
d = {}
l = []
for i in arr:
d[i] = 0
for i in arr:
d[i] += 1
for i in range(n):
if(d[arr[i]] > 1):
l.append(arr[i])
d[arr[i]] = 1
if(len(l) == 0):
l.append(-1)
return sorted(l) |
da1bc5dff342e9a4bb1f04290df23e38b1e3b4a9 | Dheeraj-1999/interview-questions-competitve-programming | /Comp pro qus and sol/gfg/placement series/Arrays/15 Merge sorted arr Without Extra Space.py | 1,049 | 3.890625 | 4 | def swap(a, b):
a, b = b, a
def mergeSorted(arr1, arr2, n, m):
flag = False
if(n < m):
arr1, arr2 = arr2, arr1
n ,m = m, n
flag = True
# print(arr1, arr2)
p1 = n-2
p2 = m-1
# k = n+m
last = arr1[n-1]
for i in range(n-2, -1, -1):
if(n <= 2):
... |
eeb45950eed6cf29c3f924e53dac533041331546 | Dheeraj-1999/interview-questions-competitve-programming | /python/programs python/p1.py | 182 | 3.65625 | 4 | k=1
for i in range(4,0,-1):
for j in range(1,5):
if k>=i:
print(k,end=" ")
else:
print(" ",end=" ")
k=k+1
print("")
k=1
|
d7a90e4dff61885b81168bd1846fe26503c50c01 | Dheeraj-1999/interview-questions-competitve-programming | /python/programs python/nameroll using oop.py | 585 | 3.65625 | 4 | class students:
def __init__ (self):
self.roll=input("enter roll number of student:")
self.name=input("enter name of student:")
def file(self):
f=open("myfil.txt","a")
f.writelines("\nROLL:\t"+str(self.roll)+"\tNAME:\t"+str(self.name))
def exit(self):
self.opt=i... |
038ff39c204885a69feed2dd2d296558c3135886 | Dheeraj-1999/interview-questions-competitve-programming | /Comp pro qus and sol/hackerrank interview preperation kit/arrays/megaprime 2 approaches/megaprime simple seive.py | 1,162 | 4.03125 | 4 | # Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
def SieveOfEratosthenes(a, n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in ran... |
bb1bb692aa10210552cfffefbd639a311e24f475 | Dheeraj-1999/interview-questions-competitve-programming | /python/programs python/2d matrix.py | 145 | 3.546875 | 4 | l=[[1,2,3],[4,5,6]]
result=[[l[rows][colomn] for rows in range(len(l))] for coloumn in range(len(l[0]))]
for i in result:
print(i)
|
2e06b390ce1fe94a900cd5b343a444fd3557a6e4 | xjtuwj/PAT-Advanced-Level-Practice | /Practice/1031-1040/1032 Sharing (25).py | 932 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
#input
Start = input("").split(" ")
Start[2] = int(Start[2])
Store_pre = []
Store_next = []
for i in range(Start[2]):
temp = input("").split(" ")
Store_pre.append(temp[0])
Store_next.append(temp[2])
Start1 ... |
b30882c67606fdbf4cf2c33215a6757aa34c6f9d | hammadasad/Neural-Networks-From-Scratch | /NNBackPropogate.py | 2,584 | 3.953125 | 4 | from numpy import exp, array, random, dot
class NeuralNetwork():
def __init__(self):
# Seed the random # generator, so it generates the same numbers every time the program execs
random.seed(1)
# Model 1 Neuron with 3 Inputs & 1 Output
# Assign random weights to a 3 x 1 matrix with... |
dd512fde1923091c850b83fcb8093a182372517b | Sakthimadhu/python2 | /p4.py | 77 | 4.0625 | 4 | a = int(input(" "))
b = a % 2
if (b>0):
print("Odd")
else:
print("Even")
|
47c23c5a49886e7f53d543246a5944e6b13b12a2 | joshisujay1996/iot-devices | /Connected_project/pi/acctuator.py | 551 | 3.53125 | 4 | #importing smtp library
import smtplib
#this function is called when we want to send mail to someone saying the temprature is changed it takes argument to whom we want to mail
def sendmail(ToMailId):
tomail=ToMailId
#initializing smtp client
server = smtplib.SMTP('smtp.gmail.com', 587)
#loggingin to my... |
ba5c64fa71b78321f0fc87c9928aae4bf28340f5 | TahaAlTamimi/python | /lec11.py | 7,330 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 09:34:21 2019
@author: owner
"""
from tkinter import *
from tkinter import messagebox
from tkinter import scrolledtext
from tkinter.colorchooser import *
# =============================================================================
# par=Tk()... |
eaafe8eb89fd709b521f0c14ee4347f2f45349f1 | jaroabel/gui-task-manager | /main.py | 7,085 | 3.59375 | 4 | # App name: Task Manager
# Description: Task manager application, capturing task name, task date,
# task description and storing all task in a text file.
# Actions: add task, update task, delete task
# Author: Jean-Marie Abel
from tkinter import *
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
from... |
b78b9aa7c593160b8c070e094644f776b65fbd52 | fredonia88/tic_tac_toe | /play_tic_tac_toe.py | 3,456 | 4 | 4 | from random import randrange
class NumberMustBeInRange(Exception):
'''used in enter_move method -> input must be an integer'''
pass
class MoveIsTaken(Exception):
'''used in enter_move method -> move must be available'''
pass
def display_board(board):
line = '+-------' * 3 + '+'
line2 = '... |
ead11b2b8b471d2c46b61999517f2d38bedd366d | pbagal0/python-labs | /assignment5.py | 3,363 | 3.90625 | 4 | #complex number
class complex:
def __init__(self,real,imaginary):
self.r=real
self.i=imaginary
def __str__(self):
return f"({self.r},{self.i})"
def __add__(self,other):
r=self.r+other.r
i=self.i+other.i
return complex(r,i)
def __sub__(self,... |
19d88c04da25f392e92c55469f8ebac6cdb5ba1b | frostickflakes/isat252s20_03 | /python/fizzbuzz/fizzbuzz.py | 1,291 | 4.15625 | 4 | """A FizzBuzz program"""
# import necessary supporting libraries or packages
from numbers import Number
def fizz(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 3.
If it is both, return 'Fizz'.
Otherwise, return the input.
"""
return 'Fizz' if isinsta... |
43b42eadad9baeccbcd9b67ef408a6b83fe5ecd1 | Swastik2561/Python-Advance-Implementation | /threading/multiple_threads.py | 412 | 3.515625 | 4 | import threading
from threading import Thread
def odd_function():
for x in range(20):
if x%2 is not 0:
print(x)
print(threading.currentThread().getName())
def even_function():
for x in range(20):
if x%2 is 0:
print(x)
print(threading.currentThread().getName())... |
5b32a432279a57bd6661d95ae0245c9dfd8a9881 | osakhsa/decorators | /3.py | 1,030 | 3.71875 | 4 | correct_password = "qwertyuiop123"
def check_password(func):
def wrapper(*args, **kwargs):
user_password = input("Введите пароль: ")
if user_password == correct_password:
func(*args, **kwargs)
else:
print("В доступе отказано.")
return wrapper
@check_password
d... |
94b4acb561be0315c826c6bfad5f012168aa0ce0 | mugumya2/pythonHack_codes | /pwd_craker.py | 899 | 4.0625 | 4 | import random
import pyautogui
# store all possible character and number in chars variable like so
#convert string chars to a list
#get password from the user using pyaoutgui interfence
#declare guess_password to store guessed password as an empty string
#give guess_password random chars from chars_list with length o... |
c062d016b88b589ffdccaa0175269439778a8ae3 | sahil-athia/python-data-types | /strings.py | 979 | 4.5625 | 5 | # strings can be indexed and sliced, indexing starts at 0
# example: "hello", regular index: 0, 1, 2, 3, 4, reverse index: 0, -4, -3, -2, -1
greeting = "hello"
print "hello \nworld \n", "hello \t world" # n for newline t for tab
print greeting # will say hello
print greeting[1] # will say 'e'
print greeting[-1] # will... |
b7bc03d691464c02b0e0a59f520b01c8620c2f6e | AkaiChan/driving | /main.py | 429 | 4.09375 | 4 | strcountry = input("where are you from?")
intAge = input("how old are you?")
intAge = int(intAge)
if strcountry == "Taiwan":
if intAge >= 18:
print("You can go test of driving exam")
else:
print("You cannot go test of driving exam")
elif strcountry == "US":
if intAge >= 16:
print("You can go test of driving ex... |
948f44c942226e7305610cd79c084d5f5dff7f27 | lcpdeb/capstone | /H.py | 363 | 3.65625 | 4 | #!/usr/bin/env python
# encoding: utf-8
from numpy import *
def H(a,b):
D=1
# # Manhattan Distance
# return D*(abs(a[0,0]-b[0,0])+abs(a[0,1]-b[0,1]))
# Eculidean Distance
return D*(abs(a[0,0]-b[0,0])**2+abs(a[0,1]-b[0,1])**2)
if __name__ == '__main__':
a=mat([[3,4,5]])
b=mat([[4,5,6]]... |
66dbfb74fb5e4203d760aef4f5f3e6b11ccf8ad4 | AlexDnipro/TAQC_tasks | /Task4/task4.py | 4,624 | 4.03125 | 4 | """This module realizes the three-point estimation technique used in project management"""
import functools, operator
class Task():
"""
This class has 5 properties that are: Task a,m,b, E and SD.
E and SD properties are initialized with the help of Task methods 'estimate' and
'standard_deviation' corre... |
9cee845b927c2ad137bb7094c97a4859694b920a | Divij808/basic_programming_exercises | /bubble__sort.py | 240 | 3.625 | 4 | lists = [4, 22, 11, 36, 9, 14, 1]
for i in range(len(lists) - 1):
for i in range(len(lists) - 1):
if lists[i] > lists[i + 1]:
p = lists[i + 1]
lists[i + 1] = lists[i]
lists[i] = p
print(lists) |
80338a9ae77a07f34f570ab5af53f0eabb3c277a | Divij808/basic_programming_exercises | /basic_command_line_calulator.py | 873 | 4.25 | 4 | import re
import math
calculator = input("enter math equation")
match = re.search(r'(\d+)(.+?)(\d+)', calculator.strip())
if match is None:
print("Do not know the maths equation")
else:
first = int(match.group(1))
second = match.group(2).strip()
third = int(match.group(3))
if second.strip() == "*"... |
27e9ed54777c84fb06243940dc3d289c7e05c32f | kaixih/learn_tensorflow | /mnist/mlp.py | 1,650 | 3.515625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
sess = tf.Session()
data_dir = 'MNIST_data/'
mnist = input_data.read_data_sets(data_dir, one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validat... |
a927276420d93eb0d125e29c3c878513a639e3cb | bmyerz/iowa-computer-science-methods | /arduino/BlinkLED.py | 618 | 3.875 | 4 | from arduino import arduino
import time
# change COM5 to the serial port that Arduino IDE shows
board = arduino.Arduino('COM5')
# tell the board that we will use digital pin 2 as an output
board.output([2])
# digital pins are binary: they can only have two values: HIGH or LOW
# set pin 2 to high
board.setHigh(2)
# ... |
66b64080373ea535642d1f67d6088489934d132d | braunke/Wk1 | /wk1part2.py | 430 | 4.0625 | 4 | print('Provide and sentence to be changed into camelcase')
#takes the input and cahnges it to lower
sentence = input().lower().title()
#error checking
for char in sentence:
if not char.isalpha():
print('Needs to be a letter')
break
sentence = sentence.replace(' ', '')
#changes the firt character to ... |
083c1de5c4d7e2120355b2e3215a3b9b05ad2bcc | andres94o/Chem160module3 | /pbc.py | 510 | 3.703125 | 4 | from random import choice
side = 4 #number of squares, 1-D
x = 0 #x is initally zero
for i in range(30): # 30 steps
x += choice((-1, 1)) # a value for x will be chosen, randomly, between 1 and -1
if x < 0: #if x is zero and the random number chosen is -1, x will be the #3, because it has 4 squres but it starts ... |
99aa0545a9294153050941aac375e3902a830475 | ivanfarevalo/Edge_Detection | /Algorithmic_Toolbox_C1/W2_Warm_up/fibonacci_remainder.py | 1,607 | 3.890625 | 4 | # python3
# Compute the last digit of the n-th Fibonacci number.
import numpy as np
# Naive implementation, stores whole fibonnaci number, used for stress testing more efficient implementations.
def get_fibonacci_remainder_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in r... |
552fcf28cdb11a055da553046c1bef05dbc34567 | ivanfarevalo/Edge_Detection | /Algorithmic_Toolbox_C1/W3_Greedy_Algorithms/max_num_prizes.py | 943 | 4.03125 | 4 | # python3
# You are organizing a funny competition for children. As a prize fund you have 𝑛
# candies. You would like to use these candies for top 𝑘 places in a competition
# with a natural restriction that a higher place gets a larger number of candies.
# To make as many children happy as possible, you are going to... |
97ab0c102c500feda7456708b7e6f4fc0828c7d2 | brianweber2/project1_build_a_soccer_team | /league_builder.py | 3,663 | 4.375 | 4 | '''
Author: Brian Weber
Date Created: November 19, 2016
Revision: 1.0
Title: Build a Soccer League
Description: You have volunteered to be the Coordinator for your town’s youth
soccer league. As part of your job you need to divide the 18 children who have
signed up for the league into three even teams - Dragons, Sharks... |
82fc933c012ac08ab5410f0e47004ad718c2c465 | limkeunhyeok/daily-coding | /programmers/Level_2/스킬트리/solution.py | 359 | 3.5625 | 4 | def solution(skill, skill_trees):
answer = 0
for word in skill_trees:
if skillTree(word, skill):
answer += 1
return answer
def skillTree(word, skill):
temp = ''
for c in word:
if c in skill:
temp += c
if not temp or (skill[0] == temp[0] and temp in skill... |
d5c13d1eb59fa47dd3ce83becfa1e3cbb254b0b3 | limkeunhyeok/daily-coding | /programmers/Level_2/가장 큰 수/solution.py | 140 | 3.546875 | 4 | def solution(numbers):
temp = list(map(str, numbers))
temp.sort(key=lambda x:3*x, reverse = True)
return str(int(''.join(temp))) |
a27391758861181ef9efde74383a97a9f115d4d5 | limkeunhyeok/daily-coding | /매일 프로그래밍/20200621/solution.py | 391 | 3.671875 | 4 | # 정수 배열이 주어지면 , 배열 안의 모든 정수의 최대 공약수(GCD)를 구하시오.
# 시간 복잡도 제한 O(n)
def gcd(num1, num2):
while num2:
num1, num2 = num2, num1 % num2
return num1
def solution(arr):
g = gcd(arr[0], arr[1])
for i in range(2, len(arr)):
g = gcd(g, arr[i])
return g
a1 = [3, 2, 1] # 1
a2 = [2, 4, 6, 8] # 2... |
838f33d865a64d55cca956b5c150fa1a797a76b1 | limkeunhyeok/daily-coding | /programmers/Level_1/최대 공약수와 최소 공배수/solution.py | 207 | 3.546875 | 4 | def solution(n, m):
d = gcd(n, m)
value = d * (n // d) * (m // d)
return [d, value]
def gcd(a, b):
if a < b:
(a, b) = (b, a)
while b != 0:
(a, b) = (b, a % b)
return a |
68a7ebfc9702db42a3e8aa20f8f359a25ca998a7 | limkeunhyeok/daily-coding | /programmers/Level_1/두 정수 사이의 합/solution.py | 230 | 3.703125 | 4 | def solution(a, b):
sum = 0
if a > b:
for i in range(b,a+1):
sum += i
return sum
elif a < b:
for i in range(a,b+1):
sum += i
return sum
else:
return a |
db0870df794a6645590780f1d1639f03d7f5dfac | limkeunhyeok/daily-coding | /programmers/Level_2/카펫/solution.py | 451 | 3.734375 | 4 | import math
def solution(brown, red):
answer = []
carpetArea = brown + red
maximum = int(math.sqrt(carpetArea))
# 빨간색 격자의 수는 (row - 2) * (col - 2)
for col in range(3, maximum + 1):
if carpetArea % col == 0:
row = int(carpetArea / col)
if (row - 2) * (col - 2) ==... |
3ab29704fb9c5e4999d3a8bf88b844bff2d79f05 | limkeunhyeok/daily-coding | /programmers/Level_2/소수 찾기/solution.py | 536 | 3.65625 | 4 | import itertools
import math
def isPrime(num):
if num <= 1:
return False
r = int(math.sqrt(num))
for i in range(2,r+1):
if num % i == 0:
return False
return True
def solution(numbers):
answer = []
numbers = list(numbers)
r = len(numbers)
for i in range(r):
... |
c8346079f44f59687db80bc1f58cba3e41d4af98 | limkeunhyeok/daily-coding | /programmers/Level_1/나머지가 1이 되는 수 찾기/solution.py | 176 | 3.734375 | 4 | def getMinNumber(number):
for num in range(2, number):
if number % num == 1:
return num
def solution(n):
answer = getMinNumber(n)
return answer |
1faf509a7933d5961df4102999dd08c753efac9c | limkeunhyeok/daily-coding | /매일 프로그래밍/20200906/solution.py | 662 | 3.84375 | 4 | # 이진탐색트리안에 X보다 크고 Y보다 작은 모든 노드 값을 프린트 하시오.
# 20
# 8 22
# 4 12
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def solution(root, x, y):
if root is None:
return
if x < root.data:
solution(root.left, x, y)
if... |
6094902ab436ef342bf1c6d5fc372deb20baaa75 | CConory/Arithmetic-by-python | /a+b.py | 436 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class Solution:
"""
@param a: An integer
@param b: An integer
@return: The sum of a and b
"""
def aplusb_1(self, a, b):
# write your code here
return (a^b)+((a&b)<<1);
def aplusb_2(sel... |
61f0641cd7f8c2afb804be8b2a9b419671eb2c56 | lazumbra/Coding-Questions | /LeetCode/moveZeroes.py | 487 | 3.53125 | 4 | class Solution:
def moveZeroes(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
zero_it = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[zero_it] = nums[i]
zero_it+=1
for i in range(zero_it, l... |
f414701abf81fe68fe6d9f82ed6f67ff474ba5fd | lazumbra/Coding-Questions | /LeetCode/rotateArray.py | 358 | 3.90625 | 4 | class Solution:
def rotate(self, nums, k):
"""
Do not return anything, modify nums in-place instead.
"""
#nums = nums[::-1]
k = k % len(nums)
print('k', k)
nums.reverse()
nums[:k] = nums[:k][::-1]
nums[k:] = nums[k:][::-1]
array1 = [1,2]
Solu... |
b1158d8ed9e4bcdf9c079443c77895b19f7d6828 | CrisOspina/crud-python | /CRUD/actualizar.py | 1,661 | 3.953125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sqlite3
# actualizar data
try:
db = 'estudiantes.db'
conexion = sqlite3.connect(db)
print("conexion realizada con exito a la bd " + db)
cursor = conexion.cursor()
listar = "SELECT * from estudiante"
cursor.execute(listar)
listarEstudia... |
c3279acc505e120baed0f7b6b9e32fc000324b61 | yeafla530/baeckjoon | /python/문자열/format연습.py | 773 | 3.84375 | 4 | print('Format example. {{}}, {}'.format('test'))
# Format example.{}, test
print('This is value {{{0}}}'.format(1212))
# This is value {1212}
print('this is {0:<10} | done {1:<5} |'.format('left', 'a'))
print('this is {0:>10} | done {1:>5} |'.format('right', 'b'))
print('this is {0:^10} | done {1:^5} |'.format('cen... |
edd7836e3acc8c5865e5d16d6a29052ac8738757 | yeafla530/baeckjoon | /python/문자열/실버5_단어정렬.py | 283 | 3.546875 | 4 | n = int(input())
words = set()
for _ in range(n):
word = input()
words.add((len(word), word))
words = list(words)
# 길이가 짧은 것부터
# 길이가 같으면 사전순으로
words.sort(key = lambda x : (x[0], x[1])) # 알아두기
for w in words:
print(w[1]) |
e2a3756d6075ab7a5d1d03181ef0a9e0a564727f | poushali-chakraborty/rock-game | /rockgame.py | 2,434 | 3.859375 | 4 | from Tkinter import *
import random
def computer_pick():
options=["rock","paper","scissors"]
return random.choice(options)
def game(user,computer):
if user==computer:
return "draw"
elif (user=="rock" and computer=="scissors") or (user=="scissors" and computer=="paper") or (user=="paper" and computer=="rock... |
67a64781c3980237066d011abebcc8bdd120aecb | python-practice-b02-927/turaev-victor | /Lab2/task_12.py | 396 | 3.546875 | 4 | import turtle
import math
r=50
t=10
n=10
turtle.left(90)
turtle.speed(0)
for i in range(n):
for i in range(180):
turtle.forward(r*math.sin(math.pi/180))
turtle.right(1)
turtle.right(0.5)
for i in range(180):
turtle.forward(t*math.sin(math.pi/180))
turtle.right(1)
turtle.r... |
62c86d943e116d8cafc2e3b5f180356b56896b1a | Kiranathas/Python-para-no-programadores | /promedio_notas.py | 673 | 4.125 | 4 | #COMPARAR notas
nota_uno=10
nota_dos=6
nota_tres=8
#promedio
promedio= (nota_uno+nota_dos+nota_tres)/3
print(promedio)
#mostrar si aprobó o no.
if promedio >=6:
print("aprobado")
else:
print("desaprobado")
# ~ El usuario debe ingresar una nota (Suponiendo que siempre es menor que 11)
# ~ Most... |
6443be4b24331f9d93bbf5d345efc294c71c4610 | Kiranathas/Python-para-no-programadores | /años_bisiestos.py | 412 | 3.828125 | 4 | # CALCULAR AÑOS BISIESTOS:
año= int(input("ingrese el año: "))
if (año % 4)== 0:
print("año bisiesto")
else:
print("no es un año bisiesto")
#otra forma:
a = input("Ingrese año: ")
a = int(a)
if a % 400 == 0:
print("Es bisiesto")
else:
if a % 4 == 0 and a % 100 != 0 :
pri... |
15fdce4a864659f68f2279e3a18fdd9ca0bc5a3b | xwlee9/python | /python/网络通信/6tcp_demo_client.py | 825 | 3.5 | 4 | import socket
import sys
def main():
# 创建套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 目的信息 服务器的ip和port
dst_ip = input("please input the dst ip: ")
dst_port = int(input("please input the dst port: "))
s_addr = (dst_ip,dst_port)
# 连接服务器
s.connect(s_addr)
# 输入需要下载的文件名
download_f... |
7ee57572aab89a0aa8dcf62ddd4831581681ff2e | xwlee9/python | /python/iterate_demo.py | 630 | 3.71875 | 4 | # nums = []
# a = 0
# b = 1
# for _ in range(10):
# nums.append(a)
# a, b = b, a+b
# for num in nums:
# print(num)
class Fibonacci(object):
def __init__(self, ite):
self.nums = list()
self.count = 0
self.a = 0
self.b = 1
self.ite = ite
def __iter__(self):
... |
7688efc87a4ad181fda10633e574094275cb5c79 | mindful-ai/28092020LVC | /day_01/transcripts/trans_input_print.py | 1,143 | 3.765625 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Inputs
>>>
>>> input()
435
'435'
>>> a = input()
345
>>> print(a)
345
>>> a
'345'
>>> a + 10
Traceback (most recent call last):
Fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.