blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
945987969a7cfc12dfdd56ef92fb9974f67329db | huang-jingwei/Coding-Interview-Guide | /chap2/13.删除无序单链表中值重复出现的节点/13_deleteDuplicates.py | 933 | 3.71875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None: # 链表为空链表为只有单个元素时,直接返回该链表
return head
preNode = head # 当前节点的前一节... |
585e8864804da7ac89941468f0426c25ed33c0fa | huang-jingwei/Coding-Interview-Guide | /chap5/02.判断两个字符串是否互为旋转词/02_chkRotation.py | 567 | 3.609375 | 4 | #处理输入
#step1:获取两个字符串的长度
stringLength=list(map(int, input().strip().split()))
n=stringLength[0]
m=stringLength[1]
#step2:获取两个字符串
str1=str(input())
str2=str(input())
#主函数入口
if len(str1)!=len(str2):
print("NO")
exit()
#若两个字符串互为旋转词,那么两个字符串进行拼接后,必定为回文字符串
string=str1+str2
left=0
right=len(string)-1
while left<right:... |
b2e1e8109c70bc245725e68e7556384157d3e9d9 | huang-jingwei/Coding-Interview-Guide | /chap2/01.打印两个有序链表的公布部分/01_printCommonPart.py | 607 | 3.796875 | 4 | def printCommonPart(array1,array2):
data=[]
index1=0
index2=0
while index1 <len(array1) and index2 <len(array2):
if array1[index1]==array2[index2]:
data.append(array1[index1])
index1 +=1
index2 +=1
elif array1[index1]<array2[index2]:
index1... |
65155a9bdd9bcd761474807ff12ea9fb768b9129 | huang-jingwei/Coding-Interview-Guide | /chap3/04.二叉树的序列化和反序列化/04_serialize_deserialize.py | 2,506 | 3.6875 | 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
... |
98d9471c41c34d894deec8c27e71ddd21fbfec8e | huang-jingwei/Coding-Interview-Guide | /chap9/12.设计LRU缓存结构/12_LRUCache.py | 752 | 3.78125 | 4 | import collections
class LRUCache:
def __init__(self, capacity: int):
self.data=collections.OrderedDict() #用有序字典存储数据
self.size=capacity #该数据结构能缓存的最多元素个数
def get(self, key: int) -> int:
if key not in self.data:
return -1
else:
self.da... |
2b6e34ea2977cc303259355fd3d2ba83ebeded23 | huang-jingwei/Coding-Interview-Guide | /chap3/15.判断一颗二叉树是否为搜索二叉树和完全二叉树/15_isValidBST.py | 1,027 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root == None:
return True
# 搜索二叉树的中序遍历是升序序列
nodeData = self.i... |
4ed717ef921f8e0b1c3a961a58ca9a60c3596d1b | huang-jingwei/Coding-Interview-Guide | /chap2/06.环形单链表的约瑟夫问题/josephusKill.py | 744 | 3.5625 | 4 | # 函数功能:单向环形链表的约瑟夫问题
def josephus(arr, length, m):
while len(arr) > 1:
# 计算当前轮要进行处决的犯人的下标
index = m % len(arr)
# 情况1:待处决的犯人是最后一名犯人
if index == 0:
arr = arr[:-1]
# 情况2:待处决的犯人在链表的中间
else:
arr = arr[index:] + arr[:(index - 1)]
return arr[0]
... |
fb8228b605e522e35535b2ab06f755a2f7e21677 | force1267/num_analysis | /hazvigaos.py | 985 | 4.21875 | 4 | print("""حذفی گاوس برای تبدیل به بالا مثلثی""")
def matprint(mat, start = 1):
m = len(mat)
n = len(mat[0])
s = ""
for i in range(start, m):
for j in range(start, n):
s += str(mat[i][j]) + "\t"
s += "\n"
print(s)
n = int(input("سایز ماتریس : ")) + 1
# 2d n*n matrice... |
e64360cc977f7ee2a696e5e8803b601f55dbb490 | saurabhgrewal718/python-problems | /printing a new dict.py | 299 | 4.03125 | 4 | # create a new dict from i to n ....(including both) such that the elemnts of dict are (i,i*i)...and print the dict after that
first_num = int(input("Enter first number : "))
last_num = int(input("Enter last number : "))
d = dict()
for i in range (first_num,last_num+1):
d[i] = i*i
print(d)
|
228dca898f80a9175d8d7d612a0a8dc34d9846d7 | saurabhgrewal718/python-problems | /factorial of a number.py | 288 | 4.25 | 4 | # Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
num=input()
print("num is "+ num)
|
bb9f3fb74b7dda9d8c004c8741d4712ef9da3297 | briandidthat/Data-Structures-PY | /__main__.py | 1,424 | 3.890625 | 4 | from trees import BinarySearchTree
from lists import SinglyLinkedList, DoublyLinkedList
from stacks import Stack, LinkedStack
from queues import Queue
from heaps import BinaryHeap
def make_tree():
tree = BinarySearchTree()
tree.put("mak", 50)
tree.put("bop", 60)
tree.put("sdd", 34)
tree.put("elo",... |
a188e34de21912eb8fdd1324da68909e5363c6d3 | jaywonhan0111/wave-1-assignment | /wave1 python file.py | 114 | 3.828125 | 4 | l = int(input("Enter the length"))
w = int(input("Enter the width"))
area = l*w;
print("Area in acre:",area/43560) |
08f943f78ec6cb82dea3e1dfbdd756ac31939b62 | punitinani/PYthon-programs | /My_Programs/oop/class_in_details.py | 1,368 | 3.90625 | 4 | class Student:
num_of_student = 0
class_teacher ='Mrs. Devid'
def __init__ (self , rno, name , mks) :
self.rollno= rno
self.name = name
self.marks = mks
self.grade = ''
Student.num_of_student += 1
def calcGrade (self) :
if (self.marks >=80... |
d791bbb4b21db902f1623270ce03b3a0a29727e5 | punitinani/PYthon-programs | /My_Programs/ord.py | 194 | 3.703125 | 4 | #convert the character value into ascii
print ord('a')
# help(ord)
# print ord("punit") not work on the string
a = "punit".encode("utf16")
print a
b = int ("123456789",10)
print b |
5343a5d4a3abe54b8ab254e38afde81b99ae034f | punitinani/PYthon-programs | /My_Programs/oop/class_def_dyanmic_way.py | 433 | 3.625 | 4 | def func(self):
print "This is function func"
def play ():
print "An external function named play"
class A_class:
def method_a (self):
print "Internal call of the funciton func as the method_a"
if (__name__ =="__main__"):
a = A_class()
a.method_a()
setattr(A_class , 'method_b' , func)
... |
0057de4c4f964f0853b7c063fda7d00fd5c5035b | punitinani/PYthon-programs | /My_Programs/oop/variables.py | 302 | 3.828125 | 4 | class another :
def __init__(self) :
self.a ='SCOT'
self.b = 19
self.c = 'GOOD'
print self.a + " is " + str ( self.b) + " years old " + "He is not " + str (self.c) + " in the chess "
if (__name__ == '__main__'):
a= another()
print "This is the end of the program " |
7c6b60ba161561c24a19a05e326c6e90dffb1727 | MartynJacques/AdventOfCode2017 | /day2/day2-2.py | 713 | 3.53125 | 4 | #!/env/bin/python
import sys
import argparse
import os
def build_parser():
parser = argparse.ArgumentParser()
parser.add_argument('inputfile')
return parser
def main(args):
data = [
line.strip('\n').split() for line in open(args.inputfile)
]
checksum = 0
result = 0
for row in... |
201409e60f41c2f062db75f968992b0514d860e3 | willoleary6/Final-Year-Project | /Workspace/Prototypes/twoLayeredNeuralNetwork/src/runner.py | 645 | 3.890625 | 4 |
import mnist_data_set_loader
import NeuralNetwork
"""
Interesting experiment checking to see what happens when you remove the hidden layers of the neural net. still achieved
87% accuracy :P
"""
# Before we can start training we must first retrieve the data set
# from the data_set_loader we will populate the traini... |
8444270637d5fca1f9f1ca4ff33fe6e8eeefd0c3 | 7209714/GeometricObject | /RectangleGEO.py | 658 | 3.5 | 4 | from GeometricObject import GeometricObject
class Rectangle(GeometricObject):
def __init__(self,width,height,color,filled):
self.setColor(color)
self.setFilled(filled)
self.__width = width
self.__height = height
def setWidth(self, width):
self.__width = width... |
fbb7600376f711761a63534db57bd95cf723c1a9 | PyLadiesSP/exercicios | /alunos_medias.py | 1,309 | 3.90625 | 4 |
quantidade_de_alunos = int(input("Digite a quantidade de alunos: "))
# lista que armazenará a média de cada aluno
media_de_todos_os_alunos = []
# lista que armazenará as notas de cada aluno
notas_de_todos_os_alunos = []
for i in range(0, quantidade_de_alunos):
num_aluno = i + 1
# atenção que float é com po... |
e5bd86f6ca62ce8c6e9c9f5d1e8d1e9396be386b | florianfmmartin/snakepy | /snake/__main__.py | 1,645 | 3.59375 | 4 | # imports
from terminal import Term
from snake import Snake
from food import Food
# app
terminal = Term()
app = terminal.term
# constants
MAX_WIDTH = app.width
MAX_HEIGHT = app.height
# create snake
snake = Snake()
# snake speed
speed = 0.1
# grow counter
counter = 1
# txt
txt_erase = app.home + app.blue_on_black... |
cb96167da7853f9385ead70b54e48d4db0af49fd | varunbelgaonkar/Beginner-Python-projects | /database_gui.py | 2,704 | 4.125 | 4 | from tkinter import *
import sqlite3
root = Tk()
root.title("Employee Data")
root.geometry("400x400")
#cxreating a databse
#conn = sqlite3.connect("employee.db")
#creating curser
#c = conn.cursor()
#creating table
#c.execute("""CREATE TABLE employees(
# emp_id integer,
# first_name text,
# ... |
6760ee17cf900f4aa2a9f2ad4d6835502fb5a6d4 | Rahuls66/Python-DataCampEssentials | /RegEx.py | 1,914 | 3.71875 | 4 | import re
s = "My 2 favorite numbers are 42 and 19"
re.findall("[0-9]",s)
['2', '4', '2', '1', '9']
s1 = "An apple a day keeps the doctor away"
re.findall("[AEIOUaeiou]", s1)
['A', 'a', 'e', 'a', 'a', 'ee', 'e', 'o', 'o', 'a', 'a']
s = "My 2 favorite numbers are 42 and 19"
re.findall("[0-9]+",s)
#Will accept more ... |
7e6fe07043d8f475cc5f53b71ff8c3a768acc1ce | Bilibotter/OneDayTwoCode | /652. 寻找重复的子树.py | 692 | 3.671875 | 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 findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
... |
0b2858be9e885e8ddd4d53751bc48165b50a42c3 | Geo3ngel/JSON-Similarity-comparitor | /src/obj_tree.py | 1,077 | 3.640625 | 4 | # This class will represent the tree datastructure necessary for processing and equating the data of json objects.
# Imports
from obj_node import node
class tree():
def __init__(self, root):
# initializes all the nodes in the tree.
self.root_node = node(root, None)
# Initia... |
9055e5b360d24c6cae49cfea89dd0299cb3ee841 | ncdxpq/optimization_theory_homework1 | /lsaacNewton_method.py | 2,260 | 3.546875 | 4 | from random import random
import numpy as np
# 函数表达式fun
function = lambda x: 100 * (x[0] ** 2 - x[1]) ** 2 + (x[0] - 1) ** 2
# 梯度向量 gradient
gradient = lambda x: np.array([400 * x[0] * (x[0] ** 2 - x[1]) + 2 * (x[0] - 1), -200 * (x[0] ** 2 - x[1])])
# 海森矩阵 hessian_matrix:二阶偏导数,[[fxx'',fxy''],[fyx'',fyy'']]
... |
b1aec985ebb54cc4c1f1b841fa293e0035d3af85 | Asphalt93/Personal | /homework/[NPD] CMYK Calculator_code.py | 2,997 | 3.59375 | 4 | import matplotlib.pyplot as plt
import PIL
global data
# The capacity of each colors' tank (각 탱크의 기본 용량을 500ml로 잡았을 때)
def bottle(c_, m_, y_, k_):
cyan_bottle = 500 - float(c_)
magenta_bottle = 500 - float(m_)
yellow_bottle = 500 - float(y_)
#Black color needs C & M & Y to be mixed
cy... |
0548e660630cca5e6e8596691500bc87cb7a2669 | brunosserrao/aulapython | /app.py | 2,932 | 3.53125 | 4 | import os
import ast
PECAS = "data/pecas.dat"
MAX_TOTAL_REGISTROS = 50
#limpar tela
def limpar_tela():
try:
os.system('clear')
except:
os.system('cls')
#iniciar arquivo
def init():
try:
arquivo = open(PECAS, 'a')
except:
arquivo = open(PECAS, 'w')
arquivo.close()
menu()
#menu principal
def menu():
o... |
2882fb44e68f464e57e10241c05a02765e4ef656 | austinapatel/Smart-Fridge | /imagecrop.py | 728 | 3.515625 | 4 | from PIL import Image
def crop(image_path, coords, saved_location):
"""
@param image_path: The path to the image to edit
@param coords: A tuple of x/y coordinates (x1, y1, x2, y2)
@param saved_location: Path to save the cropped image
"""
image_obj = Image.open(image_path)
cropped_image = i... |
d466d1e75892b28fe802ded9f603e8691326a5ba | lbetol/crawler_semantix | /semantix/spiders/nasdaq.py | 1,469 | 3.5 | 4 | # Projeto web crawler
# Processo seletivo para a empresa Semantix
# ------------------------------------------
# Autor: Alberto Barrios
# Data: 11/04/2020
# ------------------------------------------
# -*- coding: utf-8 -*-
import scrapy
from semantix.items import SemantixItemNasdaq
# classe NasdaqSpider realiza todo... |
ec296961f693257966dec438f7f03dc10876f970 | gorgo666/zadanie1 | /zadanie1.py | 850 | 3.890625 | 4 | import datetime
born = input("spisz swoją datę urodzenia w formacie 'dd-mm-yyyy': ")
date_format = '%d-%m-%Y'
try:
date_obj = datetime.datetime.strptime(born, date_format)
born = born.split("-")
bornD = int(born[0])
bornM = int(born[1])
bornY = int(born[2])
actualYear = datetime.dat... |
a06f216517baf4399cf0c4a09f09ff04d979dd5a | ATLS1300/pc02-graffiti-section13-maddieewers | /PC02_Graffiti.py | 2,044 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
'''
Turtle starter code
ATLS 1300
Author: Dr. Z
Author: MADDIE EWERS
May 29, 2020
'''
import turtle #import the library of commands that you'd like to use
turtle.colormode(255)
# Create a panel to draw on.
panel = turtle.Screen()
w = 750 # width of panel
h = 750 # height of pa... |
35ef3abdfd3f7a7dab0e2cc1a1f2417e830c1bea | ZacharySmith8/Python40 | /33_sum_range/sum_range.py | 804 | 4.1875 | 4 | def sum_range(nums, start=0, end=None):
"""Return sum of numbers from start...end.
- start: where to start (if not provided, start at list start)
- end: where to stop (include this index) (if not provided, go through end)
>>> nums = [1, 2, 3, 4]
>>> sum_range(nums)
10
>>>... |
e50d3bc24c53b9648e6499999d69579fb22d29ec | Mohammed-Shoaib/Coding-Problems | /HackerRank/Python/Hard/H0001.py | 294 | 3.5625 | 4 | # Problem Statement: https://www.hackerrank.com/challenges/maximize-it/problem
from itertools import product
def f(X):
return X * X
K, M = map(int, input().split())
N = [list(map(int, input().split()))[1:] for _ in range(K)]
S = [sum(map(f, prod)) % M for prod in product(*N)]
print(max(S)) |
a951d5b55f0cc8b7c8c2aea556d7ac3f8cf7209e | Mohammed-Shoaib/Coding-Problems | /HackerRank/Python/Medium/M0020.py | 283 | 4.0625 | 4 | # Problem Statement: https://www.hackerrank.com/challenges/validating-credit-card-number/problem
import re
def is_valid(card):
return re.search(r'^(?!.*(\d)(-?\1){3})[456]\d{3}(-?\d{4}){3}$', card)
for _ in range(int(input())):
print('Valid' if is_valid(input()) else 'Invalid') |
1f9130e9e881eae2c2b3084e7028a3a0c96b1dc3 | pipelin56/Python02 | /02.TrabajandoConPokemon.py | 1,381 | 3.5625 | 4 | fichero = open('pokemon.txt', 'r')
ListaPokemon = fichero.read().split() # Convertimos lo que tenemos en fichero a lista y lo introducimos en ListaPokemon
ListaAuxiliar = [] #Lista en la cual almacenamos momentaneamente las cadenas que vamos formando
Lista = [] #Lista mas larga que encontramos hasta el momento
for e... |
fa899ef448dc548ffb825f324030a28579b788d9 | natgaertner/noipytraining | /for.py | 903 | 3.890625 | 4 | li = 'coke,coffee,mimosa,water,bloody mary,ice tea'.split(',')
for drink in li:
print "Donny loves to drink " + drink
raw_input('first for loop done')
age_limits = [['drive',16],['smoke',18],['vote',18],['drink',21],['tell kids they bother you',35], ['collect social security',65]]
age = 1
you_can = 'at age {0} y... |
a4d08fb1a900a9336e7a18eed8837ed24f56a6b8 | OzRayan/Basketball_Team | /app.py | 3,731 | 3.546875 | 4 | import os
import time
import prompt as pt
import constants as con
TEAMS = {}
PLAYERS = [player for player in con.PLAYERS]
def clean():
"""Clean console"""
os.system('cls' if os.name == 'nt' else 'clear')
def exit_():
"""Exit program and cleaning the console"""
print(pt.prompt_bye)
time.sleep(... |
776ae8cc4ee69344a30d128842b2c1917420e3cc | mvkozlova/pythonProject | /lesson_1_4.py | 250 | 3.828125 | 4 | a = int(input('Введите целое положительное число'))
m = a%10
a = a // 10
while a > 0:
if a % 10 > m or a % 10 == m:
m = a % 10
a = a // 10
elif a % 10 < m:
a = a // 10
print(str(m))
|
4e72e41d3c643e25b9613c82a4be23ffa608b085 | ipt-summer-school/dice-rolling-simulator-flex-gloohoy | /dices.py | 1,279 | 3.734375 | 4 | import random
facets_group = []
facets2_group = []
numbers_group = []
numbers_dm = []
quantity = int( input ("how much dices?: ") )
i = 1
# спрашиваю кол-во граней
while i <= quantity:
facets = int( input ("how much facets on dice?: ") )
facets_group.append (facets)
facets2_group.append (face... |
600639eab752ea2fdbde3ee150729c5b8ef11df9 | jeevanalok/estimating-pi-using-monte-carlo-simulation | /esitmating_pi_via_montecarlo_sim.py | 3,262 | 4.5 | 4 | """
this is python program to estimate the value of pi using monte carlo simulation.
pseudocode:-
->a circle of radius r is inscribed in a square whose side is 2r
->points of random (x,y) values are generated and the points falling inside the circle are kept tracked of
->algortihm
(*)area of circle=no. of points i... |
34e02349a424c11e8e25f72e28dfbfb21bd10501 | Frank1126lin/Leecode | /reversenum.py | 428 | 4.125 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : reversenum.py
# @Author: Frank
# @Date : 2018-10-12
def reversenum(x):
"""
:type x: int
:rtype: int
"""
if x < 0 and x > -2**31 and int(str(-x)[::-1]) < 2**31-1:
return -(int(str(-x)[::-1]))
elif x >= 0 and x < 2**31-1 and int... |
92596cdbc56d01f72d911dcad52b848f502f72c3 | ilyasnoskov/python-laboratory | /laboratory1/task2.py | 743 | 4.0625 | 4 | print("""Послуги телефонної мережі оплачуються за таким правилом: за розмови до А хвилин в місяць - В грн.,
а розмови понад встановлену норму оплачуються з розрахунку З грн. за хвилину.
Ввести А, ввести В, і ввести Х, що дорівнює хвилинам які користувач витратив на розмови за місяць.""")
import func
A = func.func("A:... |
da50ea2dbed6771f589867f84304f543dcdb6ae4 | sanjiv576/LabExercises | /Lab2/nine_leapYear.py | 469 | 4.1875 | 4 | """
Check whether the given year is leap year or not. If year is leap print ‘LEAP YEAR’ else print ‘COMMON YEAR’.
Hint: • a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100
• a year is always a leap year if its number is exactly divisible by 400
"""
year = int(input("Pleas... |
8ccdd26d1ecc5918c9736bb294ebc39b8b344c56 | sanjiv576/LabExercises | /Lab4_Data_Structure__And_Iternation/Dictionary/Four_check_keys.py | 291 | 4.46875 | 4 | # Write a Python script to check if a given key already exists in a dictionary.
dic1 = {1: 'one', 2: 'two', 3: 'three'}
keyOnly = dic1.keys()
check = int(input("Input a key : "))
if check in keyOnly:
print(f"{check} key already exists.")
else:
print(f"{check} key is not in {dic1}")
|
9193689da08cab23f2b621569036570ea5d03bc2 | sanjiv576/LabExercises | /Conditions/Second.py | 330 | 4.5 | 4 | """
If temperature is greater than 30, it's a hot day other wise if it's less than 10;
it's a cold day; otherwise, it's neither hot nor cold.
"""
temp = float(input("Enter the temperature : "))
if temp > 30:
print("It's s hot day ")
elif temp < 10:
print("It is a cold day")
else:
print("It is neither hot ... |
05bc68517729cf3bd4f2463c0b52b87f52799731 | sanjiv576/LabExercises | /Lab2/ten_sumOfIntergers.py | 456 | 4.25 | 4 |
# Write a Python program to sum of three given integers. However, if two values are equal, sum will be zero
num1 = int(input("Enter the first integer number : "))
num2 = int(input("Enter the second integer number : "))
num3 = int(input("Enter the third integer number : "))
if num1 == num2 or num1 == num3 or num2 == n... |
6e65b1ee4f36c20e3e2185ddaec2c5ca03da7584 | sanjiv576/LabExercises | /Lab3/Six_reverseOfString.py | 172 | 4.5 | 4 | # Write a Python program to reverse a string.
def reversed():
"""This modules reverses a string."""
name = input("Enter name : ")[::-1]
print(name)
reversed()
|
4b69189aa69becee50a00c534ac15e1cb7814b7f | sanjiv576/LabExercises | /Lab2/eight_sum_of_three-digits.py | 279 | 4.28125 | 4 | """
Given a three-digit number. Find the sum of its digits.
10.
"""
num = int(input("Enter any three-digits number : "))
copidNum = num
sum = 0
for i in range(3):
remainder = copidNum % 10
sum += remainder
copidNum //= 10
print(f"Sum of each digit of {num} is {sum}") |
c41b1224fc1951eb9420847a83a4fd75f183d196 | sanjiv576/LabExercises | /Lab4_Data_Structure__And_Iternation/Question_answers/NIne_factorial.py | 176 | 4.34375 | 4 | # Write a program to find the factorial of a number
product = 1
num = int(input("Input a number : "))
for i in range(1,num+1):
product *= i
print(f"{num}! = {product}") |
27d6d4a16a3acb9da7f3fc436d77ec1d1433416f | sanjiv576/LabExercises | /Lab4_Data_Structure__And_Iternation/Question_answers/Four_pattern.py | 666 | 4.28125 | 4 | """
Write a Python program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
*
"""
for rows1 in range(1,6):
for column_increment in range(1,rows1+1):
print("*", end=" ")
print()
for rows2 in range(4,0,-1):
for column_decrement in range(1,rows2+1):
... |
529b127ab15d54aa298124f2721c83d40a3f7aa5 | sanjiv576/LabExercises | /Conditions/Five.py | 848 | 4.125 | 4 | """
game finding a secret number within 3 attempts using while loop
import random
randomNum = random.randint(1, 3)
guessNum = int(input("Guess number from 1 to 10 : "))
attempt = 1
while attempt <= 2:
if guessNum == randomNum:
print("Congratulations! You have have found the secret number.")
break
... |
3d444a90877f42484264377689f25562d2069e96 | oriBayo/hackerrank-solutions | /hackerrank/Food_Truck.py | 1,354 | 3.796875 | 4 | import math
from builtins import print
from datetime import datetime
def haversine(lat1, lon1, lat2, lon2):
dLat = (lat2 - lat1) * math.pi / 180.0
dLon = (lon2 - lon1) * math.pi / 180.0
lat1 = (lat1) * math.pi / 180.0
lat2 = (lat2) * math.pi / 180.0
a = (pow(math.sin(dLat / 2), 2) ... |
d7f2807a267589ceeb26b73c50fb4905acec8415 | vvrs/rndf_reader | /readrndf.py | 5,238 | 3.609375 | 4 | #/usr/bin/env python
'''
This script has classes defined to read RNDF file. These classes segregate the different
sections in order for the other scripts to have access to the data, and create waypoints
dictionary and Adjacency list.
Usage:
Create an instance of the class 'waypointsDict' and call the method '... |
9f51539430d010667a5c75af4521382f4a565761 | sadashiv30/pyPrograms | /rmotr/class1-Datatypes/printNumbersWithStep.py | 864 | 4.28125 | 4 | """
Write a function that receives a starting number, an ending number (not inclusive) and a step number, and print every number
in the range separated by that step.
Example:
print_numbers_with_a_step(1, 10, 2)
> 1
> 3
> 5
> 7
> 9
Extra:
* Use a while loop
* Use a flag to denote if the ending nu... |
84d9e2001b0c977317c5b8a4b76f7b61f12fac76 | sadashiv30/pyPrograms | /rmotr/class2-Lists-Tuples-Comprehensions/factorial.py | 671 | 4.375 | 4 | """
Write a function that produces all the members to compute
the factorial of a number. Example:
The factorial of the number 5 is defined as: 5! = 5 x 4 x 3 x 2 x 1
The terms o compute the factorial of the number 5 are: [5, 4, 3, 2, 1].
Once you have that function write other function that will compute the
factorial... |
108e7ac3c8cc36272224ba1371c2c2f26a479639 | RJocket/spider | /day14_mysql.py | 2,062 | 3.515625 | 4 | '''
mysql 增删改查 SQL语句
'''
show databases;
CREATE DATABASE scraping;
USE scraping;
CREATE TABLE urls(
id INT NOT NULL AUTO_INCREMENT,
url VARCHAR(1000) NOT NULL,
content VARCHAR(4000) NOT NULL,
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id)
);
DESCRIBE urls;
INSERT INTO urls (url, content... |
3d56c1626d60a5238ae8c29cedd943820bec8481 | MaxCodeXTC/holoviews | /holoviews/element/geom.py | 2,798 | 3.5 | 4 | import numpy as np
import param
from ..core import Dimension, Dataset, Element2D
from .selection import Selection2DExpr, SelectionGeomExpr
class Geometry(Dataset, Element2D):
"""
Geometry elements represent a collection of objects drawn in
a 2D coordinate system. The two key dimensions correspond to the... |
b3525d32194630f56c9fcc3597096be6bf1e4e51 | subaroo/HW08 | /mimsmind0.py | 2,341 | 4.65625 | 5 | #!/usr/bin/env python
# Exercise 1
# the program generates a random number with number of digits equal to length.
# If the command line argument length is not provided, the default value is 1.
# Then, the program prompts the user to type in a guess,
# informing the user of the number of digits expected.
# The pro... |
912fc0f64d281ec6c17e4a9c34e9b3984dbf39a0 | byelipk/gradient-descent-from-scratch | /city_population_runner.py | 2,020 | 4.09375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from algorithms import *
print("Testing gradient descent implementation using Food Truck dataset.")
# Step 1 - Collect our data
filename = "data/food_trucks.csv"
df = pd.read_csv(filename)
data =... |
3b8418a47cf08517de5f4362275d1709f74242b3 | eddieir/design_patterns | /iterator/mainIterator.py | 3,737 | 4.65625 | 5 | """
Iterator is a behavioral design pattern that allows sequential traversal through a complex data structure without exposing its internal details.
Thanks to the Iterator, clients can go over elements of different collections in a similar fashion using a single iterator interface.
Usage examples: The pattern is very... |
56de309777dbc133433e40f4eacffa502ac6aaf0 | eddieir/design_patterns | /MVC/game.py | 1,594 | 3.515625 | 4 | from numbers import Numbers
class Game:
class SnakeInfo:
def __init__(self,snake):
self.snake = snake
self.grow_num = 0
def grow(self,num):
self.grow_num += num
def do_growth(self):
growing = self.grow_num != 0
if growing:
... |
7a4bbfcf0d79e03fa86c5fc82c90ec1a53cf6901 | tryggth/CDT | /sphere_generator/sphere_generator.py | 23,280 | 3.671875 | 4 | #!/usr/bin/env python2
"""
sphere_generator.py
Time-stamp: <2013-03-13 13:46:52 (jonah)>
Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
This file is the top-level interface for the sphere_generator program
which generates spheres of (as close as possible to) uniform curvature
for a given surface area by mont... |
230b415353d1c843aca352daf0c900f290315bc4 | JoaoCesarRF/ExerciciosPythonBrasil | /classes/quadrado.py | 409 | 3.5625 | 4 | class Quadrado:
def __init__(self):
self.tamlado = 0
def muda_lado(self,lado):
self.tamlado = lado
def area_lado(self):
area = self.tamlado * self.tamlado
return self, area
quadrado_primeiro = Quadrado()
print(quadrado_primeiro)
quadrado_primeiro.muda_lado(6)
print(quadrado_... |
09e292e7419782df279a12ae23a31ea8bb2a7b79 | kwantaing/CD_Python_Fundamentals | /functions_intermediate1.py | 659 | 3.875 | 4 | import random
def randInt(min=0, max=100):
if(min>max):
return False
elif(max<0):
return False
if(min>0):
num = random.random()*(max-min)+min
else:
num = random.random()*max
return round(num)
print(randInt()) # should print a random integer between 0 to 1... |
0eb2a601e0913fe85e2eaf39db370d702098700b | maikkkkk/xiaobai_study_ai | /1aiwork/上课.py | 1,025 | 3.609375 | 4 | data_dict={}
#exm=("xiaoa":(1,2,3),"xiaob":(2,3,4)}
# with 表示是模块,当这个模块结束之后 会自动关闭文件
with open("E:/project/github/1aiwork/成绩单.txt",'r') as f:
lines = f.readlines()
print(lines)
for line in lines:
datas=line.split() #datas是最后一行的切割
name=datas[0]
yuwen=int(datas[1])
shxuue=int(da... |
a41fa8a78d4dc86195cdf5694127a13aaf61b83a | qlurkin/qlurkin.github.io | /docs/courses/python2be/ai/bestfirst.py | 1,216 | 3.734375 | 4 | class PriorityQueue:
def __init__(self):
self.data = []
def enqueue(self, value, priority):
# Could be better
self.data.append({'value': value, 'priority': priority})
self.data.sort(key=lambda elem: elem['priority'])
def dequeue(self):
return self.data.pop(0)['value']
def BestFS(start, successors, goals... |
790d7ab55074f1a102013525133163a69a576da9 | qlurkin/qlurkin.github.io | /docs/courses/python1ba/slides/slides5/exercices5/1_combine.py | 517 | 3.796875 | 4 | # Ecrire une fonction nommée combine() qui prends deux listes et une fonction
# en paramètres. Les deux listes seront de la même taille et la fonction reçue
# devra prendre deux paramètres.
# La fonction combine() appeler la fonction reçue avec une valeur de chaque
# liste dans l'ordre. Elle renverra la liste contenant... |
2a52a98e53dfe5c3e5f4bf81076eaa565a8eee5c | qlurkin/qlurkin.github.io | /docs/courses/python1ba/slides/slides1/Exercices1/5_even.py | 241 | 3.546875 | 4 | # Ecrire une fonction nommée even() qui renvoie la valeur booléenne True
# si elle reçoit un nombre pair et False dans le cas contraire.
def even(n):
# Votre code ici
if __name__ == '__main__':
print(even(4))
print(even(5))
|
d29d921ef23de814037235ebe5221ed64934e224 | sfmiller940/viz | /Random_Walks/1D_Stepper.py | 454 | 3.5625 | 4 | # 1D Basic Random Walk
def randomwalks(nsteps,nwalks):
import matplotlib.pyplot as plt
import random
for j in range(nwalks):
X = [0]
for i in range(nsteps):
X.append( X[i] + random.choice([-1,1]) )
plt.plot(X)
X=[0]... |
90920ea08018af4aed01466777478cb083fc9d52 | manuck/python_practice | /day3/dict_1.py | 1,033 | 3.515625 | 4 | phonebook = {
#key : value
"중국집": "02843",
"초밥집": "031",
"한식집": "043"
}
phonebook2 = dict(중국집=1, 초밥집=2)
# print(phonebook)
# print(phonebook2)
# phonebook["분식집"] = "042123"
# print(phonebook["분식집"])
#1. 좋아하는 그룹 : key - 이름 , value - 나이
twice = {
"모모": 23,
"사나": 23,
"나연": 24
}
#... |
8dde7b7de71ffa138dc98d70b31bf642a6d63ef6 | piyush0/EightQueens | /core.py | 1,890 | 3.78125 | 4 | from helpers.bit_operations import *
# Function to check whether it is safe to place the queen at this spot by checking the two diagonals and the column.
def is_safe(n, row, col, col_checker, diag1_checker, diag2_checker):
return not is_kth_bit_set(col_checker, col) and \
not is_kth_bit_set(diag1_checke... |
9afb638ca9a41c3b77c2ec6181f4b3f257c65196 | L7907661/21-FunctionalDecomposition | /src/m1_hangman.py | 2,152 | 4.4375 | 4 | """
Hangman.
Authors: Zeyu Liao and Chen Li.
""" # done: 1. PUT YOUR NAME IN THE ABOVE LINE.
# done: 2. Implement Hangman using your Iterative Enhancement Plan.
####### Do NOT attempt this assignment before class! #######
import random
def main():
print('I will choose a random secret word from a dictionary.'
... |
fcc92cf50ac64f94f3fba6983559bc15f095a705 | noahnaamad/my-first-python-blog | /Untitled1.py | 255 | 4.15625 | 4 | # print "hello cruel world"
#if 3 > 2:
# print("it works!")
#else:
# print("uh oh")
# this is a comment
def hi(names):
for name in names:
print('hey ' + name + '!')
print('whats up')
hi(['noah', 'hoshi', 'spanky', 'mitzi']) |
59c4a5256151a7afe52c55cec6effc846a02cd22 | basantech89/code_monk | /python/Michigan_Python_for_Everybody/C4_Using_Python_to_Access_WebData/codes/xmlXpath.py | 1,190 | 3.90625 | 4 | import xml.etree.ElementTree as ET
countrydata = '''<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</countr... |
e3c0ea364fb2ea37b351e795189bdf2a9e820dec | basantech89/code_monk | /python/Michigan_Python_for_Everybody/C4_Using_Python_to_Access_WebData/codes/webCrawler.py | 339 | 3.640625 | 4 | import urllib
from bs4 import BeautifulSoup
#url = raw_input('Enter URL to parse-')
url = 'http://www.dr-chuck.com/'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
#Retrieve a list of anchor tags
#Each tag is like a dictionary of HTML attributes
tags = soup('a')
for tag in tags:
print tag.... |
16fe962a5f983e21bc9979d51eeade600ed6affa | basantech89/code_monk | /python/MITx/6.00.2x_Introduction_to_ComputationalThinking_and_DataScience/codes/list comprehensions and generators.py | 128 | 3.546875 | 4 | x = [2*n for n in range(50)]
print x
y = iter([1, 2, 3])
print y
print y.next()
print y.next()
print sum(xrange(10))
|
2e186b5cdbb77f56203370115db996c7b433718c | basantech89/code_monk | /python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/converting into binary.py | 294 | 4.09375 | 4 | num = raw_input("enter an integer : ")
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ""
if num == 0:
result = "0"
while num > 2:
result = str(num%2) + result
num = num/2
if isNeg:
result = - + result
print("binary of "+str(num)+" will be "+result) |
c7f799ad98d7c4e8c68f6fb2c3684f9ec62f9b0e | basantech89/code_monk | /python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/operations on lists.py | 460 | 3.71875 | 4 | tech = ['MIT', 'Cal Tech']
ivys = ['Harvard', 'Yale', 'Brown']
univs = [tech, ivys]
univs1 = [['MIT', 'Cal Tech'], ['Harvard', 'Yale', 'Brown']]
tech.append('RPI')
for e in univs:
print 'Univs contain'
print e
print 'Which contains'
for u in e:
print ' '+u
tech.sort()
tech.index('... |
1c28520fd90c7b5a886110645be367233b472cb3 | basantech89/code_monk | /python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/global variable.py | 458 | 3.828125 | 4 | def fibMetered(x):
'''plz do not set x to be larger then 20 otherwise program will hang'''
global numCalls
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fibMetered(x-1) + fibMetered(x-2)
def testFib(n):
for i in range(n+1):
global numCalls
... |
11bec9486cb05e5a2957249cb47d750f4a947934 | ElficTitious/tarea3-CC4102 | /utilities/math_functions.py | 848 | 4.40625 | 4 | from math import *
def next_power_of_two(x):
"""Returns the next power of two after x.
"""
result = 1 << ceil(log2(x))
return result
def is_power_of_two(x):
"""Returns if x is a power of two or not.
"""
return log2(x).is_integer()
def prev_power_of_ten(x):
"""Returns the previous powe... |
23732a2acd4b58dc41baa68e9a170a808116b17d | SergiySavarin/FortyTwoTestTask | /apps/contact/utils.py | 1,352 | 3.578125 | 4 | from PIL import Image
def size(path):
""" Function calculate photo size.
args:
path: path to photo.
returns:
True: if photo is in 200x200px size.
False: if photo is more than 200x200px size.
"""
try:
original = Image.open(path)
width = or... |
d5a2fa6dbe4e5ba184c1ffc6b6d6f513946e6882 | jonathanstallings/data-structures | /merge_sort.py | 1,850 | 4.15625 | 4 | """This module contains the merge_srt method, which performs an
in-place merge sort on a passed in list. Merge sort has a best case time
complexity of O(n log n) when list is nearly sorted, and also a worst case of
O(n log n). Merge sort is a very predictable and stable sort, but it is not
adaptive. See the excellent '... |
d0b9a2d5d0e829e438603ccc658d5c92679e5b51 | jonathanstallings/data-structures | /binary_heap.py | 4,276 | 3.921875 | 4 | from __future__ import unicode_literals
class BinaryHeap(object):
"""A class for a binary heap."""
def __init__(self, iterable=(), minheap=True):
"""Initializes a binary heap, optionally with items from an iterable.
By default, the binary will sort as a minheap, with smallest values
a... |
12c2c5e488cfdb74bf799711a8823044d9d4e377 | jurijw/AdventOfCode2019 | /Day4/day4.py | 2,728 | 3.515625 | 4 | password_range = range(183564, 657474 + 1) # Puzzle input
# Assume all passwords fit the criteria
passwords = [num for num in password_range]
#passwords = [123789]
#passwords = [111111, 223450, 123789]
not_passwords = [] # list of passwords that do not fit criteria
for num in passwords:
# Two adjacent digits m... |
bb73d0ff17ad685652cad94d45d2499ac758f822 | zo-bar/rosalind | /src/com/zobar/rosalind/IEV.py | 829 | 3.640625 | 4 | '''
Created on Mar 7, 2013
@author: Zoya
'''
pairs = ['AA-AA', 'AA-Aa', 'AA-aa', 'Aa-Aa', 'Aa-aa', 'aa-aa']
def get_dominant_probability(pair):
parents = pair.split("-")
recessive_prob = 1
if parents[0].count("A") == 2 or parents[1].count("A") == 2:
recessive_prob = 0
i... |
ba3886e02069f4c757c1d4f2bee869f5021e2bd4 | zo-bar/rosalind | /src/com/zobar/rosalind/FIBB.py | 317 | 3.875 | 4 | '''
Created on Feb 28, 2013
@author: Zoya
'''
def fibb(n, k):
print ("n=%d k=%d" % (n, k))
a, b = 1, 1
i = 2
while i < n:
b = a + k * b
a, b = b, a
i += 1
print ("a=%d" % a)
print ("b=%d" % b)
print ("RESULT: %d " % a)
fibb(28, 2)
|
30e3aceaecc49efa48ef0f85e8d301a5d572ef07 | zo-bar/rosalind | /src/com/zobar/rosalind/IPRB.py | 517 | 3.5 | 4 | '''
Created on Mar 3, 2013
@author: Zoya
'''
def dominantPercent(k, m, n):
# k-both dominant
# m-half dominant
# n-recessive
total = k + m + n + 0.0
totalPair = total * (total - 1)
mm = m * (m - 1) / totalPair
nn = n * (n - 1) / totalPair
mn = n * m / totalPair
... |
41384de95f267ba2213d0576b91c93a392a67bd1 | zhouhouzhen/deepLearning_course_code | /Second_Course/Gradient_Checking.py | 19,305 | 4.5 | 4 | # Gradient Checking
# Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
# You are part of a team working to make mobile payments available globally, and are asked to build a deep learning model to detect fraud--whenever someone makes a payment, you ... |
19637bdb040e1de9aca353cef80b414d92198fd8 | Manan861/Project100 | /atm.py | 937 | 3.796875 | 4 | class atm:
def __init__(self, cardNumber, PIN):
self.cardNumber=cardNumber
self.PIN=PIN
def checkBalance(self):
print("Your balance is 56000")
def withdraw(self,amount):
newAmount=56000-amount
print("You have withdrawn amount " + str(amount)+ " Your re... |
a5ac556455789357a1452518a3f240bd4a36cbd9 | livytoolson/codesignal | /unit-02/sprint.py | 3,250 | 4.21875 | 4 | """
Note: Your solution should have O(l.length) time complexity and O(1) space complexity, since this is what you will be asked to accomplish in an interview.
Given a singly linked list, reverse and return it.
Example
For l = [1, 2, 3, 4, 5], the output should be
reverseLinkedList(l) = [5, 4, 3, 2, 1].
"""
# Singly... |
bfb002d7e3ba1eb86e392416d66b964cdb4b9e1f | dedin/sides | /sorts/sorts.py | 4,742 | 4.375 | 4 | # BUBBLE SORT
# Go through the list over and over again, swapping as you go(if necessary)
# until you go through the list w/out swapping. Can reduce number of iterations
# cos on every walk of the list, the largest ends up bn at its right position
# Simple, efficient on small data, but bad on large data
# Not good for ... |
7e2fe4b58974938d03ce73e59928eb4229ea9f4f | Alafazam/pygorithm | /pygorithm/dynamic_programming/binary_knapsack.py | 873 | 3.875 | 4 | '''
Author: Omkar Pathak
Created At: 25th August 2017
'''
def knapsack(W, value, weight, n):
'''
:param W: maximum weight capacity
:param value: an array of values of items in the knapsack
:param weight: an array of weights of items in the knapsack
:param n: number of items in the k... |
a12dca53fd39580f8e5f110183ab6c75010e01a9 | xheory/weighted-edit-distance | /src/files/csv_processor.py | 1,893 | 4.09375 | 4 | import csv
import os
class CsvProcessor(object):
"""
Object that handles the writing/loading of CSV files.
"""
def create_directory_structure(self, directory_path):
"""
Creates the directory structure for the given path. Ignores all directory creation errors on purpose.
"""
... |
739fe3c83aa6d2ae71c9fe6f0422c59c3855a62c | hugochougt/homework | /python/bitwise.py | 197 | 3.5 | 4 | # p108 Comouter Projects 2
a = int(input('Enter a bit string : '))
b = int(input('Enter a bit string : '))
print('a&b= ', a&b)
print('a|b= ', a|b)
print('a^b= ', a^b)
# д |
c4a021342947f56b479b97da0612006840381c9a | hugochougt/homework | /python/AddressBook.py | 2,044 | 4.0625 | 4 | # A command-line address-book program
class Contact:
def __init__(self):
print('Enter name: ')
self.name = input()
print('Enter email address: ')
self.emailAddress = input()
print('Enter phone number: ')
self.phoneNumber = input()
Contact.... |
e4443d50af11dff709d8cb6b8d1f896dd5ddb251 | collinsmith12/CS0 | /PE4.py | 296 | 3.5 | 4 | def PE4():
largestnumber = 0
for x in range(100, 1000):
for y in range(100,1000):
numbers = str(x*y)
if numbers == numbers[::-1]:
if int(numbers) > int(largestnumber):
largestnumber= int(numbers)
print largestnumber |
17d3631c76c5e7ba3cc84ae9acd5d04b507385c2 | collinsmith12/CS0 | /hangman final project collin ch.py | 4,768 | 4 | 4 | import random
def loadWord():
person = ['mike', 'teeter', 'thomas']
place = ['trinity', 'work', 'ocala']
thing = ['computer', 'hangman', 'printer']
listOfLists = [person, place, thing]
selectedList = random.choice(listOfLists)
secretWord = random.choice(selectedList)
if selectedLi... |
51433315d604c4cb973f97a875954c722674aa78 | kristinadarroch/django | /Django-Python-Full-Stack-Web-Devloper-master/Python_Level_One/my-notes/lists.py | 1,099 | 4.25 | 4 | # LISTS
my_list = ['adfsjkfdkfjdsk',1,2,3,23.2,True,'asd',[1,2,3]]
print(my_list)
# PRINTS THE LENGTH OF A LIST.
this_list = [1,2,3]
print(len(this_list))
print(my_list[0])
my_list[0] = 'NEW ITEM'
print(my_list)
# .append can add something to a list
my_list.append('another new item - append')
print(my_list)
listt... |
82822386bbd31af176a56f51ac8695ac685b5520 | Sagar-Khode/Object-detection | /audio.py | 1,192 | 3.5625 | 4 |
# Import the required module for text
# to speech conversion
from gtts import gTTS
# This module is imported so that we can
# play the converted audio
import os
import pytesseract as tess
tess.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
from PIL import Image
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.