blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3579c77df61944e8166e1f13d21aa41da03b0b3b | airfightergr/LearnPython | /python_study_scripts/variables.py | 856 | 3.9375 | 4 | # Variables - Python is dynamic language like LUA - no need to declare variable type
# The same scheme with local/global variables. But you don't use the "local" as in Lua.
# Python knows that is local if is inside a scope (function , if, etc).
# To modify a global inside a scope, you must the "global" in front of the ... |
a11e42bfe578982aa56b7868380da8a1f000e700 | airfightergr/LearnPython | /python_study_scripts/strings.py | 1,417 | 4.09375 | 4 | # STRINGS!!!
course = "Python Programming"
print(len(course)) # length of the string
print(course[2]) # then 3nd letter. Python starts at 0 not 1 as in Lua
print(course[-1]) # the last letter! Nice Python!
print(course[2:10]) # a range
print(course[:6]) # get from start to the 7th letter, works [3:] as 4th to end
... |
92d44cc3837264b060e6e2f05fd80c5175c8e0f6 | abergmanson/sql1 | /cars2.py | 380 | 3.75 | 4 | import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("UPDATE inventory SET quantity = 11 WHERE model = 'Accord'")
c.execute("UPDATE inventory SET quantity = 7 WHERE model = 'Focus'")
c.execute("SELECT * FROM inventory WHERE make = 'Ford'")
rows = c.fe... |
031d342c47e3c92f4874008c4bdd82cb2577543a | symickey89/poem_by_Soo_UTAustin_CS_for_LiberalArts_Class | /Feb7Python_Soo.py | 431 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#doubleTheList takes a sequence of elements as an argument
#and returns a list containing the original sequence and the
#sequence of doubled elements as separate lists.
def doubleTheList(sequence):
result=[sequence]
doubledList=[]
for element in sequence... |
11b1818fd982c2f79d014ffa454dc0e12192bbcd | SricardoSdSouza/Curso-da-USP | /setup/Iluminotecnica.py | 2,947 | 3.984375 | 4 | 'Calculando a Iluminação'
print("ESTE PROGRAMA VISA CALCULAR A ILUMINAÇÃO NECESSÁRIA PARA SEU COMODO")
import math
comprimento = float(input("Digite o valor do comprimento = "))
altura = float(input("Digite o valor para a altura = "))
largura = float(input("Digite o valor da largura = "))
k=round(float((comprimento*lar... |
00bce1986d472a81b26c8a6b9d1342ef31f0928e | SricardoSdSouza/Curso-da-USP | /coursera 3/exer1.py | 771 | 3.90625 | 4 | '''def cria_matriz(tot_lin, tot_col, valor):
matriz = [] #lista vazia
for i in range(tot_lin):
linha = []
for j in range(tot_col):
linha.append(valor)
matriz.append(linha)
return matriz
x= cria_matriz(2,3,99)
print(x)
def tarefa(mat):
dim = len(mat)
for i in ra... |
a53b308bfab05a4a3fb1b90fe855b34e6f1e09ec | SricardoSdSouza/Curso-da-USP | /exe8junho.py | 165 | 3.78125 | 4 | '''
count= 0
while count <= 10:
print(count,"Olá Mundo")
count = count + 1
'''
i=1
n=int(input("Digite um numero"))
n=0
while i < n:
i = i+1
n=n+1
|
fed0a0eed528e25c562d1c18eaf65ad9a31fc7d5 | SricardoSdSouza/Curso-da-USP | /Modularizar/Bhaskara.py | 754 | 3.96875 | 4 |
print("Vamos calcular as raízes de uma equação de 2º grau")
import math
class Bhaskara:
def delta (self, a, b, c):
return b ** 2 - 4 * a * c
def main(self):
a_dig=float(input("Digite o coeficiente de a = "))
b_dig=float(input("Digite o coeficiente de b = "))
c_dig=float(input("Digite o c... |
7c94a7f567708648cc21f6c6c969b9a3d99e9835 | SricardoSdSouza/Curso-da-USP | /Coursera 2/exercicios da aula/exer3.py | 623 | 3.890625 | 4 | def fazAlgo(string):
pos = len(string)
stringMi = string.lower()
string = string.upper()
stringRe = ''
while pos >= 0:
if string[pos-1] == 'A' or string[pos-1] == 'E' or string[pos-1] == 'I' or string[pos-1] == 'O' or string[pos-1] == 'U':
stringRe = stringRe + string[pos-1]
... |
e6f61709283d5052108f0016d7481af280b65120 | SricardoSdSouza/Curso-da-USP | /Exercicios enviado2/exercicio 2L2a.py | 142 | 4.03125 | 4 | import math
numero = int(input("Digite o número= "))
Fizz = numero
resto = Fizz
if resto %3 == 0:
print("Fizz")
else:
print(numero)
|
b6f6b294e3322674f545c341e364edcb78b6b9fb | SricardoSdSouza/Curso-da-USP | /Coursera 2/envio 6º exercicio/fibonacci.py | 147 | 3.953125 | 4 | def fibonacci(n):
if n < 2: # base da recursão
return n
else:
return fibonacci(n-1) + fibonacci(n-2) #chamada recursiva
|
c43c6a512ae81a0709522391eb8d1e2ea9bd2d91 | SricardoSdSouza/Curso-da-USP | /Coursera 2/exercicios da aula/Fazendo_select_sort_1.py | 1,037 | 3.859375 | 4 |
def ordenação_por_seleção(lista):
tamanho_da_lista = len(lista)
for i in range(tamanho_da_lista -1):
indice_menor_elemento =i
for k, elemento_analisado in enumerate(lista[i+1:],start = i+1):
if elemento_analisado < lista[indice_menor_elemento]:
indice_menor_... |
6255a90146d47c7d97ab8b31d8844806a81428c2 | SricardoSdSouza/Curso-da-USP | /Coursera 2/exercicios da aula/primeira alula Lematriz.py | 856 | 4.0625 | 4 | # matrizes
#a = [[1, 2, 3],[3, 5, 6],[7, 8, 9]]
def cria_matriz(num_linhas, num_colunas):
""" (int, int) -> matriz (lista de listas)
cria e retorna uma matriz comnum_linhas linhas e num_colunas
colunas em que cada elemento é digitado pelo usuário.
"""
matriz = [] # lista vazia
for i in range(nu... |
3bc0beecd6d9fa9a295c0fe366e9f587e1f9de14 | SricardoSdSouza/Curso-da-USP | /Exercicios enviado3/testarSePrimo1.py | 185 | 3.765625 | 4 | n = int(input("Digite um número inteiro: "))
mult=0
for count in range(2,n):
if (n % count == 0):
mult += 1
if(mult==0):
print("primo")
else:
print("não primo")
|
5259c2a25362a4ab9042a98a8bd677bf6270b9df | SricardoSdSouza/Curso-da-USP | /coursera 3/str_menor.py | 604 | 3.59375 | 4 | nomes = []
def menor_nome(list):
"""
-> Função devolve o menor mome escrito
param: lista de nomes
"""
menor = cont = 0
for i in list:
nomes.append(i.strip())
for i in nomes:
a = len(i)
if cont == 0:
menor = a
nome_m = i.capitalize()
... |
a2095e048399e153a25d66844efcc624dba9d3d5 | renwotao/exercise | /python/returnFunc.py | 1,219 | 3.859375 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''
返回函数
'''
# 函数作为返回值
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
# 不需要立刻求和,可以不返回求和的结果,而是返回求和的函数
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
print(f)
print(f())
... |
86c799523fd5c0a89d511f889441d1f28394b48c | renwotao/exercise | /python/for.py | 417 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
sum = 0
for x in[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
'''
function:
range() 生成一个整数序列
list() 转换为list
'''
print(list(range(5)))
sum = 0
for x in range(101):
sum = sum + x
print... |
729301bd1cb68f3e5ac9c5499101ec3bb218c546 | renwotao/exercise | /python/partialFun.py | 600 | 4.0625 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''
偏函数
'''
# int()函数可以把字符串转换为整数
print(int('12345'))
# int()函数提供额外的base参数,默认值为10
print(int('12345', base=8))
print(int('12345', 16))
def int2(x, base=2):
return int(x, base)
print(int2('1000000'))
print(int2('1010101'))
# functools.partial就是创建一个偏函数,不需要自己定义int2()
imp... |
52bd9273d3d51340ab1026cd23ab8fd76611cf0f | renwotao/exercise | /python/enumClass.py | 930 | 4.0625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Enum
可以把一组相关敞亮定义在一个class中,且class不可变,
且成员可以直接比较
'''
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',... |
eb148bc2bafe24a5b22a025b7175e251cc150b0c | alangshur/pure-image | /pure/hash/phash.py | 8,763 | 3.703125 | 4 | from abc import ABCMeta, abstractclassmethod
import math
class VariableGrid:
"""
Defines an encapsulation system for variable-sized
grids of pixel data. A VariableGrid object is instanitated
using the intended dimensions of the container and then
loaded using manual function calls.
Attribute... |
3748e8d5b6eea88df3ecf3a3da5879288a47abcc | AndreFull/EntregadeExercico | /entregaBlueEdTech3/ex1.py | 1,297 | 4.46875 | 4 | #01 - Utilizando estruturas condicionais faça um programa que pergunte ao usuário dois números e mostre:
# A soma deles;
# A multiplicação entre eles;
# A divisão inteira deles;
# Mostre na tela qual é o maior;
# Verifique se o resultado da soma é par ou impar e mostre na tela;
# Se a multiplicação en... |
f1a4f94d8d5abf31ec1884a6df52f8b04aed6db1 | Nurs312/miniProjects | /find_end.py | 397 | 3.734375 | 4 | def find_end(number):
for num in range(1, number + 1):
str_num = str(num)
if 5 <= int(str_num) <= 20:
print(f'{num} попыток.')
elif str_num[-1] == '1':
print(f'{num} попытка.')
elif 1 < int(str_num[-1]) < 5:
print(f'{num} попытки.')
else:
... |
89652455d502e288e874396db3e5eadf2632bbb3 | Xrehman/CheetayAssignment | /Q2.py | 568 | 4.09375 | 4 | #Question: 2
#Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array.
#Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
def equilibriumPoint(arr,n):
totalsum = sum(arr)
lsum = 0
... |
985ec1e717f3b3322dca6242212a225141b412fc | rueiting/Program-Algonthm | /功課喔8.19.py | 1,697 | 3.84375 | 4 | '''
message = input("Enter a message to endcode or decode:\n")
message = message.upper()
output = ""
for letter in message:
if letter.isupper():
value = ord(letter) + 15
letter = chr(value)
if not letter.isupper():
value -= 30
letter = chr(value)
output += letter
... |
5d79ea2d9b74dd361982a1b3e77ab30d76ecd875 | MMRevanth/flask-simple-api | /test.py | 573 | 3.515625 | 4 | import sqlite3
db=sqlite3.connect('../templates/country.db')
db.execute("create table countryIndia (S_No int, States char(50), Capital_City char(50), Popular_Cities char(100))")
db.execute("""insert into countryIndia values (1,"Tamil Nadu","Chennai","Trichy,Madurai,Thanjavur,Kanyakumari"),(2,"Kerala","Thiruvananthapur... |
c914e1e190962e0da63b62472030fa9d34e5178a | skredenmathias/code-challenges | /add_two_numbers.py | 1,284 | 3.59375 | 4 | def convert(list):
# convert int list to string list
s = [str(i) for i in list]
# convert back to int & join list items using join()
res = int("".join(s))
return(res)
result_ll = ListNode()
arr1 = []
arr2 = []
# traverse through LL
current = l1
# print(current)
while current is not None:
... |
31951e77f2ad973902792c501e177fc017773cc4 | skredenmathias/code-challenges | /linked_list_cycle.py | 726 | 3.828125 | 4 | # Given a linked list, return the node where the cycle begins.
# If there is no cycle, return null.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head):
# traverse the LL
current ... |
f8f8c0be956582dd89a130caf3ac22d0ee0cc1db | hemil/Whatsapp-Chat-Analysis | /wordcloud_group.py | 1,900 | 3.53125 | 4 | import sys
import re
from nltk.corpus import stopwords
from nltk.stem.lancaster import LancasterStemmer
__author__ = "hemil"
usage = """Usage: python wordcloud_group.py "avengers_chats_9_may.txt,avengers_chats_28_dec.txt" | pbcopy
pbcopy will put the output of this code to your clipboard.
The Multiple files support i... |
c32366150e07fd48e54242ba356cf0ad23c2d044 | fkahraman/YOUTUBE | /ABSTRACTMETHOD/main.py | 1,229 | 3.96875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Author : Fatih Kahraman
Mail : fatih.khrmn@hotmail.com
"""
from abc import ABC, abstractmethod
class ChessPieces(ABC):
@abstractmethod
def show_move(self):
pass
@abstractmethod
def show_count_in_board(self):
pass
class... |
9f4060eca8dd8b4d1667caa998a4468328fa4a67 | jk-me/santa_cli_game | /main.py | 17,518 | 3.640625 | 4 | from sys import exit
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
class inventory:
hairpin=False
money=False
butterknife=False
orange=False
diamond=False
sword=False
butter=False
elfID=False
cc=False
fertilizer=False
keys=False
cabbage=False
heart=Fal... |
2a01e1e93ef010a39ad5dba1a9aaff0795fc9b42 | kevinlondon/leetcode | /0000-0999/076_minimum_window_substring.py | 1,572 | 3.53125 | 4 | class Solution:
def minWindow(self, s: str, t: str) -> str:
# could be duplicates in `t`
# when adding a character of a type, look to see what the oldest of that type is
# if it can be removed, do so. then look to see if that affects the longest / shortest item
# maybe we use a prio... |
5b2a33b1b00c87118939550b06a8a61ab2bcc975 | kevinlondon/leetcode | /0000-0999/343_integer_break.py | 626 | 3.640625 | 4 | class Solution:
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if not n:
return 0
prod = None
if n == 2:
return 1
elif n == 3:
return 2
while n:
if n % 3 ==... |
e11fd05568fa262df8f17a6712131d0507d05997 | kevinlondon/leetcode | /0000-0999/073_set_matrix_zeroes.py | 671 | 3.515625 | 4 | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
columns, rows = set(), set()
n_col, n_row = len(matrix), len(matrix[0])
for row in range(n_col):
for column in range(n_ro... |
d9d93fbd59721451ff826024b80b3765fd59ecda | kevinlondon/leetcode | /0000-0999/406_queue_reconstruction_by_height.py | 538 | 3.65625 | 4 | from collections import defaultdict
class Solution:
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
queue = []
by_height = defaultdict(list)
for person in people:
by_height[person[0]].app... |
d3fda3ce6c65d26e4afe831a124cc54be80822ce | kevinlondon/leetcode | /0000-0999/009_palindrome_number.py | 391 | 3.640625 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if not x:
return True
x = str(x)
is_even = len(x) % 2 == 0
midpoint = int(len(x) / 2)
l_bound = midpoint if is_even else midpoint + 1
r_bo... |
5c99acba76e33e9ff35b6c9149ead13b63dbd1f6 | kevinlondon/leetcode | /2000-2999/2115_find_all_possible_recipes.py | 1,769 | 3.53125 | 4 | """
Ideas:
* Seems like this is a dynamic programming problem, where we can use memoization to help determine if we have the ingredients available.
* Need to build a set of supplies, then do a set diff between what's available from the current ingredients
* For any missing ingredient, we have to assume it's a recipe. W... |
bea68abcac648baea480e1c116c68b25e580dc57 | kevinlondon/leetcode | /1000-1999/1650_lca_binary_tree_iii.py | 558 | 3.71875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
if not p or not q:
return False
... |
46be163054295f236892573f1e3383ff06219d72 | kevinlondon/leetcode | /0000-0999/708_insert_into_circular_ll.py | 1,117 | 4 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head: 'Optional[Node]', insertVal: int) -> 'Node':
new_node = Node(insertVal)
if not head:
new_node.next = new_node... |
e736fb07f1440b45293e3a84ccc1e621b8d628f5 | kevinlondon/leetcode | /0000-0999/728_self_dividing_numbers.py | 548 | 3.578125 | 4 | class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
self_dividing = []
for i in range(left, right+1):
chars = str(i)
is_self_dividing = True
for c i... |
f5006d17598499422799874e0cd2e57611d4c55f | kevinlondon/leetcode | /0000-0999/230_kth_smallest_in_bst.py | 755 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from queue import PriorityQueue
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
if ... |
968a1cdcd4563a1649f79997ec6f131832731e46 | kevinlondon/leetcode | /1000-1999/1861_rotating_the_box.py | 1,815 | 3.75 | 4 | STONE = '#'
OBSTACLE = '*'
EMPTY = '.'
class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
"""
Obstacles:
Stone = '#'
Stationary Object = '
Ideas:
Maybe we start from the end of the array and build out the bottom rows first.
We ... |
cdcb0879cc5ad156ea0402603f127c8c19d89840 | kenny5660/cats | /algorithms/first_python/3d.py | 106 | 3.625 | 4 | n = int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print("%d * %d = %d"%(i,j,i*j)) |
70912de71849cdf40ba167fd74de99a432904abc | drmartirosian/PY_JS_DAILYS | /PYTHON_PROJ/DAY1-10/PYTHON1-10.py | 24,332 | 3.859375 | 4 | #PYTHON100
#======================DAY1=========================#
# -----------------PRINT------------------------#
# print("Hello world!")
# -----------------QUOTES WITHIN QUOTES---------#
#print("print('What to print?')")
# -----------------LINE BREAK-------------------#
# print("TEST \n TEST")
# -----------------... |
432570a926b7aba29281271cc22f73207f050821 | drmartirosian/PY_JS_DAILYS | /PYTHON_PROJ/DAY20_SNAKE/food.py | 622 | 3.984375 | 4 | from turtle import Turtle
from random import randint, random
class Food(Turtle): #inherit Turtle class functions into Food class
def __init__(self): # Make food dot
super().__init__() #initialize inherited class (Turtle)
self.shape("circle")
self.penup()
self.shapesize(stretch_len... |
addb88c8864cf07f5a347321f5ccbd86df5d41f0 | vvalotto/SenialSOLID | /persistidor/mapeador.py | 4,839 | 3.875 | 4 | """
Modulo que convierte o mapea una estructura de objeto python en otra
para persistirlo de acuerdo a almacen definido (archivo plano, xml, BD)
"""
from abc import ABCMeta, abstractmethod
class Mapeador(metaclass=ABCMeta):
"""
Clase base del mapeo (abracta)
"""
# Lista los tipo de dato base (fin del ... |
9c53f0f48c9ccd29801b674e3f5d556bea96abe4 | GRajaraju/NLP | /text2vectors.py | 1,222 | 4.21875 | 4 | # A simple method to convert sentences into vectors.
import numpy as np
import re
sample_text = """Natural language processing (NLP) is the ability of a computer
program to understand human language as it is spoken. NLP is a component of artificial intelligence (AI)."""
def wordTokens(sample_text):
"""Tokenize t... |
e0491e22057aa3abab88313ce4e47ac3246c3ddf | fac3d/projects | /python/raspberrypi/gpio_blink.py | 581 | 3.5625 | 4 | #!/usr/bin/python
# gpio_blink.py
# by Scott Kildall (www.kildall.com)
# LED is on pin 4, use a 270 Ohm resistor to ground
# run as sudo gpio_blink.py
# http://www.instructables.com/id/Raspberry-Pi-Python-scripting-the-GPIO/step6/Blink-an-LED-in-Python/
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPI... |
c6c3dceff55c6e454edca59be378fe6c99019682 | blossombudle/yeo | /Machine_Learning/tensorflow/basic/mytest.py | 180 | 3.734375 | 4 | for i in range(0,9):
if i%4==0:
for j in range(1,10):
print(' ', end='')
if j==5:
print('*', end='')
print(" ", end='')
|
1b81706321b12c64dff9d88a4a4bd8ceb499a1a7 | akmishra30/python-projects | /python-basics/graph/histogram-chart.py | 469 | 3.640625 | 4 | import matplotlib.pyplot as plt
import matplotlib.style as style
# For adding style in graph
style.use('ggplot')
ages = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
pop_ages = [22, 25, 30, 12, 46, 80, 57, 87, 56, 39, 40, 49, 68, 103, 123, 18, 79]
plt.ylabel('Y Axis')
plt.xlabel('X Axis')
plt... |
7dcf6bd5aca6c0f7daf1c13e63e6bf1ed5bd2e23 | akmishra30/python-projects | /python-basics/graph/bar-chart.py | 468 | 3.890625 | 4 | import matplotlib.pyplot as plt
import matplotlib.style as style
# For adding style in graph
style.use('ggplot')
x1 = [5,8,9,10]
y1 = [2,5,7,5]
x1 = [5,8,9,10]
y1 = [2,5,7,5]
x2 = [4,6,8,10]
y2 = [3,5,7,9]
#plt.bar(x1, y1, label='Data 1', color='b')
# If you wish to add multiple bar in graph
plt.bar(x2, y2, label='... |
0530cc0f819d5afd854d592d07dab7a563295aaf | justinelai/Sprint-Challenge--Hash-BC | /hashtables/ex2/ex2.py | 1,319 | 3.640625 | 4 | # Hint: You may not need all of these. Remove the unused functions.
from hashtables import (HashTable,
hash_table_insert,
hash_table_remove,
hash_table_retrieve,
hash_table_resize)
class Ticket:
def __init__(self, s... |
ee4f3a3fa03605840ec049bd87f35f3fd2d4dc50 | LibroWu/Codes | /others/Python_rsa/genkey.py | 1,262 | 3.59375 | 4 | from random import*
def isPrimeNumber(n):
cnt=0
d=n-1
while d%2==0:
cnt+=1
d//=2
k=0
while k<100:
k+=1
a=randint(2,n-2)
x=pow(a,d,n)
if x==1 or x==n-1:
continue
i=1
while i<cnt:
i+=1
x=x*x%n
... |
0db486505c134da98af1691f3fa22191a7c9df58 | klandhu/PyQt5learn | /9.2Pointer_点的绘画.py | 1,852 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In the example, we draw randomly 1000 red points
on the window.
Author: Jan Bodnar
Website: zetcode.com
Last edited: August 2017
我们在窗口里随机的画出了1000个点。
"""
from PyQt5.QtWidgets import QWidget,QApplication
from PyQt5.QtGui import QPainter
from PyQt5.... |
c2676d168962df64bc9765f716480f52b7063e56 | fagan2888/spread_calculator | /spread_analysis.py | 6,412 | 3.875 | 4 | import pandas as pd
import unittest
# constant for input filename
INPUT_FILE = "sample_input.csv"
# ====================
# Helper functions for manipulating input file
def read_csv(filename):
""" Return a pd.Dataframe of the given file input.
:param file filename: a csv file contains data of corporate bon... |
7a414302eefb0f61bbc0c88efd2f721efcf7539a | pranav-kural/learn-python-by-doing | /ms-keypress.py | 1,670 | 3.734375 | 4 | """keypress - Detecting OS of user based on a single key entry"""
# run from command line
if __name__ == '__main__':
print("For program to detect your OS, please press any letter key")
# Exception block for Windows input
try:
import msvcrt
def getkey():
""" Wa... |
4327ca639df9e76e766d66d2ce4cc9be476f7165 | Biggymot/phone_book | /phone_book.py | 6,013 | 4.03125 | 4 | import pickle
phone_book = [{"surname": "Bogach", "name": "Dmytro", "age": 36}]
def print_entry(number, entry):
print "[ " + str(number) + " ]" + "-----------------"
print "Surname: " + entry["surname"]
print "Name: " + entry["name"]
print "Age: " + str(entry["age"])
def print_phonebook():... |
49cd91b0970eed47ad0bb40ea19a253ce26f370a | marin1401/aoc2019 | /06.py | 934 | 3.5625 | 4 | #Day 6
with open('./06.txt') as myinput:
inputlines = myinput.readlines()
orbits = [line.strip().split(')') for line in inputlines]
#Part 1
def count_orbits(current_object, counter, counters):
counter += 1
counters.append(counter)
for object_1, object_2 in orbits:
if current_obj... |
75839222c6704113e72ca5b8c7101265d2d6edd0 | 85hzc/dataAnalyse | /tongzi2018_python数据分析学习/DataAnalysisLearning/make_df.py | 315 | 3.65625 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
import pandas as pd
url = 'https://developers.douban.com/wiki/?title=book_v2'
def make_df(cols, ind):
data = {c: [str(c) + str(i) for i in ind] for c in cols}
return pd.DataFrame(data,ind)
if __name__ == "__main__":
print(make_df(['apple','peach','pear'],range(3))) |
5c30b8d173e25ee5924b96fb1fb9e83add739049 | SuperHapyFunTime/SpamBot | /src/SpamFilter.py | 857 | 3.609375 | 4 | import os
from collections import Counter
emailDataDir = '../data/training-mails/'
def getWordsAndFeq(emailDir):
all_words = []
for filename in os.listdir(emailDir):
emailContent = open(os.path.join(emailDir, filename), 'r')
for i, line in enumerate(emailContent):
if i == 2: # Bo... |
4b2b238e2702d488eb13cf7f0d634dc0c1b7776b | abhinand5ai/Fluency | /codeJam/cipher.py | 1,565 | 3.53125 | 4 | import math
def primes_list(limit):
a = [True] * limit
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in range(i * i, limit, i): # Mark factors non-prime
a[n] = False
tests = int(input())
def factorize(num):
primes ... |
fcf53c784c0524a897083fd2f55bca2a0738c2ea | abhinand5ai/Fluency | /LC/Arrays/RotateArray.py | 609 | 3.75 | 4 | class Rotation:
def rotate(self, nums: list[int], k: int) -> None:
n = len(nums)
k = k % n
curr = count = 0
while count < n:
start = curr
tmp = nums[start]
while True:
curr = (curr + k) % n
tmp, nums[curr] ... |
825146f930340f0617ecad83f65e631c85acc107 | abhinand5ai/Fluency | /LC/0105ConstructBinaryTree.py | 1,207 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return f"TreeNode({self.val}, {self.left}, {self.right})"
class Solution:
def buildTr... |
0ac2581d3fff2f548439362a2dd7d02f3f719c8a | abhinand5ai/Fluency | /LC/0310MinimumHeightTree.py | 829 | 3.5625 | 4 | from collections import defaultdict
import math
class Solution:
def findMinHeightTrees(self, n: int, edges: list[list[int]]) -> list[int]:
if n == 1:
return [0]
graph = defaultdict(list)
degree = [0] * n
for a, b in edges:
graph[a].append(b)
... |
ee47393bdac8f2ec8d8e57af9ecf41e9ef9db24d | abhinand5ai/Fluency | /LC/Trie/Trie.py | 1,884 | 3.921875 | 4 | class Node:
def __init__(self, char):
self.char = char
self.children = []
self.is_word = False
def get_char(self):
return self.char
def get_child(self, ch: str):
for child in self.children:
if child.get_char() == ch:
return ... |
bf42762485ab5c8ab1243d4046976c0b59a6a344 | abhinand5ai/Fluency | /LC/0721MergeAccounts.py | 1,655 | 3.75 | 4 | from collections import defaultdict
from typing import List
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
en = {}
p = {}
r = defaultdict(int)
def find(e):
if e not in p:
p[e] = e
if p[e] == e:
... |
c593793febd168f56e8195d166c5841bcd4e7714 | abhinand5ai/Fluency | /LC/TikTok.py | 2,461 | 3.765625 | 4 | '''
Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example 1:
Input: board = [
["X","X","X","X"],
["X","O","O","X"],
["X","X","O","X"],
["X","O","X","X"... |
db1ff71c6ad57f106193463d004c6905ef409495 | abhinand5ai/Fluency | /HR/Bit/AndProduct.py | 489 | 3.53125 | 4 | import unittest
class Bit:
@staticmethod
def and_product(a, b):
xor = (a ^ b)
i = 0
while (2 ** i) < xor:
i += 1
return ~(2 ** i - 1) & a
class BitTest(unittest.TestCase):
def setUp(self) -> None:
self.sol = Bit()
def testAndProduct(self):
... |
36f832c6148296721d80b325e948be06bb3ca5d3 | abhinand5ai/Fluency | /LC/TIQ/myatoi.py | 2,845 | 4.3125 | 4 | import unittest
'''
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits... |
6ae25076645a1f9c45764547937616fa09f4c6a2 | JMBoter/Euler-Problems | /6_SumSquare_Difference.py | 358 | 3.90625 | 4 | def summed_squares(x):
result = (x*x*x)/3 + (x*x)/2 + x/6
return int(result)
def sum_squared(x):
result = (sum(range(x+1)))**2
return int(result)
from datetime import datetime
startTime = datetime.now()
print (sum_squared(100) - summed_squares(100))
print ("It took {0} seconds to excecute this code."... |
279234fbb799ca006218dcd619862b1d7b934dc4 | 18rwalsh/AFPwork | /Splicing out introns 3.py | 430 | 3.515625 | 4 | dnaSeq = "ATCGATCGATCGATCGACTGACTAGTCATAGCTATGCATGTAGCTACTCGATCGATCGATCGATCGATCGATCGATCGATCGATCATGCTATCATCGATCGATATCGATGCATCGACTACTAT"
#find exon 1
exon1 = dnaSeq[0:63]
#find intron
intron = dnaSeq[63:90]
#find exon 2
exon2 = dnaSeq[90:]
#print out coding and non coding sections
print('Original sequence: {0}'.forma... |
accec812cfdb1ca76b4eb72c93c7aebbcfcd98f3 | SohamGhosh123/Dictionary | /Untitled-1.py | 800 | 3.671875 | 4 | import json
from difflib import get_close_matches
d=json.load(open("C:/Users/dipak/Desktop/Dictionary/dictionary.json"))
def translate(w):
w=w.lower()
if w in d:
return d[w]
elif len(get_close_matches(w,d.keys()))>0:
yn=input("Did you mean %s instead? Enter yes or no "%get_close_matc... |
816503585ec01d0131a622a9825401aa313b5a13 | nuSapb/basic-python | /Day2/command_line_arguments/grade_cmd_argv.py | 226 | 3.96875 | 4 | import sys
print(sys.argv)
grade = int(sys.argv[3])
if grade >= 90:
if grade == 100:
print('A+')
else:
print('A')
elif grade >= 80:
print('B')
elif grade >= 70:
print('C')
else:
print('F') |
11c3543b59b8d5efc48619ca7dfb49477b4752e9 | agiri801/python_key_notes | /_08_Loops/_06_Fibonaci_while.py | 164 | 4.125 | 4 |
# printing fibonaci series
terms=int(input('Enter number of terms:'))
i=1
t1=0
t2=1
while i <= terms:
print(t1,end=' ')
t1,t2=t2,t1+t2
i +=1
print()
|
8b65bdaa43fb0ba96a1f38775a182a7b1a3a5762 | agiri801/python_key_notes | /_07_Decision_making/_11_Different_Range_fun.py | 300 | 3.625 | 4 |
for i in range(1,11):
print(i)
print('-'*40)
for j in range(5,0,-1):
print(j)
print('-'*40)
for a in range(10,0,-1):
print(a)
print('-------------------------------------')
for s in range(1,10,5):
print(s)
|
090c290c78e874e7f0feb8f7242ae9efc34507fa | agiri801/python_key_notes | /_08_Loops/_05_Factorial_For_while.py | 273 | 3.9375 | 4 |
# Factors of given number using for loop and while loop
n=int(input('Enter a integer:'))
for i in range(1,n//2+1):
if n%i==0:
print(i,end=' ')
print(n)
'''
i=1
while i <= n//2:
if n%i == 0:
print(i,end=' ')
i +=1
print(n) '''
|
c9b19d558cad0dbd0adda25981e6ab86a67784e4 | agiri801/python_key_notes | /_12_Oops/_06_Employee.py | 2,374 | 3.59375 | 4 |
class Employee:
def __init__(self,empid,name,deportment,mail=''):
self.empid=empid
self.name=name
self.dept=deportment
self.mail=mail
def getDeportment(self):
return self.dept
def setDeportment(self,deportment):
self.dept=deportment
def show(self):
... |
20571edba4ad6e7d814318de7aa06254d97aa1d7 | Devraj789/python-files | /Function.py | 215 | 3.953125 | 4 | # def add(x,y):
# return x+y
# sum = add(10,20)
# print(sum)
def oddoreven(n):
if(n%2 == 0 ):
print("The number is even")
else:
print("The number is odd")
s= int(input("Enter a number"))
oddoreven(s)
|
bb16e9163bcc21c404d1f0f08d97171cfefdc64d | Devraj789/python-files | /q1.py | 584 | 3.640625 | 4 | import random
i=0
counter = 0
counters = 0
countersa = 0
if(i<10):
d = random.randint(1,100)
e = random.randint(1,100)
f = random.randint(1,100)
counter = counter + d
counters = counters + e
countersa = countersa + f
i=i+1
print('Sum of 1st counter is:',counter)
print('Sum of 2nd counter is:',counter... |
b9cbf907951bd2628282495abe7603fb0872c99e | aubreybaes/DataStructures2018 | /Palindrome_Checker.py | 1,287 | 3.96875 | 4 | #Mae Aubrey Baes
#github.com/aubreybaes
#DATA STRUCTURES AND ALGORITHM ANALYSIS
#A SIMPLE PALINDROME CHECKER
#enter the palindrome and define it
#I've used part of Peter Norvig's Palindrome
aub = "A man a plan a cameo Zena Bird Mocha Prowel a rave Uganda Wait a lobola Argo Goto Koser Ihab Udall a revocation... |
e3a3ee70cb37c496605f40a4c22140ec6b8fcf9b | Rosebotics/PythonGameDesign2018 | /camp/RJ/Day 1 - The Game Loop, Colors, Drawing and Animation/04-Drawing.py | 689 | 3.859375 | 4 | # My first Pygame program.
# Authors: Many people and <Albus Dumblydore and Villager#64>
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
ypos = 450
clock = pygame.time.Clock()
pygame.display.set_caption("My Rising Sun")
while True:
clock.tick(60)
for event in pygame.event.... |
b4fab3feb3c8a261d9f4c610f1aec6b4cb7359d0 | Rosebotics/PythonGameDesign2018 | /camp/Alexa/Day 1 - The Game Loop, Colors, Drawing and Animation/05-Animation.py | 603 | 3.546875 | 4 | # My first Pygame program.
# Authors: Many people and Alexa, Aarna, and Madison
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("My moving objects")
xpos = 50
clock = pygame.time.Clock()
while True:
clock.tick(100)
for event in pygame.event.get()... |
df0789458442d830efad6ade25b049c4b2c82f9a | Rosebotics/PythonGameDesign2018 | /camp/DavidM and Emma/OpenCV-Introduction/src/m2_reading_displaying_and_writing_images.py | 2,136 | 4.125 | 4 | """
Reads a jpg image and writes it as a png.
Displays images.
Important functions in the cv2 library.
-- imread
-- imwrite
-- imshow
-- waitKey
Authors: David Mutchler (based on examples from others), September 2012.
"""
import cv2 # Use cv2, not cv, wherever possible - cv2 is newer.
import numpy # Usual... |
1763cfa94e62d5aeab44bfe321613166fb82dfc7 | Rosebotics/PythonGameDesign2018 | /camp/Z_2019_Solutions/DogBark/DogBark.py | 1,314 | 3.5625 | 4 | import pygame, sys
def main():
# pre-define RGB colors for Pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
IMAGE_SIZE = 470
TEXT_HEIGHT = 30
# initialize the pygame module
pygame.init()
pygame.font.init()
# prepare the window (screen)
screen = pygame.display.set_mode((IMAGE_... |
788b2845915fb9b9c8440656e530556c0cbe6b75 | Rosebotics/PythonGameDesign2018 | /camp/DavidM and Emma/Day 1 - The Game Loop, Colors, Drawing and Animation/05-Animation.py | 600 | 3.625 | 4 | # My first Pygame program.
# Authors: Many people and Gandalf.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("My moving objects")
xpos = 50
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
print(ev... |
9011394173f652dd10f1164e56563a4b994db6fc | Rosebotics/PythonGameDesign2018 | /camp/Rachel/Day 1 - The Game Loop, Colors, Drawing and Animation/05-Animation.py | 744 | 3.796875 | 4 | # My first Pygame program.
# Authors: Many people and Rachel
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
xpos = 50
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
print ( event )
if event . type == pygame.QUIT:
... |
a7646018b6674dd7665f04739c683cdfd34cabdb | nmalkin/objective-turk | /bin/subtract | 688 | 3.703125 | 4 | #!/usr/bin/env python
"""
Subtract the lines in the second file from the lines in the first file
"""
import argparse
def subtract(filename1, filename2):
with open(filename1, 'r') as file1:
with open(filename2, 'r') as file2:
lines1 = file1.readlines()
lines2 = file2.readlines()
... |
861e208e781a563dcdbf6479c3f9faee6c24c3da | Jburt4/ComSci-Repository | /Sonar.py | 2,759 | 3.84375 | 4 | import sys
import random
import time
def torps():
print('\nLaunching torpedo.')
tx = int((r + 30)/4)
ty = int((c + 6)/4)
game[tx][ty] = '>>>'
print('\nFollowing torpedo using sonar')
time.sleep(5)
printboard()
print('\nFollowing torpedo using sonar')
game[tx][ty] = '~~~'
tx = int((r + 10)/2)
ty = int((c + ... |
1ebf3a60cd64c66a82c25c2cd6fceffacb3a7b4b | Jburt4/ComSci-Repository | /Digit Addition.py | 193 | 3.609375 | 4 | import sys
#Worked with Henry
global num
num =[]
def addition(n):
if n < 1:
print(sum(num))
else:
dig = n%10
n = n // 10
num.append(dig)
addition(n)
addition(int(input('Number')))
|
2e28a0b574ee346590852a7e3d05c70fc901093b | Jburt4/ComSci-Repository | /Goofy Name Generator.py | 985 | 3.828125 | 4 |
first = ["stinky","lumpy","buttercup","gidget","crusty","greasy","fluffy","cheeseball","chim-chim","poopsie","flunky","booger","pinky","zippy","goober","doofus","slimy","loopy","snotty","falafel","dorkey","squeezit","oprah","skipper","dinky","zsa-zsa"]
last1 = ["diaper","toilet","giggle","bubble","girdle","barf","liz... |
b7c5bd479d6159b8ef4f264f5397a0a5d6de4245 | Jburt4/ComSci-Repository | /Sorted numbers between 1 and 100.py | 171 | 3.765625 | 4 | import random
Mylist = []
x = 0
while x < 10:
x = x + 1
num = int(random.uniform(1,101))
if num%3 == 0:
print(num)
else:
Mylist.append(num)
print(sorted(Mylist))
|
e2119184f55f43734b75590dd070b46881fabb79 | Jburt4/ComSci-Repository | /Subtracting Function.py | 278 | 4 | 4 | def subtract(a,b):
try:
a = int(a)
b = int(b)
return a-b
except TypeError:
print('Wrong Data Type')
return None
subtract('1','2')
# Subtract('a','b') --> None
# Subtract('1','2') --> -1
# Subtract(1,'2') --> -1
# Subtract(1,2) --> -1
# Subtract('a',2) --> None |
cc2fb0f91d1b7c9f8b60faf5a1a9665d0b8ff22a | S5151S/Assignment_1 | /Assignment1.py | 364 | 4.15625 | 4 | #Below is a function in python that for each position in the list, sums up all numbers other than the number at that position. For example, given [1,2,3,4], it will return [9,8,7,6].Optimize this function so that it runs faster.
def special_sum():
lst=[1,2,3,4]
total=sum(lst)
total_li=[total-x for x in... |
6426357e64f55a85cd45e6d0f6f3ac9ab7bf0379 | phuocidi/fun | /Dynamic Programming/Longest Increasing Subsequence/mergeSort.py | 686 | 3.78125 | 4 | #! /usr/bin/env python3
def merge(arr, l,m, r):
n1 = m - l + 1
n2 = r - m
L = [0]*n1
R = [0]*n2
for i in range(0, n1):
L[i] = arr[l+i]
for j in range(0,n2):
R[j] = arr[m+ 1 +j]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] < R[j]:
arr[k] = L[i]
i +=1
else:
... |
b314545f6f3e8ec786dee6cfab937f186b61bdc3 | phuocidi/fun | /Sorting/MergeSort/main.py | 1,028 | 3.734375 | 4 | #!/usr/bin/env python3
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
# Copy tmp left array
for i in range(0, n1):
L[i] = arr[l + i]
#Copy tmp right array
for j in range(0, n2):
R[j] = arr[m + 1 + j]
i = 0 # start index for left arr
j = 0 # start index... |
33f063645d6885881b7e242ce7b4ee5af8cc5c0f | BitnooriLee/Python-Exercise | /Prac06192.py | 351 | 3.609375 | 4 | a_n=0
a_nplus1=1
a_nplus2=1
while(a_nplus2<100):
print(a_nplus2)
a_nplus2=a_nplus1+a_n
a_n=a_nplus1
a_nplus1=a_nplus2
def abc(x):
if x>=0:
return x
else:
return -x
print(abc(-3))
def, for
Pascal's triagle
Decimals of it
Prime numbers... |
769ab3b753b2dc02e5557e1627480c1043d25f3d | wwwwodddd/Zukunft | /codechef/FOOTCUP.py | 121 | 3.609375 | 4 | for t in range(int(input())):
x, y = map(int, input().split())
if x == y and x > 0:
print('YES')
else:
print('NO') |
237f5db2fc9e70f8e5e5b022e065765a307232db | wwwwodddd/Zukunft | /leetcode/word-pattern.py | 397 | 3.53125 | 4 | class Solution:
def wordPattern(self, s: str, a: str) -> bool:
a = a.split()
if len(s) != len(a):
return False
if len(set(s)) != len(set(a)):
return False
g = {}
for i in range(len(s)):
if a[i] not in g:
g[a[i]] = s[i]
... |
5be283032790ac9015ea370132ac1f68fe93426a | wwwwodddd/Zukunft | /luogu/P2293.py | 169 | 3.53125 | 4 | m = int(input())
n = int(input())
r = 1
while r ** m <= n:
r *= 2
l = r // 2
while l < r - 1:
mid = (l + r) // 2
if mid ** m <= n:
l = mid
else:
r = mid
print(l) |
698d30a73cf3df0f7de1ebab5a1da4c3b5f6f829 | wwwwodddd/Zukunft | /leetcode/smallest-string-starting-from-leaf.py | 582 | 3.625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
z='~'
def dfs(x,s):
... |
34f63ce00ceb49430614695502421a2e0b6d6dc3 | wwwwodddd/Zukunft | /atcoder/nyc2015_1.py | 87 | 3.5625 | 4 | n = int(input())
s = '{:b}'.format(n)
if s == s[::-1]:
print('Yes')
else:
print('No') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.