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 |
|---|---|---|---|---|---|---|
aad4be12b0893c559eb9cd30e16e4a7c4ca7a4da | theshevon/A2-COMP30024 | /david/board.py | 7,805 | 3.703125 | 4 | from math import sqrt
from david.game_state import *
class Board():
SIZE = 3
COLOURS = { "red", "green", "blue" }
# starting nodes for the different teams
START_NODES = {
"red" : { (-3,0), (-3,1), (-3,2), (-3,3) },
"blue" : { (0,3), (1,2)... |
8195f33921a0e3d81ebdef458e02854ac4853683 | theshevon/A2-COMP30024 | /john/player.py | 1,289 | 3.828125 | 4 | """
Implementation of an Autonomous agent that will play the Chexers board game
against two other players.
Version No: 0.2
Version Details:
Agent that's greedy on the distance to an exit tile. However, if it can cut an
opponent's piece, then it will.
Written by David Crowe and Shevon Mendis, May 2019
"""
from john... |
d2fd5afd38c0191cdc657af4e99e62da817b7f0f | theshevon/A2-COMP30024 | /adam/decision_engine.py | 2,458 | 4.1875 | 4 | from math import sqrt
from random import randint
class DecisionEngine():
"""
Represents the agents 'brain' and so, decides which node to move to next.
"""
EXIT = (999, 999)
colour = None
exit_nodes = None
open_node_combs = None
init_node... |
9513e1fbbcfa8505e3dc9a4e9734284dbedf12b9 | theshevon/A2-COMP30024 | /Wildcat/player.py | 1,158 | 3.671875 | 4 | """
Implementation of an Autonomous agent that will play the Chexers board game
against two other players.
Version No: 1.1
Version Details:
- Uses Best Reply Search
Current Issues:
Written by David Crowe and Shevon Mendis, May 2019
"""
from Wildcat.board import *
from Wildcat.decision_engine1 import *
c... |
05837520862e526971539c980ef0a1c02dfa7e26 | TonyzBi/Machine-Learning | /Collections_Cards/Vector.py | 1,031 | 3.5 | 4 | # -*- coding: utf-8 -*-
from math import hypot
import os
from collections import namedtuple
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return "Vector(%r, %r)" % (self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
... |
391b8c9e384cebeaf3101c3cffd158473146b970 | KavikaPalletenne/Python | /definitionfinder.py | 461 | 3.5625 | 4 | import requests
from lxml import html
word = input("What is the word you want to search?")
definitionURL = ("https://www.dictionary.com/browse/" + word)
page = requests.get(definitionURL)
tree = html.fromstring(page.content)
definition = tree.xpath('/html/body/div/div/div/div[2]/div/main/section/section/d... |
2d5efd3d74852d234b6a782df5addea6acdb1dd8 | Calebp98/Euler-Problems | /problem14/main.py | 439 | 3.703125 | 4 | def collatz(n):
print(n)
collatz.count +=1
if (n==1):
return True
elif (n%2==0):
n = n/2
else:
n = 3*n+1
collatz(n)
def collatzLen(n):
collatz.count = 0
collatz(n)
return(collatz.count)
# maxVal = 1
# term = 0
# collatzLen(100)
# for i in range(1000000):
# i = 1000000-i
# if(collatzL... |
6382b30274963b95914bdc2ac97d989cba55dcd7 | MFDOOMiile/oop_fruit_stand | /chall_menu_oop.py | 961 | 3.984375 | 4 | import sys
from challenge_oop import Fruit, Barrel
class Menu:
def __init__(self):
self.fruit_barrel = fruit_barrel
self.choices = {
"1": self.add_fruits,
"2": self.show_fruits,
"3": self.remove.fruits,
"4": self.empty.fruits,
"5": exit
... |
8273da9ef7fb33ab57d238d677465cebd66a07b0 | narokiasamy/internship1 | /06-20-19/temperatureConverter.py | 548 | 4.25 | 4 | # temperature must be typed with corresponding temperature scale unit! (ex: 32F or 68C)
temperature = str(input("temperature reading: "))
# temperature conversions
if "C" in temperature:
removeLetter = int(temperature.rstrip("C"))
fahrenheitCalculation = (int((removeLetter * 1.8) + 32))
print (str(fahrenheitCalc... |
a220c8cf2ae254f3a399cdfe17542ca9f508780d | sucman/Python100 | /11-20/14.py | 1,419 | 4.125 | 4 | # -*- coding:utf-8 -*-
'''
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
'''
a = int(raw_input("请输入数字:"))
print "{} = ".format(a),
while a not in [1]: # 循环保证递归
... |
aa0f0e30f131831956eea0f155ed6c09e127da22 | milanmeu/AOC | /Day6Part1.py | 366 | 3.703125 | 4 | file = open("input6")
yes = 0
line = file.readline()
while line:
yes_questions = set()
while line and line != "\n":
for letter in line:
if letter != "\n":
yes_questions.add(letter)
line = file.readline()
yes += len(yes_questions)
yes_questions = set()
l... |
1da42c0dd13f869bc7a8f1b100594106caf16775 | sasazlat/fcnd_udacity | /from_grids_to_graphs/bresenham/bresen_ham.py | 4,169 | 4.03125 | 4 | # coding: utf-8
# ## Bresenham
# In[3]:
import numpy as np
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
plt.rcParams['figure.figsize'] = 12, 12
# Your task is to implement the bresenham function given two points $p_1$ and
# $p_2$ as inputs. The function should return the li... |
1a81b34eea06f527710d41409a5cce8cc640a7c4 | sasazlat/fcnd_udacity | /from_grids_to_graphs/a_star_city/a_star_city.py | 8,630 | 3.609375 | 4 | # coding: utf-8
# ## Finding Your Way In The City
#
# In this notebook you'll combine the work of previous exercises to calculate a
# minimal series of waypoints in order to get from a start location to a goal
# location.
#
# You'll reuse and modify your algorithms from:
#
# - A*
# - Configuration Space
# - Collineari... |
227f3ab2be572b835b8339cbd305f3acb12fd5ee | sasazlat/fcnd_udacity | /planning_as_search/BFS/DFS.py | 4,480 | 4.375 | 4 |
# coding: utf-8
# # Breadth-First Search
# In this exercise you'll implement the breadth-first search algorithm.
# In[1]:
# Import numpy and Enum
import numpy as np
import queue
from enum import Enum
import BFS
# https://wiki.python.org/moin/TimeComplexity gives a solid overview of Python
# data structures and ... |
c8518ce8e34b076be79b59a491c3b1a08cedc2ca | wingeeer/Projects | /TDT4136 - Introduction to artificial intelligence/Assignment3graphTraversal/astarPart2.py | 7,353 | 3.65625 | 4 |
import heapq
from collections import deque
from PIL import Image, ImageDraw
class Cell():
#Class for each cell (1x1) of the board with parameters:
# x - the x coordinate of the cell
# y - the y coordinate of the cell
# parent - allows relations between the cells on a path
# g - cost from start cell ... |
76fab41704109dd494ca152ccfa3671a0aaaf551 | abstract-monk/euler | /python/problem02.py | 598 | 3.953125 | 4 | #!/usr/bin/python
# Project Euler Problem 2
# -----------------------
# Even Fibonacci Numbers:
# Each new term in the Fibonacci sequence is generated by adding the previous
# two terms. By starting with 1 and 2 , the first 10 terms will be:
# 1,2,3,5,8,13,21,34,55,89,...
# By considering the term in the Fibonacci s... |
44fc4fc60e1be6ada3f029d518e95a4d657347a6 | r4b3rt/leetcode_solutions | /0198_House_Robber/Solution1.py | 912 | 3.6875 | 4 | from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
elif len(nums) == 1:
return nums[0]
dp = [0 for i in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nu... |
875953f79ed02834dce251bbbb473e11bb09af97 | TebanRiveros/TrabajosPython | /py6_retos2/reto11.py | 137 | 3.703125 | 4 | lista1=list(range(11))
lista2=list(range(11,21))
print(lista1,"\n",lista2)
lista1.extend(lista2)
print("la lista final es: ", lista1)
|
e64ce76efe95c4d4122be1921d692d13ba509d6b | TebanRiveros/TrabajosPython | /py4_comprension/palabras.py | 123 | 3.921875 | 4 | A=['almeja','mantequilla','elefante','sol','pasta']
solo_a=[A[x] for x in range(len(A)) if A[x][-1]=='a' ]
print(solo_a) |
f0a5f248e43258e5e910b6ea1b935134b6abcc30 | TebanRiveros/TrabajosPython | /py3_ciclos/lista.py | 189 | 3.5 | 4 | def llene_lista(A,B):
n=len(A)//2
C=[]
for i in range(n):
d=(A[i+1])**2
e=d*B[2*i]
f=e+B[n+i]
C.append(f)
return C
A=[4,6,8,2]
B=[2,1,0,-1]
print(llene_lista(A,B)) |
099744ac89805c8026f7a4553b3c97b272c6b201 | RandomUsername1010/test | /prisoners_dilemma.py | 900 | 4.03125 | 4 | import random
def mySolution(history):
(you, them) = history[-1]
check = []
check.append(them) # Get the action of the opponent
# If the opponent colludes, have a 75% chance of betraying
# and a 25% chance of colluding
if "C" in check:
number = random.randint(1, 100)
if number ... |
b598d038b137c34e8d79afe39fe881042878f3d7 | Zhezhang-Jerry/ACIT-2515-Inclass-prac | /sample.py | 849 | 4.09375 | 4 | class Point:
def __init__(self, x, y):
print("I am creating a Point object")
self.x = 0
self.y = 0
def print(self):
print("I am Point", self.x, self.y)
class Student:
def __init__(self, name, student_number):
self._name = name
self.student_number = "A" + stu... |
6412c4e6746ebd149867ed017642ef312af5d514 | lp55323/Python-exercise | /Day2_Exercise2.py | 1,328 | 3.828125 | 4 | china = {
'辽宁省':{
'大连市':['甘井子区','中山区'],
'沈阳市':['沈河区','沈北区']
},
'吉林省':{
'长春市':['南关区','九台区'],
'四平市':['梨树县','双辽县']
},
'黑龙江省':{
'哈尔滨市':['道里区','道外区'],
'伊春市':['嘉荫县','农场区']
}
}
while True:
for i in china:
print(i)
shengfen = input('你想去哪个省... |
260ebcd387e66bf0a17576468d5e6e1c3b6cee61 | manerain/savy | /proj02/proj02_02.py | 598 | 4.4375 | 4 | # Name:
# Date:
# proj02_02: Fibonaci Sequence
"""
Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci
sequence is a sequence of numbers where the next number in the sequence is the sum of the
previous two numbers in the sequence. The sequence looks like this:
1, 1, 2, 3, 5, 8, 13.... |
14806fa3430e98e4d783c4b1d7248f36a1d08858 | FumihisaKobayashi/udemy_python3 | /control_structure/Value_check.py | 221 | 3.5625 | 4 | #is_ok = True
is_ok = 1 #値にヘンスが入っていたらTrueになる
is_ok = ''#値が入っているかどうかで判定できる[]
#False, o, o.o, '',[],(),{},set()
if is_ok:
print('ok!')
else:
print('No!')
|
3f611b141ac2c6d4fb2471e650abed795270acd2 | FumihisaKobayashi/udemy_python3 | /control_structure/for.py | 557 | 3.703125 | 4 | some_list = [1, 2, 3, 4, 5]
"""
i = 0
while i < len(some_list): #中身を順に出力
print(some_list[i])#some_listのi番目
i += 1
"""
"""
for i in some_list: #some_listから(反復処理)inで入れていき、イテレーターをinでいれていく
print(i)
#自分で1ずつ足していく必要がない
for s in 'abcde':#文字abcdeから順に取り出す
print(s)
"""
for word in ['my', 'name', 'is', 'Mike']:
if wor... |
81e1f211ebab777268c5d62064945ea04569271b | FumihisaKobayashi/udemy_python3 | /basic/lesson1.py | 329 | 3.9375 | 4 | num = 1
name = 'Mike'
is_ok = True
#typeで型が分かる
print('num', type(num))
print(name, type(name))
print(is_ok, type(is_ok))
#型変換
new_num = int(name)
print(new_num, type(new_num))
#型宣言、書くこともできるが宣言は使わない
num: int = 1
name: str = "1"
#1から始めない syntaxerrorでる |
93eef432348d79088341d6c56e2af0423bfc9b5b | FumihisaKobayashi/udemy_python3 | /control_structure/dic_for.py | 182 | 4.09375 | 4 | d = {'x': 100, 'y': 200}
#単純にループするとキーだけ表示
print(d.items())
for a, v in d.items():#.items()メソッド
#
print(a, ':',v)#aとvに代入される
|
dd5da324562a7d3569f7c0f91dcaca60c67f311b | FumihisaKobayashi/udemy_python3 | /word_method.py | 502 | 3.96875 | 4 | s = 'My name is Mike. Hi Mike'
print(s)
is_start = s.startswith('My') #myから始まってるか調べる(s.starteith)
print(is_start)
print('*******************')
print(s.find('Mike'))#'Mike'文字列
print(s.rfind('Mike'))#後ろから検索
print(s.count('Mike'))#'Mike'の個数
print(s.capitalize())#最初大文字あと小文字
print(s.title())#全ての 文字列の最初大文字
print(s.upper())... |
5ddf658fab5b36cf57e30bfa994dc15eab2be6c7 | Tej-Singh-Rana/Socket-Clash | /sender.py | 731 | 3.71875 | 4 | #!/bin/python3
#This is for sender section.
import socket
target_ip = "127.0.0.1"
target_port = 8080
#Now we are creating UDP socket.
# Ipv4 , UDP
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #This part will use sender and receiver both.
msg=input("Enter your message : ")
#Now we ca... |
f84f7e7815d63aa3f00fd9d661751aa1b6540596 | arjun921/her | /her.py | 2,476 | 3.5 | 4 | import os
import sys
import base64
import requests
import shutil
import speech_recognition as sr
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
# Speech recognition using Google Speech Recognition
try:
# for testing purposes, we're just... |
48cb2d3941f64013cd1a66a90ea71019a9eb6baf | cristian1barajas/EjemplosPython | /MaterialPython/listas.py | 608 | 3.90625 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
# pop nos sirve para eliminar el ultimo elemento de una lista
# del para borrar ciertos elementos de determinadas pocisiones
# ''.join(variable) nos ayuda a convertir una variable en una lista
# append nos ayuda a añadir nuevos elementos a una lista
lista = [1,2,3,4,5,6,7... |
599dd1b0b3f4d390b5a427014d1f3497cd4b42a6 | cristian1barajas/EjemplosPython | /MaterialPython/Introduccion_al_hacking/w.py | 296 | 3.75 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
import shutil
import sys
import os
def main():
print(len(sys.argv))
if len(sys.argv) == 2:
for n in range(0,int(sys.argv[1])):
shutil.copy(sys.argv[0],sys.argv[0]+str(n))
else:
print("Faltan argumentos")
if __name__ == '__main__':
main() |
0baa5692dce09d548d9ad6f39460dd38de1dc809 | tainaracamila/PizzaPricePredictions | /main.py | 1,408 | 4.40625 | 4 | """
Prevendo o Preço da Pizza
Suponha que você queira prever o preço da pizza.
Para isso, vamos criar um modelo de regressão linear para prever o preço da pizza, baseado em um atributo da pizza
que podemos observar. Vamos modelar a relação entre o tamanho (diâmetro) de uma pizza e seu preço.
Escreveremos então um prog... |
0f06590c2dfb1774da6e2d57617a39b0eadf6ec3 | BrownJake/Brown_NRS528 | /Coding_Challenge_8/Challenge_8.py | 2,635 | 3.75 | 4 | # Coding Challenge 8
# Creating a function
# For this coding assignment I created a buffer function that can be used with point, line, and polygon data.
# I demonstrate this function using data for these three feature class types using course data from NRS 522.
# This buffer function will set the workspace, print... |
ceb004bbdb2272415757a4288cc2407d0f7a8f6c | nemesek/ProjectEuler | /Python/EulerPython/Euler/Problem4.py | 601 | 4.09375 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
#def findMaxPalindrome(seq):
# max = 0
# for x,y in ((x,y) for x in seq for y in seq):
# if str(... |
137772e58ae2eedb7b39e59f7d7b4dca4546b2fa | matthewcornell/peepweather | /forecast/ZipCodeUtil.py | 1,587 | 3.5625 | 4 | import csv
import re
def makeZipInfoTuples():
"""
Loads zipcode-clean.csv into memory
:return: a list of 5-tuples of the form: (csv_zipcode, city, state, latitude, longitude)
"""
zipInfoTuples = []
with open('forecast/zipcode-clean.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile... |
244c11a91e5d1894196fb975234354c463ab7e40 | bsantos2/DataStructuresAlgos3 | /problem_5.py | 4,464 | 3.78125 | 4 | ## Represents a single node in the Trie
class TrieNode:
def __init__(self, value = None):
self.value = value
self.children = {}
self.isword = False
self.word = None
return
def clean_trie(self, node):
if node:
for x in node:
if node[x]:... |
b167e65d417a28e2febd32205c9e253a3b1ba594 | yrtgfd/homeworks | /lab 2/Multtable.py | 258 | 3.5 | 4 | def mult_table(m, n):
p = len(str(m * n))
n_length = len(str(n))
for i in range(1, n + 1):
print('{:_>{P}}_=_{:_>{K}}_{}'.format(i * m, i, m, P=p, K=n_length))
return True
m, n = [int(i) for i in input().split(',')]
mult_table(m, n) |
728619372d2a1429895cf732e44851b428fe65a2 | cliptic/Machine_Learning_Projects | /svm/svm_author_id.py | 1,942 | 3.515625 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preproce... |
b834571a81fe9524658d11477b5e0ad67f74f569 | RakibRyanRemon1/py4e | /assignment7.2.py | 374 | 3.75 | 4 | # Use the file name mbox-short.txt as the file name
file_name = input("Enter file name: ")
fh = open(file_name)
count = 0
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
pos = line.find('0')
total += float(line[pos:pos + 6])
count += 1
average = total... |
11f2fae0b317c7ce7e83c410dd210aa747e2b2a0 | NgyAnthony/python-course | /Chapter 3/Exercises/3.2-4.py | 283 | 4.15625 | 4 | words = ["Hello", "my", "same", "is", "Anthony", "Okayy", "Heyyy"]
def count_words():
count = 0
for word in words:
if word.count(str()) == 6:
count +=1
print(word, "is 5 str long.")
print(count, "words with 5 in length.")
count_words() |
98b734b491f2c70a5501327b4e7b818e4cd5a77b | NgyAnthony/python-course | /Chapter 4/Exercises/4-9.py | 734 | 3.609375 | 4 | import turtle
hisa = turtle.Turtle()
window = turtle.Screen()
window.bgcolor("lightgreen")
hisa.speed(0)
def draw_star(animal, length, angle):
"""
Draw a 5 points star
"""
for _ in range(5):
animal.right(angle)
animal.forward(length)
def move_away(animal, units, turn):
"""
Mo... |
0a4bedf31f01da7bbd5df9e32ac26d32a317f7aa | overdev/SpaceGame | /spacegame/sat.py | 4,688 | 3.6875 | 4 | __author__ = 'Jorge'
# A Python implementation of Separating Axis Theorem
import pygame
from spacegame.vectors import Vector
from spacegame.geometry import *
__all__ = [
# "AABB" # still deciding whether to add it or not.
"Interval",
"get_axes",
"get_separating_axis"
]
class Interval(object):
... |
349515c9908dcb3bb4841e86fb46b967be6eb416 | amughalbscs16/Python-Practice | /factorial.py | 423 | 3.9375 | 4 | #Trying Python for the First Time Writing Simple functions and stuff.
def factorial1(number): #1 Tab = Start Definition/Body of Function/for/if/while or other conditionals.
factorial=1;
while (number>0):
factorial=number*factorial;
number-=1
print(factorial)
return factorial
factoria... |
333c966ac41102066a682a55c44259946c0f3b82 | ankokudzura/lab_2 | /Задание_3.py | 322 | 3.953125 | 4 | def check(num):
while(num % 2 == 0):
num = num / 2
while(num % 3 == 0):
num = num / 3
while(num % 5 == 0):
num = num / 5
return num
n =int(input("введите число: "))
cal=1
i=1
while (cal<n):
i=i+1
if (check(i)==1):
cal+=1
print(i)
|
2b93272460187f0373702d69c4879e8ccafda703 | fxbp/spd_ex4 | /utils.py | 417 | 3.671875 | 4 | def read_file():
words = dict()
path ='words.txt'
with open(path) as fp:
line=fp.readline()
while line:
line=line[:-1] # per eliminar l'ultim caracter que hi ha a la linia (salt de linia)
charNum = len(line)
if charNum not in words.keys():
... |
ac8752c09623ef59a11f5cdf828e6c7057fd77a7 | andrewrm98/Connect4-AI | /Homework1/ex1.py | 2,295 | 3.640625 | 4 | class ConnectFour:
def __init__(self, board, w, h):
"""Class constructor"""
# Board data
self.board = board
# Board width
self.w = w
# Board height
self.h = h
def isLineAt(self, x, y, dx, dy):
"""Return True if a line of identical tokens exists s... |
de45b8a6a5622a3f0e7a3f7d70f3ed984aba693c | saeidalidadi/python-course | /projects/word-game/table_view.py | 534 | 3.765625 | 4 | import tkinter as tk
def drawTable(window, letters_sequence):
"""Create an side*side grids with letters.
Args:
window (TK): an instance of tkinter window
Returns:
None
"""
side_len = len(letters_sequence)
for row in range(side_len):
for col in range(side_len):
letter_container = tk.Frame... |
06122d96ac425780e7a8e9c2e6eda02e4731d7ad | vectominist/ZJ-Solutions-in-Python | /Basic/a248.py | 665 | 3.609375 | 4 | import sys
# Big Number Division with Precision N
def fast_pow(x, n):
res = 1
while n > 0:
if n & 1:
res *= x
x = x ** 2
n >>= 1
return res
def digits(x):
res = 0
while x > 0:
res += 1
x //= 10
return res
for s in sys.stdin:
num = s.spli... |
58da74e4bb2280845041a085808ba214525fc7c4 | vectominist/ZJ-Solutions-in-Python | /Other/c908.py | 1,752 | 3.640625 | 4 | import sys
import math
EPS = 1e-9
def ABS(x):
if x > 0:
return x
else:
return -x
for s in sys.stdin:
num = s.split()
N = int(num[0])
for i in range(N):
s = sys.stdin.readline()
num = s.split()
x1 = float(num[0])
y1 = float(num[1])
R1 = float(num[2])
x2 = float(num[3])
y2 = float(num[4])
R2... |
49ac65b2f89da5ca8a0bae46592c1fb45eeb4da6 | lydiacupery/leet-code | /add-one-row-to-tree/python/solution.py | 1,377 | 3.6875 | 4 | from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
toReturn = ''
stack = [self]
while(len(stack) > 0):
curr = stack.po... |
c3b48b91fdaea9a19a2ae641fef982b5fcf19eec | xleon/CursoCiudadRealPython | /7_listas.py | 544 | 4.4375 | 4 | """
Ejemplos para trabajar con listas
"""
LIST = [1, 2, 3, 4, 5, 'seis', 'otra cosa']
print(LIST)
print(LIST[0])
print(LIST[4])
print(LIST[2:5])
print(LIST[:3])
print(LIST[2:])
SIZE = len(LIST)
print('tamaño de la lista:', SIZE)
del LIST[2]
print(LIST)
LIST[2] = 'TRES'
print(LIST)
# concatenar dos listas
LIST += ... |
795b38a4447f17041c48356e241316673a205584 | xleon/CursoCiudadRealPython | /16_herencia.py | 891 | 4.375 | 4 | """ Herencia de clases """
class Vehicle:
def __init__(self):
self.wheels = 0
self.name = self.__class__.__name__
print('Constructor de', self.name)
def move(self):
return 'moving'
class Car(Vehicle):
def __init__(self):
super().__init__()
self.wheels = 4
... |
47e46f8192bf96af5cfa1a09ec8ecfb05d917bf2 | jffry7/code-you-own-quiz | /test-code/quiz3_manipulation.py | 258 | 3.59375 | 4 | #!/usr/bin/python
# coding=utf-8
s = 'test'
print ('a' + s)[1:] # a+'string' then prints 1-end. it exclude a
print s[0] + s[1:] # will not work if s=''
print s + '' # it adds null ''
print s[0:] # it prints from first char and doesnt cause error for ''
|
5247d921121ab3d353329cf63c494246c9c4c562 | jffry7/code-you-own-quiz | /code-your-own-quiz.py | 9,721 | 3.8125 | 4 | #!/usr/bin/python
# coding=utf-8
"""This is Udacity Code your own quiz project."""
# multiple level of quiz difficulty
# 2 subject quiz. Unable to increase at this time
# User decides how many wrong guesses before they lose
# Quiz type: Fill in the blanks
# Quiz level: 1 ~ 4 with 5 question in each level
import random... |
8daeb028befa4a5f2620bd7a3551e22013454461 | fengyeye96/py24_api_test_project | /common/handle_request.py | 1,766 | 3.515625 | 4 | """"
封装的目的:
封装的需求:
发送post请求,发送get请求,发送patch请求,
代码中如何做到不同请求方式的接口去发送不同的请求加判断
"""
import requests
class HandleRequest:
def send(self,url,method,params=None,data= None,json = None,headers = None):
# 将请求的方法转换为小写
method = method.lower()
if method =="post":
return req... |
5fe9a247540c1e4832eb6fd9d5c65645782ff8e6 | ryosuke071111/MachineLearningMath | /test.py | 292 | 3.734375 | 4 | import numpy as np
import matplotlib.pyplot as plt
# f(x) = (x-1)**2
# 今 x=2,y=1
x = 3
def f(x):
return ((x-2)**2)
while f(x) > 0.1:
current_x = x -0.2 *((2 * x) - 4)
x = current_x
print(f(x))
log = "誤差が最も小さくなる数値は{0}です".format(x)
print(log)
|
87930655288cabb07e7792ba99f23d11f831b067 | diwas405/Diwas-Thapa | /Divisors of natural number.py | 971 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 11:54:39 2020
@author: Diwas
"""
# find all the divisors for a natural number between 2 and 9
#==============================================
# modules
#==============================================
import numpy as np
import matplotlib.pyplot as p... |
d00d956fce5d69ed51f00cf5ee5c027eace7d0d3 | nozberkaryaindonesia/UMTS-Multiplexing | /OVSFTree.py | 1,222 | 3.515625 | 4 | import math
numberOfMobile=512
class Node:
def __init__(self, val):
self.l = None
self.r = None
self.v = val
self.used=False
class Tree:
def __init__(self):
self.root = None
self.root=Node(1)
thislevel = [self.root]
for i in range(0,math.ceil(math... |
3b291b7d6a83ea992612d3f1eb94d21dafb8b20a | jazheng1/switch-config-tool | /config_generator/port_reconfig.py | 897 | 3.78125 | 4 | # This program is designed to modify an existing switch port using designated templates of config.
# It first asks for a switch name to connect to, then a port you want to modify, along with user/pass for the switch.
# Then it displays the current config of the port and asks what template you want to use to modify it... |
fb8432000144909ff1f73a6bf5d4b401f78c15fe | JoakimBe/pycrashcourse | /Part1/conditionals.py | 606 | 3.84375 | 4 | myAge = 20
yourAge = 101
counter = 0
isActive = False
if myAge > yourAge:
print("You are older then me!")
elif myAge < yourAge and yourAge > 100:
print("Wow! You are really old!")
else:
print("I am older then you!")
# if isActive:
# print("isActive == "+str(isActive))
# else:
# print("isActive == ... |
608fa741d77efdcfc3a7e35ec7461262dafdb78f | JoakimBe/pycrashcourse | /Part1/functions_example.py | 618 | 3.6875 | 4 | import decimal
vat = 0.25
products = [
{'name': 'klet', 'price': 100},
{'name': 'klut', 'price': 125.5},
{'name': 'klat', 'price': 150}
]
def calc_price_incl_vat(price, vat):
price_sum = price+(price*vat)
return float(price_sum)
for product in products:
priceInclVat = decimal.Decimal(calc_pr... |
66ac7292e98626dfd4722b1644e8b5cb7e4ec8f9 | Mostafa-At-GitHub/Design_of_Computer_Programs | /Week3/decorated_tools.py | 2,061 | 3.625 | 4 | from functools import update_wrapper
def decorator(d):
"""Make function d a decorator: d wraps a function fn."""
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
# def decorator(d): # alternative definition
# return lambda fn: update_wrapper(d(fn), f... |
756807939ce427d376446b51d12d229acc3099cc | rajunrosco/PythonExperiments | /CollectionFunctions/CollectionFunctions.py | 2,174 | 4.125 | 4 | import os
import sys
from functools import reduce
def FilterTest():
keylist = ["a","a|ps4","b","b|ps4","b|win64","c","c|win64"]
# filter list with lambda function that returns all strings that contain "ps4"
# filter() takes a function evaluates to "true", items that you want in the list
# in the case ... |
2ba5d20643e4ed718f00c66292c4d441723ba253 | jaminthorns/grammar-parser | /grammar-parser/ProductionRule.py | 754 | 3.625 | 4 | class ProductionRule():
"""Represents a production rule in a context-free grammar."""
def __init__(self, LHS, RHS):
# Nonterminal representing the left-hand side of this production rule
self.LHS = LHS
# List of Symbols that represent the right-hand side of this rule
self.RHS = RHS
# Boolean indicating whe... |
200820d980c64745b46a3af62bcbddeaf7ed4b05 | VictorASF/Python | /Exercicio C7.py | 271 | 3.796875 | 4 | print("-"*10 + "Pitando" + "-"*10)
a = float(input("Insira a altura da parede: "))
l = float(input("Insira a largura da parede: "))
print("Altura: {:.2f} - Largura: {:.2f} - Area: {:.2f}".format(a, l, a*l))
print("Sera preciso {:.2f} Litros de tinta".format((a*l)/3)) |
5933a1096fd418b92f01e96b10b2df7d7efa391f | VictorASF/Python | /exercicio I7.py | 296 | 3.9375 | 4 | from datetime import datetime
now = datetime.now()
maior = 0
menor = 0
for a in range(1, 6):
n1 = int(input('Ano de nascimento: '))
if now.year - n1 >= 18:
maior += 1
else:
menor += 1
print('''Maior que 18: {}
Menores que 18: {}'''.format(maior, menor))
|
a222e1f1f1eb767e2b93923d2e8957b72e06734b | VictorASF/Python | /exercicio K4.py | 400 | 3.84375 | 4 | l1 = []
while True:
a = str(input('Numero: '))
a = a.strip()
if a != '':
if a.isnumeric:
l1.append(a)
else:
break
else:
break
for i in range(len(l1)):
print(l1[i], end=' ')
l1.sort()
print('\n')
for i in range(len(l1)):
print(l1[i],... |
b6c9d5a633a691dc7a67b363dacedec70964ad72 | VictorASF/Python | /exercicio D4.py | 471 | 3.5 | 4 | '''
Exercicio Python 4D Curso udemy
Victor A. de Souza Fonseca
'''
import pygame
#Pygame sempre deve ser iniciado antes de qualquer coisa
pygame.init()
pygame.display.set_mode((200,100))
#Buscando a musica na pasta
pygame.mixer.music.load('musica.mp3')
#A musica tem que dar play
pygame.mixer.music.play()... |
896bd467c3d4d5ee4f1e2faa4042b21ae6e965ee | VictorASF/Python | /exercicio R1.py | 2,929 | 3.890625 | 4 | import math
def soma(x, y):
som = x + y
print('\n{:^15}'.format('SOMA'))
print('{} + {} = {}\n'.format(x, y, som))
def substracao(x, y):
sub = x - y
print('\n{:^15}'.format('SUBTRAÇÃO'))
print('{} - {} = {}\n'.format(x, y, sub))
def divisao (x, y):
try:
div = x / y... |
937aa03df780d07096427426bc2925236abd2dce | VictorASF/Python | /exercicio J4.py | 246 | 3.921875 | 4 | num = 0
soma = 0
quant = 0
while num != 999:
num = int(input('Insira o numero: '))
if num != 999:
soma += num
quant += 1
print('A soma total foi {} e a quantidade de numeros digitados foram {}'.format(soma, quant)) |
e43f9e5742dd84b6dc037e58ae189c1ce4a33938 | VictorASF/Python | /exercicio I4.py | 124 | 3.9375 | 4 | print('Tabuada')
n1 = int(input('Insira o numero:'))
for a in range(1,11):
print('{} X {} = {}'.format(n1,a, n1*a)) |
7ad0cd0904667a20ca8ab94edd8ba3c9d1e098ca | seungchulee/baekjoon | /16000-16999/16114.py | 315 | 3.53125 | 4 | x, n = map(int, input().split())
if n == 1:
if x < 0:
print("INFINITE")
else:
print("0")
elif n == 0:
if x > 0:
print("INFINITE")
else:
print("0")
elif n % 2 == 1:
print("ERROR")
else:
if x > 0:
print("%d"%((x-1)/(n/2)))
else:
print("0")
|
d23b1d9332426377201ebbf15936ff9b71c56fdc | seungchulee/baekjoon | /17000-17999/17214.py | 1,269 | 3.5 | 4 | import operator
string = input()
if string[0] != '-':
string = '+' + string
lists = []
data=""
for i in range(len(string)):
if i==len(string)-1:
data+=string[i]
lists.append(data)
elif string[i+1]=='-' or string[i+1]=='+':
data+=string[i]
lists.append(data)
data=""
... |
9a13a3c0af0d6433b37c955678b8e0342e4d74a9 | seungchulee/baekjoon | /swea/1256.py | 276 | 3.5625 | 4 | n = int(input())
for i in range(n):
k = int(input())
string = input()
lis = []
for j in range(len(string)):
lis.append(string[j:])
lis.sort()
if k > len(lis):
print("#%d none"%(i+1))
else:
print("#%d %s"%(i+1,lis[k-1]))
|
2f923e79a27dcdc239f15d21d57c25eb75eb286c | clintko/LearnCode_Python | /HW_enya/TocHW3.py | 753 | 4.0625 | 4 | """
Homework 3
"""
import sys
import operator
#searchStr = sys.argv[1]
searchStr = "NowNew#abc,2014#abc"
#fileName = sys.argv[2]
fileName = 'HW3_Data.txt'
terms = dict()
#print(searchStr, fileName)
for term in searchStr.split(","):
terms[term] = 0
# read in file and search for each pair of terms
with open(fileN... |
fc3f5a31b96031708dc7c481a216cabdbc00e4ec | mashizzle/textblackjack | /bj.py | 3,506 | 3.828125 | 4 | import random
suit = ['HEARTS', 'DIAMONDS', 'CLUBS', 'SPADES']
rank = {'ACE': 11, 'TWO': 2, 'THREE': 3, 'FOUR': 4, 'FIVE': 5, 'SIX': 6, 'SEVEN': 7, 'EIGHT': 8, 'NINE': 9, 'TEN': 10, 'JACK': 10, 'QUEEN': 10, 'KING': 10}
# Represents the card class with the suit and type of card
class Card():
def __init__(self, suit,... |
8d6730d1c463a918871182e09a8b5fa3ac0b5f76 | Softhouse/gomoku_python | /solutions/iteration_1/model.py | 2,766 | 3.578125 | 4 | from events import *
UNKNOWN = ' '
PLAYER_BLACK = 'b'
PLAYER_RED = 'r'
class GameEngine(object):
"""
Tracks the game state.
(solutions/iteration_1)
"""
def __init__(self, evManager, height, width):
# Create a grid of given height (nr of rows) and width (nr of columns)
self.width ... |
33eeb3d1bb47459a32eda95b80cf7ad6a5cd1cbe | Botany-Downs-Secondary-College/password_manager-ethan-vanwijk | /pass manager.py | 1,451 | 4.09375 | 4 | #defines vars
chosen = 0
name = ""
age = 0
pas = []
users = []
pass_inpt = ""
i = 0
user = ""
usepas = []
brec = "____________________________ \n"
#intro
print("--welcome to password manager--")
#menu
def menu(name, age):
print("welcome {}" .format(name))
if age < 13:
prin... |
a5620ca9a95af19ba0f43bc50b95411480912700 | Joldiazch/AirBnB_clone_v2 | /web_flask/4-number_route.py | 931 | 3.5625 | 4 | #!/usr/bin/python3
""" that starts a Flask web application """
# import flask
from flask import Flask
app = Flask(__name__)
# strict_slashes allow that this route work with /my_route and /my_route/
@app.route('/', strict_slashes=False)
def root():
""" return Hello HBNB """
return 'Hello HBNB!'
@app.route(... |
81e3a6f303bd3960dbbc50723479d604204140b3 | LangtechKHMin/PythonASTParser | /example.py | 281 | 3.6875 | 4 | def mysum(a, b):
return a+b
A = 5
B = 9
C = 10
if C == 10:
print("True")
C = A
for i in range(C):
print(i)
elif B == 10:
print("True")
C = B
for i in range(C):
print(i)
else:
print(mysum(A, B))
print("False")
|
189db2044712ae0ec07d4a69cd11fa47ea5b7cb3 | mpawlak2/tempearly | /tempearly/conditions.py | 1,582 | 3.859375 | 4 | """
This module provides functionality to implement if operator in string templates.
An 'if' operator can be used as a block operator within block tags, e.g.,
<% if a == b %>
...
<% endif %>
Every 'if' operator has to be of that form:
- opening and closing block tags
... |
58c5c976749e83c798b7e7efed071ecf00f9aef3 | ekodavidkurnia/Python-Assignment | /Practice/M/Modules/test5.py | 320 | 4.03125 | 4 | def addition(a,b):
"""
this function will return addition of
two variable
"""
return a+b
def mul(a,b):
"""
this function will return multiplication of
two variable
"""
return a*b
def power(a,b):
"""
this function will return power of
variable
"""
return a**b |
7c360c14c630c0d2214d61b9e6371d6098a167d5 | jcockbain/python-algorithms | /dynamic_programming/climb_stairs.py | 519 | 3.78125 | 4 | # brute force recursion
def climb1(n):
if n < 3:
return n
return climb1(n - 1) + climb1(n - 2)
# top-down
def climb2(n):
cache = {
0: 0,
1: 1,
2: 2,
}
for i in range(3, n + 1):
cache[i] = cache[i - 1] + cache[i - 2]
return cache[n]
# bottom-up
de... |
30122874892256ca6feda9aeda11383728631715 | jcockbain/python-algorithms | /trie/trie.py | 1,006 | 3.90625 | 4 | from collections import defaultdict
class TrieNode():
def __init__(self):
self.children = defaultdict()
self.terminating = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
cur = self.root
for i in range(len(word)):... |
89a78dd2c0c3144cf897bad8a7291d61ce3d9ca2 | arunnagendran89/fractionalEquations | /fractionalOperand.py | 9,042 | 3.984375 | 4 | from exceptions import *
class FractionalOperand:
"""
Class to objectify fractional operand strings.
Parameterize the whole number, numerator and denominator of a fractional operand.
Format is <wholeNumber><underscore><numerator><forward slash><denominator>
valid examples:
3_1/4
-3_1/4
... |
0d0207a98ee6f9dcebbb680e318ca953b7f4be96 | B203110-2021/BPSM_Lecture17 | /exercise17.py | 7,002 | 3.53125 | 4 | #!/usr/bin/python3
import re
accessions = ['xkn59438','yhdck2','eihd39d9','chdsye847','hedle3455','xjhd53e','45da','de37dp']
# PROCESS list of accessions
for acc in accessions:
print(acc)
#All we need to do is to add the criteria as we loop through each of the accessions; we can add them one by one to check each... |
1f310441b94862edfb5ed9ff988173da5d4d42da | Laksara1996/CO322 | /Lab01/fib.py | 451 | 3.765625 | 4 | #!/usr/bin/python
import time
start = time.time()
def fib_r(x) :
if (x <= 2):
return 1
return fib_r(x-1) + fib_r(x-2)
def fib_i(x) :
a = 1
b = 1
fib = 1
i = 2
while i < x:
fib = a +b
a = b
b = fib
i+=1
return fib
x = 1
#print ("Fib... |
f7b07bb218eec4fc4a7d51436891b474d724517a | ngladkoff/2020P1 | /ambulancias.py | 4,053 | 3.546875 | 4 | # Ambulancias
MAXIMO = 5
VALOR_NULO_VECTORES_NUMERICOS= 0
INDICE_NO_ENCONTRADO = -1
class ErrorValorMinimo(Exception):
pass
class ErrorValorMaximo(Exception):
pass
class ErrorDia10(Exception):
pass
def ValidarNoDia10(ingreso_usuario):
if ingreso_usuario * 5 == 50:
raise ErrorDia10
def ingr... |
27d503df05c34a8b75051e52c2525477c7228c62 | ngladkoff/2020P1 | /funciones.py | 288 | 3.625 | 4 | # Modulo Funciones
import funciones2
def suma(a,b):
return a + b
def contar_hasta():
hasta = int(input("Hasta que nro desea contar? "))
funciones2.contar(hasta)
def iniciar():
print("Procedimiento principal de funciones")
if __name__ == '__main__':
iniciar()
|
d5091ae176babec50680d2fe3be96d6062f6cb8c | ngladkoff/2020P1 | /tuplas.py | 1,153 | 4.0625 | 4 | from dataclasses import dataclass
@dataclass
class Alumno:
nombre: str
apellido: str
edad: int
# tuplas
lista = [9,8,7]
tupla1 = (1,2,3)
tupla2 = 1, 2, 3
print(tupla1[2])
# tupla1.append(4) -> error
def mi_funcion():
return (2,3,4,5)
a = mi_funcion()
print(a)
a,b,c,d = mi_funcion()
print(a)
print... |
fc033748c4779fc16e745ca3992f7955857ef150 | ngladkoff/2020P1 | /funciones2.py | 154 | 3.71875 | 4 | # Funciones 2
def contar(hasta):
for i in range(hasta):
print(i)
'''
i = 0
while i < hasta:
print(i)
i = i + 1
''' |
c8667f9e98ea8d037dd4c01d650334dc0cfb872d | RossBerry/cs-3210-projects | /data_class.py | 399 | 4.09375 | 4 | from dataclasses import dataclass
@dataclass
class InventoryItem:
'''Class for keeping track of an item in inventory.'''
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
@dataclass
class C:
a: int ... |
5f7d2f7c98ee18158f6ef24a3064ebed40f3c7c3 | LucasHuls/OpdrachtenGroep5 | /Jesse Overveld/Python/EINDPROJECT/real/py4.py | 6,516 | 4.0625 | 4 | __author__ = 'Les Pounder'
#The lines below import modules of code into our game, in particular these import time functions to allow us to pause and stop the game, and random provides a method of choosing random numbers or characters.
from time import *
from random import *
import os,sys
#This is a function, we use i... |
2fcf7ead07ca6265dede67700cc8c78922a3be13 | LucasHuls/OpdrachtenGroep5 | /Bram van Nek/html/tests/pythonproject.py | 1,186 | 3.703125 | 4 | import turtle
wn= turtle.Screen()
wn.title("dodge ball")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(1)
# paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=3, stretch_len=1)
paddle_a.penup()
paddle_a.goto(0, -250)
#... |
6da5746d2e06b64d3ddd533c2f15084104be3522 | LucasHuls/OpdrachtenGroep5 | /Bram van Nek/html/tests/toetspythonopdracht1.py | 248 | 3.953125 | 4 | x = input("geef aantal doelpunten team A:")
y = input("geef aantal doelpunten team B:")
if x == y:
print("het is gelijkspel allebij 1 punt")
elif x > y:
print("team A heeft 3 punten")
elif x < y:
print("team B heeft 3 punten")
input()
|
f2a5dc0eb57b10d0ccc0acc17c6b5bf3b060c585 | anuragdogra2192/Data_structures_with_python3 | /arrays/TwoSumII_unique_pairs.py | 1,839 | 4.21875 | 4 | '''
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number.
Let these two numbers be numbers[index1] and numbers[index2]
where 1 <= first < second <= numbers.length.
Return the indices of the two numbers,
... |
cbccd61d0a69bbcf0337f3149bba0c0aa4c719e4 | anuragdogra2192/Data_structures_with_python3 | /SlidingWindows/MaxConsecutiveOnes.py | 1,794 | 3.8125 | 4 | """
Given a binary array nums,
return the maximum number
of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
... |
c529568c0c22bc9cbee2c64265c8c32147c310e8 | anuragdogra2192/Data_structures_with_python3 | /arrays/ReturnAnArrayOfPrimes/Return_array_of_primes.py | 870 | 4.34375 | 4 | """
Write a program that takes an integer argument and
returns all the primes between 1 and that integer.
For example, if the input is 18, you should return [2, 3, 5, 7, 11, 13, 17]
Hint: Exclude the multiples of primes.
"""
#Given n, return all primes up to and including n.
def generate_primes(n):
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.