blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a545413a46b6c0eef01af78d3abea03ed73069dd | Mofadhuman/learngit | /students.py | 1,767 | 3.703125 | 4 | def print_menus():
print("="*30)
print("输入数字1添加学生")
print("输入数字2查找学生")
print("输入数字3修改学生")
print("输入数字4删除学生")
print("输入数字5显示所有学生")
print("输入数字6退出")
def add_student():
name=input("请输入你要添加学生名字")
age=input("请输入你要添加的学生年龄")
qq=input("请输入你要添加的学生的QQ号码")
stu={"name":name,"age":age,"qq":qq}
stus.append(stu)
def se... |
42e785292e1f84024ae3c85a5a965712b72e2f79 | thai321/CS170 | /HWs/9/hw9.py | 2,499 | 3.828125 | 4 |
def overlap(s1,s2): #O(k^2n^2)
if len(s1) < len(s2):
s1,s2 = s2, s1
# print "len(s2) = ", len(s2)
for i in xrange(0,len(s1) - len(s2)):
if s1[i:i+len(s2)] == s2:
print "Here1"
return i, len(s2)
for i in xrange(len(s1) - len(s2), len(s1)): #inside
if s1[i:] == s2[:len(s1) - i]:
print "here2"
retu... |
d935a5afb9fef4ab95c387910fce022ccedb5959 | adityadesle/Python-2 | /Web Book/web_book.py | 2,170 | 3.59375 | 4 | from urllib.request import urlopen,urlretrieve
from bs4 import BeautifulSoup
#File path to store the webpages
FILE_PATH = ""
URL = ""
PAGES = []
IMAGES = []
#Function to fetch web page
def fetch_page(link):
#Main page HTTP response
html = urlopen(URL+"/"+link)
#Extracting HTML from the resp... |
3c87d19a0355021a713fe21f8508b8ba05a3fbdf | winstonliu/AI-Final-Project | /main/monte_carlo.py | 6,779 | 3.75 | 4 | from main import reversi;
import random;
from copy import deepcopy;
import itertools;
all_nodes = {};
class Node(object):
def __init__(self, board, player):
'''Build a new node object with no parents.
Children will automatically be initialized to all valid moves, but thier nodes will not be searc... |
949dded321f2df2e92e7c04f99958fda817c4464 | sunshinewxz/leetcode | /31-nextPermutation.py | 769 | 3.515625 | 4 | class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
index = len(nums)-1
while(index > 0 and nums[index]<=nums[index-1]):
index -= 1
if index == 0:... |
e73a163512bd50ad94d72bf94c18104250799c9f | Elvis-Lopes/Curso-em-video-Python | /exercicios/ex101.py | 465 | 3.921875 | 4 | from datetime import datetime
def voto(nascimento):
anoAtual = datetime.now()
idade = anoAtual.year - nascimento
if idade < 16:
return print(f'com a {idade} não pode votar')
elif idade > 16 and idade < 18 or idade >60:
return print(f'com a idade {idade} o voto é opcional')
else:
... |
0f02d5c7267b437b6a1cf59dcc7af8105cc5fd98 | chaquen/python_course | /palabra_reservada_del.py | 227 | 3.515625 | 4 |
vocales="a e i o u"
lista= vocales.split()
print(lista)
print("eliminar elemento de lista")
del lista[3]
print(lista)
print("eliminar variable, ver error, indica que variable ya no esta definida")
del vocales
print(vocales) |
1df26110dca88714061a356d1b176908908b22d0 | Soham-coder/Raspberry_pi_edge_ML | /DWT_quantized/form_dict.py | 509 | 3.53125 | 4 | import os
category_list = []
image_list_new = []
input_image_dir = input("Enter path of image directory where images are present:")
print("Entered image directory is : ", input_image_dir)
pic_list=os.listdir(path = input_image_dir)
for image in pic_list:
image_list = image.split('_')
category = image_list[3].st... |
80f7b1b3a7f162678f2a5cb704eb35015c53b2c5 | ahmad-moussawi/python-exercices | /odd_even.py | 144 | 4.125 | 4 | # odd numbers: 1, 3, 5, 7, 9 ...
# even numbers: 0, 2, 4, 6, 8, 10 ...
x = 7
is_even = x % 2 == 0
print(f"Is {x} an even number?", is_even)
|
9757fd99979e72d5cdd910680105be05341343f5 | Lynguyen237/practice_probs | /count_islands.py | 2,475 | 4.09375 | 4 | '''
https://leetcode.com/problems/number-of-islands/
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the gri... |
cbe5debb85ec979de723602272976638f4daf1b5 | pradeepsathyamurthy/Python-Programming | /course2/week-2 - Files/practice_week2_files.py | 1,721 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 18:55:25 2016
@author: prade
"""
# 7.1 Write a program that prompts for a file name, then opens that file and reads through the file,
# and print the contents of the file in upper case. Use the file words.txt to produce the output below.
# You can download t... |
3b9f8536fa14d129023dc718a53a1d2a4b61a270 | KyungHoon0126/Algorithm | /이것 취업을 위한 코딩 테스트다 with 파이썬/DFS & BFS/Pratice.py | 2,503 | 4.125 | 4 | # Stack
stack = []
stack.append(5)
stack.append(2)
stack.append(3)
stack.append(7)
stack.pop()
stack.append(1)
stack.append(4)
stack.pop()
print("Stack Asc : ", stack)
print("Stack Desc : ", stack[::-1])
# Queue
from collections import deque
# 큐(Queue) 구현을 위한 deque 라이브러리 사용
queue = deque()
queue.append(5)
queue.... |
19524e31a18eda1af79012f82e1229bfa0783791 | lcmartinez45/Python | /lab6/grades_Martinez.py | 756 | 3.765625 | 4 | # Lillian Martinez
# Date: 4/14/19
# Program Description:This function will calculate the average of all 5 test scores and
# return the average.
def calc_average(score1, score2, score3, score4, score5):
# Declare Variables
average = 0.0
average = (score1 + score2 + score3 + score4 + score5) / 5
... |
27fb6f05a80dfd4a021f64ee0c89d3b6fd0adffd | spike688023/The-Python-Workbook-Solve-100-Exercises | /all_exercises/80_spike.py | 769 | 4.03125 | 4 | """
這題 跟前一題 的差別,在於,
要把密碼 沒有滿足的條件,給 寫進去。
"""
Isnumberic = False
Isupper = False
while True:
password = input("Enter new password: ")
for i in password:
if i.isnumeric():
Isnumberic = i.isnumeric()
if i.isupper():
Isupper = i.isupper()
if i.isnumeric() and i.isupp... |
ed03cc6e11339e6d1ca41ef8a9a3af63bef94aa2 | GregDMeyer/quantum-advantage | /analysis/count_gates.py | 5,653 | 3.59375 | 4 | """
This script generates circuits for computing x^2 mod N, and counts the number
of gates in the circuit, as well as gate depth and other useful quantities.
Command-line options and usage can be viewed by passing the `-h` flag
(or inspecting the parse_args function below).
(c) Gregory D. Kahanamoku-Meyer 2021
"""
f... |
5be2897c865d717a1e49a222257ff0670976aed2 | AndreyPirogov/python | /exercise5.py | 518 | 3.8125 | 4 | proceeds = int(input("Введите выручку: "))
cost = int(input("Введите издержки: "))
profit = proceeds - cost
if profit >= 0:
print("Компания работает без убытков")
print(f"Рентабельность {profit / proceeds}")
worker = int(input("Введите количество сотрудников: "))
print(f"Прибыль на одного сотрудника:... |
4a6c65a4779c89a16f4a7d5412c6c02e7e1a19a6 | kingtelepuz5/python3_code | /python_project/complex.py | 3,066 | 3.78125 | 4 | a = complex(7, 3) #a = 7 + 3i float
print("real",a.real)
print("вещ",a.imag)
b = [1, 'word ', 2, complex(3,7)] #list
print(len(b))
print(b[0])
print(b[3])
c = list(range(10))
print(c)
d = list('cat')
print(d)
p1 = ["Earth","Lun"]
p2 = ["Earth","Lun"]
p1.extend(p2)
print(p1)
del p1[2]
print(p1)
message = 'Q... |
ee617c860e23b7c465d7388fd3e721d3ddb9231c | AleksPi27/DementiyGHFirst | /homework01/caesar.py | 2,466 | 4.4375 | 4 | import typing as tp
def encrypt_caesar(plaintext: str, shift: int = 3) -> str:
"""
Encrypts plaintext using a Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
""... |
608fb04886f454c8d7b6a8134efc8e50bef9de0d | reqctoe/Impala | /code/classes/car.py | 1,875 | 3.953125 | 4 |
class Car():
"""
Creates car objects with an ID, location, length and orientation.
"""
def __init__(self, car_ID, orientation, col, row, length):
self.id = car_ID
self.orientation = orientation
self.row = int(row)
self.col = int(col)
self.length... |
74f7382a66c3da20742ffb285f655dbfdf95c2e1 | Neelanjan-Goswami/Raspi | /RaspberryPi-master/PushbuttonLED.py | 662 | 3.703125 | 4 | #Pushbutton + LED
# Author: Niam Moltta
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(16, GPIO.OUT)
try:
while True:
inputValue= GPIO.input(12)
if (inputValue == False): #Not pressed
pri... |
a7082bb289a45eef4f0a40f2e18c7bbbc5e65a85 | WeiyuCheng/FIA-KDD-19 | /src/influence/hessians.py | 7,265 | 3.53125 | 4 | ### Adapted from TF repo
import tensorflow as tf
from tensorflow import gradients
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
# from matrix_factorization import MF
def hessian_vector_product_test(ys, xs, v):
"""Multiply the He... |
be2bdf9f2e5cb2ebbce82233de6ffb239cf51cbc | siddhantshukla-10/SEE-SLL | /3/3b/app2.py | 745 | 3.53125 | 4 | import sys
import os
from functools import reduce
if(len(sys.argv)!=2):
print("Invalid arguments!")
sys.exit()
if(not(os.path.exists(sys.argv[0]))):
print("File path does not exist!!")
sys.exit()
if(sys.argv[1].split('.')[-1]!="txt"):
print("Invalid file format")
sys.exit()
wordLen = []
dict={}
f = open(sys.... |
6feab5b4009d757b62858c0a2b2be4411558c2fd | yingjianjian/ops | /python/wxldap/passwd.py | 838 | 3.640625 | 4 | from random import choice
import string
passwd_length = 8
passwd_count = 1
number = string.digits #通过string.digits 获取所有的数字的字符串 如:'0123456789'
Letter = string.ascii_letters #通过string.ascii_letters 获取所有因为字符的大小写字符串 'abc....zABC.....Z'
passwd = number + Letter #定义生成密码是组成密码元素的范围 字符+数字+大小写字母
def generate_p... |
15865df5bbabbf452560509310ec882267f152e5 | darrencheng0817/AlgorithmLearning | /Python/leetcode/NQueens.py | 1,511 | 3.96875 | 4 | '''
Created on 1.12.2016
@author: Darren
''''''
The n-queens puzzle is the problem of placing n queens on an n��n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of... |
eed0fc7382361b1f2198904e2fd6b5b354880b46 | borko81/python_fundamental_solvess | /Office_Chairs.py | 342 | 3.59375 | 4 | num = int(input())
all = 0
for _ in range(1, num + 1):
chairs, taken = input().split()
len_chairs = len(chairs)
taken = int(taken)
if taken > len_chairs:
print(f'{taken-len_chairs} more chairs needed in room {_}')
else:
all += 1
if all == num:
print(f'Game On, {a... |
91a1973cb77baf4be023b5d83256df3de24939a9 | shaan2348/hacker_rank | /anagram.py | 450 | 3.578125 | 4 | #this a random program found in the notifications
# s1 = input()
# s2 = input()
#
# set1 = set()
# set2 = set()
#
# for i in s1:
# set1.add(i)
# for i in s2:
# set2.add(i)
#
# diff = set1.symmetric_difference(set2)
# #print(diff)
# print(len(diff))
# # print(set1)
# # print(set2)
#Method 2:
s1 = input()
s2 = ... |
99905fb5a1031367b1a96b7f01a6c1b5f273d043 | Florapie/green-hand | /ex43_1.py | 862 | 3.6875 | 4 | class Student(object):
def __init__(self,name,gender):
self.name=name
self.__gender=gender
def setGender(self,gender):
# if gender == 'male':
# self.__gender=gender
# elif gender =='female':
# self.__gender=gender
# else:
# raise ... |
7b06f1a4751e273c2ba3d2343ce8e28a32981be2 | greenfox-velox/bizkanta | /week-03/day-04/palindrome2.0.py | 836 | 4.46875 | 4 | # Create a function that searches for all the palindromes in a string that are at least than 3 characters, and returns a list with the found palindromes. Example:
#
# output = search_palindromes('dog goat dad duck doodle never')
# print(output) # it prints: ['dad', 'dood', 'eve']
def is_palindrome(string):
return... |
a734c695787fd762b0adaaf3098fc97fc17b9dcf | anmolparida/Interview_Questions_Python | /MatrixSum.py | 624 | 4.375 | 4 | # # Creating the Matrix from input
#
# numberOfRows = int(input('Enter the numberOfRows: '))
# numberOfCols = int(input('Enter the numberOfCols: '))
#
# matrix = []
# for c in range(numberOfCols):
# row = []
# print('<< Enter the values in row wise >> ')
# for r in range(numberOfRows):
# rowValue = ... |
b1b84c5fcfa76c77145ad363a5310fb7df7c2d01 | amir0320/programming_foundations_with_python | /mindstorms.py | 704 | 4 | 4 | import turtle
def draw_turtles():
window = turtle.Screen()
window.bgcolor("yellow")
amir = turtle.Turtle()
amir.shape("turtle")
amir.color("green")
amir.shapesize(3,3,3)
amir.speed(1)
amir.pencolor("white")
amir.pensize(5)
for unuesd in range(4):
amir.forward(100)
... |
685608ab25bd6c1a0578c6b92bc24dded379f153 | qhuydtvt/c4e21 | /session3/fav.py | 350 | 4.0625 | 4 | fav_items = ['neflix', 'quora', 'medium', 'redbull']
while True:
command = input("What do you want (C, R, U, D) ?").upper()
if command == "C":
new_item = input("New item? ")
fav_items.append(new_item)
print(fav_items)
elif command == "R":
for i, item in enumerate(fav_items)... |
5bdbf35b09a1b2ef9a613541897efa1114e41d48 | lemonnader/LeetCode-Solution-Well-Formed | /greedy/Python/0310-minimum-height-trees(广度优先遍历).py | 1,967 | 3.5625 | 4 | from typing import List
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return [i for i in range(n)]
from collections import defaultdict
from collections import deque
in_degrees = [0] * n
# True 表示保留,如果设置为 ... |
5cec1de3717c724e8f2ee780fbe4aaabf93853b9 | gmsmartinez/Python | /DIAGRAMACION2/ejercicio17.py | 420 | 3.796875 | 4 | cantidad=int(input("ingrese la cantidad de numeros: "))
suma=0
par=0
impar=0
for i in range(1, cantidad+1):
num=int(input(f"Digite el numero{i}: "))
suma=suma+num
if num%2==0:
par=par+num
else:
impar=impar+num
print("la suma de todos los numeros es: ",suma)
print("la suma... |
42bf3b920ff4726a1f574b94ced1e0a90be7f145 | JZDBB/Algorithm-Python | /leetcode/longestPalindrome.py | 1,143 | 3.78125 | 4 |
def longestPalindrome(s):
"""
:param s: A string
:return nums: longest palindrome numbers
"""
list_s = list(s)
nums = 0
res_list = []
if len(list_s) == 0:
return s
if len(list_s) == 1:
return s
for i in range(len(list_s)):
res = []
for j in range(... |
d2390a115f08c8e997bfeeee5b287c21e8b0b09a | frederr97/nyc_taxi_trips | /main.py | 1,883 | 3.5 | 4 | # -*- coding: utf-8 -*-
import questions as qt
import os
def main():
menu = None
while menu != '0':
os.system('cls')
print('---------------------------------------------------------------------------------------')
print(' NYC Taxi Trips')
pri... |
243c0c37e459546af083f70aba22bc0e519080bd | jmpierre1/TP1_GIT | /module.py | 345 | 3.71875 | 4 | # calcul du produit de deux nombres passés en argument.
def produit(a,b):
return a*b
# calcul le quotient de deux nombres
def division(a,b):
if(b==0):
print("L'entrée fournie est invalide, on ne divise pas par zéro")
else:
return a/b
#calcul la différence de deux nombres
def soustraction(... |
19e501d1bf967d0810089ce3bcbca6d176260a01 | jasercion/textmoji | /reg_letter.py | 440 | 3.703125 | 4 | import pyperclip
def split(string):
return [char for char in string]
if __name__ == '__main__':
inputstring = input("Enter string to convert: \n").lower()
charlist = split(inputstring)
index = 0
for x in charlist:
if x.isalpha():
charlist[index] = ":regional_indicator_"+x+":"+... |
2d4ff33f075623ab1b950ff35556bfaf7a5f6037 | Lineroy/Memory-Trainer | /memory_trainer_v2.py | 17,733 | 3.59375 | 4 | from random import randint # Random number, how we will compare.
from time import sleep # Time for think, wait and etc.
from colorama import init, Fore, Style # View of program!
from os import system # For clearing console.
from ctypes import windll # Calculation of the system language, the first process.
imp... |
535d22040c8a6b027160389830c272c19c0e5713 | dilciabarrios/Curso-Python | /6_Programa_interactivo/programaejemplo.py | 140 | 3.5 | 4 | miNombre = input ('Introduce tu nombre:')
miEdad = input ('Ingresa tu edad:')
print ('Hola me llamo:', miNombre, 'y tengo', miEdad, 'años') |
09f5f1065ea0bbbd961a21f295170b500d5114b7 | Kumar20-21/Global-Fourier-Continuation | /First_kind.py | 2,535 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def function_tau(x, in_radius, out_radius):
if abs(x) <= in_radius:
return 1
elif in_radius < abs(x) < out_radius:
radius = (abs(x)-in_radius)/(out_radius-in_radius)
return np.exp((2*np.exp(-1/radius))/(radius-1))
else:
... |
6639fc2e3fa368cf2503f3c656c0044caa623f79 | shedolkar12/DS-Algo | /Tree/inorder_stack.py | 616 | 3.671875 | 4 | class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def inorder(A):
stack = []
ret = []
curr = A
done = 0
while not done:
if curr:
stack.append(curr)
curr = curr.left
else:
if len(stack)>0... |
5280c4dc72c5b321f2a79ac236556dd33e13d9ee | Michael-Jalloh/rover | /rover/rover/motor.py | 575 | 3.53125 | 4 |
class Motor(object):
def __init__(self, name="motor"):
self.name = name
self.speed = 0
self.direction = "f"
def stop(self):
self.direction = "s"
self.speed = 0
def forward(self):
self.direction = "f"
def backward(self):
self.direction = "b... |
dacbebd65d8eeff9c960f592ecd45dfb485613d1 | Yongyiphan/PlantDict | /GBA_Final.py | 17,039 | 3.890625 | 4 | # Import time for time.sleep() and datetime for timestamp
import time
from datetime import datetime
# Import sys for sys.exit()
import sys
# Main Code
def main():
filename = "myplants Original.txt" # assigning myplants.txt to variable named "filename"
# Main Menu
mainMenu = {}
mainMenu[0] = "==== Mai... |
0b864fb3382f9dd7988928720a542f02e2899aa0 | jlsalmon/pyTree | /test/testTree.py | 4,099 | 3.8125 | 4 | '''
Unit test case for Tree class.
Created on Aug 25, 2012
@author: yoyzhou
'''
import unittest
from Tree import Tree as Tree
(S, T) = range(2)
class TestTree(unittest.TestCase):
def setUp(self):
"""
Test Tree structure:
Root
|___ C01
| |___ C11
... |
fabb6f4b04c3ac94cfd433742d6ac6ffedb24b9b | Mazen-Alalwan/PXW | /dictionary/templates/dictionary/testing.py | 294 | 4.125 | 4 | while True:
height = input("are you tall?\n")
gender = input("what's you gender\n")
if height == "yes":
height = "tall"
elif height == "stop" or gender == "stop":
break
else:
height = "short"
print(" You're a " + gender + " and your " + height)
|
cda9aa05a008c1cd2db37b7f1ae7f4ba9c8f585f | alexandre146/avaliar | /media/codigos/295/295sol6.py | 157 | 3.578125 | 4 | x1,y1 = int(input()),int(input())
x2,y2 = int(input()),int(input())
import math
a = (x2-x1)**2
b = (y2-y1)**2
dxy = math.sqrt(a+b)
print ('%.4f'%dxy)
|
0ef6fd8c7c0b752cf10eaa13fd77c8c6dc125ce5 | shashidhar0508/python-training | /set1/conditional-control-transfer-statements/conditonal-st/iterative.py | 182 | 4.15625 | 4 | # for loop
for i in range(10):
print("i value in for loop is ", i)
# Nested for loop
for i in range(1, 6):
for j in range(1, i + 1):
print("*", end=" ")
print()
|
ce51e68b1b180e15b4379e30a858e738e6bcce8f | ptrwn/training | /homework1/task_05/max_subarr/task05.py | 761 | 4.21875 | 4 | """
Given a list of integers numbers "nums".
You need to find a sub-array with length less equal to "k", with maximal sum.
The written function should return the sum of this sub-array.
Examples:
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
result = 16
"""
from typing import List, Tuple, Union
Response = ... |
e01037cc34ffe9556963a50893dfb50e21e21b8a | camargo800/Python-projetos-PyCharm | /PythonTeste/aula08.2.py | 264 | 3.796875 | 4 | from math import sqrt
num=int(input('digite um número: '))
raiz=sqrt(num)
print('a raiz de {} é igual a {:.2f}'.format(num,raiz))
import emoji
print(emoji.emojize('Olá Mundo :earth_americas:', use_aliases=True))
import random
n = random.randint(1,60)
print(n) |
9c939f99f406fd44aacd7b5af9f60b7b5dd42e6d | tracyvierra/vigilant-pancake | /For Fun/guess_age.py | 150 | 4.03125 | 4 | birth_year = input('What year were you born? ')
age = 2021 - int(birth_year)
print('You were born in ' + str(birth_year))
print(f'Your age is: {age}') |
62a3d111b3cf4fa13a8be42969a00499964145f4 | Sanjaykkukreja/aiml-1 | /pandas/pandasCRUDdf.py | 3,701 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 23:02:15 2020
@author: mrizwan
Description: Modifying data in dataframe (CRUD)
Outputs are defined in the docstrings for easy understandin
"""
import pandas as pd
col = ['manufacturer','class','model']
df = pd.read_csv('data.csv', names = col)
pr... |
b32bde9e57ac92df85a208ffc68cde9a29c9a211 | petercampbell01/python_assignment1 | /python_code_validator.py | 1,756 | 3.71875 | 4 | import py_compile
class CodeValidator:
"""
Class to validate files before parsing
Author: Peter
>>> validate = CodeValidator()
>>> result = validate.validate_files(['plants.py','LinkedListNode.py'])
plants.py successfully validated
LinkedListNode.py successfully validated
>>> len(resul... |
9d1c44d446f65a62468c1176972b4ee10bd404b6 | VinayakBagaria/Python-Programming | /New folder/hackerearth_it.py | 463 | 3.578125 | 4 | # Count no. of times hackerearth comes in a string
n=int(input())
string=input()
hc=string.count('h')
ac=string.count('a')
ec=string.count('e')
cc=string.count('c')
kc=string.count('k')
rc=string.count('r')
tc=string.count('t')
least=hc/2
if(ac/2<least):
least=ac/2
if(ec/2<least):
least=ec... |
dd98cbb625674bd7a49a1d437a315d3156b878d1 | Pankaj-GoSu/Data-Structures-Tutorials-Python | /Data Structure and Algorithems by apna college/Prefix_Expression_Implementation.py | 2,362 | 4.125 | 4 | # ========== Prefix Expression Evaluation Using stack =============
#======= First we implement stack =====
class Stack():
def __init__(self,n):
self.stack = []
self.size = n
self.top = None
def push(self,data):
if len(self.stack) == self.size:
print("Stack Over... |
3416a40f33667e7356864ca1cbd04febc874806e | skaser85/Py5 | /Vector.py | 15,077 | 4.28125 | 4 | import math
import random
class Vector():
"""
The Vector class defines 2D and 3D mathematical vectors as well providing
various methods for working with them.
"""
def __init__(self, x, y, z=0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f'Vector... |
fd735a152ddda4e9ab7b2a8dbecfc4183ccfe8c2 | dwbelliston/python_structures | /sorting/merge_api.py | 3,423 | 4.25 | 4 | #!/usr/bin/env python3
def merge_lists(list1=[], list2=[], keys=['percent', 'count', 'word']):
'''Merges two sorted lists into a new, sorted list. The new list is sorted by percent, count, alpha.'''
"""
>>> a = [1, 3, 5, 7]
>>> b = [2, 4, 6, 8]
>>> [i for i in linear_merge(a, b)]
[1, 2, 3, 4,... |
369bcd44a155bb1f783c02020c123d58134f8232 | archeranimesh/HeadFirstPython | /SRC/Chapter_10-Function-Decorators/10_any_no_arguments.py | 376 | 3.546875 | 4 | def myfunc_args(*args, **kwargs):
if args:
for a in args:
print(a, end=" ")
print()
if kwargs:
for k, v in kwargs.items():
print(k, v, sep="->", end=" ")
print()
if __name__ == "__main__":
myfunc_args()
myfunc_args(1, 2, 3)
myfunc_args(a=10, ... |
85129e7993e3ba1783a90c25dc34bec7880b6b9a | aduplessis/wordsearch | /wordsearch_solver.py | 8,550 | 3.546875 | 4 | class Solver:
def __init__(self, word_file, puzzle=None, puz_file=None):
# Checks whether puzzle can be assigned
assert (
not(puzzle is None and puz_file is None) or (puzzle is not None and puz_file is not None)
), "Not able to get puzzle or provided both puzzle and file... |
785b68f873495f931cd4a20eb05f34f9843cc162 | paulwilliamsen/madlib-cli | /madlib.py | 1,336 | 4.3125 | 4 | print("Please enter a word, number or phrase in the prompts provided")
"""
A command Line Madlib program that takes in user input, writes into new file and prints to the screen.
"""
import re
def get_template():
"""
Inital reading of the given file
"""
with open('./initial_text.txt', 'r') as templa... |
d2cf4ef3f51d0a660879988d652d447a3ce659bd | DarioCampagnaCoutinho/logica-programacao-python | /modulo03-estruturascondicionais/exercicios/exercicio03.py | 169 | 4.03125 | 4 | from math import sqrt
numero = float(input('Número = '))
if numero >= 0:
print('Raiz = {}'.format(sqrt(numero)))
else:
print('Dobro = {}'.format(numero * 2))
|
239dd8105e0761b157ed45d74a1bf925fb7ae81b | sukritishah15/DS-Algo-Point | /Python/stack.py | 3,836 | 4.46875 | 4 | #implementation of stack using OOP
#stack is used to store and retrive data
# the process for stack is FILO i.e.first in last out
class stack:
def __init__(self):
#constructor for stack
self.mylist=[]
self.size=0
self.maxsize=5
#function to display elements of stack
def disp... |
01e748a2deb33ce41c4ac31528e6266f3e41097c | klaudiaplk/n_puzzle | /pszt_n_puzzle/misc.py | 1,888 | 4.03125 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def animate(path, board_height):
"""Board animation.
:param path: list of steps leading to the solution
:param board_height: board height
"""
fig, ax = plt.subplots()
plt.axis('off'... |
dd3b310be4be2355d70e3dbb15015f9bd28810d4 | JeremyBarbosa/PyChat | /server.py | 5,625 | 3.53125 | 4 | import threading
import socket
#
# A variety of functions to manage caching Usernames and their corresponding socket
#
userDict = {}
dictLock = threading.Lock() # With each client having its own thread, be sure to lock any access to this directory
def addUser(userName, userSocket):
with dictLock:
userDict... |
6a6a1fb50970288e7bffbfd966e0982113f84dca | dbcalitis/ICS3U-Unit4-02-Python-Factorial | /factorial.py | 915 | 4.46875 | 4 | #!/usr/bin/env python3
# Created by: Daria Bernice Calitis
# Created on: Sept 2021
# This program is a factorial program
def main():
# This function multiplies all numbers 1 to the given number (factorial)
"""the list of factorial products starts
with 1 because 0! = 1"""
# If these variables down bel... |
7e00e49d8b56c1f64a54b425960734b0eec0551e | sakshipadwal/python- | /Python/list1.py | 1,455 | 4.21875 | 4 | print ('Hello World')
My_list=[10,40,50,20,30,10,40,10]
Your_list=['saw','small','foxes','he','six']
print("The First List created",My_list)
print("The Second List created is",Your_list)
My_list.append(60)
print("After Appending First List created",My_list)
My_list.insert(1,70)
print("After inserting at 2nd pos... |
c13cd7d23e6295c8acab7d921077113408841068 | pummarin/cyber-security | /Assignment1/AES_encrypt.py | 1,155 | 3.609375 | 4 | import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
BLOCK_SIZE = 16
def pad(s): return s + (BLOCK_SIZE - len(s) %
BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
def encrypt(raw, password):
private_key = hashlib.sha256(password.encode("utf... |
49b7f596238c3e5c55492b91accaedce87ee4749 | bokukko7/AOJ_AtCoder | /AtCoder/ABC171/C-2.py | 584 | 3.71875 | 4 | def readinput():
n=int(input())
return n
def getKeta(n):
m=n-1
base=0
keta=1
base+=26**keta
while(m>=base):
keta+=1
base+=26**keta
return keta
def naming(keta,n):
alph='abcdefghijklmnopqrstuvwxyz'
geta=26*(26**(keta-1)-1)//25
m=n-geta-1
name=''
for _... |
76c1cb9f39ab883e8097d53a1f9cc2de9d1e517f | srikanthpragada/PYTHON_19_MAR_2021 | /demo/oop/add_fun.py | 171 | 3.8125 | 4 | def add(a, b):
if isinstance(a, int) and isinstance(b, int):
return a + b
else:
return int(a) + int(b)
print(add(10, 20))
print(add("10", "20"))
|
fd0e7e0ec291e6734f0da9aec73f207e11edd2de | sushmita-swain/Data_science_project | /Python Project/week_4/image_resize/image_resize.py | 3,969 | 3.875 | 4 | # Pillow is a fork of the Python Imaging Library (PIL). PIL is a library that offers several standard procedures for manipulating images.
# It supports a range of image file formats such as PNG, JPEG, PPM, GIF, TIFF and BMP.
# Installation
# pip3 install Pillow
# The Image Object
# A crucial class in the Python I... |
34740df953531c5983e84aa1cd63d37435a8b228 | yjchang-tw/sc-projects | /stanCode_Projects/break_out_game/breakout.py | 4,800 | 3.625 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
YOUR DESCRIPTION HERE
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120 # 120 frames per second.
NUM_LIVES = 3
def main(... |
e8a26423295ecee16c957c4b771b9f070849831b | yedhukrishnan/image-processing-algorithms | /median_filter.py | 1,121 | 3.828125 | 4 | # Median filter
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
def median_filter(image):
(row, col) = image.shape
# Define a matrix to store the new image
filtered_image = np.zeros(image.shape)
# Pad the original image with zeros to apply median filter
image = np.lib.p... |
6c25445357b48f4e4063c9c7403b7813c6d86676 | lnogueir/interview-prep | /problems/minKnightMoves.py | 1,152 | 3.734375 | 4 | '''
Prompt:
Given a knight coordinate in a chess board and a target coordinate
return the minimum number of moves to get to the target location.
'''
# knight possible moves:
# (x+2, y+1), (x-2, y-1), (x+2,y-1), (x-2,y+1), (x+1,y-2), (x+1, y+2), (x-1, y+2), (x-1,y+2)
def isInBoard(n, x, y):
return 0 <= x < n and 0 ... |
a5b8e862a2e7fc228783b0cc83e769cb4704641f | MisaZivanovic/Hangman-game | /V2 | 7,634 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import random
import json
# functions
def empty(wrd):
word_length=len(wrd)
print(word_length*" "+word_length*"_")
print(word_length*" "+ " |")
print(word_length*" "+ " |")
print(word_length*" "+ " |")
print(word_length*" "+ " |")
... |
f02e366627ee8664e4bf8e47e2581303baaff6ff | shiran-valansi/problemSolving | /rearangeMatrix.py | 4,038 | 4.0625 | 4 | import time
def rearrangeOnDiagonals(a, corner):
"""
Given a 2d array, and a number corner, rearrange the elements of the array in the following way:
if the original array look like this:
1,2,3
4,5,6
7,8,9
if corner = 1: if corner = 2: if corner = 3: if corner = 4:
1,3,6 ... |
2d4f922e8d00fa4247972255da9615c8e19e1a86 | AlexKraft/TelegramBots | /_scheduler.py | 4,469 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 12:43:02 2019
@author: pc
"""
#------------------------------------------------------------------------
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be print... |
9c005fbec9a90e9e8efe7ad871c3372d18f27380 | amgautam/Multilingual-Chat-Application | /server.py | 6,310 | 3.890625 | 4 | import socket
import select
HEADER_LENGTH = 10
## getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")... |
d8d97b387ddaac9867162a88dad96ad54a1a9b6a | masonbrothers/resistor-optimizer | /resistors.py | 2,551 | 3.90625 | 4 | # Resistors
import itertools
def fromSI(string):
fix = string[len(string)-1]
if isinstance(string[len(string)-1], (int, long)) != True:
string = string[:-1]
if fix == 'k':
multipiler = 1e3
elif fix == 'M':
multipiler = 1e6
elif fix == 'G':
multipiler = 1e9
elif fix == 'T':
multipiler ... |
59429ee5ee8ca7e0edd5fe634b9e3e46f97d9c73 | Muhammad-Ahmed-Mansoor/Python-tic-tac-toe | /TwoPlayerTicTacToe2.py | 2,952 | 3.921875 | 4 | import os;
def boardPrint(): #displays the board
global board
print('\n') #two blank lines for clarity's sake
for i in [7,8,9,4,5,6,1,2,3]:#to match keyboard numpad
if i % 3 !=0:#to avoid '|' at the end of a row
print(board[i],'|',end=' ')
else: #to insert new ... |
20317d1b73a8ea45e5ff3ebd417cec43979bb5a8 | jakubfolta/Censor | /censoredWord.py | 722 | 3.734375 | 4 | def replaceCensoredWord(text, word):
splittedText = text.split()
for index, each in enumerate(splittedText):
if each == word:
splittedText[index] = len(word) * '*'
return ' '.join(splittedText)
print(replaceCensoredWord('abh dkkfir kvko keje kaka fnjeribv kaka', 'kaka'))
def replaceCensoredWord(text,... |
971484826b8bf18c759f3619022362905e39cdfd | galipkaya/exercism-python | /change/change.py | 805 | 3.5625 | 4 | def change(coins, amount):
result = [amount+1] * (amount+1)
coins_results = [[] for _ in range(amount+1)]
result[0] = 0
for i in range(1, amount+1):
for coin in coins:
if i >= coin and result[i - coin] + 1 < result[i]:
result[i] = result[i-coin] + 1
... |
e7eaffbcf1091c3da6b24662d1452a18d63b4833 | DDBostonHAM/list_app | /main.py | 1,168 | 4.0625 | 4 | import os
#Initialize list
shopping_list = []
def show_help():
#Give Guidence
print("Available Commands: ")
print(" \
Enter 'HELP' to show this help.\n \
Enter 'SHOW' to see current list.\n \
Enter 'DONE' to exit list.\n \
Enter 'DELETE' to remove item from list.")
def show_list():
p... |
e350312bb980c345df76b509731410440d2f4e61 | GenosseBlaackberry/MIPT_B02-113 | /lab 2 (Turtle 1)/Exercise 4.py | 159 | 3.703125 | 4 | import turtle
turtle.shape('turtle')
import math
turtle.speed(10)
def ex4():
for i in range(360):
turtle.forward(1)
turtle.left(1)
ex4()
|
d840135972a26e69a5816383b348bd2c61517017 | tpatil2/Python | /sets.py | 314 | 4.1875 | 4 |
# does not print duplicates
groceries = {'milk','eggs','bread','rice', 'eggs'}
print(groceries)
if 'milk' in groceries:
print("you already have")
else:
print("you need milk")
trip = {'pune':'collge','islampur':'home','kota':'classes','chico':'MS'}
for k,v in trip.items():
print(k,"is ",v)
|
66a2742c9d440f974d776eb68b8be6fbfa43dea9 | Gttz/Python-03-Curso-em-Video | /Curso de Python 3 - Guanabara/Mundo 01 - Fundamentos/Aula 10 - Condições (Parte 01)/033 - Maior_e_Menor.py | 644 | 4.0625 | 4 | # Exercício Python 033: Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número:"))
n3 = int(input("Digite o terceiro número:"))
menor = n1
if menor > n2:
menor = n2
if menor > n3:
menor = ... |
1d872414a963f6a76fc8308a203de7ef0b3cf608 | naveenk4545/Practice-set | /missing_num.py | 298 | 3.546875 | 4 | class sol:
def missing_num(num):
n=[0]*(len(num)+1)
for i in num:
n[i] += 1
missing = []
for i in range(len(n)):
if n[i]==0 and i != 0:
missing.append(i)
return missing
ob = sol()
print(ob.missing_num([1,2,4,5]))
|
ecfbff1402b20dd8f2c7ebd646f840cab56c5b0e | mdjdot/pysamples | /pysamples/pyprocess/pymultiprocess.py | 494 | 3.5625 | 4 | #!/usr/bin/env python3
from multiprocessing import Process
import time
import os
def sleep(n: float):
print("start process: %d" % os.getpid())
time.sleep(10)
def start():
now = time.time()
processes = []
for _ in range(0,10):
p = Process(target=sleep, args=(5,))
p.start()
... |
4eae969446d23ff77263ece47eb093a95a746e23 | implse/Simple_Algorithms | /Sierpinski_triangle.py | 852 | 3.953125 | 4 | # Sierpinski Triangle
n = 8
grid = [["." for _ in range(n)] for i in range(n)]
# Iterative Method
def sierpinski_triangle_iterative(grid, n):
row = 0
col = 0
cote = 1
grid[0][0] = "#"
while cote < n:
for row in range(cote):
for col in range(cote):
grid[row][col +... |
48638648998f4d1794c92c5b82a8826acd9df226 | yeonsoy/Python-4-weeks | /Week3/ex5.py | 98 | 3.625 | 4 | a = [1,2,3,4,5,6,7]
some_value = '1'
if some_value not in a :
a.append(some_value)
print(a) |
8362ad6da7d17881f4b14d2435fe2c3cec93d072 | nloadholtes/brass | /src/gui/MessageBox.py | 4,073 | 3.53125 | 4 | #!/usr/bin/env python
#
# MessageBox.py
# May 17, 2007
# Nick Loadholtes
#
# This classwill display messages on the screen
#
from Events import *
from pyglet import font
class BottomMessageBox:
def __init__(self, screen, manager):
'''The magical init fo rthe MessageBox
justification - 0 (default)... |
1a5aca036a1f0130ba48478bb82c912c0cf6b6ec | yckfowa/Automate_boring_stuff | /Ch.12/link verification.py | 245 | 3.515625 | 4 | import requests
from bs4 import BeautifulSoup
url = input("Please enter the url to begin download: ")
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, 'html.parser')
for link in soup.select('a'):
print(link) |
2936a8753f24c46f99398a51cc512aba231bc8eb | soham0511/Python-Programs | /PYTHON PROGRAMS/super.py | 958 | 3.84375 | 4 | class Person:
country="INDIA"
def __init__(self):
print("Initializing Person")
def breathe(self):
print("I am Breathing...")
class Employee(Person):
company="OYO"
def __init__(self):
super().__init__()
print("Initializing Employee")
def getSalary(self... |
95a6246aaa78f91657fdf53e313ec34c7ba06f52 | pspelman/algorithms | /python/basic13.py | 4,467 | 4.375 | 4 | # basic 13 in python
# print array 1 to 255
def get_array_1_to_255():
array = []
for num in range(1,256):
array.append(num)
return array
# print "array: ", get_array_1_to_255()
# Write a function that would get the sum of all the even numbers from 1 to 1000. You may use a modulus operator for th... |
519167ecf3643f5ca9b94c8f44967f38c0292792 | rlorenzini/githubtest | /testwork8.py | 1,103 | 4.0625 | 4 | #rock paper scissors
#rock>scissors>paper>rock
print("\nLET THE STRONGEST SURVIVE!!!\n")
user1 = ""
user2 = ""
print("\nPress q to Quit. ")
def winner():
if user1 == "rock":
if user2 == "rock":
print("\nTIE.\n")
elif user2 == "paper":
print("\nPLAYER TWO WINS.\n")
... |
4da04440706fa83185cd8790e95c4bd6c78c1272 | robertsj/poropy | /pyqtgraph/examples/Flowchart.py | 2,452 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
This example demonstrates a very basic use of flowcharts: filter data,
displaying both the input and output of the filter. The behavior of
he filter can be reprogrammed by the user.
Basic steps are:
- create a flowchart and two plots
- input noisy data to the flowchart
- flowchart con... |
e5ca63cb9010e088719311af2411259c2052df86 | ryland-e-atkins/complexa | /database_replication/python/data_generator.py | 3,159 | 3.5 | 4 | import random
import json
from collections import OrderedDict
from util import *
from data_gen_util import *
def generateTable(tableName, totalCount, fieldDictList):
"""
Writes a table of values to a file
tableName: string of table name
fieldDictList: list of dictionary items that represent f... |
f18cdf51f078e695cdc8950ab50126b0e2d93f55 | davidhuangdw/leetcode | /python/834_SumofDistancesinTree.py | 961 | 3.734375 | 4 | from unittest import TestCase
# https://leetcode.com/problems/sum-of-distances-in-tree/
class SumofDistancesinTree(TestCase):
def sumOfDistancesInTree(self, N: 'int', edges: 'List[List[int]]') -> 'List[int]':
e = [[] for _ in range(N)]
for i, j in edges:
e[i].append(j)
e[j]... |
c8996ec994c5d5d0f5afe492c7c10ab4d6d690d4 | eustone/SMS-2 | /courses/main.py | 978 | 3.53125 | 4 | from subjects import Subject
import csv,sqlite3
connect = sqlite3
class Course:
course_list = []
def __init__(self,title = '',department=''):
self._title = title
self._department = department
Course.course_list.append(self)
def get_course_title(self):
return self._title
... |
7a1dd2d442c19ef0f929671ca9b7eed23f3c7d55 | mrinxx/Pycharm | /PDF 24-09/7.py | 370 | 4.125 | 4 | #Escribe un programa que solicite tres números al usuario y calcule e imprima por pantalla su suma.
suma=0 #inicializo la variable
num1=float(input("Introduzca el primer numero: "))
num2=float(input("Introduzca el segundo numero: "))
num3=float(input("Introduzca el tercer numero: "))
suma=num1+num2+num3
print ("La ... |
45674fe20be411b67b63879c14c26882d2d6a721 | rene-d/edupython | /codes/heron.py | 449 | 3.515625 | 4 | # Calculer l'aire d'un triangle avec la formule de Héron
# https://edupython.tuxfamily.org/sources/view.php?code=heron
# calcul de l'aire d'un triangle avec la formule de Héron
a, b, c = demande ("Entrez les longueurs des 3 côtés du triangle séparées par des virgules.")
p = (a + b + c) / 2 #p e... |
c73a70eaaf6d414db7b7e2b3547c188a73478129 | shivanichauhan18/hacker-rank | /is_stringValid.py | 138 | 3.5 | 4 | a="aacbbd"
dict={}
for i in a:
count=0
for j in a:
if i==j:
count=count+1
dict[i]=count
print dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.