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 |
|---|---|---|---|---|---|---|
8cecc89f0127ea698f03f262031503763a9ce3bc | ldcrchao/PycharmProjects | /python基础语法/异常处理.py | 2,407 | 3.625 | 4 | # try : 正常执行时执行的代码块 except: 如果有异常执行的代码 finally : 无论是否异常都会执行的代码
# 可以保证异常时后续的代码仍能运行不会中断
# 系统抛出异常
def func(length):
try :
if length >= 18 :
print('顺哥的鸡鸡还行不太短')
else:
print(length / 0)
# func(18) 如果输入的参数不对会抛出类型错误异常,然后会找到对应的异常类型执行相应代码块
except TypeError :
... |
af0ffc4ef074f2facdcdc90a0c5167dde4caea67 | Isisr/assignmentOrganizer | /assignmentOrganizer.py | 1,597 | 4.34375 | 4 | '''
Created on Feb 10, 2019
@author: ITAUser
ALGORTHM:
1) Make a .json text file that will store our assignments
2) IMport our .json file into our code
3) Create user input for finding assignments
4) Find the users assignments in our data
-If the users input is in our data
-The users input isn't in our data
'... |
285fb339822b56f0c22d29a7097dd3f8316b10ea | JhonaB-11/taller1_algoritmos | /punto3.py | 662 | 3.828125 | 4 | estatura = ""
promEstatura = 0
contE = 0
auxEstatura = 0
iterador = True
print("PROMEDIO ESTATURA")
estatura = int(input( "Ingrese la estatura " ))
while (estatura > 1):
contE += 1
auxEstatura += estatura
promEstatura = auxEstatura/contE
print("El promedio de estatura de los " + str(contE) + " ... |
cd2e7aa00df147af407e04e21ff82b7bf4b8e2d3 | abahman/MIT6.00.1x | /hello.py | 483 | 3.625 | 4 | print 'hello, Ammar'
#print 1+1
#
#temp = '32'
#if temp > 85:
# print "Hot"
#elif temp > 62:
# print "Comfortable"
#else:
# print "Cold"
#
#temp = 120
#if temp > 85:
# print "Hot"
#elif temp > 100:
# print "REALLY HOT!"
#elif temp > 60:
# print "Comfortable"
#else:
# print "Cold"
import sys
print... |
e1f3dec2138053ff5d83fc6d40a90e2b703760ad | dastratakos/Minesweeper | /board.py | 9,520 | 4.25 | 4 | '''
file: board.py
----------
This file contains the implementation for a minesweeper board.
'''
import random
'''
class: Board
----------
This class describes the properties of a minesweeper board.
'''
class Board:
'''
function: __init__
----------
This function initializes a Board object.
Member... |
511485bcb18e45e9ce01552aa8de0f644dcba5c1 | NormanGaviola/DATALGO--PRELIMS | /SAMPLE.py | 3,872 | 3.859375 | 4 | """Norman Raphael M. Gaviola
DATALOG Lab01
Feb. 12, 2020
I have neither received nor provided any help on this (lab) activity, nor have I concealed any violation of the Honor Code."""
from abc import ABC, abstractmethod
class Polygon(ABC):
def __init__(self,LS):
self.NS = len(LS)
self.... |
9b647e7adeb4698353ab3169bdba4af0ad23a426 | alextodireanu/algorithms | /bubble_sort.py | 410 | 4.375 | 4 | # bubble sort algorithm
def bubble_sort(bs_list):
"""Method to bubble sort a given list"""
n = len(bs_list)
# reading all the elements in our list
for i in range(n-1):
for j in range(n-i-1):
if bs_list[j] > bs_list[j+1]:
bs_list[j], bs_list[j+1] = bs_list[j+1], bs_li... |
67ff35bc0965ec88618dbc9df635c44c8027f082 | JasmineRain/Algorithm | /Python/Greedy Algorithm/1518_Easy_换酒问题.py | 588 | 3.5625 | 4 | class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
remain = numBottles
ans = numBottles
while remain >= numExchange:
ans += remain // numExchange
remain = remain // numExchange + remain % numExchange
return ans
if __name__... |
dd0754ccbd5875c495b422cf3547684bb2258f6e | JasmineRain/Algorithm | /Python/Back Track/60_Hard_排列序列.py | 966 | 3.765625 | 4 | import math
class Solution:
def getPermutation(self, n: int, k: int) -> str:
seq = 0
ans = ""
flag = [False] * (n + 1)
def backtrack(num, trace):
if num == n:
nonlocal seq
nonlocal ans
seq += 1
if seq == ... |
8ed4f885bbb1564ef6a96fadd99cc3aa1ea4c711 | JasmineRain/Algorithm | /Python/Others/58_Easy_最后一次单词的长度.py | 317 | 3.84375 | 4 | class Solution:
def lengthOfLastWord(self, s: str) -> int:
if not s:
return 0
return len(s.strip().split(" ")[-1])
if __name__ == "__main__":
S = Solution()
print(S.lengthOfLastWord(s="Hello World"))
print(S.lengthOfLastWord(s=" "))
print(S.lengthOfLastWord(s="a "))
|
c84c3bfcd6944546ea69a516ce52094269023729 | JasmineRain/Algorithm | /Python/Back Track/980_Hard_不同路径III.py | 1,592 | 3.625 | 4 | from typing import List
class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
ans = []
srow, scol = 0, 0
erow, ecol = 0, 0
length = 0
visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
for i in range(len(grid)):
... |
3d7236af5e80a8fadcce5fefb49555b52876f555 | JasmineRain/Algorithm | /Python/Back Track/216_Medium_组合总和III.py | 876 | 3.546875 | 4 | from typing import List
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans = []
candidates = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def backtrack(start, value, trace):
if len(trace) > k:
return
if value == n and len(trace) == k:
... |
1bb0453eabb5b170047a1947a539b8f06168957f | JasmineRain/Algorithm | /Python/Back Track/1467_Hard_两个盒子中球的颜色数相同的概率.py | 740 | 3.78125 | 4 | from typing import List
from itertools import product
import math
class Solution:
def multinomial(self, n):
return math.factorial(sum(n)) / math.prod([math.factorial(i) for i in n])
def getProbability(self, balls):
print(self.multinomial([1, 2, 3]))
k, n, Q = len(balls), sum(balls) //... |
2b82c5083eff0fea7c9766793bb42f469e9494b3 | JasmineRain/Algorithm | /Python/Dynamic Programming/523_Medium_连续的子数组和.py | 574 | 3.5625 | 4 | from typing import List
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
Hash = {0: -1}
residual = 0
for j in range(len(nums)):
residual += nums[j]
if k != 0:
residual = residual % k
if Hash.get(residual) is n... |
f40be0e51e69f8213ef4e20311f5dd091447b317 | JasmineRain/Algorithm | /Python/Others/48_Medium_旋转图像.py | 660 | 3.921875 | 4 | from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n // 2):
for j in range((n + 1) // 2):
matrix[i][j], matrix[... |
75e336d75a270f95f58c018a3b0fc4128d929bf5 | JasmineRain/Algorithm | /Python/Double Pointers/75_Medium_颜色分类.py | 595 | 3.671875 | 4 | from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
p0 = p1 = 0
for i in range(len(nums)):
if nums[i] == 1:
nums[i], nums[p1] = nums[p1], nums[i]
p1 += 1
elif nums[i] == 0:
nums[i], nums[p0]... |
ea3606fdda931da3a50e23b99caef646dcfb3fe3 | JasmineRain/Algorithm | /Python/Double Pointers/81_Medium_搜索旋转排序数组.py | 956 | 3.6875 | 4 | from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> bool:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return True
if nums[left] < nums[mid]:
... |
b0787b6f09fc61a6fb2c8fe27fa98f934d3932bb | JasmineRain/Algorithm | /Python/Sort/插入排序.py | 356 | 3.875 | 4 | class Solution:
def insertSort(self, nums):
for i in range(1, len(nums)):
for j in range(0, i):
if nums[j] < nums[i]:
continue
nums[i], nums[j] = nums[j], nums[i]
if __name__ == "__main__":
S = Solution()
nums = [4, 2, 3, 1, 5, 1]
... |
80c5b25ffbaef6de35202493c0c4dbca65a3a8fc | JasmineRain/Algorithm | /Python/Others/24_Medium_两两交换链表中的节点.py | 672 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
pre = ListNode()
slo... |
3a4a0baafee6e016443bd1bcd3dc4299cfdacec4 | JasmineRain/Algorithm | /Python/Double Pointers/350_Easy_两个数组的交集II.py | 602 | 3.609375 | 4 | from typing import List
from collections import Counter
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
ans = []
exist = Counter(nums1)
for num in nums2:
... |
90d4d36d0b33792ec8ac1b76fecf7adca1ef61af | JasmineRain/Algorithm | /Python/Linked List/82_Medium_删除排序链表中的重复元素II.py | 663 | 3.59375 | 4 | # Definition for singly-linked list.
from collections import Counter
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode(0, head)
slow = dummy
fa... |
be90d77863e9a3da2d4d767b5f754db36c545c29 | JasmineRain/Algorithm | /Python/Double Pointers/287_Medium_寻找重复数.py | 939 | 3.734375 | 4 | from typing import List
class Solution:
# 二分查找
# def findDuplicate(self, nums: List[int]) -> int:
# left, right = 1, len(nums) - 1
# while left < right:
# target = (left + right) // 2
# total = 0
# for num in nums:
# if num <= target:
# ... |
1e297aa296bb5d19ec73f4cdc1ab00de3c66be62 | JasmineRain/Algorithm | /Python/Back Track/1286_Medium_字母组合迭代器.py | 1,045 | 3.734375 | 4 | class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.seq = -1
self.ans = []
flag = [False] * len(characters)
def backtrack(index, trace):
if len(trace) == combinationLength:
self.ans.append(trace)
r... |
a9dc15f32638c785910049f1d262a4943eafd0f6 | diegord13/programas | /pruebas/visualizacion.py | 1,003 | 3.703125 | 4 | import numpy as np
def tablero():
tablero = [[str(i) for i in range(j,(j)*2)] for j in range(5)]
for num in tablero:
print(num)
#tablero()
def tablero2():
tablero = [[str(i) for i in range(j*3,(j+1)*3)] for j in range(3)]
for num in tablero:
print(num)
#tablero2()
def tablero... |
8ac0ff3826a01324a3e7501a460c037c750ef9bd | diegord13/programas | /Retos/sesiones/sesion10/sesion10.py | 2,669 | 4.40625 | 4 | """
Funciones
La verdad es que hemos venido trabajando con funciones desde que empezamos con archivos .py
En Python, definimos una función con la siguiente estructura
def funcion(parametros)
Recuerda que los parametros son opcionales!
"""
def suma(a,b):
print(a+b)
#suma(3,4)
#Actividad 1
def caja():
... |
87f1dc5d79de0ca7c6f2939dd020fb1610672e27 | diegord13/programas | /Bases de datos/consultaryordenar.py | 230 | 3.65625 | 4 | import sqlite3
conexion = sqlite3.connect("basededatos1.db")
cursor = conexion.cursor()
cursor.execute("SELECT * FROM PERSONAS ORDER BY edad")
lista = cursor.fetchall()
for persona in lista:
print(persona)
conexion.close() |
dfdef1d9ed7bb11475e4547a845838e592c1487c | diegord13/programas | /Bases de datos/ejercicio.py | 466 | 3.796875 | 4 | import sqlite3
conexion = sqlite3.connect("basededatos.db")
cursor = conexion.cursor()
#cursor.execute("CREATE TABLE productos(id integer, nombre text, precio integer)")
#datos_productos = [(1,'Impresora',300),(2,'Raton',20),(3,'Ordenador', 600)]
#cursor.executemany("INSERT INTO productos VALUES(?,?,?)", datos_pro... |
4a4c8b2d07ea2bacadbb092380786603f3018cb2 | rvbugs0/HRSolutions | /algorithms/dynamic-programming/fibonacci-method/solution.py | 371 | 3.640625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def computeTN(a,b,n):
if(n==2): return b
if(n==1): return a
if(n<=0): return 0
else:
c= computeTN(a,b,n-2)
d= computeTN(a,b,n-1)
z=(d*d)+c
return z;
a,b,n=raw_input().split(" ")... |
8aedac9cc35461ba6258502c0d04b84c98760bc7 | Mybro1968/AWS | /Python/02Basics/example/03Number.py | 342 | 4.1875 | 4 | from decimal import *
number1 = int(input("What is the number to be divided? "))
number2 = int(input("What is the number to divided by? "))
print(number1, " / ", number2, " = ", int(number1 / number2))
print(number1, " / ", number2, " = ", float(number1 / number2))
print(number1, " / ", number2, " = ", Decimal... |
cb1eac4cf03cd124ef59ab1a51f6795bb8a50799 | Mybro1968/AWS | /Python/05Files/05Files/03FileReadLineByLine.py | 290 | 3.78125 | 4 | # Program : 03FileReadByLine
# Author : John Merchant
# Date : 06May2016
# Purpose : Example to open and read file by line
file = open("filename.txt","r")
print("First line:")
print(file.readline())
file.seek(0)
print("First line again")
print(file.readline())
file.close()
|
a51cafd8e5a3eaf78fe28d734db7d6fe74c76867 | Mybro1968/AWS | /Python/04ControlFlow/03DataTypes/Exercises/01String.py | 169 | 3.796875 | 4 | ####
#01String.py
# strings 3 words together
####
word1 = "Good"
word2 = "Day"
word3 = "Gary"
sentence = word1 +" " + word2 + " " + word3
print(sentence)
|
0f2920f5267dcc5b41d469e363af037264c5d342 | Mybro1968/AWS | /Python/05Files/Exercise/01WriteTeams.py | 392 | 4.125 | 4 | # Purpose : writes a file with input for up to 5 names
file = open("teams.txt","w")
count = int(input("how many teams would you like to enter? "))
#team_name = input("Please enter a team name: ")
for n in range(count):
if count !=0:
team_name = input("Please enter a team name: ") + "\n"
... |
8ad0259f445544903d31d436be304848dd4ec8fa | K4cp3rski/Programowanie-I-R | /Ćwiczenia 27.04/cw2.py | 1,062 | 3.8125 | 4 | class Menager_hasla:
def __init__(self):
pass
stare_haslo = []
def uzyskanie_hasla(self):
if len(self.stare_haslo) != 0:
haslo = self.stare_haslo.pop()
self.stare_haslo.append(haslo)
return haslo
else:
return "Null"
def ustawianie... |
5fdfab89dfb5291bc07436c9e5e373ed5ac6ad3a | K4cp3rski/Programowanie-I-R | /Ćwiczenia 9.03/zad4.py | 452 | 3.5625 | 4 | import time
start = time.process_time()
a = int(input("Jaką liczbę chcesz potęgować? \n"))
n = int(input("Do jakiej potęgi chcesz ją podnieść? \n"))
# print(f"a={a},n={n}")
def Pot(a,n):
if n == 0:
return 1
elif n % 2 == 1 :
return a * (Pot(a, (n - 1) / 2)) ** 2
else:
return a * (Po... |
883a0591c63d7dcc2b127cc96511e47b582cf6db | talapus/DMTool | /RollBones | 758 | 3.84375 | 4 | #!/usr/bin/env python
import sys
from random import randint
def print_dice(die, rolls):
print('\n--- ' + str(rolls) + 'd' + str(die) + ' ---')
def print_usage():
print('\n' + ' RollBones #1 #2')
print(' #1: enter a number for die type (eg: number of faces)')
print(' #2: enter a number for how man... |
1b276b2c29e4230c3da4b2ae448f1d0c6d0407a1 | talapus/DMTool | /edifice | 1,302 | 3.609375 | 4 | #!/usr/bin/env python
from sys import argv
from sys import stdout
from random import randint
def edifice(place):
location = {}
location['rural'] = ['Farmhouse', 'Barn', 'Shack', 'Cannery', 'Butcher']
location['urban'] = ['Police station', 'Fire station', 'Grocery Store', 'Bank',
'... |
c61beebc60d234068ec3982799ca1c4a8fcb34e4 | dragon-slayer875/projectTurqoise | /tt.py | 1,873 | 3.828125 | 4 | import random
import tkinter as tk
#layout
#functions
def input_int():
while True:
args=input()
if args.isnumeric()==True:
args=int(args)
break
else:
print('Not a number. Try again')
continue
return args
def input_name():
while True:... |
eea020ba98d78b165782462487f5314d2c98cc57 | consileonpl/naked_thursday | /threads-compo/threads.py | 261 | 3.796875 | 4 | #!/usr/bin/env python
import threading
import time
def thread():
print("Hello World")
time.sleep(1)
t1 = time.time()
for i in range(100000):
threading.Thread(target=thread).start()
t2 = time.time()
print("Time: {:.1f} seconds".format(t2 - t1))
|
b4ebf94351b11e8f65d57e14ac9c24209dfc9f5e | Dyksonn/CursoPython | /ex06-dobro-triplo-raiz.py | 174 | 3.75 | 4 | n = int(input('Digite um valor: '))
raiz = n ** (1/2)
print(
f'O dobro de {n} vale {n*2}.\n O triplo de {n} vale {n*3}.\n A raiz quadrada de {n} e igual {raiz:.2f}')
|
710486037a460f3b4b54c163d8facfc4ae785afd | Dyksonn/CursoPython | /ex11-Pintando-Parede.py | 274 | 3.734375 | 4 | larg = float(input('Largura da parede: '))
alt = float(input('Altura da parede: '))
print(
f'Sua parede tem a dimensão de {larg} x {alt} e sua área é de {larg*alt:.2f}m².')
print(
f'Para pintar essa parede, você precisa de {(larg*alt)/2:.2f}L de tinta.')
|
f96f43eb647649704b0b66caf52ddce8d6cda48d | feelipemendes/python | /ex8_calcSal.py | 206 | 3.609375 | 4 | salarioHora = input('Entre com o seu salario por hora: ')
horasMes = input('Entre com as suas horas trabalhadas: ')
salario = salarioHora * horasMes
print ("Seu salario nesse mes foi de: "),salario
|
a7a63e4035c3b521326e6f941bf737210fd81d1b | marcrune/Automate-the-Boring-Stuff | /collatz.py | 312 | 4.09375 | 4 | def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 != 0:
print((number * 3) + 1)
return (number * 3) + 1
print('Type in an integer: ')
n = int(input())
var = collatz(n)
while var != 1:
var = collatz(var)
|
be9e8583883ebac7ff1c9a6d1f10685d311d57d8 | OfficerRabbit/py_Flask_Project | /main.py | 3,439 | 3.796875 | 4 | """
1/29/18 CF
Create a Flask web app to write notes to a database
Tutorial
Part 1
https://medium.com/python-flask-django-tutorials-and-tips/how-to-build-a-crud-application-using-flask-python-framework-3a398b04c3c6
Part 2
http://tutorialsfordevs.com/tutorials/p... |
6b06b17601db13468cb668d63df1582e33c5de0b | zzwei1/Python-Fuzzy | /Python-Tutorial/Numerology.py | 2,629 | 4.15625 | 4 | #!usr/bin/python
# Function to take input from Person
def input_name():
""" ()->int
Returns sum of all the alphabets of name
"""
First_name= input("Enter the first Name")
Middle_name= input("Enter the middle Name")
Last_name= input("Enter the last Name")
count1=count_string(First_name)
... |
b6f88b153c314c146153525da5871742ecfb440d | dicleoztur/subjectivity_detection | /sentimentfinding/performtest2.py | 185 | 3.609375 | 4 | '''
Created on Mar 8, 2013
@author: dicle
'''
from datetime import datetime
start = datetime.now()
print 'hello'
end = datetime.now()
delta = end-start
print type(delta)
print delta |
6e911289bc9f57d6a15c2a7aad54425bc44adb8e | fatihwin/Python-Courses-for-Beginners-Fatihwin | /returns-the- value-to-the-variable.py | 123 | 3.765625 | 4 | #returns the value to the variable #
x = 900
print(x)
#print will take the argument x as the value in the variable #
|
14b98649de60ba260ebdb07ed14b6edfa9c7c5b7 | Luciana1012/Blockchain | /blockchain act1.py | 6,546 | 3.828125 | 4 | """"
This file contains code for Blockchain Banking activities.
Last modified : 28/4/2021
Author: Luciana C., castorinaluciana@gmail.com
Customer Department, Licesing ....
"""
import json
################################# Activity 1 ##########################################3333
class User():
"""... |
20b5b26e28989a0bd3d98cdcbeaf3583351eeef5 | jkatem/Python_Practice | /FindPrimeFactors.py | 431 | 4.15625 | 4 |
# 1. Find prime factorization of a given number.
# function should take in one parameter, integer
# Returns a list containing all of its prime factors
def get_prime_factors(int):
factors = list()
divisor = 2
while(divisor <= int):
if (int % divisor) == 0:
factors.append(divisor)
... |
ad9e99a3eb91465656b45ae54024b3e262f0d207 | tobigrimm/adventofcode2019 | /5/solve.py | 3,528 | 3.65625 | 4 | #!/usr/bin/env python3
with open("input") as inputfile:
orig_instructions = [int(i) for i in inputfile.readline().strip().split(",")]
"""opcodes:
1: addition: 3 parameters, param 3 = 1+2
2: multiplication: 3 parameters, param 3 = 1*2
3: input: 1 param, saves input() to address param1
4: output: 1 param, outputs... |
8dde664bca5a81df8a91e7522427218931db4be4 | mmingalov/geekbrains-math | /05/5.py | 1,254 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Дополните код расчетом коэффициента корреляции x и y по формуле
n = 100
r = 0.77
x = np.random.rand(n)
y = r*x + (1 - r)*np.random.rand(n)
plt.plot(x,y,'o')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
a = (np.sum(x)*np.sum(y) - n*np.sum(x*y))/(np.sum(... |
1cf893ad83869d1fcdef0224ce888a060f9db349 | MingkaiMa/Python-Programming | /Assignment/Assignment_1/superpower.py | 2,716 | 3.65625 | 4 | import sys
str_list = input("Please input the heroes' powers: ")
try:
super_power_list = [int(n) for n in str_list.split()]
except ValueError:
print('Sorry, these are not valid power values.')
sys.exit()
try:
nb_of_swiches = int(input('Please input the number of power flips: '))
except ValueError:
... |
027a5c92a25a77b7291dce9752095101c76a41ce | MingkaiMa/Python-Programming | /Quiz/Quiz_5/quiz_5.py | 3,223 | 3.65625 | 4 | # Randomly generates a grid of 0s and 1s and determines
# the maximum number of "spikes" in a shape.
# A shape is made up of 1s connected horizontally or vertically (it can contain holes).
# A "spike" in a shape is a 1 that is part of this shape and "sticks out".
#
# Written by Mingkai Ma and Eric Martin for COMP9021
... |
4a88c41d2cdfada64ade30509f28fafbc18e09a7 | MingkaiMa/Python-Programming | /Quiz/Quiz_8/quiz_8.py | 3,170 | 3.796875 | 4 | import sys
from random import seed, choice
from array_queue import *
from collections import defaultdict
def display_grid():
for i in range(dim):
print(' ', end = '')
for j in range(dim):
print(' ', grid[i][j], end = '')
print()
print()
try:
seed_arg = int(input('Ente... |
6350f3af9ce51046b0142f37aff48570f432ebe9 | faddy/ds-with-python | /ds/main/data_structures/graphs.py | 2,294 | 3.734375 | 4 | # implementation of a graph
# every node in a graph is represented by a Vertex object
# each Vertex object has a dictionary where:
# each key is a neighbour vertex id
# the values are weight of the edges
class Vertex(object):
def __init__(self, key):
self.id = key
self.neighbours = {}
d... |
6276b3ebe39e66f5337866d0103c3cb07d47a09a | faddy/ds-with-python | /ds/main/trees/parse_tree.py | 1,485 | 3.5625 | 4 | from data_structures.stacks import Stack
from trees.tree_structures import TreeNode
import operator
operators = '*+/-'
op_dict = {'*': operator.mul, '+':operator.add,
'/': operator.truediv, '-': operator.sub}
def build_parse_tree(expression):
if not expression:
return None
expression =... |
ff7a52a14eeab67a5268672c79d9aa646ae7fa49 | faddy/ds-with-python | /ds/main/sorting_searching/sequential_search.py | 288 | 3.828125 | 4 | def sequential_search(list_of_values, item):
if not list_of_values or not item:
return False
pos = 0
found = False
while pos < len(list_of_values) and not found:
if item == list_of_values[pos]:
found = True
pos += 1
return found
|
3e61c4dcfc7f8a530f47f60a72f16a39d8fbe4a8 | faddy/ds-with-python | /ds/main/linked_list_problems/nth_to_last_element.py | 561 | 4 | 4 | #!/usr/bin/python
from data_structures.linked_lists import Node
from linked_list_problems.utils import create_linked_list, print_list
def nth_to_last_element(head, n):
if not head: return None
if n <= 0 : return None
endp = head
for i in range(n):
if not endp: return None
else: endp =... |
e085d02a268b5bd23f6321a8140b6bbe3aa6a2f1 | faddy/ds-with-python | /ds/main/threading/reader.py | 458 | 3.53125 | 4 | import threading
class Reader(threading.Thread):
def __init__(self, name, cache):
threading.Thread.__init__(self)
self.name = name
self.cache = cache
print 'Thread with name {0} has been initialized'.format(name)
def run(self):
print 'I am in the run method, bro'
... |
1b0a183bb9b2fb44721ed553c9570cb4932df71d | faddy/ds-with-python | /ds/main/data_structures/linked_lists.py | 3,098 | 3.875 | 4 | class Node(object):
def __init__(self, initdata):
self.data = initdata
self.nxt = None
def get_next(self):
return self.nxt
def set_next(self, node):
self.nxt = node
def get_data(self):
return self.data
def set_data(self, newdata):
self.data = newd... |
22a82a26176f0d7617c45caa2e960545dc984ad2 | ShivonQ/Simple_RPG | /character/Character.py | 1,297 | 3.671875 | 4 | from random import randint
class Character:
def __init__(self, name):
self.name = name
self.strength = 1 # This is the base damage
self.armor = 0 # This is the base armor rating
# # Damage vs Armor, if damage <= armor 'You Missed'
# self.money = 0
self.current_hp = ... |
23aa739c90600f704abc469181a69c50ab037617 | ShivonQ/Simple_RPG | /character/Fighting.py | 1,017 | 3.9375 | 4 | import random
class NumGen():
def _battle(self):
hero = int (input("Please enter a number up to 10. "))
monster = random.randint(1,10)
""" x and z can both be used below without errors -- testing/learning"""
randomNumber = random.randint(1,50)
print ("hero attack does" , r... |
eaef06c719d031ba51befb38fa163e990056635e | Vagacoder/PythonStudy | /w3schools/025-numpyArraySearch.py | 631 | 3.84375 | 4 | #
# * Python Numpy Array Search
#%%
import numpy as np
a1 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'c', 'd', 'c'])
i = np.where(a1 == 'c')
print(i)
print(type(i))
print(a1[i])
# %%
a2 = np.array([1, 2, 3, 4, 5, 6, 7, 8])
l = np.where(a2%2 == 0)
print(l)
print(a2[l])
# %%
# ! searchsorted() which performs a ... |
c560785019ab60b3e6321513ee0e1cdecc4de791 | Vagacoder/PythonStudy | /pandas/046-pandasReshap.py | 685 | 3.578125 | 4 | #
# * Pandas Reshape tables\
# TODO: This is advanced method, come back later
#%%
import pandas as pd
try:
titanic = pd.read_csv('data/titanic_test.csv')
air_q = pd.read_csv('data/air_quality_long.csv', index_col='date.utc', parse_dates=True)
except Exception as ex:
print(ex)
titanic.head()
air_q.he... |
3c1498a5628d356b57d6cf71eec3d47fc820e364 | Vagacoder/PythonStudy | /w3schools/020-pickle.py | 718 | 3.53125 | 4 | #
# * Python pickle
#%%
import pickle
person1 = {
'name': 'Alex',
'age': 30,
'pay': 4000.0,
'vacation': False
}
person2 = {
'name': 'Bob',
'age': 25,
'pay': 2518.50,
'vacation': True
}
database = {}
database['person1'] = person1
database['person2'] = person2
with open('./data/perso... |
9b17c6aff7441503c449f9ff67d9fa40930c8741 | Vagacoder/PythonStudy | /w3schools/033-numpyRandomBinomial.py | 670 | 3.890625 | 4 | #
# * Python Numpy Random Binomial Distribution
#%%
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
import seaborn as sb
x = random.binomial(n=10, p=0.5, size=10)
print(x)
# %%
sb.distplot(random.binomial(n=10, p=0.5, size=1000), hist=True, kde=False)
plt.show()
# %%
# * difference... |
c7cbc16f0fd9ff3e1aa2de0edfe09a711bb53fa5 | Vagacoder/PythonStudy | /w3schools/005-list.py | 420 | 4.0625 | 4 | #
# * List operations
#%%
l1 = ['apple','banana', 'cherry']
l1.append('orange')
print(l1)
# %%
l1 = ['apple','banana', 'cherry']
l1.insert(0, 'orange')
print(l1)
# %%
l1 = ['apple','banana', 'cherry']
l1.remove('banana')
print(l1)
# %%
l1 = ['apple','banana', 'cherry']
l1.pop()
print(l1)
# %%
l1 = ['apple','banana... |
c9c1c56eb8e2d5310359cc7415c89e65bf970cad | Vagacoder/PythonStudy | /pandas/045-pandasStatistics.py | 1,145 | 3.703125 | 4 | #
# * Pandas Statistics
#%%
# * Load csv file
import pandas as pd
titanic = pd.read_csv('data/titanic_test.csv')
titanic.head()
# %%
# * mean of column
ageMean = titanic['Age'].mean()
print('Mean of age column is: {}'.format(ageMean))
# %%
# * median, multiple columns
ageMedian = titanic[['Age', 'Fare']].median(... |
2d91ccf089497c875142f913f449969efefbd468 | amanmishra98/python-programs | /assign/2-if else/string comparison.py | 508 | 4.09375 | 4 | a=input("enter 1st string\n")
b=input("enter 2nd string\n")
c=input("enter 3rd string\n")
if a<b and a<c and b<c:
print(a)
print(b)
print(c)
if a<c and a<c and c<b:
print(a)
print(c)
print(b)
if b<a and b<c and a<c:
print(b)
print(a)
print(c)
if b<c and b<a and c<a:
... |
586053553610e2ebc482ec02bc42c507a96504aa | amanmishra98/python-programs | /array/insert element by user.py | 199 | 3.96875 | 4 | from array import *
a=array('i',[])
n=int(input("enter total no of element in array\n"))
for i in range(1,n+1):
x=int(input("enter no\n"))
a.append(x)
for i in a:
print(i,end="")
|
2ef29349623d6d121bf97960142ef71c348cd864 | amanmishra98/python-programs | /ditionary/dictionary2.py | 188 | 3.78125 | 4 | d={21:'aman',26:'ankit',7:'abhijeet',31:'arvind'}
d1={'a':'aman','s':'shu','g':'golu','k':'krati'}
print(d)
print("type of: ",type(d))
print(d1)
print("type of: ",type(d1))
input()
|
7b6b48c3f5cc553ee12b61c8603ab6308c45fcfc | amanmishra98/python-programs | /assign/4-for loop/find first n no in python.py | 562 | 3.53125 | 4 | #print first n prime no using for loop
l=[]
l1=[]
i=1
n = int(input("Enter the number:"))
for k in range (1, (n+1)):
c=0
for j in range (2, (i+1)):
if (i%j==0):
c = c+1
#print(c)
if (c==1):
print (i)
l.append(i)
#print(l)
i... |
e89b9d01414b7f20ceb3e5e64d4e90e317b3a731 | amanmishra98/python-programs | /mini projects/tic-tac-toe3.py | 2,411 | 4.03125 | 4 | '''tic-tac-toe player vs computer'''
#to understand this game we can remove hash comments like print(l1)
from numpy import *
from random import *
arr=array([['a','b','c'],['d','e','f'],['g','h','i']])
flag=0
for i in arr:
print(i)
l1=['a','b','c','d','e','f','g','h','i']
###################################... |
eed9873ab2f4c6f680606b54336ea4601919fb27 | amanmishra98/python-programs | /assign/4-for loop/prime no between two no.py | 325 | 3.953125 | 4 | #print prime no between two no using while and for loop
n1 = int(input("Enter the number:"))
n2 = int(input("Enter the number:"))
k=n1
while k<=n2:
c=0
# k=k+1
for j in range (2,k+1):
if (k%j==0):
c = c+1
#print(c)
if (c==1):
print (k)
k=k+... |
a677d4055dbe59dec016fe09756f57176d7ddc6c | amanmishra98/python-programs | /assign/14-class object/class object10.py | 577 | 4.1875 | 4 | #2.define a class Account with static variable rate_of_interest.instance variable
#balance and accountno. Make function to set values in instance object of account
#,show balance,show rate_of_interest,withdraw and deposite.
class Account:
rate_of_interest=eval(input("enter rate of interest\n"))
def info(se... |
136b6e19a4df29dc6956b329af1712bcb9cad726 | amanmishra98/python-programs | /assign/5-list/square of n natural no in list.py | 205 | 3.96875 | 4 | #square of elements of list
n=int(input("enter no\n"))
l=[]
print("enter elements to be insert in list")
for x in range(1,n+1):
a=int(input())
l.append(a**2)
print(l)
input()
|
d6ddbb779dc0aeead021e8520f1ee112113c3140 | amanmishra98/python-programs | /ditionary/ditionary3.py | 202 | 3.671875 | 4 | '''d=dict(21='aman',26='ankit',7='abhijeet',31='arvind')'''#error
d1=dict(a='aman',s='shu',g='golu',k='krati')
#print(d)
#print("type of: ",type(d))
print(d1)
print("type of: ",type(d1))
input()
|
c8d97617885d607149931d5ded48769844068b51 | amanmishra98/python-programs | /assign/6-string/reverse a string.py | 198 | 4.4375 | 4 | #WAPS to reverse a string by user
s=input("enter string\n")
print("string is: ",s)
print("reverse of string is:",end=" ")
for x in s[len(s)-1::-1]:
print("%s"%x,end="")
input()
|
8265c18a5344c85d76ca67601d613501cd660841 | alessandraburckhalter/Exercises | /ex-07-land-control.py | 498 | 4.1875 | 4 | # Task: Make a program that has a function that takes the dimensions of a rectangular land (width and length) and shows the land area.
print("--" * 20)
print(" LAND CONTROL ")
print("--" * 20)
# Create a function to calculate the land area
def landArea(width, length):
times = width * length
prin... |
1a51c717a6e111f4f6f2252d6734fba2691f9b64 | Axelum-tech/oop | /ex1.py | 896 | 4.03125 | 4 | ################declare the class##############
class FruitBox:
################init function#################
def __init__(self,apples,oranges):
self.apples = apples
self.oranges = oranges
def __add__(self,m):
return self.apples+m.apples+self.oranges+m.oranges
def __s... |
1a47d7910965b48449cec484ace34966b5f720c4 | bazerk/katas | /euler/problem6.py | 620 | 3.515625 | 4 |
def euler_problem6(until):
sum = 0
sum_square = 0
for i in range(1, until):
sum += i
sum_square += i * i
return (sum * sum) - sum_square
def euler_problem6_2(until):
sequence = map(lambda x: (x, x * x), range(1, until))
sums = reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), s... |
5b8fe72fd81b5ebb09d48774e3259dc5b69c05d7 | bazerk/katas | /tree_to_list/tree_to_list.py | 939 | 4.25 | 4 | def print_tree(node):
if not node:
return
print node.value
print_tree(node.left)
print_tree(node.right)
def print_list(node, forwards=True):
while node is not None:
print node.value
node = node.right if forwards else node.left
def transform_to_list(node, prev=None):
i... |
ba8a572deda6d5bf0b1ccc419f587000eac21b4b | bazerk/katas | /euler/test_euler.py | 2,141 | 3.640625 | 4 | import unittest
import euler
class EulerTests(unittest.TestCase):
def setUp(self):
pass
def test_check_number_is_palindrome(self):
self.assertEqual(euler.test_prime(2), True)
self.assertEqual(euler.test_prime(3), True)
self.assertEqual(euler.test_prime(4), False)
self... |
e1457bf4d8d8cbbfcc02c230fc6d72e082a96a15 | bazerk/katas | /euler/problem45.py | 1,372 | 3.796875 | 4 | # -*- encoding: utf-8 -*-
"""
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = ... |
d02706de8c00710489a25034d224c2a92a96a5a5 | bazerk/katas | /euler/problem17.py | 1,510 | 3.609375 | 4 | import re
ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen']
tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
'eighty'... |
0df966b157494397878b54212fd44c8e328c1211 | Alexander-Stanley/Programming-II | /Prac 1/broken_scores.py | 213 | 3.96875 | 4 | score = float(input("Enter your score: "))
if score < 0 or score > 100:
print("Invalid score, try again")
elif score >= 90:
print("Excellent")
elif score >= 50:
print("Passable")
else:
print("Bad") |
95c2fe3d1b70f8bcb8b18465bb62a81e88c82635 | javpelle/ComputerAlgebra | /Sage/AGUIALE/02_euclid_extended.py | 1,683 | 4.0625 | 4 | def euclid_extended (a, b, first=True):
'''
Algoritmo extendido de euclides (Identidad de Bezout).
Resuelve la identidad:
mcd(a,b) = a*s + b*t
Devuelve el resultado en el formato (r,(s,t)).
La versión del algorimo usada es la que viene en
[wikipedia][algoritmo], que usa matrice... |
18693a56084ff2e85c919108d8e690996f736373 | eaalhvdw/Konkurrence-Opgaver-NCPC-Problems | /ncpc_functions.py | 3,263 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 12 00:28:04 2020
@author: jhaj
"""
import problem_a_14
import problem_i_14
def A_2013(N, t):
t.sort(reverse=True)
day_number = 1
max_days = []
for n in t:
result = day_number + n + 1
max_days.append(result)
day_number += 1
retu... |
07fa010a4ee02bca4a52c67dd00ebfe31aa2bc3f | AlexPerri/Practice-Problems | /1_3.py | 232 | 3.890625 | 4 | # Take a sentence and replace all spaces with "%20"
def makeUrl(string) :
print(string.replace(" ", "%20"))
def main() :
makeUrl(input("Enter a sentence\n"))
input("Press Enter to close")
if __name__ == "__main__" :
main()
|
724c9f3972e7ac35d0e74054ae8652aa7d040e56 | Mark-McAdam/cs_lambda | /graphs/deque_practice.py | 794 | 4.0625 | 4 | from collections import deque
dq = deque("abcdefg")
print("Deque:", dq)
print("Length - DQ", len(dq))
print("left side", dq[0])
print("right side", dq[-1])
dq.remove("c")
print("Deque: remove c", dq)
print()
print("populating")
# Add to the right
d1 = deque()
d1.extend("abcdefg")
print("extend :", d1)
d1.append... |
2301c57af423c616840312a43e4d8180e4446475 | Mark-McAdam/cs_lambda | /hash-tables/code_challenge_monday.py | 896 | 4.0625 | 4 | """Add up and print the sum of the all of the minimum elements of each inner array:
[[8, 4], [90, -1, 3], [9, 62], [-7, -1, -56, -6], [201], [76, 18]]
The expected output is given by:
4 + -1 + 9 + -56 + 201 + 18 = 175
You may use whatever programming language you'd like.
Verbalize your thought process as much as possib... |
f3ff8b052610ee6bbbb7e72220ecd76d50acbcf2 | Mark-McAdam/cs_lambda | /hash-tables/applications/crack_caesar/crack_caesar.py | 1,300 | 3.734375 | 4 | # Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Your code here
# Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Your code here
with open("applications/crack_caesar/ciphertext.txt") as f:
words = f.read()
replace_chars = [
" ",
'"',... |
39dc53ae520aa6d2ecaa1a9d315cf86e27989f69 | M10307431/Jingho | /WSN_simulation/Practice/MeetRatio_Puzzle/puzzle1.py | 1,574 | 3.578125 | 4 | import Image
import turtle
from PIL import Image
import canvas
from Tkinter import *
import Tkinter
import tkMessageBox
def Drawpath():
wn=turtle.Screen()
alex=turtle.Turtle()
alex.forward(50)
alex.left(90)
alex.right(30)
wn.mainloop()
def Puzzle():
top = Tkinter.Tk()
... |
5a6f444779a550bd2b5baeb38423e6f7227a963a | mrczl/Python-study | /1-4 List 2.py | 1,275 | 3.859375 | 4 | # 1-4 List 2
print ("------1-4 List 2-------")
print ()
# list 2.1 改变列表:元素赋值
print ("2.1 改变列表:元素赋值")
print ("list1 = [1,1,3,4]")
list1 = [1,1,3,4]
print ("list1[1] = 2")
list1[1] = 2
print ("list1=",list1)
print ("------------------------")
print ("***Exercise 1***")
months = ["January","February","Match","May","June"... |
87658d050ace22701252e392fa0fcd31c24fc48b | mrczl/Python-study | /3-3 function4.py | 421 | 3.859375 | 4 | # 3-3 function4
#数字n的阶乘算法
#常规方法
x = int(input("Enter a number >"))
def factorial(n):
result = n
for i in range(1,n):
result *= i
return result
result = factorial(x)
print("%d 的阶乘是:%d" % (x,result))
#递归写法
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
res... |
9612e9e726c336a987c8503ac04e0be2a188edf6 | 22lizabeth/Text_Based_Adventure_Game | /adventureGame.py | 4,458 | 3.53125 | 4 | from locations import *
from bag import *
from effects import *
class AdventureGame:
def __init__(self):
self.resetAll()
def resetAll(self):
self.bag = Bag()
self.effects = Effects()
self.location = Location(self.bag, self.effects)
self.userInput = ""
#GAME PLAY FUNCTIONS
def pla... |
6f6c1e8d043b23e48da3e7696977516b96a73e98 | NujjA/Tech-Interview-Practice | /solutions.py | 6,790 | 4.09375 | 4 |
def question1(s, t):
'''Given two strings s and t, determine whether some anagram of t
is a substring of s. For example: if s = "udacity" and t = "ad",
then the function returns True. Your function definition should
look like: question1(s, t) and return a boolean True or False.'''
# If s does... |
3b5a7183a5726964c47da13d1a62f06c28666643 | 6Glory9/python-final | /basic/do_if.py | 145 | 3.828125 | 4 |
a = 100
if a >100:
print("大于100")
elif a==100:
print("等于100")
elif a<100:
print("小于100")
else: print('不可能的事') |
fd58379227a26aa0c7f0d646aabee8117d434f38 | anurasharma/Calc | /Calci.py | 244 | 4.03125 | 4 | num1=input("Enter the number: ")
num2=input("Enter the another number: ")
result= int(num1)+ int(num2)
print(result)
num3=input("Enter the Number: ")
num4=input("Enter the another number: ")
Result2= float(num3)+ float(num4)
print(Result2)
|
f7cac2efa1ab9f0d6b870ee0e7c9549092beafef | BCajati/AIQ1 | /TestBoardSets.py | 1,303 | 3.75 | 4 | from TileBoard3 import *
from copy import deepcopy
from queue import *
def listsAreSame(x, y, len):
newList = [i for i, j in zip(x, y) if i == j]
if newList.__len__() == len:
return True
else:
return False
def boardsAreSame(board1, board2):
if listsAreSame(board1.sortedTiles(), board2.... |
0911ea40d9db9dbf57eaeab96fd3485920fa7a7e | supimpinha/estudo_dirigido_1 | /2.py | 230 | 3.703125 | 4 | "2 Escreva um programa que leia um valor em metros e o exiba convertido em milímetros."
metros = float (input("Infome um valor em metro(s)"))
milimetros = metros * 1000
print ("O valor em milimetros será de:", milimetros)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.