blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e5a4dee9f86a8c5b2996fc2487d86a2bf516c25d | Lindisfarne-RB/MAGS-PY-L2-PROG | /game11.py | 3,014 | 4.0625 | 4 | import random
def choose_random_word():
words = []
with open('sowpods.txt', 'r') as file:
line = file.readline()
while line:
words.append(line.replace("\n", "".strip()))
line = file.readline()
choice = words[random.randint(0, len(words) - 1)]
return choice
print("Welcome to Hangman!")
secret_word = choose_rando... |
17e763bdefed1e9db924b0d5b0377a020f8b8b88 | Lindisfarne-RB/MAGS-PY-L2-PROG | /game2.py | 2,519 | 3.5 | 4 | import pygame
import random
import sys
pygame.init()
WIDTH = 800
HEIGHT = 600
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BACKGROUND_COLOR = (11,230, 207)
player_size = 50
player_pos = [WIDTH / 2, HEIGHT - 2 * player_size]
enemy_size = 50
enemy_pos = [random.randint(0, WIDTH - enemy_size), 0]
enemy_list... |
0bdc2064420ea2c0fd64ed948afb2c2f9bf9df06 | florespadillaunprg/Validadores-en-python | /Boleta 19.py | 1,185 | 3.9375 | 4 | # INPUT
cliente=input("Ingrese el nombre del cliente:")
RUC=int(input("Ingrese el numero de RUC:"))
colonia=input("Ingrese la marca de la colonia:")
desodorante=input("Ingrese la marca del desodorante:")
talco=input("Ingrese la marca del talco:")
precio_de_la_colonia=float(input("Ingrese el precio de la colonia:"))
pre... |
f649bebf1f0e90b1f9d48da63b8420748dfb59cc | florespadillaunprg/Validadores-en-python | /Verificador 01.py | 466 | 4 | 4 | # encotrar el divedendo a partir del algoritmo de la divison
dividendo,divisor,cociente,residuo=0,0,0,0
# asignacion de valores
divisor=10
cociente=5
residuo=2
#calculo
dividendo=(divisor*cociente)+residuo
#verificador
verificador=(dividendo!=52 or divisor==residuo)
# mostrar valores
print("divisor =", divisor)
pri... |
396f33d410a603ad7ba0e977621ba15e6c107f4f | florespadillaunprg/Validadores-en-python | /Verificador 08.py | 436 | 3.5 | 4 | # calcular la energia de un electron
energia,masa,longitud,tiempo=0.0,0.0,0.0,0.0
# asignacion de valores
masa=5
longitud=10
tiempo=2
# calculo
energia=masa*(longitud**2)/tiempo**2
# verificador
verificador=not(energia<tiempo and masa==longitud)
# mostrar valores
print("energia =", energia)
print("masa =", masa)
pr... |
32033b5663ecc0fc8b905f8dc5a9362a29294e17 | florespadillaunprg/Validadores-en-python | /Verificador 10.py | 583 | 3.765625 | 4 | # calcular el tiempo de encuentro de dos autos
tiempo_de_encuentro,velocida_auto1,velocidad_auto2,distancia=0.0,0.0,0.0,0.0
# asignacion de valores
velocida_auto1=9
velocidad_auto2=6
distancia=150
# calculo
tiempo_de_encuentro=distancia/(velocida_auto1+velocidad_auto2)
#verificador
verificador=not(tiempo_de_encuentr... |
1b46437fb65a3d9515f07bb2bed3a3614196756d | florespadillaunprg/Validadores-en-python | /Boleta 05.py | 1,288 | 3.953125 | 4 | # INPUT
cliente=input("Ingrese el nombre del cliente:")
numero_de_DNI=int(input("Ingrese el numero de DNI:"))
numero_de_RUC=int(input("Ingrese el numero de RUC:"))
marca_de_celular01=input("Ingrese la marca del celular01:")
marca_de_celular02=input("Ingrese la marca del celular02:")
marca_de_celular03=input("Ingrese la... |
ef229ad0584d3f80335bb432b45932a6772b908e | florespadillaunprg/Validadores-en-python | /Verificador 02.py | 630 | 4.125 | 4 | # encontrar la diagonal principal de un paralelepipedo
diagonal_principal,diagonal01,diagonal02,diagonal03=0,0,0,0
# asignacion de valores
diagonal01=3
diagonal02=4
diagonal03=5
#calculo
diagonal_principal=(diagonal01**2)+(diagonal02**2)+(diagonal03**2)
#verificador
verificador=(diagonal_principal>=23 and diagonal01... |
eb893ff332875411416969830c3c535572decfe9 | SKeerthi02/48-days-leet-code-challenge | /ser_and_dser.py | 1,283 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
577cc77831393252e5ac6448801bee87f74d0aed | normoes/sameFiles | /files/packages/fileSearch.py | 3,677 | 3.546875 | 4 | import re
def case_sensitivity(case):
def new_func(func):
def func_wrapper(*args, **kwargs): #line, pattern, substitute
return func(case, *args, **kwargs) # line, pattern, substitute, case
return func_wrapper
return new_func
"""
def tags(tag_name):
def tags_... |
d3be90c830f81175151815f582b47035fd742367 | PovedaJose/TAREA-INVESTIGACION | /TareaInves/Menu1.py | 19,184 | 3.703125 | 4 | from Calculadora import calEstandar, calCientifica
from opeNumeros import Basico, Intermedio
from lista import Lista
from cadena import Cadena
import os
class Menu:
def __init__(self, titulo, opciones=[]):
self.titulo = titulo
self.opciones = opciones
def menu(self):
pri... |
5ec90b876e916f77f560830fa906b564ab97e707 | eyusti/tic_tac_toe | /tic_tac_toe.py | 18,469 | 3.875 | 4 | from random import randint
import math
import copy
import unittest
class Board:
def __init__(self):
self.board = [["?","?","?"],["?","?","?"],["?","?","?"]]
self.player_turn = None
def __repr__(self):
return "{0}|{1}|{2}.{3}|{4}|{5}.{6}|{7}|{8}".format(self.board[0][0],self.board[0... |
4e5eb4aa2206e13ca6e9725a864f4aa2c8f5b9c5 | csirelia/data_processing_using_python | /week2/totitle.py | 201 | 3.640625 | 4 | aStr = 'What do you think "No Pain, No Gain"?'
tempStr = aStr.split('\"')
print(tempStr)
if tempStr[1].istitle():
print('%s is the title' % tempStr[1])
else:
print('%s is not the title' % tempStr[1]) |
3405c62e2241c1b3eb15420cd9712a33d09f25be | pateljainilanilbhai/pythonprograms | /listsort.py | 277 | 3.796875 | 4 | def contains(x,y):
for i in x:
if(i==y):
return True
return False
x=input("enter few numbers for the list")
y=list(x.split(" "))
z=[]
print(y)
for i in y:
z.append(int(i))
z.sort()
print(z)
inp=input("input any number")
print(contains(x,inp))
|
2fe99b3de17ef011157d15df3d70cd9c4e28bedb | pateljainilanilbhai/pythonprograms | /railfence.py | 1,633 | 3.890625 | 4 | def printFence(fence):
for rail in range(len(fence)):
print(''.join(fence[rail]))
def encryptFence(plain, rails, debug=False):
cipher = ''
length = len(plain)
fence = [['#'] * length for _ in range(rails)]
# build fence
rail = 0
for x in range(length):
fence[rail][x] = ... |
ee47520136fb5e63637610ebb8484ed8cfafb78d | pateljainilanilbhai/pythonprograms | /14practical.py | 539 | 4.34375 | 4 | """Write a program (using functions!) that asks the user for a long string function.
containing multiple words. Print back to the user the same string, except
with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me."""
... |
bb689f3d405a3b77a13e9502326100850e9ec6cf | pateljainilanilbhai/pythonprograms | /tinkter.py | 3,148 | 3.671875 | 4 | import tkinter as tk
from tkinter import *
window =tk.Tk()
window.title("My Python First Window")
r=window
button = tk.Button(window, text='Stop', width=25, command=window.destroy)
master=r
w = tk.Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_... |
bf9284e941d92392d5437fd631e6de8f7e7a2cc9 | rishabhmanu/TicTacToe | /TicTacToe.py | 2,751 | 4.0625 | 4 | # A command based Tic-Tac-toe game
flag = 0
theBoard = {'top-l':' ', 'top-m':' ', 'top-r':' ',
'mid-l':' ', 'mid-m':' ', 'mid-r':' ',
'low-l':' ', 'low-m':' ', 'low-r':' '}
def printBoard(board):
print board['top-l'] + '|' + board['top-m'] + '|' + board['top-r']
print '-+-+-'
... |
5db045984a3a73a94f041e016571022ccc328cdb | 9oelM/permu | /permu.py | 2,602 | 3.921875 | 4 | #!/usr/bin/env python
from itertools import permutations
import argparse
from pathlib import Path
from typing import List
def wordlist(path_to_wordlist):
try:
Path(path_to_wordlist).read_text()
except:
print(f'failed to read a file from path: {path_to_wordlist}')
exit(-1)
return pat... |
60e94695439a894b7738571a1c899ea135b68b96 | brianhouse/terminal_moraine | /tree_simulator/tree.py | 5,891 | 3.609375 | 4 | import time, threading, math
from random import random, randint, choice
class Leaf():
number = 0
def __init__(self, tree, limb):
self.id = Leaf.number
Leaf.number += 1
self.tree = tree
self.limb = limb
self.tree.leaves.append(self)
@property
def position(self... |
12a9dc2496d483533920ee42fe756ee1efb1a1ad | hakusama1024/Practice | /tmp.py | 930 | 3.625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def Read():
stack_main = []
output = []
opNumber = int(raw_input())
for i in range(opNumber):
op = raw_input().split()
if len(op) == 1 and op[0] == "pop":
pop(stack_main, output)
elif len(op) == 2 a... |
889b94556555bac1131cad4610fb94c61a7d1b3d | hakusama1024/Practice | /3_Sum.py | 644 | 3.6875 | 4 | def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
size = len(nums)
if size == 0 : return res
nums.sort()
for i in range(size-2):
target = -nums[i]
l = i+1; r = size-1
while l < r:
if nums[l]+nums[r] == target:
... |
fa63590cfc66a60e0c9760c0e91797074be15550 | lowlySJY/assignments--MIT-6-0001-fall-2016 | /ps1c.py | 1,640 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 9 15:38:41 2020
@author: jinyi
"""
annual_salary = float(input("Enter the starting salary: "))
total_cost = 1000000
semi_annual_raise = .07
high_rate = 10000.0
low_rate = 0
portion_saved = high_rate
monthly_salary = annual_salary / 12
portion_dow... |
6347cc8e2ae20eef8ee2bad16a5bc888a66ff7fa | lucasharzer/Teste_Python | /exfn.py | 895 | 4.0625 | 4 | print('\033[1;31mFunção de Notas:\033[m')
def notas(*n, sit=False):
"""
-> Funcao para analisar notas e situacoes de varios alunos.
n: uma ou mais notas dos alunos (aceita varias)
sit: valor opcional, indicando se deve ou nao adicionar a situaçao
return: dicionario com varias informacoes sobre a si... |
5ed9798f5be9e44bc4abcba09c231babaccf7d09 | miltestcf/TareasCardenasPicado | /Errores_Flake8_Arreglado.py | 2,212 | 3.53125 | 4 | '''Código realizado por Milton Esteban Cárdenas Fley
y Sebastián Picado González Estudiantes de Ingeniería
en Mecatrónica en el Instituto Tecnológico de Costa Rica.
Con el propósito de crear muchos errores detectables en flake8.
Unos caracteres más que hicieron falta'''
import time # Se importa el módulo time
time.s... |
b9efbe78151578243dfe5ce2f018c6bd035b60ee | FarahNaz504/BSEF15M504 | /FCFS(new).py | 700 | 3.765625 | 4 | #!user/bin/python
print("First Come First Serve Algo")
a_time1=[]
b_time1=[]
p={}
p_num=input("Enter total number of processes:")
for index in range(0,p_num):
a_t=input("Enter arrival time:")
if(index==0):
min=a_t
elif(a_t<min):
min=a_t
a_time1.append(a_t)
b_t=input("Enter burst time:")
b_time1.append(b_t)
p... |
632a9c1dbf3d10afa9c4447f4ad98ba9b7eb2802 | jerilkuriakose/Website-Prediction | /GettingData/convert.py | 415 | 3.65625 | 4 | """
Converting the URLs from JSON format to CSV
"""
import json
import csv
# Read the JSON file
with open('convertlinks/convert.json') as data_file:
data = json.load(data_file)
# Get the required links
links = [d['convertedUrl'] for d in data]
# Saving as '.csv' file
with open('data/converted.csv', 'wb') as... |
2877df13dc28b1856e63812a36a1fcc649eaa508 | gourishankerJK/DataStructureGKV | /Graphs/BreadthFirstSearch.py | 2,074 | 4.0625 | 4 | class Queue():
def __init__(self, size=100):
self.Max_size = size
self.front = self.rear = -1
self.arr = size * [None]
def enqueue(self, value):
if((self.rear == self.Max_size - 1 and self.front == 0) or (self.rear + 1 == self.front)):
print("\nQueue is full")
... |
cb03394314ed7f461f758845dee3901037babf24 | gourishankerJK/DataStructureGKV | /Linkedlist/LinkedList.py | 3,936 | 4.09375 | 4 |
class LinkedList:
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __init__(self):
self.first = None
self.last = None
self.len = 0
def length(self): # returns the length at just o(1) ,i.e constant time
retur... |
dc276d14e302d374d147e9dc1eddc70c54193c9d | gourishankerJK/DataStructureGKV | /Lab/Matrix.py | 521 | 4.28125 | 4 | row = int(input("Enter the number of rows: "))
col = int(input("Enter the number of columns: "))
matrix = [[int(input("Enter the element: ")) for i in range(col)] for j in range(row)]
for r in matrix :
print(r)
minimum = matrix[0][0]
maximum = matrix[0][0]
for i in range(row):
for j in range(col):
if m... |
fc84648b9c1151e20bc6c19e4cf8ec0f3b23cc5a | Skull1991/NitEsh | /whatlol.py | 5,759 | 3.640625 | 4 | from tkinter import *
from tkinter import messagebox
import sqlite3
import random
skull=Tk()
global bill_no
global c_name
global c_phone
def clear():
c_name.set('')
c_phone.set('')
item.set('')
rate.set(0)
quantity.set(0)
welcome()
def exit():
op = messagebox.askyesno("Do you really want t... |
f937b37176eceee8c98b22178651178b4f610eb2 | balajisuresh1359/Data-structures | /graph.py | 2,430 | 4.09375 | 4 | from collections import defaultdict
#----------------------------------------------------------------------------
#Graph creation
class Node():
def __init__(self, data,next = None):
self.data = data
self.next = next
def AdjacencyList(num_nodes):
adjList=[None]*num_nodes
i=0
while i<num_nodes:
print("En... |
45b1a168548128916527cd34920c766266b42082 | malarcukdiana/Malarcyu_Lab_3 | /3_2.py | 313 | 3.875 | 4 | '''Рекурсивна формула для обчислення факторіалу:
n! = (n-1)! * n, якщо n > 0,
0! = 1'''
def fact(n):
if n == 0:
return 1
return fact(n-1)*n
n = int(input('n = '))
result = '{0}! = {1}'.format(n, fact(n))
print(result)
|
ab7707d77544c9c6ab8476e8df52059386d3771b | AnastasiiaLatysh/google_service_api | /test_data/random_data.py | 356 | 3.875 | 4 | import string
from random import choices
def get_random_string_with_digits(string_length=10):
"""
Generate random string with ASCII letters in lower case mode
:param string_length: (int) length of string which should be generated
:return: (str)
"""
return ''.join(choices(string.ascii_lowercase... |
08db7c2a5798fb8b175afffd3337bf9b90474dfb | vmcustodio/curso_share_ufscar | /VanessaCustódio_EX02/VanessaCustódio_EX10.py | 132 | 3.875 | 4 | raio = float(input("digite o raio da circunferencia: "))
area = 3.14159*(raio*raio)
print("a area é igual a = {:.4f}".format(area)) |
75084926804890951eeaff0ba302ab192aa3b21b | vmcustodio/curso_share_ufscar | /VanessaCustódio_EX05/VanessaCustódio_EX10.py | 466 | 4.09375 | 4 | x = int(input("Digite um numero pra imprimir essa quantidade de numeros primos: "))
qtdePrimos = 0
numero = 2
while qtdePrimos < x:
cont = 3
if numero ==2:
print(numero)
qtdePrimos +=1
elif not(numero % 2 ==0):
while cont < numero:
resto = numero%cont
cont+=2
... |
1ff717a3c5326d9a57e6689c2844e4e5e0e24efd | vmcustodio/curso_share_ufscar | /VanessaCustódio_EX02/VanessaCustódio_EX03.py | 226 | 3.6875 | 4 | dias = int(input("digite os dias: "))
horas = int(input("digite as horas"))
minutos = int(input("digite os minutos"))
segundos = int(input("digite os segundos"))
total = print((dias*86400)+(horas*3600)+(minutos*60)+(segundos)) |
4733cd2a99c822ff870da0b1a2babbf89aa27874 | vmcustodio/curso_share_ufscar | /VanessaCustódio_EX06/VanessaCustódio_EX02.py | 113 | 3.578125 | 4 | lista = [7,8,6,7,2,6]
cont = 0
soma = 0
while cont < len(lista):
soma += lista[cont]
cont+= 1
print(soma) |
a3efd4c411775307c6cbd54adf79e4f30c221c2a | alexsieusahai/dim | /src/algorithms/binSearch.py | 1,796 | 3.75 | 4 |
def dirBinSearch(dirsLinkedList, dirs, substr, oldIndex):
"""
Find the directory in dirs such that it begins with substr
If it exists, return the node
otherwise, don't do anything
Note that dirs begins with '..', so we don't want to bin search over that, hence our left index starting at 1
... |
07b6a1ce4f558cd94e8bbd1fdb62b6a744a3b379 | alexsieusahai/dim | /src/dataStructures/lineNode.py | 430 | 3.546875 | 4 | class LineNode:
def __init__(self, line, lastNode):
"""
`line` is a string which will be the value of this node
`lastNode` is the pointer of the node before it
"""
self.value = line
self.colors = []
for c in line:
self.colors.append(0) # set all c... |
345b9a879c2795fe859f3eb0992f4cdfce4e725c | Edward-Knighton/Regulation.gov_Webscraper | /sentiment_analysis_research/usingTxtBlob.py | 460 | 3.515625 | 4 | from textblob import TextBlob
#this program takes a string and returns support
#oppose, or neutral depending on its sentiment
#def sentimentAnalysis(text):
text = """I oppose the proposed Section 301 action imposing new tariffs. American families and small businesses are still struggling to make ends meet, and we c... |
a62fd7a3d312f21d2eadf0e30600deae5180e9a7 | Kalebu/Automate-shutdown-python | /app.py | 1,199 | 3.703125 | 4 | import os
import platform
OS_type = platform.system()
OS_type = OS_type.lower()
def shutdown(time):
'''
It automate shutdown by scheduling the
time for computer to shutdown
'''
if OS_type == 'linux':
shutdown_str = 'shutdown -t '+ str(time)
elif OS_type == 'windows':
time = ... |
f97dfd4c92e82d30dc28f530b4e2267671753ea7 | iammosespaulr/selfies | /selfies/utils.py | 7,297 | 3.90625 | 4 | from typing import Iterable, Set, Tuple, List, Union
def len_selfies(selfies: str) -> int:
"""Computes the symbol length of a SELFIES.
The symbol length is the number of symbols that make up the SELFIES,
and not the length of the string itself (i.e. ``len(selfies)``).
:param selfies: A SELFIES.
... |
869ceeac3fb9e9d6e20f5e181438a7a3963c1049 | Eyobkibret15/coin-change | /coin_change.py | 5,155 | 4.3125 | 4 | available_coins = [1, 2, 5, 10, 20, 50, 100]
change_to_be_made = int(input("enter the change to be made. "))
while change_to_be_made < 0:
print("change_to_be_made should be positive number ")
change_to_be_made = int(input("enter the change to be made. "))
def coin_change_for_canonical_coin_system(cha... |
43b73f41a02bf63d689961db7ef7502221eba66f | kurohai/advent-of-code-2016 | /day_03.py | 1,393 | 3.53125 | 4 | #!/bin/env python
import sys
def parse_lines_v2(lines):
c1 = [i[0] for i in lines]
c2 = [i[1] for i in lines]
c3 = [i[2] for i in lines]
i = len(lines)
c = 0
t1 = list()
t2 = list()
t3 = list()
all_those_triangles = list()
while c < i:
l = lines[c].strip().split()... |
a40c9d67c2f93f3cc8694704d7f4be2f622135e3 | bobbybotbop/brazilTurtle | /main.py | 1,895 | 3.59375 | 4 | import turtle
t = turtle.Turtle()
t.speed(0)
num1 = 3
num2 = 14
number1 = 16
number2 = 1
def drawRectangle():
t.penup()
t.goto(-300, 150)
t.color('green')
t.pendown()
t.begin_fill()
for i in range(2):
t.forward(500)
t.right(90)
t.forward(300)
t.right(90)
t.end_fill()
t.penup()
def d... |
f27931ee38b5f2945fad6a2726a7fc078943e56a | jackeast23/PythonBible | /tuples.py | 275 | 4.28125 | 4 | # Tuples are like lists that cannot be changed
our_tuple = (1,2,3,"A", "B","C")
print(type(our_tuple))
print(our_tuple[0:3])
our_list = [1,2,3,4,5,6,7]
our_list[2] = 100
print(our_list)
# This will not work for tuples
# our_tuple[2] = 100
A = [1,2,3]
print(tuple(A))
|
de52fcfac8ddb77a0a409735888b2edf38af1622 | Wealthysdot/Zuri | /initails.py | 751 | 3.640625 | 4 | from budgetApp import Budget
start = Budget("budget")
def init():
print("Welcome to EagleBudget")
try:
to_do = int(input("What would you like to do:\n"
"Enter 1 to create budget \n"
"Enter 2 to enter expenses \n"
"Enter 3 t... |
d40f1c9ccf03c93d469b4a13ce2a78f407578ba6 | Piragix/hello | /test.py | 217 | 3.59375 | 4 | print("Hejsan svenjsan mister baboonga")
print("Jonathan, where are my balls Jonathan?")
location = input("Jonathan, where are my balls Jonathan?" )
print(f"Go to {location}, and bring me my balls Jonathan") |
d039e70ea3f12cfc5737f420b0e569bac1f41cd0 | StianHanssen/AlgDat | /div/Merge Sort.py | 821 | 3.921875 | 4 | import random
__author__ = 'Stian'
def merge_sort(list):
list = [[i] for i in list]
while len(list) != 1:
item1 = list.pop()
item2 = list.pop()
list.insert(0, merge(item1, item2))
return list[0]
def merge(list1, list2):
newList = []
while not list1 or not list2:
it... |
09a68d8bff548d2b9d53a0395cee4271c1c355e0 | tonhathuy/Machine-Learning | /Neural_Network/layer/activation_layer.py | 972 | 3.734375 | 4 | from layer import Layer
class ActivationLayer(Layer):
def __init__(self, input_shape, output_shape, activation, activation_prime):
"""
input_shape: dau vao input mang (1,4)
output_shape ....
activation C
activation_prime : C'
"""
s... |
cf04fa14bdcd130a404c1625d94c82bbc9efde35 | Lindisfarne-RB/GUI-L3-tutorial | /chrish.py | 4,085 | 4.1875 | 4 | # functions go here
import random
def welcome(name):
print("Welcome", name + "!")
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
# if they say yes, output 'program continues'
if response == "yes" or response == "y":
response =... |
4206296518f89f3742c14e79cbe9378ea4ab5899 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson28.py | 4,430 | 4.6875 | 5 | ''' LESSON 7.3
LEARN
Using a LabelFrame
Tkinter and ttk also offer us the LabelFrame widget. A LabelFrame is exactly what it sounds like - a frame with a label. We can pass in an optional text argument to put a label on the frame. It also puts a border around it automatically:
my_labelframe = ttk.LabelFrame(root, text=... |
3c8f02031bb679436441b130fdce80bb7c5743e1 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson35.py | 3,423 | 4.09375 | 4 | '''Adding a command to Radiobutton widgets
So, all of our radiobuttons use the same variable but they each have different values. This is because for a radiobutton, we generally want to know what the user chooses out of a set. In our example, they're choosing a color, but they can only choose one.
Let's add a function... |
25247c791f7a1cbbe94ded918f40633acac870e8 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson12.py | 2,001 | 4.0625 | 4 | '''Adding the amount entry field
Ok, now we need to create a variable so that we can store the value the user types in, and create the Entry field itself.
Users might want to enter an amount like $65.50 so we'll need to use a DoubleVar() which will let us store float values. When we do this, it puts the value 0.0 into... |
9b8e6fc4de11b71eeed370e0607615873a87b4b9 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson15_Button_action2.py | 2,772 | 4.40625 | 4 | '''Themed tkinter widgets or ttk
If you put tkinter code into a Python editor on your computer such as IDLE or PyCharm and run it, you might be disappointed with how plain the GUI looks. This might make you want to brighten it up with some colors and things like we did with our submit button. However, as we've mentione... |
97b1d9972b69c6ac57571ae5c38fda83106ea371 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson4.py | 1,534 | 4.71875 | 5 | '''More on creating a label
In the first lesson we had a look at how to create a window and add a label. In this lesson we are going to take a closer look at labels!
When we create a label, there are a few other parameters we can set in addition to the parent and the text. Let's look at some:
my_label = Label(root, t... |
5d1dc2d1e2eb2a12976edd744f35c2bb7792753b | Lindisfarne-RB/GUI-L3-tutorial | /Lesson8.py | 1,366 | 4.46875 | 4 | '''Getting to know the Entry widget.
A widget that is commonly needed in a GUI app is an Entry widget. This is a basic text input field that the user can type into. Let's see how it works:
name_entry = Entry(root, textvariable=name, width=30)
Usually, we would have it linked to a variable because we most likely want t... |
a45e687f8662470eebbe0101057d00e0ec79b13c | Lindisfarne-RB/GUI-L3-tutorial | /Lesson41.py | 5,073 | 4.09375 | 4 | '''Updating our GUI display
Alright, the final step in this version of our app! Now we need to update the details_label so that we can see the new account balances. To do this we'll need the following:
Each of the balance variables
To calculate the total balance
A string that we can plug all of the values into and set... |
af0af537f84089987b90b21e76f3c87704dd11ad | ShuangyuandData/CRISP-DMpro1 | /attach2.py | 5,105 | 3.59375 | 4 | import pandas as pd
import numpy as np
from collections import defaultdict
#import AllTogetherSolns as s
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error
import matplotlib.pyplot as plt
## Putting It All Toge... |
70e69af824b0e63853b3d7ac809763c6dbb82039 | mahdidahmani/Python | /syracuse.py | 618 | 4 | 4 | # Calcule de la suite de Syracuse
# 1er Programme sur Python
def syracuse(Nombre,Count,Max) :
while Nombre != 1 :
print(Count," : ",Nombre)
if Nombre%2 == 0 :
Nombre = Nombre // 2
else :
Nombre = Nombre * 3 + 1
Count += 1
if Nombre >= Max :
... |
f15fdec0e64219334af96a7c867be1c6d8a8e4da | ihjohny/UVA-Solutions | /UVA-Solutions-Python/458 - The Decoder.py | 223 | 3.6875 | 4 | # 458 - The Decoder
while True:
sentence = str(input())
if(len(sentence)>0):
decrypted=''
for i in range(len(sentence)):
decrypted+=chr(ord(sentence[i])-7)
print(decrypted)
else:
break
|
f6e2cedfae00c3616df12fcdf95eec78f29d1013 | Sam-tech-max/dnd-Helper | /Server/Equipment/Item.py | 13,418 | 3.640625 | 4 | class Item:
def __init__(self, name: str = "meat, chunk",
itemType: str = "generic", cost: int = 3,
costType: str = "gp", amount: int = 1):
self.name = name
self.itemType = itemType
self.cost = cost
if(not(costType == "cp" or costType == "sp" or
costType == "ep" or costType == "gp" or costType == ... |
d52a03e2fbb19f94c5e6fb5e3e8ae6b17c26290e | stefangelova/python-testing | /applications/python.py | 100 | 3.875 | 4 | import math
number = float(input("Enter a number:"))
answer = math.sqrt(number)
print(answer) |
e1b958a41b92283537866f513022118f9177ed64 | ayazhassan-courses/project-dragonfly | /Code/my new algo.py | 6,293 | 3.5625 | 4 | import hashlib
import math
import tkinter as tk
from tkinter import filedialog
def get_index(string,prime): # n = number of index
string = string.lower()
m = hashlib.sha256(str.encode(string))
hash_result = m.hexdigest()
index_number= int(hash_result,16) % prime
return (index_number,str... |
eb746fd8c9387d8da1677c107d112680fb8924e6 | duran221/curso_python | /34.Modulos(Practica)/funciones_matematicas.py | 338 | 3.796875 | 4 |
#Vamos a crear varias funciones en este modulo:
def sumar(num1,num2):
print(f"El resultado es: {num1+num2}")
def restar(num1, num2):
print(f"El resultado es: {num1 - num2}")
def multiplicar(num1, num2):
print(f"El resultado es: {num1 + num2}")
def potencia(num1, num2):
print(f"El resultado es: ... |
ba4dd93899c220c4c51643ee2dd9fb78d8b85e11 | duran221/curso_python | /45.interfaces_graficas_entry_grid/interfaces.py | 1,480 | 4.375 | 4 |
#Importando la libreria tkinter
from tkinter import *
#Creando la ventana
ventana= Tk()
#Creando el panel o Frame
frame= Frame(ventana, width=500,height=500)
#Importante-Empaquetar el frame:
frame.pack()
#En lugar de pack() o place() se es posible añadir el metodo grid() el cual nos permite ubicar los elementos co... |
36745a4595738dab769db7028a8eb22b4b1694b5 | duran221/curso_python | /15.Bucles(Practica)/bucles.py | 567 | 4.03125 | 4 |
#Se puede comprobar si un correo electronico tiene el formato correcto de una manera muy sencilla:
email= "cristian@gmail.com"
contador=0
#Podemos recorrer una cadena de texto de la siguiente manera:
for i in email:
if(i=="@" or i=="."):
contador+=1
if(contador>=2):
print("Formato correcto")
else:
... |
fdf00857cbbf58f880e206b180b8d70aecee0da6 | pragya1010/Automation-using-Jenkins | /palindrome.py | 242 | 3.6875 | 4 | def palindrome(s):
if isinstance(s, str):
return s[::-1]
else:
s = str(s)
return int(s[::-1])
def add(a, b):
return a+b
def test_palindrome():
assert palindrome("Pragya") == "aygarP"
def test_add():
assert add(1,2) == 3 |
cbb6126f3e10b09edb731e7e67adede0cddbcd36 | DavidMHoang/The-Self-Taught-Programmer | /TSTP/Chapter12/ch12-2.py | 186 | 3.75 | 4 | import math
class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return (2 * math.pi * self.radius)
circle = Circle(10)
print(circle.area())
|
eff5f5afa5ee5090114da7f96b539b90171f0112 | DavidMHoang/The-Self-Taught-Programmer | /TSTP/Chapter4/ch4-4.py | 377 | 3.859375 | 4 | def func1(x):
"""
Function that divides the parameter by 2.
:param x: int.
:return: x divided by 2.
"""
return x / 2
def func2(x):
"""
Function that multiplies the parameter by 4.
:param x: int.
:return: x times 4
"""
return x * 4
def main():
var1 = func1(6)
var... |
101b092f232bec65febff05874ccf9d0466d3474 | MAXIMZOLOTYKH11/proj4 | /main.py | 812 | 3.90625 | 4 | while True:
play = input('Start the game: ')
if play == "Yes":
text = str(input('Enter text in russian language: '))
letter = str(input('Enter letter: '))
v_letter = 'аеёиоуыэюяАЕЁИОУЫЭЮЯ'
c_letter = 'бвгджзйклмнпрстфхцчшщъьБВГДЖЗЙКЛМНПРСТФХЦЧШЩЪЬ'
signs = ' !"#$%&()*+,-.... |
7bc094e6061ee8354fe0b26dce93d3ac13fcea70 | palyaros02/AOD | /7/7_dynamic.py | 1,737 | 3.765625 | 4 | task = """
20(1). Посчитать число последовательностей нулей и единиц длины n, в которых не встречаются две идущие подряд единицы.
Динамическое программирование
"""
import time
def timeit(f): # декоратор для замера времени
def wrap(*args):
time_start = time.time()
ret = f(*args)
time_end ... |
5d42cabe32ffeb8addda48f310de3363b05aa29c | MTT-NDL/BTVN | /BTVN4/Ex5.py | 2,719 | 3.78125 | 4 | PoN = input('Enter \'play\' to start the game: ')
if PoN.lower() == 'play':
print('NHAP O CHO PHEP TINH DUNG VA X CHO PHEP TINH SAI')
point = 0
while 1:
print('Point = ', point)
from random import randint
tf = randint(0,1) # 0 == False, 1 == True
pt = randint(0,1) # 0 == +, 1 == -
a = ra... |
7a19f786230d852125160dfc8951bfcafc460abc | qhzhuang/gitdemo | /Chapter02/进程demo.py | 1,156 | 3.546875 | 4 | import threading
import time
import multiprocessing
# balance = 0
lock = threading.Lock()
balance = 0
def fun1(a, b, c):
global balance
for i in range(5):
# lock.acquire()
time.sleep(0.5)
balance -= a
balance += a
# print("a:", a, "b:", "c", c)
# print... |
e9dd02ca7c0415c9b6ba8f71214960d4827b7c01 | balamuruganjbm/code-kata | /Sorting-1.py | 615 | 3.5625 | 4 | arrLen1 = int(input())
arr1 = list(map(int,input().strip().split()))[:arrLen1]
arrLen2 = int(input())
arr2 = list(map(int,input().strip().split()))[:arrLen2]
newArray=dict()
for val in range(arrLen1):
if arr1[val] in newArray.keys():
newArray[arr1[val]] += 1
else:
newArray[arr1[val]]=... |
3e4c0ac60bb08ae538119d11c23e3484487385bf | mklin47/python3.6-collections | /tuple_test.py | 1,734 | 3.875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# Python 的元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,列表使用方括号。
# 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
# 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用
# 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合tuple1 + tuple2
# 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组
name_tuple = ('hahaxiao', 'ganlanzhi')
old_id = id(name_... |
1b35b87a9622867294c4af7f334aa6e91425257f | niteshmrh/ASSIGNMENT-PYTHON_TILL_LOOP-REGex | /ASSIGNMENTS_PYTHON_Q10_DISJOINT_DICT.py | 640 | 4.03125 | 4 | def main():
myDict={"Sharp":"smart", #defining my dictionary
"Bright":"student",
"clever":"fox",
"Dumb":"stupid"
}
myDict2={"fool":"stupid",
"joy":"happy",
"Sharp":"smart",
"Dumb":"stupid"}
disjoint_pairs = dict()
for key in myDict:
if (ke... |
1333deacbe18d8d5e1f66fdf1617d76bf2e8b8e7 | hongpan0507/Programming | /Python/pycharm/tutorial/tutorial.py | 506 | 3.625 | 4 | #Notes:
#
#
import time;
num1 = 0.1
num2 = 100
str1 = "hello"
list = [785, 'name', 70.2]
print (list)
print(list[0])
print(list[0:]*2)
if num2 == 100:
if num1==1:
print (num2)
else:
print(str1)
else:
print("Num2 is one hundred")
for num2 in range (100, 105):
print(num2)
++num2
w... |
1f555ad8d60ef83cd8226f9455bd88b7ed4b6aa7 | nabin47/leetcode | /linked-list/21-merge-two-sorted-lists.py | 1,133 | 3.859375 | 4 | # Time Complexity: O(n+m)
# Space Complexity: O(m)
# Approach: Iterative
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None:
return l2
elif l2 == None:
... |
2019c940140eb093e4f08a4d53c34101d2c60479 | ikottman/devcon-word-cloud | /submission_cleaner.py | 1,200 | 3.609375 | 4 | from nltk.stem import WordNetLemmatizer
import string
class SubmissionCleaner:
@staticmethod
def combine_similar_words(words_list):
lemmatizer = WordNetLemmatizer()
reduced_list = []
# find the lemma of each word
for word in words_list:
reduced_list.append(lemmatize... |
ba6dbcbbcc739a3e39985ac2b662b1c3fad7eba4 | Gayathri547/DAY1_main | /STRINGS/3_Sum_generator.py | 522 | 4.1875 | 4 | ############ 1st way without using functions
print("***** 1st way *****")
x = input("enter the digit you want to copy:\n")
y = int(input("enter your number:\n"))
l = list(x*y)
print(l)
sum = 0
for i in l:
sum += int(i)
print(sum)
############ 2nd way by using functions
print("***** 2nd way *****")
def fun1(a1,a2):... |
0c66609bbabc2780e4bd9788c74f9d0a41dbd098 | Gayathri547/DAY1_main | /BASICS/7_str_count.py | 357 | 3.96875 | 4 | ################## 1st way
print("***** 1st way *****")
a=input("enter a string\n")
b=input("enter the character that you want to search")
print(a.count(b))
################## 2nd way
print("***** 2nd way *****")
c = 0
x= input("enter a string:\n")
y = input("enter the character you want to search:\n")
for i in x:
... |
b062b6da3403c2c5a3396a165885f99b229e8d17 | Gayathri547/DAY1_main | /BASICS/2_fn_ln_reverse.py | 882 | 4.5 | 4 | #Prompt user for first, last names and print them in reverse order.
##########################1st way
#By considering the first and last names have to print as lastname follwed by its first name
print("\n***** 1st way *****")
x = input("enter your first name:\n")
y = input("enter your last name:\n")
print("your name i... |
cae30a024ce669b9ef6b7b9b787fad1649184a0a | kachergis/trajSRTjs | /python/bv_script_sequence_making_online.py | 5,244 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 14:48:07 2020
@author: Bas Vegt
Purpose: creating text file containing number 1-4 to feed into another programm
Requirements:
Alpha: We need 960 steps, 240 sequence, every sequence 40 times.
Alpha note one: Each need to appear 39 times in the randomized... |
0d8cf0e4b69dfb86f45abf8b79441135eb062993 | falhajji/python | /functions_task.py | 1,544 | 4.40625 | 4 | from datetime import datetime
#userdate=datetime.(year, month, day)
#or you can use today = datetime.now()
#birthdat
def check_birthdate(year, month, day):
today = datetime.now()
DOB = datetime(year, month, day)
#DOB has to be defined here within the function so the code can recognise the paramters of year month ... |
6201917b4345abefb81055e41af8bbce02a2cebc | JinyongYoon/Python-for-everyone | /py4e2 - Data Strucutre/exercise/exercise6~8.py | 1,225 | 3.84375 | 4 | # Exercise6.5
text = "X-DSPAM-Confidence: 0.8475"
start = text.find("0")
data = float(text[start+1 :])
print(data)
words = 'Hello World'
print(words[0:1])
# Exercise7.1
fhandle = open("/Users/jinyong/py4e/mbox-short.txt")
for line in fhandle:
line = line.rstrip()
print(line.upper())
# Exercise7.2
fname = ... |
9f5d47b59d703da9e49f814f6cc57965229e3012 | C-CCM-TC1028-102-2113/programs-that-require-calculations-Sara-SV5822 | /assignments/03Promedio/src/exercise.py | 386 | 3.625 | 4 | def main():
#escribe tu código abajo de esta línea
cal_1=float(input('Calificación de la materia: '))
cal_2=float(input('Calificación de la materia: '))
cal_3=float(input('Calificación de la materia: '))
cal_4=float(input('Calificación de la materia: '))
prom=(cal_1+cal_2+cal_3+cal_4)/4
print('El promed... |
a876173acd45c88a65db82f1255448d6938dffbd | eignatenkov/aoc2020 | /solutions/day_18.py | 1,927 | 3.75 | 4 | def parse_line(line):
result = []
split = line.strip()
for symb in split:
if symb != ' ':
try:
result.append(int(symb))
except:
result.append(symb)
return result
def find_opening_bracket(line):
bracket_counter = -1
for i in range(... |
5bf615b02f6433096cef653cd77c74a3b1603325 | ishanimandli/RestaurantRating | /ratings.py | 1,095 | 4.125 | 4 | """Restaurant rating lister."""
def creates_dictionary(filename):
restaurant_dictionary = {}
given_file = open(filename)
for line in given_file:
line = line.rstrip()
words = line.split(":")
restaurant_dictionary[words[0]] = words[1]
return restaurant_dictionary
def prints_rati... |
813799c3b9894398f573346fd7011833b66241f3 | MaKYaro/prog_Klykin | /dragon_game/gameunit.py | 486 | 3.609375 | 4 | class Attacker:
"""Общий класс для всех объектов игры"""
health = None
attack = None
answer = None
def attack(self, target):
"""
Нападение на соперника
:param target: соперник
:return: Value
"""
target.health -= self.attack
def is_alive(self):
... |
c90fbf2afe3b0634ab8fb81e42146d45e670410c | MaKYaro/prog_Klykin | /turtle.my/turtle9.py | 354 | 4.28125 | 4 | import turtle
t1 = turtle.Turtle()
t1.shape('turtle')
def circle_r(length: float, number: float):
"""Рисует окрудность с поворотом вправо"""
for step in range(number):
t1.forward(length)
t1.right(180/number)
t1.left(90)
for numbers in range(3):
circle_r(1, 200)
circle_r(0.4, 100)
... |
32d5b0fde3a340de4e9ea542e2a5111925e865e8 | UjeanPoloz/python_hw | /homework_20.py | 951 | 3.5625 | 4 | import random
def diff_positive_negative(num_limit, ind = 100, lower_bound = -100, upper_bound = 100):
negative_var = 0
positive_var = 0
for i in range(ind):
num_limit.append(random.randint(lower_bound, upper_bound))
if num_limit[i] < 0:
negative_var = negative_var + num_limit... |
ced68971f774d952597e6ca74d0803dff9ac0bdf | UjeanPoloz/python_hw | /homework_15.py | 436 | 3.890625 | 4 | var_x1 = 2
var_y1 = 2
radius_1 = 5
var_x2 = 9
var_y2 = 9
radius_2 = 8
def cirles_intersects(x1, y1, r1, x2, y2, r2):
center_distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
sum_radius = r1 + r2
return center_distance <= sum_radius and center_distance >= abs(r1 - r2)
if cirles_intersects(var_x1,var_y1,radius... |
66dd587d413c3b753978d0fd9ee34b910e8e5e68 | danjamthelamb/Python-Challenge | /PyBank/Main.py | 1,432 | 3.625 | 4 | import os
import csv
month_count = 0
profit_losses = 0
last_month = 0
this_month = 0
change = 0
greatest_inc = 0
greatest_dec = 0
average_change = 0
change_tally = 0
budget_data_path = os.path.join('Resources', 'budget_data.csv')
with open (budget_data_path, newline='') as budget_data:
read_budget_data = csv.rea... |
80a7a3f627fe20ec5eacb8e2135d75f1699fc3ab | monalipawar92/Python-Programming | /break2.py | 204 | 3.984375 | 4 |
n = int(input("Enter any number:"))
number = [10,11,12,13,15,16,17,18]
for a in number:
if a == n:
print ("Number found in list")
break
else:
print ("Number not found in list") |
83e9d93ff50e85cbf98d7b340554e4fc62ed1bd4 | akashghanate/OpenCV | /imageSegmentation/contours.py | 934 | 3.84375 | 4 | #segmentation - partitioning images into different regions
#contours are the continuous lines or curves that bound/cover the object completely
# contours are important in object dtetection and shape analysis
import cv2
import numpy as np
#image
image=cv2.imread('/home/akashkg/OpenCV/images/order-copy.jpg')
cv2.imsho... |
6a2e6568a28c1a79658748788e38d898ddfc304d | frestea09/Python | /src/aritmatika/aritmatika_pertama.py | 835 | 3.734375 | 4 | #name-file : aritmatika.py
from __future__ import print_function
import os
def main():
#mengambil input dari dekstop
bilanganPertama = int(input('Bilangan Pertama: '))
bilanganKedua = int(input('Bilangan Kedua: '))
#aritmatika python
hasilPenjumlahan = bilanganPertama + bilanganKedua
hasilPengur... |
17f93bd7201e59f837ac1a5973d1661014e72976 | mandhyan/handwrittingOCR | /knnOCR.py | 1,143 | 3.53125 | 4 | import cv2
import numpy as np
#Load the training image
img = cv2.imread("handwritten.png")
#Convert this Image in gray scale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]
# Make it into a Numpy array. It ... |
8083427dae144ddd5050032cd0944a1e8d5f5275 | jeslinmx/advent2020 | /3.py | 500 | 3.59375 | 4 | # Problem: https://adventofcode.com/2020/day/3
# Input
from sys import stdin
trees = [[char == "#" for char in line.strip()] for line in stdin]
# Part 1
from itertools import count
def collisions(right, down):
return sum([
trees[row][col % len(trees[0])]
for row, col in zip(range(down, len(trees),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.