blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
baed6319f4390e3d1a5f91a531f4ecba47f87832 | chrysmur/Python-DS-and-Algorithms | /reversing_strings.py | 132 | 4.21875 | 4 | def reverseString(string):
'''Returns a string in reverse order'''
print(string[::-1]) #O(n)
reverseString('hi i am chrys') |
8c958cc6fc0a70f123a73a919f313a7615801d1b | yothebob/file-counter | /count-files/count_files.py | 1,316 | 3.6875 | 4 | import os
from os import path
'''
A small utility to count all the files in a given master folder (main_dir)
- folders donot get added to count
to use (in terminal locally) -
1. go to count_files folder (cd ~/path/to/count_files)
2. type python3 -c "from count_files import main;main('/home/user/path/to/disire... |
a914d165c1439bcfe25e45971e3568c4d3705a1e | brijeshsahu/hello | /test.py | 533 | 3.625 | 4 |
#loopstr = "return List.of(new rList("Brijesh1"), new rList("Brijesh2"), new rList("Brijesh3"), new rList("Brijesh4"));"
# loopstr = "return List.of(new rList("Brijesh1"), new rList("Brijesh2")
# appendstr = ", new rList(" + '"' + "Brijesh" + i +'")'
def stringapp ():
mainstring = "return List.of("
for i in ... |
211505c790b228d865de8893cae1ef83a341ba6f | MechatronixX/TrailerReverse | /helperfunctions/constant_rotation_code.py | 1,533 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
#############################################################################################################################
# constant_rotation(constant,angle) #
# ... |
fbc098c8a118510d4ca09b7fd628de6b5d69ad2e | 4nnina/Python_Project | /stellaQuad.py | 817 | 3.578125 | 4 | import turtle
def spezzataQuad(t, lato, livello):
if livello == 0:
t.forward(lato)
else:
spezzataQuad(t, lato / 3, livello - 1)
t.right(90)
spezzataQuad(t, lato / 3, livello - 1)
t.left(90)
spezzataQuad(t, lato / 3, livello - 1)
t.left(90)
... |
28e9426e7001c6e96c86121aff5b28315bfce24f | tcsfremont/curriculum | /python/pygame/maze/03_maze.py | 2,899 | 3.515625 | 4 | from pygame.locals import *
import pygame, sys
import maze_generator
WIDTH = 800
HEIGHT = 800
BLACK = (0, 0, 0)
RED = (255, 20, 0)
YELLOW = (255, 255, 0)
GRAY = (100, 100, 100)
GREEN = (0, 200, 0)
speed = 3
px = 100
py = 100
status = "new_game"
direction = ""
tile_x = 0
tile_y = 0
pygame.init()
screen = pygame.dis... |
d146d5541c713488ed3e3cc0497baea68cf368ff | tcsfremont/curriculum | /python/pygame/breaking_blocks/02_move_ball.py | 1,464 | 4.15625 | 4 | """ Base window for breakout game using pygame."""
import pygame
WHITE = (255, 255, 255)
BALL_RADIUS = 8
BALL_DIAMETER = BALL_RADIUS * 2
# Add velocity component as a list with X and Y values
ball_velocity = [5, -5]
def move_ball(ball):
"""Change the location of the ball using velocity and direction."""
ba... |
52dca49503204649407f1e5a6068ff4ff2876dd2 | tcsfremont/curriculum | /python/tkinter/example-game/main.py | 4,036 | 3.578125 | 4 | """
JumpyGuy: An Example Tkinter Canvas Game
Requirements:
Keyboard input
Game loop
Gravity
Splash Screen, play button
Score
Save data to text file
"""
import tkinter as tk
import GameObjects
from Vector import Vector
from random import randint
class Game(tk.Canvas):
def __init__(self, m... |
7190d1fc0e3277184a8b5852bb46d6d572305d3c | hazinudin/hacktiv8_043_HA | /pertemuan_2/exercise_1.py | 213 | 3.828125 | 4 | a = input("Masukkan angkan: ")
#a = int(a)
print (type(a))
print("Nilai a: {0}".format(a))
remainder = a%2
if remainder > 0:
print("Nilai a adalah bilangan ganjil")
else:
print("Nilai a adalah bilangan genap") |
56cb3dc1b9ef863246aa518d8a83b90b3f0c2d9d | trcooke/57-exercises-python | /src/exercises/Ex07_area_of_a_rectangular_room/rectangular_room.py | 830 | 4.125 | 4 | class RectangularRoom:
SQUARE_FEET_TO_SQUARE_METER_CONVERSION = 0.09290304
lengthFeet = 0.0
widthFeet = 0.0
def __init__(self, length, width):
self.lengthFeet = length
self.widthFeet = width
def areaFeet(self):
return self.lengthFeet * self.widthFeet
def areaMeters(sel... |
935e8136b2da504ce9d9695a2c6cc9228b43951f | gchh/python | /code/8-4.py | 2,514 | 3.671875 | 4 | class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name: %s)'%self.name
__repr__=__str__
print(Student('Michael'))
s=Student('Michael')
print(s)
class Fib(object):
def __init__(self):
self.a,self.b=0,1
def __iter__(se... |
750f8c4d04bdd56ed851412e6b4b478ff9b4a0c3 | gchh/python | /code/7-5.py | 1,295 | 4.1875 | 4 | class Student(object):
def __init__(self,name):
self.name=name
s=Student('Bob')
s.score=90
print(s.__dict__)
del s.score
print(s.__dict__)
class Student1(object):
name ='Student'
p=Student1()
print(p.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
print(Student1.name) #打印类的name属性
p.name='Mich... |
76c075036bdd0b243d4a563537a5f3b8082bdc3d | Davidprogramming1986/TicTacToe-Python | /test.py | 386 | 3.875 | 4 | board = [0, 1, 'O', 3, 'X', 5, 6, 7, 'X']
free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board))
free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board))
while True:
print(free_spaces)
player_choice = input('Select your square > ')
player_choice = int(player_choice)
print(type(p... |
9709138c05b3249535afa63d5ef56ef62efa3bb1 | letstinker/microstat | /tempreader.py | 1,878 | 3.515625 | 4 | import time
import dht
from machine import Pin
class Temperature():
current_temp = 0 # Store in Celsius
system = 'celsius'
def __init__(self, system='celsius'):
self.system = system
def temp(self):
if self.system == 'fahrenheit':
return self.fahrenheit()
return se... |
d25f3b137fd5ca0bbd8b0d9dcffbaa864400e2c6 | pinkrespect/HappyHappyAlgorithm | /MergeSort.py | 248 | 3.578125 | 4 | def split(List):
index_no = len(List)
half = int(index_no/2)
print(half)
left_List = List[0:half]
right_List = List[half:index_no]
return left_List, right_List
split(split([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]))
|
83d9d49419a87e961abf560f8a64aa0f9b32f5eb | pinkrespect/HappyHappyAlgorithm | /complete/1914.py | 271 | 3.9375 | 4 | #Hanoi tower
def hanoi(n, from_pos, to_pos, aux_pos):
if n == 1:
print(from_pos, "->", to_pos)
return
hanoi(n - 1, from_pos, aux_pos, to_pos)
print(from_pos, "->", to_pos)
hanoi(n - 1, aux_pos, to_pos, from_pos)
hanoi(3, 'A', 'B', 'C')
|
2cd0617ee9947584a86478f998eb1fcd81aeef71 | pinkrespect/HappyHappyAlgorithm | /quickSort_NoCheatSheet.py | 862 | 3.984375 | 4 | # swap, partitioning, quickSort(recursion)
# low index, high index, store index, pivot value, pivot index
from random import randint
def swap(array, i, j):
_ = array[i]
array[i] = array[j]
array[j] = _
def partitioning(array, low, high):
pivotIndex = randint(low, high)
pivotValue = array[pivotInd... |
6289134ecc6f923b1e656dedb627a4f0ce45095d | kqyang0000/python3-fishc | /012/array.py | 286 | 3.703125 | 4 | list1 = [123, 456]
list2 = [124, 789]
print(list1 > list2)
print(list1 + list2)
list1 *= 5
print(list1)
print(123 in list1)
dir(list1)
print(list1.count(123))
print(list1.index(123))
print(list1.reverse())
print(list1)
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)
|
93b625394363477e1ce6f8c86ac8955f9b6f08a3 | aviv86/RavenDB-Python-Client | /pyravendb/tools/pkcs7.py | 891 | 3.71875 | 4 | class PKCS7Encoder(object):
"""
Technique for padding a string as defined in RFC 2315, section 10.3,
note #2
"""
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, block_size=16):
if block_size < 2 or block_size > 255:
... |
10be402e437bc70ed369d54b6eb555aeb9dea225 | CassandraTalbot32/round-up-using-classes | /TM112_18D_TMA02_Q5_ZY659778.py.py | 1,695 | 3.953125 | 4 | # TM112 18D TMA02 Question 5
def float_rounded_up(float):
"""Round up a float to the nearest integer"""
integer = int(float)
if int(float) != float:
integer = int(float + 1)
return integer
# Add your code here
class floor():
width = 100
length = 100
height = 10
... |
82f10b38d8681d1de310295eb301af18b137d631 | federicorenda/ctr-design-and-path-plan | /ctrdapp/optimize/optimizer.py | 607 | 3.5 | 4 | from abc import ABC, abstractmethod
class Optimizer(ABC):
def __init__(self, heuristic_factory, collision_checker, initial_guess, configuration):
self.tube_num = configuration.get("tube_number")
self.precision = configuration.get("optimizer_precision")
self.configuration = configuration
... |
3f639c6809001fef89b2d54722bd24f1ee0edc20 | Jovanez/flask | /testeBanco.py | 256 | 3.53125 | 4 | from banco import Cinema,Filme, Programacao,db
db.connect()
cine = Cinema.select(Cinema).where((Programacao.filme == 3)& (Programacao.cinema == Cinema.codigo)).join(Programacao).join(Filme).group_by(Cinema.codigo)
for c in cine:
print(c.nome +" \n") |
71400d34dacc010d4351186485e9266fda5e7513 | kosvicz/swaroop | /user_input.py | 338 | 4.15625 | 4 | #!/usr/bin/env python3
#--*-- conding: utf-8 --*--
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input('Введите текск: ')
if(is_palindrome(something)):
print('Да, это палиндром')
else:
print('Нет, это не палиндром')
|
aac5371cae30991aa57698c725d2f9dbd07658aa | mccabedarren/python321 | /p5.p5.py | 943 | 3.875 | 4 | Location = input('Enter your Location:')
if Location== 'Dublin':
print ('You entered Dublin. Dublin is in Leinster')
elif Location == 'Belfast':
print ('You entered Belfast. Belfast is in Ulster')
elif Location == 'Cork':
print ('You entered Cork. Cork is in Munster')
elif Location == 'Limerick':
print... |
9ba7fb40eacf3ebca5c5fb9a5ac9e823f1ef9df0 | mccabedarren/python321 | /p12.p3.py | 1,098 | 4.46875 | 4 | #Define function "sqroot" (Function to find the square root of input float)
#"Sqroot" calculates the square root using a while loop
#"Sqroot" gives the number of guesses taken to calculate square root
#The program takes input of a float
#if positive the program calls the function "sqroot"
#if negative the program... |
dc5b545562df84e36ce8696cdaa33e0239a37001 | mccabedarren/python321 | /p13.p2.py | 431 | 4.46875 | 4 | #Program to print out the largest of two user-entered numbers
#Uses function "max" in a print statement
def max(a,b):
if a>b:
return a
else:
return b
#prompt the user for two floating-point numbers:
number_1 = float(input("Enter a number: "))
number_2 = float(input("Enter another number: "))
... |
58755bd3db06ed522fc54b552b87fa769719e0d1 | mccabedarren/python321 | /p6.p1.py | 232 | 4.0625 | 4 | #prompt user for two separate ints (x,y)
# if x +y > 100 , print "that is a big number!"
#Exit program
x = int(input('input an int:'))
y = int(input('input another int:'))
if x + y > 100:
print('That is a big number!')
exit()
|
31a449aab5fcf84187fc5cb62e5b26ba65e030a0 | Prometeo/python-code-snippets | /palindrome.py | 171 | 4.15625 | 4 | def palindrome(a):
""" This method checks whether a given string is a palindrome """
return a == a[::-1]
if __name__ == '__main__':
print(palindrome('mom'))
|
f427be78dd85ca42496722c2ba110c1db6a5158e | Prometeo/python-code-snippets | /most_common.py | 249 | 4.0625 | 4 | def most_commmon(lst):
""" This method returns the most frequent element that appears in a list """
return max(set(lst), key=lst.count)
if __name__ == '__main__':
numbers = [1, 2, 1, 2, 3, 2, 1, 4, 2]
print(most_commmon(numbers))
|
92a3125c830392873920de61ef52c78d048d1290 | xiaocuizi/python3 | /py_learn/com/gemini/pic/createpic.py | 782 | 3.5 | 4 | from PIL import Image, ImageDraw, ImageFont
import random as random
# 生成随机的字母
def rndChar():
return chr(random.randint(65, 90))
# print(rndChar())
# 随机颜色
def rndColor1():
return (random.randint(64, 256), random.randint(64, 256), random.randint(64, 256))
def rndColor2():
return (random.randint(32, 127)... |
653a43a7ccdb8ee230cc46c107b4ac2d21b040d0 | xiaocuizi/python3 | /py_learn/com/gemini/object/person.py | 473 | 3.5625 | 4 | class person:
def cry(self):
print("大哭")
def __init__(self): ## 构造方法(专有方法) 当实例化对象的时候,就会调用
self.cry()
p1 = person()
class person2:
def __init__(self, sex, name):
self.sex = sex ## 给person实例对象顶一个实例变量sex,然后赋值为sex
self.name = name
def speck(self):
print(self.na... |
2008c87c3adaffbfa0467a86a44b41a5b09c0031 | xiaocuizi/python3 | /py_learn/com/gemini/scope/__init__.py | 381 | 3.796875 | 4 | def fun():
a = 3 ## 闭包外的函数变量
print(a)
def inside():
b = 4 ## 局部变量
x = int(10) ## 内置作用域,通过系统函数创建的数据集、、
y = 2 ## 全局变量
a=4
def fun():
global a ### 声明加权限 ,就可以修改,否则引用函数外的变量是只读的,不得修改
a=5
print(a)
fun()
print(a) |
579a158f6690c0ef213558d27d74cd77263b37ee | xiaocuizi/python3 | /py_learn/com/gemini/list.py | 369 | 3.796875 | 4 | print("---------------------")
ls=[5,True,"34343"]
print(ls)
ls.append("找")
print(ls)
ls2=[1,2,3]
ls.extend(ls2)
print(ls)
ls.insert(3,"张龙")
print(ls)
del ls[1]
print(ls)
ls.pop()
print(ls)
ls.pop(4)
print(ls)
ls.remove("张龙")
print("---------------------")
ls2 = [1,25,7,4]
ls2.sort();
print(ls2)
ls2.reverse()
print(l... |
deebb2a59355871d9ea00a7502336c1c7e2dbe6f | jasonglassbrook/code-challenges | /leetcode/valid_palindrome.py | 4,005 | 3.953125 | 4 | #!python3
############################################################
class Solution:
def isPalindrome(self, s: str) -> bool:
return self.isPalindrome__pointers(s)
def isPalindrome__reverse_slice(self, s: str) -> bool:
# Handle trivial cases.
if len(s) < 2:
return Tru... |
bc4fe0b9663c18a0147f33c0399d9cb16a380d7f | jasonglassbrook/code-challenges | /leetcode/invert_binary_tree.py | 6,132 | 4.21875 | 4 | #!python3
############################################################
from typing import Union
from leetcode.tools.binary_tree import TreeNode
#-----------------------------------------------------------
class Solution:
MAIN = "invertTree"
def invertTree(self, root: TreeNode) -> TreeNode:
retu... |
6685ea3f7aa0d211ee99961d7f16cb291ba723ef | jasonglassbrook/code-challenges | /leetcode/best_time_to_buy_and_sell_stock.py | 3,599 | 4 | 4 | #!python3
############################################################
from typing import List
#-----------------------------------------------------------
class Solution:
MAIN = "maxProfit"
def maxProfit(self, prices: List[int]) -> int:
return self.maxProfit__tracking_buy_price(prices)
def... |
cd94720d183e0d8490662531dd369727db345c1a | jasonglassbrook/code-challenges | /leetcode/longest_palindromic_substring.py | 1,942 | 4.03125 | 4 | #!python3
class Solution:
def longestPalindrome(self, string: str) -> str:
result = ""
for i in range(len(string)):
# print("center:", i)
odd_palindrome = self.find_odd_palindrome_from_center(string, i)
# print("odd palindrome:", odd_palindrome)
... |
e0fc45ba2b2da28b629f3c6bf7ce6c85d4334ca4 | elizabethadventurer/Treasure-Seeker | /Mini Project 4 part 1.py | 1,575 | 4.28125 | 4 | # Treasure-Seeker
#Introduction
name = input("Before we get started, what's your name?")
print("Are you ready for an adventure", name, "?")
print("Let's jump right in then, shall we?")
answer = input("Where do you thnk we should start? The old bookstore, the deserted pool, or the abandoned farm?")
if answer == "the d... |
c9b8122e000cb0a4fa6c65088b67d082ea0a9c32 | nimit3/python-basics | /array.py | 3,278 | 4.0625 | 4 | no = [1, 2, 3, 4, 5]
# # [from:to] this sytanx will work here tooo
# print(no[0:3])
# print(no[2:]) # this will print everyting from 2nd index
# 2d arrays matrix
# matrix = [
# [1, 2, 3],
# [4, 5, 6]
# ]
# # we can store mutliple types of elements in list. same like JS
# arr=['fwqfq',12,122,1331,'fwqfwqf', ... |
0006ed639bdc78c81f70363c4148a9a69fa212f7 | civic/generic-anova | /check.py | 364 | 3.53125 | 4 | import sys
def calc(prev, current, target):
Kp = 20
Ki = 0.5
p = (target -current) * Kp
i = ((target-current) + (target-prev))*10/2*Ki
print("{:.3f}\tp={:.2f} i={:.2f} power={:d}".format(current, p, i, int(p+i)))
prev = float(sys.argv[1])
current = float(sys.argv[2])
target = float(sys... |
bbaf4883efe9a4a34487a6d9b1316cd1f54156ab | Bhanditz/ISBN-13-checksum-generator | /ISBN13.py | 548 | 4.03125 | 4 | code = input('Please enter the ISBN-13 number with or with \'-\'s: ')
codex = ''
for each in code:
if each is '-':
pass
else:
codex = codex + each
code = codex
code = code[::-1]
code_even = code[1::2]
code_odd = code[::2]
total = 0
for x in code_odd:
y = int(x)
total = total + (y * ... |
37fdff5b7a156971e0a016814b93fd2dc6770095 | kompiangg/math-operation-in-python | /modulus.py | 400 | 3.796875 | 4 | print("Perhatikan bentuk berikut")
print("-" * 19)
print("| a mod b = hasil |")
print("-" * 19)
a = int(input("Masukkan a : "))
b = int(input("Masukkan b : "))
if (a > 0 and b > 0) or (a < 0 and b < 0):
hasil = a - int(a/b) * b
elif (a == 0 and b >= 0):
hasil = 0
elif a > 0 and b == 0:
hasil = a
elif a < ... |
2f96931fad2b0596415a6308e5d479367245a56a | AfinFirnas/Muhammad-Firnas-Balisca-Putra_I0320063_Abyan_Tugas5 | /I0320063_soal2_tugas5.py | 845 | 3.84375 | 4 | # Program Grading Nilai
Nama = str(input('Masukkan Nama Anda : '))
Nilai = int(input('Masukkan Nilai Anda : '))
if Nilai < 60 :
print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah E')
elif 60 <= Nilai <= 64 :
print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah C')
elif 65 <= N... |
4987d647d883befa0e2787bc7006c0db4a49decd | vicentecm/URI_respostas | /1008.py | 216 | 3.5 | 4 | # URI 1008
numero_do_func = int(input())
numero_horas = int(input())
valor_hora = float(input())
horas_x_valor = numero_horas*valor_hora
print(f"NUMBER = {numero_do_func}")
print(f"SALARY = U$ {horas_x_valor:.2f}") |
a38d89434004dd34144ec1352c813dc335354db5 | HohlovIlya/math_modeling | /lab_1_pr_4.py | 138 | 3.71875 | 4 | a = [1, 5, 'Good', 'Bad']
b = [9, 'Blue', 'Red', 11]
print(a[1]+b[3])
print(a[2]+b[2])
print(a[0]*b[0])
print(a[1]**b[3])
print(a+b) |
c7dfc4469d6c380e96e010197bfc86ec473c3c48 | graememorgan/adventofcode | /day16.py | 637 | 3.734375 | 4 | from re import findall
match = {"children": 3, "cats": 7, "samoyeds": 2, "pomeranians": 3, "akitas": 0, "vizslas": 0, "goldfish": 5, "trees": 3, "cars": 2, "perfumes": 1}
sues = [{k: int(v) for k, v in findall("([a-z]+): ([0-9]+)", line)} for line in open("day16-input").read().splitlines()]
print [
reduce(
lam... |
7f661c828e0b1dff2eba26b0f14832f5c8f27267 | Gereaume/L2 | /math/TP2/Exercice1/Exercice1.py | 486 | 3.6875 | 4 | #!/usr/bin/python3
# coding: utf-8
# from __future__ import division
from random import *
import matplotlib.pyplot as plt
import numpy as np
N=int(input("Saisir le nombre de tirage : "))
l=np.array([0]*20)
for i in range(N):
S=0
for d in range(3):
S=S+randint(1,6)
l[S]=l[S]+1
print ("---")
for i in range... |
55ca7df15d0ec947e09b3c0390030ea750143a6c | zingpython/webinarPytho_101 | /five.py | 233 | 4.25 | 4 | def even_or_odd():
number = int(input("Enter number:"))
if number % 2 == 1:
print("{} is odd".format(number))
elif number % 2 == 0:
print("{} is even".format(number))
even_or_odd()
# "Dear Mr.{} {}".format("John","Murphy") |
ee27e088d0490f70ed7b5b4b00b8b19edd2aa762 | M-Faheem-Khan/Matrix-Encryption | /decrypt.py | 1,196 | 3.734375 | 4 | class create(object):
# convert to original array
def original_key(self, key, msg):
temp = []
for i in range(len(msg)):
temp.append(msg[i]/key[i])
return temp
# converts ascii values to string
class convert_from(object):
def string_to_int(self, array):
converted_... |
86ae639c1bcee8f1ef6274c4878fcd9aa3f41f99 | HolyCash/SelfP | /ex_5.py | 172 | 3.78125 | 4 | x = input("Put your number here please:")
def func1(x):
try:
return float(x)
except (ValueError):
print("Enter the number please.")
print(func1(x))
|
e535489eb731ee8c8f0b95fcfe70aeb271d97a30 | Robvanzoelen/Bingo | /Bingo card.py | 5,353 | 3.734375 | 4 | # Part 3 of assignment LCP: create a bingo card and mark the terms
# Team: Evert Schonewille & Rob van Zoelen
with open("bingo_terms.txt", "r") as input_file: # Use the file 'bingo_terms' as input
inp = str(input_file.readlines()) # Make string of the input from fil... |
81188e106fd95f879224e4e352050f8c5118a304 | another-computer/hanabi-py | /Hanabi/Deck.py | 1,144 | 3.859375 | 4 | from Card import Card
from Card import colors
from Card import numbers
from random import shuffle
class Deck(object):
def __init__(self, difficulty):
self.cards = []
self.frequencies = [3, 2, 2, 2, 1]
self.excluded_colors = ["Unknown"]
if difficulty == "Normal":
... |
7390058675a8e0347be9f57ed1545b41fa9e8f12 | SalmaHazem310/MidtermImageSegmentation | /shallow_neural_network_image.py | 3,175 | 3.5625 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
class NeuralNetwork():
def __init__(self):
self.weights = np.random.uniform(-1, 1, size = 1)
def segmoid(self, x):
return 1 / (1+ np.exp(-x))
def segmoid_derivative(self, x):
return x * (1 - x)
def train(self, t... |
6e6545bf2e9b4a7ff360d8151e6418168f777ff8 | sagarujjwal/DataStructures | /Stack/StackBalancedParens.py | 986 | 4.15625 | 4 | # W.A.P to find the given parenthesis in string format is balanced or not.
# balanced: {([])}, [()]
# non balanced: {{, (()
from stack import Stack
def is_match(p1, p2):
if p1 == '[' and p2 == ']':
return True
elif p1 == '{' and p2 == '}':
return True
elif p1 == '(' and p2 == ')':
... |
06b3257978638ef255f9a457522402e79948fbc2 | sagarujjwal/DataStructures | /List&Array/min&max_of_array.py | 394 | 3.921875 | 4 | #Find the maximum and minimum element in an array
def minmaxArray(list):
x = list[0]
y = list[1]
if x>y:
max=x
min=y
else:
max=y
min=x
for i in range(2,len(list)):
if max < list[i]:
max= list[i]
elif min > list[i]:
min=list[i]
... |
30815e5dc345089512ec5d8aefaeb252e38da2bf | McCoyAle/100-days-of-code | /python-hardway/ex5/ex5.py | 580 | 3.5 | 4 |
my_name = 'Alexandra McCoy'
my_age = 31
my_height = 66 # inches
my_weight = 161 # lbs
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print "Let's talk about %s." % my_name
print "She's %d inches tall." % my_height
print "She's %d pounds heavy." % my_weight
print "Actually, that's not too heavy."
print "He's g... |
380769147add0ecf5e071fa3eb5859ee2eded6da | alexmeigz/code-excerpts | /trie.py | 1,185 | 4.40625 | 4 | # Trie Class Definition
# '*' indicates end of string
class Trie:
def __init__(self):
self.root = dict()
def insert(self, s: str):
traverse = self.root
for char in s:
if not traverse.get(char):
traverse[char] = dict()
traverse = traver... |
93e3864e7fb2eef442177f2b6fab3b1f922a4b19 | LozovskiAlexey/Computational-Algorithms | /lab_05/main.py | 2,690 | 3.625 | 4 | from math import pow
CONST = 0 # константа Pнач/Tнач
# класс функции T(z) чтоб по всем функциям не таскать много перменнных
class T_function(object):
def __init__(self, t0, tw, m):
self.T0 = t0
self.Tw = tw
self.m = m
def count(self, z):
return self.T0 + (self.Tw - self.T0)... |
d5ac9b9c4c0ff99cfadd0bf6f48824d994f8582d | GT-ARC/gradoptbenchmark | /util/database.py | 3,423 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on 28.03.2019
@author: christian.geissler@gt-arc.com
"""
'''
A small, simple dirty dictionary database class, that can be used to simply store, save and load data to/from .json.
The data is stored in a tree of dictionaries that are automatically created when referenced by a ... |
68fc3b5b321975420962fbbd42783034c20fec99 | vishnu13579/principles-of-computing | /#5 - Word Wrangler.py | 4,634 | 4 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
import math
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new... |
9553ae83e83d03cf7ee73eaf32d153b5eea8a6ef | cartland/algorithms | /python/sort.py | 6,130 | 3.734375 | 4 | # Copyright 2017 Chris Cartland. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
c8e35a091a3e57b0ff80252f2179702f514bc21b | ezgoca/cursoEmVideo | /Exercicio28.py | 459 | 3.78125 | 4 | from random import randint
from time import sleep
# lista = [1,2,3,4,5]
lista = randint(0,5)
num_user = int(input('Em que numero estou pensando entre 0 a 5?\n'))
# num_programa = random.choice(lista)
# if num_user == num_programa:
print('-=-'*20)
print("Processandor....")
sleep(3)
print('-=-'*20)
if num_user == lista:
... |
e80ea3211da7da949dfc61c325f7bdf3a2de6de4 | ezgoca/cursoEmVideo | /exercicio5.py | 132 | 3.953125 | 4 | n=int (input('Digite um numero: '))
a= n-1
s= n+1
print('Analisando o valor {}, seu antercesor é {} e o sussesor {}'.format(n,a,s)) |
2efc13f292147b1f4f74ccb4dad7e3d113e6818b | ezgoca/cursoEmVideo | /Exercicio29.py | 219 | 3.78125 | 4 | vel = float(input('Digite a velocidade do carro: \n'))
if vel >= 80:
multa = (vel - 80) * 7
print('Você foi multado com o valor total R${}'.format(multa))
else:
print('Tenha um bom dia e uma otima viagem')
|
2d830b044ad4b57d053424d2c432e13ad5d7aa1a | EgorBedokurov/-2-03.11.2020 | /Lesson_2.3.py | 553 | 3.84375 | 4 | #v=int(input('с какой скоростью едет Василий? - '))
#t=int(input('где будет Василий через - '))
#x=v*t
#print=('Вася будет на отметке ' + str(x))
print('с какой скоростью едет Василий? - ')
v=int(input())
print('сколько времени Василий проехал? - ')
t=int(input())
dis=v*t
if dis <=100:
print('Вася будет... |
b49e031ff5b347ccc0eaad9ce0243d4f56d71768 | Ibarra11/TicTacToe | /tic_tac_toe.py | 4,055 | 3.921875 | 4 |
def game():
markers = [[],[]]
player = 0
board = [['','',''] , ['','',''], ['','','']]
remainingPositions = 9
hasWon = False
def init():
markers[0] = input('Player 1 choose your marker: ').upper()
markers[1] = input('Player 2 choose your marker: ').upper()
def placeInputOn... |
a382e60f41f1128bf470ce9fbd904bdf9f676cc8 | chrisbouton/325Program4 | /campusRecycle.py | 16,992 | 3.828125 | 4 | #Christopher Bouton and A.....
#Dr. Lori
#Advanced Data Structures 325
#Program 4: Campus Recycling
import csv
import time
#data = vertex
class Vertex():
def __init__(self, data, index):
self.data = data
self.edges = LinkedList()
self.found = False
self.index = index
d... |
9663fb189d01e3f220a18d11d2d246c01244570b | sekiguchikeita/python_pra1 | /omikuji.py | 365 | 3.796875 | 4 | import random
a = random.randint(0,80)
print("あなたの運勢は")
print("")
if a < 2:
print("大吉")
elif 2 <= a < 10:
print("中吉")
elif 10 <= a < 20:
print("小吉")
elif 20 <= a < 40:
print("吉")
elif 40 <= a < 50:
print("末吉")
elif 50 <= a < 55:
print("凶")
elif 55 <= a < 80:
print("中凶")
else:
print("大凶"... |
69eb2c097713ae1851b1638c54bf24acc387a88f | jedrzejwalega/projekty | /cwiczenia3.py | 310 | 4.03125 | 4 | if "dog" in "dog":
print(True)
else:
print(False)
if "dog" in "god":
print(True)
else:
print(False)
# na stringach:
# .lower()
# .upper()
# .replace(x, y)
# .count() - ile razy cos wystepuje w stringu
# .index() - pierwsze wystapienie danego znaku, jego index
# .isalpha() - czy ma same litery |
df1da214cc55d92786f4d3c4c85d5f8effef0289 | jedrzejwalega/projekty | /best_k/__init__.py | 1,500 | 3.59375 | 4 | import numpy as np
# BEST_K FUNKCJA
def best_k(nums):
biggest = 0
for k in range(0, len(nums) + 1):
new_biggest = funkcja(nums, k)
if biggest == 0:
biggest = new_biggest
else:
biggest = max(biggest, new_biggest)
if type(new_biggest) is str:
... |
667cce2320c15725e716608c72ef5a58c0b43534 | altoid/misc_puzzles | /py/indeed/whiteboard.py | 2,881 | 3.84375 | 4 | #!/usr/bin/env python
# syntax rules
import unittest
def indentation(line):
if not line:
return 0
return len(line) - len(line.lstrip())
def is_valid(lines):
"""
:param lines:
:return: the line number of the first invalid line,
-1 if all lines valid
"""
indentation_level... |
460f4323140734a4ff38e6fcf79c1ef8966d4010 | altoid/misc_puzzles | /py/interview1/BAK/lego.py | 3,432 | 3.90625 | 4 | #!/usr/bin/env python
import math
import pprint
pp = pprint.PrettyPrinter()
def choose(n, r):
return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))
def count(height_n, width_m):
# total # of combinations
# - number that have a seam in one position
# + number that have a seam in two p... |
75d2375e0d1cd7bde0cee78eaa1c60b1edede051 | altoid/misc_puzzles | /py/palindrome/solution.py | 1,393 | 3.796875 | 4 | #!/usr/bin/env python
# determine whether an integer is a palindrome.
#
# cases:
#
# very large number
# 2 digit number
# 3 digit number
# 1 digit number
# negative number
import unittest
def is_palindrome(x):
# reverse the number and see if it's equal
x_copy = x
rev_x = 0
while x_copy != 0:
... |
b9b0babaf3de0499bbd5253dd1570060c44cb060 | altoid/misc_puzzles | /py/file_io/myfileinput.py | 3,088 | 3.59375 | 4 | # my implementation of the FileInput class
# processing will stop if a file can't be opened for any reason
# this is an iterable
import sys
_state = None
class MyFileInput():
def __init__(self, files=[]):
files_to_read = files
if not files_to_read:
if len(sys.argv) > 1:
... |
fe7456456b22ca948b06f1a84c2d9f3b78b909f5 | altoid/misc_puzzles | /py/prime_bits/same_bits_successors.py | 4,206 | 3.875 | 4 | #!/usr/bin/env python
# not part of prime bits solution, but related fun problem: given a positive integer, find the next
# largest number with the same number of bits set. so if we are given this:
#
# +---+---+---+---+---+---+---+---+---+---+---+---+
# | | | | 1 | | 1 | 1 | | | 1 | 1 | |
# ... |
30c7f7592ee2dee97e4a6a0af5fd974868b8c033 | markusdlugi/aoc-2020 | /day08.py | 1,118 | 3.65625 | 4 | from copy import deepcopy
def run_command(program, ip, acc):
command, arg = program[ip]
if command == "acc":
acc += int(arg)
elif command == "jmp":
ip += int(arg) - 1
elif command == "nop":
pass
ip += 1
return ip, acc
def run_program(program, acc, print_on_loop):
... |
22ae8a42d2274bd41b67a55578413797c54998db | pythagitup/21_game | /Game_messages.py | 422 | 3.796875 | 4 | from Card import Card
def show_score(card):
if card.owner == 'Player':
print(f'Your hand is worth {card.points}.')
else:
print(f'The computer\'s hand is worth {card.points}.')
def winner(player,computer):
if player.points > computer.points:
print(f'\nCongratulations! You beat the c... |
6da9510d575469face38b44838a163973e9fe837 | Sandeep-Narahari/Regex-Software-Services-Assignments | /Python1/Assignment10.py | 259 | 3.953125 | 4 | d1={"a":1,"b":2,"c":3,"d":4}
d2={"b":2,"d":4,"f":6,"g":7}
d3={}
def disJoint():
union=dict(d1.items() | d2.items())
intersection=dict(d1.items() & d2.items())
d3=dict(union.items() ^ intersection.items())
return d3
print(disJoint()) |
5a791721dc41503aa74efee27ce3222269d5aa05 | MindVersal/CodeForcesSolutions | /000-099/000-009/9A/9A.py | 453 | 3.875 | 4 | """
Program for solution problem 9A
"""
def calculate_probability():
input_numbers = [x for x in input()]
big_number = input_numbers[0] if input_numbers[0] >= input_numbers[2] else input_numbers[2]
probability = {
'1': '1/1',
'2': '5/6',
'3': '2/3',
'4': '1/2',
'5'... |
d913bf5746d8c059e87cee2d88d26caf3f9d64d5 | imsoncod/Coding-Specialist-Professional-1st | /4차/4차 1급 5_solution_code.py | 373 | 3.5 | 4 | def solution(n):
answer = ''
for i in range(n):
answer += str(i%9 + 1)
answer = answer[::-1]
return answer
#아래는 테스트케이스 출력을 해보기 위한 코드입니다.
n = 5
ret = solution(n)
#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은", ret, "입니다.") |
3979d1a1bf4fe936b13030197ef5069f38e07941 | imsoncod/Coding-Specialist-Professional-1st | /5차/5차 1급 7_solution_code.py | 502 | 3.609375 | 4 | def find(parent, u):
if u == parent[u]:
return u
parent[u] = find(parent, parent[u])
print(parent)
return parent[u]
def merge(parent, u, v):
u = find(parent, u)
v = find(parent, v)
if u == v:
return True
parent[u] = v
return False
def solution(n, connections):
answer = 0
parent =... |
bf9b0a1a41542dde154f1b4217edddbba3a4975b | imsoncod/Coding-Specialist-Professional-1st | /4차/4차 1급 4_solution_code.py | 2,036 | 3.546875 | 4 | n = 4
def find_not_exist_nums(matrix):
nums = []
exist = []
for i in range(n*n+1):
exist.append(False)
for i in range(0, n):
for j in range(0, n):
if matrix[i][j] != 0:
exist[matrix[i][j]] = True
for i in range(1, n*n+1):
if ex... |
e4aa0b49485ed2a7c448a6be01865f5143ee22f4 | mhtarek/Codeforces-solved-problems | /A. Petya and Strings.py | 215 | 3.53125 | 4 | x = lambda: input().lower()
a = x()
b = x()
if a==b:
print(0)
for i in range(len(a)):
if(a[i] > b[i]):
print(1)
break
elif(a[i]<b[i]):
print(-1)
break
|
1e726c2adf6c52542b488f9fa561b17b75c06893 | jenniferllee/object-orientation-assessment | /assessment.py | 3,913 | 4.59375 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
ENCAPSULATION: You can combine data and functionality in a package or
"capsule" so that similar ideas are organized together.
ABSTRACTION: You can hide details that are not crucia... |
0602f9b8f2f8e231e571e3db47a677a9083c1341 | brownboycodes/problem_solving | /code_signal/reverse_in_paranthesis.py | 883 | 3.9375 | 4 | """
Write a function that reverses characters
in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
"""
def reverseInParentheses(inputString):
s=[]
for i in range(len(inputString)):
# push the index of the current opening bracket
... |
03995a46974520e6d587e3c09a24fa1c98a6423f | brownboycodes/problem_solving | /code_signal/shape_area.py | 443 | 4.1875 | 4 | """
Below we will define an n-interesting polygon.
Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1.
An n-interesting polygon is obtained by taking the n - 1-interesting polygon
and appending 1-interesting polygons to its rim, side by side.
Y... |
298ce4a268c6242ee4b18db1b5029995ebaa183f | brownboycodes/problem_solving | /code_signal/adjacent_elements_product.py | 362 | 4.125 | 4 | """
Given an array of integers,
find the pair of adjacent elements that has the largest product
and return that product.
"""
def adjacentElementsProduct(inputArray):
product=0
for i in range(0,len(inputArray)-1):
if inputArray[i]*inputArray[i+1]>product or product==0:
product=inputArray[i... |
d1868513900a2bd788f17592361ef278602dbaaa | brownboycodes/problem_solving | /code_signal/is_lucky.py | 347 | 3.9375 | 4 | """
Ticket numbers usually consist of an even number of digits.
A ticket number is considered lucky if the sum of the first half of the digits
is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.
"""
def isLucky(n):
n=list(map(int, str(n)))
l=len(n)
return sum... |
fc6966de40440fc04560b436437f32b94fe82efc | petrovplamenph/Artificial-Intelligence-python-implementations-from-scratch | /kmeans.py | 4,327 | 3.53125 | 4 | import math
from statistics import mean
import matplotlib.pyplot as plt
import random
class Cluster:
def __init__(self,horiz_pos, vert_pos):
self._horiz_center = horiz_pos
self._vert_center = vert_pos
def horiz_center(self):
"""
Get the averged horizontal cent... |
edd691959c2b746f73c8f57539479f08949c78fa | J3rry-L/python | /intro_loops.py | 2,734 | 3.765625 | 4 | def sumFromZeroToN(n):
s = 0
while (n > 0):
s = s + n
n = n - 1
return s
print("sumFromZeroToN tests:")
print(sumFromZeroToN(-3))
print(sumFromZeroToN(4))
print(sumFromZeroToN(10))
def sumAtoB(a,b):
s = 0
while a <= b:
s = s + a
a = a + 1
return s
print("subAtoB tests:")
print(sumAtoB(0, 1)... |
5f9603cbec0f881926829c976e12db1151b6e811 | FuriousFlash/MCDM-Problem | /dataloader.py | 212 | 3.5 | 4 | import csv
def loadCsv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
for i in range(len(dataset)):
#print(dataset[i])
dataset[i] = [float(x) for x in dataset[i]]
return dataset |
a521e9127959f9d773e819793cb1b34403ab25bb | C109156238/MIDTERN | /4.py | 937 | 3.875 | 4 | x=int(input("please input x:"))
y=int(input("please input y:"))
if x==0 and y==0 :
print("該點位於原點")
if x==0 and y>0 :
a=y**2
print("該點位於上半平面Y軸上,離原點距離為根號",a)
if x==0 and y<0 :
a=y**2
print("該點位於下半平面Y軸上,離原點距離為根號",a)
if x>0 and y==0 :
a=x**2
print("該點位於右半平面X軸上,離原點距離為根號",a)
if x<0 an... |
7bc4a52c429701105db8cbcae30ff5c69f939365 | C109156238/MIDTERN | /12.py | 292 | 3.515625 | 4 | a=input("輸入一整數序列為:").split(' ')
tmp=[]
ans=0
for i in a:
if tmp.count(i)==0:
tmp.append(i)
for i in tmp:
if a.count(i) >= len(a)/2:
ans=i
if ans ==0:
print("過半元素為:NO")
elif ans != 0:
print("過半元素為:{}".format(ans)) |
f427e8ea3d097b17c7414b5b3752737441e3e48b | yogeshrakate/Sagveek_Test | /Sagveek_test_solution_8.py | 453 | 3.9375 | 4 | '''
Question No. 8
Write a function that takes a list of integers and
returns the largest sum of non-adjacent numbers.
For example:
input:[2,4,6,2,5] ----> Output:13===>2+6+5
input:[5,1,1,5] ----> Output:13===>5+5
'''
def LargeSum(l):
incl = 0
excl = 0
for i in l:
new_excl = max(excl, incl)
... |
47edc5e19c8ebd3ea6956d89e52a5ca7eebcebba | timthetinythug/practicePython | /grid.py | 17,062 | 4.125 | 4 | """Assignment 1 - Node and Grid
This module contains the Node and Grid classes.
Your only task here is to implement the methods
where indicated, according to their docstring.
Also complete the missing doctests.
"""
import functools
import sys
from container import PriorityQueue
@functools.total_order... |
925821fed0786002a29bde0804c4408e5fc6302f | mbilalashraf/AILabAssignment | /Assignment1.py | 1,153 | 3.78125 | 4 | #1. Considering the image below, develop the adjacency matrix representation of the graph.
# Find the in-degree and out-degree of V6
from IPython.display import Image
Image(filename='img.png')
adj =[[0,1,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,1,0,0],
[0,... |
b13732fe04f00f6247b61565a1090bfb5b6a3e52 | kirubeltadesse/Python | /examq/test2.py | 1,004 | 4.0625 | 4 | # kirubel Tadesse
# Dr.Gordon Skelton
# J00720834
# Applied Programming
# Jackson State University
# Computer Engineering Dept.
# Write a program that uses the same file. Have that program produce the largest and smallest value from the file. You can just modify the program in No. 6 above to solve this problem.
im... |
98edf9ce118f9641f55d08c6527da8d01f03b49a | kirubeltadesse/Python | /examq/q3.py | 604 | 4.28125 | 4 | # Kirubel Tadesse
# Dr.Gordon Skelton
# J00720834
# Applied Programming
# Jackson State University
# Computer Engineering Dept.
#create a program that uses a function to determine the larger of two numbers and return the larger to the main body of the program and then print it. You have to enter the numbers from the... |
9b773282655c5e3a6a35f9b59f22ddb221386870 | AyvePHIL/MLlearn | /Sorting_alogrithms.py | 2,275 | 4.21875 | 4 | # This is the bubbleSort algorithm where we sort array elements from smallest to largest
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed (more efficient).
# Last i eleme... |
2486925e16396536f048f25889dc6d3f7675549a | NathanielS/Week-Three-Assignment | /PigLatin.py | 500 | 4.125 | 4 | # Nathaniel Smith
# PigLatin
# Week Three Assignment
# This program will take input from the usar, translate it to PigLatin,
# and print the translated word.
def main ():
# This section of code ask for input from the usar and defines vowels
word = input("Please enter an English word: ")
vowels = "AEIOUaeiou"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.