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 |
|---|---|---|---|---|---|---|
47a6f8b87464ffc3a320a6dd9d79b16940d86794 | CatonChen/algorithm023 | /Week_01/21.合并两个有序链表.py | 1,328 | 3.765625 | 4 | #
# @lc app=leetcode.cn id=21 lang=python3
#
# [21] 合并两个有序链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
... |
9f006c9beecb29b7474b7bb458ad70ba43ba4bae | Tordensky/laby | /teams/hma030_inf2101_oblig2/src/message.py | 766 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class message:
""" Class encapsulating messages.
Used with the protocolBase for transferring messages between peers. """
def __init__(self):
""" Initializes the object with a message (string) if input is given. """
self.msg = []
def add(self, msg):... |
08ba6f102fa5e01b3c6c4cd0ec20c7f955261cf0 | aj3x/adventofcode2020 | /day9/day9.py | 1,100 | 3.515625 | 4 | import userin
#
# sort range of numbers
# while sorting add to key map
def convertArr(item):
return int(item)
preamble = 25
parsedArray = map(convertArr, userin.default.splitlines())
# check numbers between (n/2,n)
# binary search sorted array for being in between range
# try going up and down till reaching... |
58401ce6e6a3876062d2a629d39314432e08b64f | mattling9/Algorithms2 | /stack.py | 1,685 | 4.125 | 4 | class Stack():
"""a representation of a stack"""
def __init__(self, MaxSize):
self.MaxSize = MaxSize
self.StackPointer = 0
self.List = []
def size(self):
StackSize = len(self.List)
return StackSize
def pop(self):
StackSize = self.StackSize()
... |
be8eecacddb448aa1cef0d9a2213178cb2655e80 | felixnext/tf-argonaut | /argonaut/models/simple.py | 2,386 | 3.640625 | 4 | '''
Defines some simple baseline models.
author: Felix Geilert
'''
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers as lyrs
class ConvNet(tf.keras.Model):
'''Defines a simple convolutional model.
Args:
num_layers (int): Number of layers to use
num_classes (int): Number of c... |
f02c48c3687acd676ab39c789211d8f554652649 | iemeka/python | /exercise-lpthw/form.py | 850 | 3.65625 | 4 | from sys import argv
script, file = argv
prompt = "$$- "
print "Hello!"
name = raw_input("please enter your name %s" % prompt)
print "Welcome %s. How are you?" % name
doing = raw_input(prompt)
print "Nice to know you're %s" % doing
print "I am going to ask a few questions about you if that's ok?"
print "Type 'ok' o... |
a81e12e0195a19d01957ec210feb85aacc461fd8 | iemeka/python | /exercise-lpthw/snake4.py | 1,746 | 4.09375 | 4 | #we gave the number value to the variable name "car"
cars = 100
#we gave variable name a number value too
space_in_a_car = 4.0
#same here with "drivers"
drivers = 30.0
#and also with "passengers"
passengers = 90
#we created the variable "cars_not_driven" and assigns two variables defined previously to it
#the result is... |
31b272d2675be1ecfd20e9b4bae4759f5b533106 | iemeka/python | /exercise-lpthw/snake6.py | 1,792 | 4.21875 | 4 | #declared a variable, assigning the string value to it.
#embedded in the string is a format character whose value is a number 10 assigned to it
x = "There are %d types of people." % 10
#declared a variable assigning to it the string value
binary = "binary"
#same as above
do_not = "don't"
# also same as above but with w... |
ed10b4f7cebef6848b14803ecf76a16b8bc84ca4 | iemeka/python | /exercise-lpthw/snake32.py | 713 | 4.40625 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
fo... |
bb1a2972bc806e06fe6302c703c158130318bf07 | iemeka/python | /exercise-lpthw/snake20.py | 1,128 | 4.21875 | 4 | from sys import argv
script, input_file = argv
# a function to read the file held and open in the variable 'current_file' and then passed..
# the variable is passed to this functions's arguement
def print_all(f):
print f.read()
# seek takes us to the begining of the file
def rewind(f):
f.seek(0)
# we print the nume... |
d26f6248dedc9e0fa11f461dfaa246e811c17f80 | chenshaobin/python_learning_demo | /map_reduce_demo.py | 1,520 | 4 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num2(s):
return DIGITS[s]
return reduce(fn, map(char2num2, s))
# print... |
fc21b2b82f9da9cc41c9e61f709635ddbec7c6da | MelisseCabral/Lab-Prog-1-2014.1 | /media_do_maior_e_menor/m.py | 499 | 3.703125 | 4 | # coding: utf-8
# Melisse Cabral, 114110471
# Média do Maior e Menor
num = int(raw_input())
maior = num
menor = num
numeros = []
cont = 0
while num >= 0:
num = int(raw_input())
numeros.append(num)
if num > maior and num >= 0:
maior = num
if num < menor and num >= 0:
menor = num
media = (maior + menor) / 2.... |
8d5493d6d22701be1f409a5b7f4a7380f731512e | MelisseCabral/Lab-Prog-1-2014.1 | /somadiv5/m.py | 186 | 3.828125 | 4 | # coding: utf-8
# Melisse Cabral, 114110471
# Soma Dos Divisiveis por 5
n = int(raw_input())
soma = 0
for i in range(1,n+1):
num = int(raw_input())
if num % 5 == 0:
soma += num
print soma
|
a5daf669e7bcf9315bbeadf8bb0ead7d8b6d7876 | MelisseCabral/Lab-Prog-1-2014.1 | /menor_dos_extremos/m.py | 520 | 3.625 | 4 | # coding: utf-8
# Melisse Cabral, 114110471
# Menor dos Extremos
n = int(raw_input())
lista = []
menor = 0
cont_menor = 0
cont_maior = 0
for i in range(n):
num = int(raw_input())
lista.append(num)
if int(lista[0]) >= int(lista[-1]):
menor = int(lista[-1])
else:
menor = int(lista[0])
for i in lista:
if i < m... |
63788308ae2eeefbeb65ec9cf9551d3f8269b421 | ajcheon/project_euler | /problem_4.py | 240 | 3.8125 | 4 | # largest palindrome made from the product of two 3-digit numbers
palins = []
for i in range (100, 1000):
for j in range (100, 1000):
prod = str(i * j)
if prod == prod[::-1]:
palins.append((int)(prod))
print max(palins) |
85034cba0c67348981ca40573a5c185743afd565 | ajcheon/project_euler | /problem_10_sieve.py | 902 | 3.59375 | 4 | # Find the sum of all the primes below two million.
# 1/4/13
import math
import time
# FOR DEBUGGING ONLY
def is_prime(n):
for i in range (1, n):
if n % i == 0 and i != 1 and i != n:
return False
return True
#---------------------------------------------
#limit... |
3d3bb07c0afda8d2c9943a39883cbbee67bfe4b1 | icgowtham/Miscellany | /python/sample_programs/tree.py | 2,130 | 4.25 | 4 | """Tree implementation."""
class Node(object):
"""Node class."""
def __init__(self, data=None):
"""Init method."""
self.left = None
self.right = None
self.data = data
# for setting left node
def set_left(self, node):
"""Set left node."""
... |
1eb9a54a4c86c72594064717eb0cd65c6376421d | icgowtham/Miscellany | /python/sample_programs/algorithms/quick_sort_v1.py | 1,352 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""Quick sort implementation in Python."""
def partition(array, begin, end):
"""Partition function."""
pivot_idx = begin
"""
arr = [9, 3, 4, 8, 1]
pivot = 0
i = 1, begin = 0
3 <= 9 -> swap -> [3, 9, 4, 8, 1]
pivot = 1
i = 2, pivot = 1
4 <= 9 -> swap -> [... |
2395e627570a75a0ea72fdf243cd5b28e155d0e0 | TTvanWillegen/AdventOfCode2019 | /3/main.py | 3,790 | 3.640625 | 4 | def main():
part_one()
part_two()
def part_one():
print("Part One")
center = (0, 0)
with open("input.txt", "r") as input_file:
wires = []
for line in input_file:
wire = set()
actions = line.rstrip().split(",")
coord = center
for actio... |
cac92e1610c7ce6de0e01393d907ff28837ea12f | smyoung88/Election_Analysis | /PyPoll_Challenge.py | 5,404 | 3.9375 | 4 | # Import 'csv' and 'os' modules
import csv
import os
# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_results.txt")
# Initialize a total vote counter... |
ebd8fcf43f3afc982cee8ca946346f431d3c6232 | SlawomirK77/to-lab | /iterator.py | 1,714 | 3.921875 | 4 | from collections import defaultdict
from abc import ABCMeta, abstractmethod
class Iterator(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def has_next():
"""Returns Boolean whether at end of collection or not"""
@staticmethod
@abstractmethod
def next():
"""Return the object... |
a0425a6f44b7adbce69881aac60a34448c6248cc | Copoka11/tkTest | /tkTest/test_12.py | 536 | 3.703125 | 4 |
from tkinter import *
from tkinter.messagebox import *
root = Tk()
btn1 = Button(root, text="Info", font=("Tahoma", 20), command = lambda: showinfo("ShowInfo", "Info:"))
btn1.grid(row=0, column=0, sticky="ew")
btn2 = Button(root, text="Warning", font=("Tahoma", 20), command = lambda: showwarning("ShowWarning", "Wa... |
9f30c9c040e81a68f30c85fa46a4560dd811f83c | hiteshdua1/codescripter | /pong_the_game.py | 6,759 | 3.984375 | 4 | #Running CodeSkulptor Link !
#http://www.codeskulptor.org/#user23_ePlWtu2yPB_14.py
# Implementation of classic arcade game Pong
#for left bar use
# w-up
# s-down
#for right bar use
# up arraow key-up
# down arow key-down
import simplegui
import random
# initialize globals - pos and vel encode vertical... |
5d70ae6c1247088f697a811dc9e5aa5e34eb1660 | jes5918/TIL | /Algorithm/SWEA/파이썬SW문제해결 List2/4843_special.py | 600 | 3.5 | 4 | def selectionsort(li, x):
for i in range(0, x):
min_li = i
for j in range(i, N):
if li[min_li] > li[j]:
min_li = j
li[i], li[min_li] = li[min_li], li[i]
return li
T = int(input())
for tc in range(1, T+1):
N = int(input())
lists = list(map(int, input... |
9caf98a84cf6d290cbaf6ea8fcb816f0a1a113ff | jes5918/TIL | /Algorithm/BEAKJOON/4. while/1110.py | 452 | 3.5 | 4 | import sys
def pluscycle(a, b, count):
count += 1
c = b
d = (a + b) % 10
if digit_10 == c and digit_1 == d:
return count
else:
return pluscycle(c, d, count)
number = int(sys.stdin.readline())
count = 0
digit_10 = number // 10
digit_1 = number % 10
if 0 <= number < 100:
print(p... |
0110bb1681a49709787a9e9658dcd81f5d4f02d4 | Manikantha-M/python | /basics/functions.py | 186 | 3.546875 | 4 | def fun():
print('ahh')
print('ahh2')
fun()
def fun2(x):
return 2*x
a=fun2(3)
print(a)
print(fun2(9))
def fun3(x,y):
return x+y
e=fun3(5,4)
print(e)
print(fun3(6,4)) |
cc8511249b184b15fb4636f493d4318af11af484 | Manikantha-M/python | /programs/lcm-list.py | 242 | 3.53125 | 4 | def lcm(x,y):
if x>y:
x,y=y,x
for i in range(y,(x*y)+1,y):
if i%x==0:
return i
l=list(map(int,input().split()))
n1=l[0]
n2=l[1]
lcmf=lcm(n1,n2)
for i in range(2,len(l)):
lcmf=lcm(lcmf,l[i])
print(lcmf) |
1fc339caacbfcd2082e737dfb99dfe2eef05c23e | Manikantha-M/python | /programs/reverse-str.py | 61 | 3.53125 | 4 | s=input('Enter:')
rev=''
for i in s:
rev=i+rev
print(rev) |
25765c6183a968c6ef857cce53febe4cec561ee5 | Manikantha-M/python | /programs/palindrome-num.py | 155 | 3.796875 | 4 | n=int(input('Enter:'))
temp=n
rev=0
while temp>0:
dig=temp%10
rev=rev*10+dig
temp//=10
if rev==n:
print('Palindrome')
else:
print('No') |
1f891ba81bc7a351543f93b26b51c9f4f3468500 | Manikantha-M/python | /programs/perfectnum.py | 196 | 3.5625 | 4 | n=int(input('Enter:'))
if n>0:
s=0
for i in range(1,n):
if n%i==0:
s+=i
if s==n:
print('Perfect number')
else:
print('No')
else:
print('No') |
4d3b7ec95a5a0c3523b7724968843c749c7c8cfd | zw161917/python-Study | /基础学习/旧文件/函数调用_1.py | 426 | 3.625 | 4 | #调用函数_1--绝对值
print (abs(100))
print (abs(-100))
print (abs(20),abs(-20))
#调用函数_1——最大值
print (max(1,2,3))
print (max(-3,-2,-3))
#调用函数_1——数据类型转换
print (int('123'))
print (int (12.76))
print (str(123))
print (str(12.12))
print (float(1))
print (float('11'))
#调用函数_1——转换16进制
n1=255
n2=1000
print... |
2cc68d9b0c8b59733fa4cece8c1e78a51482b941 | zw161917/python-Study | /基础学习/旧文件/函数式编程_匿名函数.py | 514 | 4.03125 | 4 | #直接传入匿名函数 lambda代表匿名函数
import functools
print(list(map(lambda x: x * x,[1,2,3,4,5,6,7,8,9])))
#把匿名函数当做变量
f = lambda x: x * x
print(f)
print(f(5))
#把匿名函数当做返回值返回
def build(x,y):
return lambda : x * x + y * y
fd = build(1,2)
print(fd())
#还可以将函数对象 *args **kw
int2 = functools.partial(int,base=2)
pr... |
7b32c55a90309e4b8e658c6108dac9952df5a462 | pooja89299/loop | /star.py | 565 | 3.875 | 4 | # n=int(input("enter the number"))
# i=1
# while i<n:
# j=1
# while j<i:
# print("*"*j,end="")
# j=j+1
# print()
# i=i+1
# num=int(input("enter the num"))
# if num>10:
# print("your gessing low")
# elif num==10:
# print("your gesing equal")
# else:
# print( "your gessing hi... |
0baeac450af1436820d72eacea3309115fb90dd1 | znharpaz/MomandDad | /oldDrawing.py | 537 | 3.5 | 4 | import turtle
import random
h = 10
wn = turtle.Screen()
Zach = turtle.Turtle()
Hello = turtle.Turtle()
Hello.right(180)
Zach.speed(100000)
Hello.speed(100000)
wn.colormode(255)
while True:
for i in range(10,100000000, 20):
a = random.randint(0,256)
b = random.randint(0,256)
c =... |
292786e5944509904615df89d685a6ae16997dc9 | itskeithstudent/CTA-Project | /mainy.py | 29,420 | 4.125 | 4 | #Couple skeleton functions to get started with random num generator to start with
import numpy as np
import time
def random_array_generator(array_size, low=0, high=100):
'''
random_array_generator - returns numpy random array of defined size over a defined range
size of array defined by array_size, minimum... |
87a7bf018c136bd581849c94d94150d043e70581 | albertogeniola/TheThing-HostController | /src/HostController/miscellaneus/MacAddress.py | 1,906 | 4.0625 | 4 | import re
class MacAddress:
"""
Wrapper for handling MacAddress. It taks a parameter in the constructor which may be an instance of MacAddress or
a string. The class will parse the string/mac and will store it in a fixed format. Using this class everywhere in
the code will ensure consistency in the MA... |
70a8687994ed41534c9074b2e86f915075f96f26 | yurekliisa/BBC | /Server/ChatBot/CLI/cli.py | 233 | 3.5 | 4 | from Bot import ChatBot as bot
ob = bot.ChatBot.getBot()
i = 0
print("Print exit to leave")
while True:
text = input("Q : ")
if text == 'exit':
break
print("A : "+ob.response(text))
print("Ended successfully")
|
dd2474245cce8d7e9dac7f0a6473ee0b1358c9a9 | erikluu/Lunar-Module-Game | /src/landerFuncs.py | 2,766 | 3.859375 | 4 | import math
def showWelcome():
print("\nWelcome aboard the Lunar Module Flight Simulator\n")
print(" To begin you must specify the LM's initial altitude")
print(" and fuel level. To simulate the actual LM use")
print(" values of 1300 meters and 500 liters, respectively.\n")
print(" Goo... |
6c89ec5e41a42bae9abdaa042d18852391a1d39f | antcalkins/Capstone | /arguments.py | 4,367 | 3.75 | 4 | """ This code is designed to hash files and create a pandas dataframe that can be referenced by a graphical interface
and modified by the user.
Authors: L.E. Rogers and A.B. Calkins
Last Edited: 16/02/2021"""
import hashlib
import glob
import argparse
import pandas as pd
from datetime import datetime
import platform
d... |
b2b14f37ca46d7819d3585ee650c1f8f3fb03493 | osamamohamedsoliman/Linked-List-2 | /Problem-4.py | 1,014 | 3.671875 | 4 | # Time Complexity :O(n)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
# Your code here along with comments explaining your approach
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, hea... |
d4594cd71821f49dcbac0068666bbdcd073f5b7d | qisaw/se370_Assignment_2 | /drive.py | 2,784 | 3.796875 | 4 | '''
Created on 27/08/2013
The underlying Drive class which actually stores all data in a real text file.
USE AS IS.
NO MODIFICATION WITHOUT PERMISSION.
@author: robert
'''
import os
class Drive(object):
'''
A drive.
You can be sure that all drives have at least 3 blocks and less than 1000 blocks.
'''
... |
a8ecbb89b15e22a9d6587c8429704f234f3cce9e | samineup0710/geneses_pythonassignment3rd | /checkingstring.py | 649 | 3.953125 | 4 | userinput = input("enter a input in strings:")
import re
"""set counters"""
upp=0
sc =0
num = 0
"""checking and counting"""
for ch in userinput:
if (ch>='a'and ch<='z'):
low = low+1
if(ch>='A' and ch<='Z'):
upp = upp+1
if re.match("^[!@#$%^&*()_]*$", ch): #regex checking special chara... |
a5b069842ace8cfab75a81333432b78ff0de0143 | Gerrydh/sample-python-code | /Compartmentalisaion2(W6).py | 371 | 3.84375 | 4 | #different way to do compart.py
def gcd(x, y):
while x != 0 and y != 0:
if x > y:
x = x % y
else:
y = y % x
if x == 0:
return y
else:
return x
print("GCD of 6 and 15:", gcd(6, 15))
z = gcd(221, 323) # dont have to put this in the print line, crea... |
55b9c9b05bcaa82321000ef230e049cab763a7f9 | sovello/palindrome | /palindrome_recursive.py | 632 | 4.28125 | 4 | from re import *
def reverseChar(word = '' ):
reversed_word = ''
for letter in word:
if len(word) == 1:
reversed_word = reversed_word + word
else:
reversed_word = reversed_word+word[-1]
word = word[:len(word)-1]
reverseChar(word)
return rev... |
d67dcca89e007ebad4fcf36dcbb7736341bc5f22 | jimmychen09/practicepython | /Ex25 Guessing game two.py | 1,093 | 4.03125 | 4 | #http://www.practicepython.org/exercise/2015/11/01/25-guessing-game-two.html
'''
Game 1 with binary
'''
print("Guess a number between 0 and 100")
first = 0
last = 101
counter = 0
guesses = []
while True:
middle = (first + last)//2
print("Is it...", middle, "?")
inp = input("Is it higher, lower or correct... |
8da2fe1e1b0e3f42a2d8e5ff1ce42c725518aa40 | jimmychen09/practicepython | /Ex4 Divisors.py | 253 | 3.8125 | 4 | #http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
num = int(input("Enter a number: "))
print([i for i in range(1, num + 1) if num % i == 0])
# l = []
# for i in range(1, num + 1):
# if num % i == 0:
# l.append(i)
# print(l) |
65ce43ee9a9318d037767a3619483db61556c2ba | jimmychen09/practicepython | /Ex10 List overlap comprehensions.py | 235 | 3.734375 | 4 | #http://www.practicepython.org/exercise/2014/04/10/10-list-overlap-comprehensions.html
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print([x for x in set(a) for y in set(b) if x == y]) |
80439cda56f781c192db39cebf41b397d392225e | jimmychen09/practicepython | /Ex3 List less than ten.py | 196 | 3.796875 | 4 | #http://www.practicepython.org/exercise/2014/02/15/03-list-less-than-ten.html
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input("Choose a number: "))
print([i for i in a if i < num]) |
1d88cd26d0b1285ae88a60a8f15a8666a82e1c0e | amitmals/Python-Projects | /PyBanking/PyBank_akm2.py | 3,483 | 3.75 | 4 | #Import the classes
#Keep the input file named "budget_data.csv" in the same folder as the python script
#Output file name: "Output_File.csv"
#Open the input file
# Cycle through all the rows (remove header)
#Print to terminal and output file
import os
import csv
#open the file budget_data.csv as read only(default)... |
46b26aab885b89f75b6f3f959efb714d0da00ae0 | kirtykumari98/Polynomial_Regression | /Polynomial_regression.py | 1,201 | 3.703125 | 4 | #importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataest
df=pd.read_csv('Position_Salaries.csv')
X=df.iloc[:,1:2].values
y=df.iloc[:,2].values
#Building the Linear Regression model
from sklearn.linear_model import LinearRegression
linear_regres... |
9bb6c9536c1e0b422f25163359dce6794e52e136 | gnishant01/ShowRenamer | /showRenamer.py | 4,307 | 3.5 | 4 | #-------------------------------------------------------------------------------
# Name: ShowRenamer
# Purpose: To rename every episode of a TV series, fetching the title of the episode from IMDb
# Author: Gaurav Nishant
#-------------------------------------------------------------------------------
#... |
571b04f2c7074d04c64206675b12b8c3bf4ecdca | lowellmower/nand_to_tetris | /projects/06/A.py | 1,329 | 3.515625 | 4 | import re
REGX_A_COMMAND = r"^@(?P<value>\d+)$"
class ACommand:
"""
ACommand is the class responsible for interpreting the A instructions from assembly
and converting those to their respecitve binary forms. For a detailed spec see the
README.md in the root of this project.
Basic A instructions lo... |
4aa56ef1e444aa37fdb753292fd868cd6659896b | JonathanRider/calculatorgame | /calculator.py | 4,810 | 3.6875 | 4 | def negative(value = 0):
def neg(num):
return -1 * num, 1
return neg
def reverse(value = 0 ):
def reverse_2(num):
neg = -1 if num < 0 else 1
num_rev = str(abs(num))[::-1]
return int(num_rev) * neg, 1
return reverse_2
def mirror(value = 0):
def mirror_2(num):
... |
f646e3774ac2343f9c189cb971b06601c93eefa7 | himanshu81494/udacity-fsnd-p2 | /tournament/tournament.py | 3,615 | 3.828125 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the database."... |
85f6893ae854200ee989d5b43f217b37f645c7ba | truas/kccs | /python_overview/python_unit_testing/primes.py | 793 | 3.984375 | 4 |
class Prime:
def is_prime(self,number):
"""Return True if *number* is prime."""
if number in (0, 1):
return False
if number < 0:
return False # can we combine these last two ?
for element in range(2, number):
if number % element == 0:
... |
87661803c954900ef11a81ac450ffaaf76b83167 | truas/kccs | /python_overview/python_database/database_03.py | 1,482 | 4.375 | 4 | import sqlite3
'''
The database returns the results of the query in response to the cursor.fetchall call
This result is a list with one entry for each record in the result set
'''
def make_connection(database_file, query):
'''
Common connection function that will fetch data with a given query in a specific D... |
5217a281d3ba76965d0cb53a38ae90d16e7d7640 | truas/kccs | /python_overview/python_oop/abstract_animal_generic.py | 2,001 | 4.25 | 4 | from abc import ABC, abstractmethod #yes this is the name of the actual abstract class
'''
From the documentation:
"This module provides the infrastructure for defining abstract base classes (ABCs) in Python"
'''
class AbstractBaseAnimal(ABC):
'''
Here we have two methods that need to be implemented by any clas... |
a1df134da6c83c138e437c167bec3e3e6043a2c1 | truas/kccs | /python_overview/python_oop/polymorphism_alternative.py | 985 | 4.03125 | 4 |
class BadCake:
def makeCake(self,):
print("Making a simple cake")
def makeCake(self, stuff):
print("Making a simple cake, with " + stuff + " inside")
class GoodCake:
def makeCake(self,stuff=None):
if not stuff:
print("Making a simple cake")
else:
p... |
cd1da3a25cc681578afaf342b6441a8c1e98da22 | abyanjan/US-Airline-Tweet-Analysis-Dashboard | /app.py | 6,145 | 3.515625 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import re
from sklearn.feature_extraction.text import CountVectorizer
... |
c3ee005e9bac986eb8155678561dffa728a39c8f | rpalri/declare_terminal | /Declare_WIP.py | 6,659 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import itertools
import random
vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king', 'ace']
suits = ['spades', 'clubs', 'hearts', 'diamonds']
orig_deck = [list(tup) for tup in itertools.product(vals, suits)]
deck = orig_deck[:]
player_count =... |
418aa76b306c3ddd7e502a65ac4098a93a9e352f | chris-tse/Python-Assignment-2 | /assn.py | 1,092 | 4.03125 | 4 | # Initialize ID number for ease of testing
ID = 112971666
# As written in class
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
else:
i = 2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True
# Gener... |
70fc0e4e7f50a4f821780c521827e448545f37fa | AbdohDev/Pyson | /util/validations.py | 1,328 | 3.84375 | 4 | from user import UserManager, User
def username_validation(username):
if str(username).__len__() == 0:
return False, "Please enter the valid username", None
user = UserManager().find_user_by_username(str(username).strip())
if user is None:
return False, "User does not exist", None
re... |
9620a88aa77292cf0c882521ba2cbe7678c8d879 | rjsilmaro/python-project-for-data-engineering | /extract_data_using_API.py | 322 | 3.515625 | 4 | import json
import requests
import pandas as pd
from pandas import json_normalize
url = "http://api.exchangeratesapi.io/v1/latest?access_key=87080aa2710f5b6f98b3386c79712e62"
data = requests.get(url).text
exchange_rate = pd.read_json(data)
exchange_rate = exchange_rate["rates"]
#print(exchange_rate)
exchange_rate.t... |
185e34aa22d5e92c7bf133d2cd8240c641df6412 | udacity/AIND-Recognizer | /asl_data.py | 12,022 | 3.609375 | 4 | import os
import numpy as np
import pandas as pd
class AslDb(object):
""" American Sign Language database drawn from the RWTH-BOSTON-104 frame positional data
This class has been designed to provide a convenient interface for individual word data for students in the Udacity AI Nanodegree Program.
For e... |
657a325906fecd7b706bcc9510d8d3d44ee2420f | Mutugiii/golclinics-dsa | /classwork/01/warm_up.py | 676 | 3.953125 | 4 | # Space complexity O(1)
def reverse_helper(A, start_index, end_index):
while start_index < end_index:
# Python Clever
# A[start_index], A[end_index] = A[end_index], A[start_index]
# Generic - Using a temporary variable for switch
temp = A[start_index]
A[start_index]... |
4b0e8971211845a0875bf88ba0b23d8ee16204a0 | devdgit/Simple_Python_game | /game.py | 1,134 | 4 | 4 | import random
class Game:
def __init__(self, name, bal):
self.name = name
self.bal =bal
def win(self):
winning = random.randint(1,10)
#self.bal += winning
print "You Won The Game. Points earned: " + str(winn... |
ba3360349707699f6dc244cda93def2efe175230 | hadoopaws8/English-letters-python-coding | /prime_numbers_limit.py | 243 | 4.03125 | 4 | lower=int(input("enter lower element: "))
upper=int(input("enter upper element: "))
for i in range(lower,upper):
if i>1:
for j in range(2,i):
if i%j==0:
break
else:
print(i)
|
5bcf10a630df1bba2580cd255aa92255f9062269 | hadoopaws8/English-letters-python-coding | /for_enumerate.py | 83 | 3.71875 | 4 | l=['a','b','c','d','e']
for i,j in enumerate(l):
print("index",i,"value",j)
|
d2f0b746fed613694a66a716a7b580d7d1219414 | hadoopaws8/English-letters-python-coding | /E_letter.py | 175 | 3.734375 | 4 | for i in range(5):
for j in range(4):
if (j==0 or i==0 or i==2 or i==4):
print("*",end="")
else:
print(end=" ")
print()
|
f0c289169c7eea7a8d4675450cda1f36b10c3baf | alexeydevederkin/Hackerrank | /src/main/python/min_avg_waiting_time.py | 2,648 | 4.4375 | 4 | #!/bin/python3
'''
Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant,
a customer is served by following the first-come, first-served rule, Tieu simply minimizes
the average waiting time of his customers. So he gets to decide who is served first,
regardless of how sooner or ... |
2bca2de382e9ee902062fdfdef87862fce473ec5 | LukeJVinton/pi-projects | /rpesk/morse_code.py | 3,114 | 3.609375 | 4 |
# 02_blink_twice.py
# From the code for the Electronics Starter Kit for the Raspberry Pi by MonkMakes.com
import RPi.GPIO as GPIO
import time
def word_separation(pin):
sleep_time = 7
GPIO.output(pin, False) # True means that LED turns on
time.sleep(sleep_time)
def pulse(pin, length = "dot"):
... |
6033592ae372bada65743cdb8cad06e78b5546a4 | EkataShrestha/Python-Assignment | /Assignment 1.py | 2,195 | 4.125 | 4 | print(" ASSIGNMENT-1 ")
"-------------------------------------------------------------------------------"
print("Exercise 1:---------------------------------------------------")
width = 17
height = 12.0
delimiter = '.'
##1. width/2:
print("answer number 1 (width/2) is:", width/2)
print( type(width/2) )
##2. wid... |
cc84e0ef270f72f7acf08475e170077d7f250080 | 16030IT028/smartinterviewspreperation | /checksubsequence.py | 734 | 3.703125 | 4 | """Given 2 strings A and B, check if A is present as a subsequence in B.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each line contains 2 space separated strings - A and B.
Constraints
1 <= T <= 1000
1 <= len(A), len(B) <= 1000
'a' <= A[i],B[i] <= 'z'
Output Format
F... |
146e6eebe52e4c88787f2e276ef58aa463dd6ccd | gemking/COMProj1- | /venv/Scripts/parsermodRevised1.py | 33,474 | 3.703125 | 4 | import sys
import re
with open(sys.argv[1], "r") as file: #opens file
filelines = file.read().splitlines() # reads file and splits lines
file.close() #closes file
insideComment = 0
keywords = ["if", "else", "while", "int", "float", "void", "return"] #denotes all keywords
symbols = "\/\*|\*\/|\+|-|\*|//|/|<=|<... |
2b1ca91c21fffbb99c3dc411fd9d507df9923096 | vccabral/crashncompile | /parse_inputs.py | 730 | 3.515625 | 4 | #!/Users/bracero/code/crashncompile/venv/bin/python
from sys import stdin
remove_new_lines = True
split_by_char = True
special_character = "#"
remove_empty_last_cell = True
remove_all_empty = True
def get_rid_of_newlines(str1):
return str1[0:-1]
def split_by_special_char(str_arr):
accum ... |
90b380c2f84d1b9d56d68224aaae9d58e31ae7ba | Sammyuel/LeetcodeSolutions | /islands2.py | 1,558 | 3.921875 | 4 | from collections import deque
class Solution(object):
def append_if(self, queue, x, y):
"""Append to the queue only if in bounds of the grid and the cell value is 1."""
if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):
if self.grid[x][y] == '1':
queue.append((x... |
7f39eac47889ee3645f3f99610784fb3d1ccbb6b | Sammyuel/LeetcodeSolutions | /reorderlist.py | 983 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
if not head or not head.next:
return
slow = head
fast = head.next
previoous ... |
e3064817ccf6b20632485a1c1cd52864d3dfc6fe | felipesavaris/pythonstuds | /s3.3-coleçoes-python/a26-listas.py | 3,162 | 4.34375 | 4 | """
listas -> são como vertores/matrizes;
são dinâmicas e podem armazenar qualquer tipo de dados
listas aceitam repetição
ex: lista = []
"""
# funções interessantes:
"""
# verificar se valor está contido na lista
num = 8
if num in lista_4:
print(f'{num} -> Número encontrado.')
else:
print(f'{num} -... |
767125d9ac4d1bee62d953f2f20bc49740d7a4fa | xlii0064/algorithms | /year2/dijkstra/roadPath.py | 23,454 | 4.0625 | 4 | class Vertex:
def __init__(self,u):
"""
Functionality of the function is to make instance of vertex
Time complexity:O(1)
Space complexity:O(1)
Error handle:None
Precondition:u must be a number
:param u: the index number of the vertex to be made
... |
ff9f8aa35da14934dc7976be668bda7c6e757374 | leandrohl/python-image-processing | /6-suavizacao/suavizacao_pela_media.py | 1,993 | 3.84375 | 4 |
'''
A suavisação da imagem (do inglês Smoothing), também chamada de „blur‟ ou
„blurring‟ que podemos traduzir para “borrão”, é um efeito que podemos notar nas fotografias
fora de foco ou desfocadas onde tudo fica embasado.
Esse efeito é muito útil quando utilizamos
algoritmos de identificação de objetos em im... |
c2f0c31e5223eaec9db32e80a267e942ae66710e | mousexjc/basicGrammer | /org/teamsun/mookee/faceObject/011staticMethod.py | 410 | 3.5625 | 4 | """
静态方法:类和对象都可以调用静态方法
和普通的函数没什么区别
"""
class StudentB:
param1 = "param1"
def __init__(self):
pass
# 加 @staticmethod 装饰器即可
@staticmethod
def testStaticMethod(stra):
print("This is a static method:" + stra)
stu = StudentB()
stu.testStaticMethod("object")
StudentB.testSt... |
ee92f82c3045780e90ec02a533f0f3d86921b3cb | mousexjc/basicGrammer | /org/teamsun/mookee/basic/006dict.py | 667 | 4.09375 | 4 | """
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
"""
dictVar = {"a": "av", "b": "bv", 3: "cv"}
print(dictVar[3])
var1 = {"a": 1, 2: 2, 3: "c", "4": dictVar}
print(var1["4"])
var2 = {1: "a"... |
2b82cd1ea8697747b28486a7987f99dceea7775a | mousexjc/basicGrammer | /org/teamsun/mookee/senior/c012_1funcType.py | 452 | 4.53125 | 5 | """
Chapter 12 函数式编程
匿名函数
格式:lambda param_list: expression
lambda:关键字
expression * :只能是【表达式】
"""
# 正常函数
def add(x, y):
return x + y
f = lambda x, y: x + y
print(f(2, 3))
print("=====================")
# 三元表达式
# 其他语言:表达式 ?true结果 : false结果
# Python : true结果 if 表达式 else false结果
x = 1
y = 2
a =... |
ab23dfabe747fc2f15041233ef96da9b1f830f84 | hiyouga/cryptography-experiment | /MyCrypto/utils/galois_field.py | 5,015 | 3.625 | 4 | class GF: # A python implementation of Galois Field GF(2^n)
def __init__(self, data, order):
assert isinstance(data, int)
self.data = data
self.order = order
if order == 1:
self.modulo = 0b10 # x
elif order == 2:
self.modulo = 0b111 # x^2+x+1
... |
3aec5f005f09c98d7645a691961960a1f75b6cc7 | pite2019/pite2019s-t1-g1-davidegualandris | /task.py | 1,720 | 4.03125 | 4 | class Matrix:
""""
Defining the constructor
ul = upper left
ur = upper right
bl = below left
br = below right
"""
def __init__(self, ul, ur, bl, br):
self.__ul = ul
self.__ur = ur
self.__bl = bl
self.__br = br
# Getters and setters
def get_ul(sel... |
dc7d915b87aeed1779e5a0095074238868701201 | avisek-3524/Python- | /gcd.py | 245 | 3.96875 | 4 | ''' write a program to print the gcd of the two numbers'''
a = int(input('enter the first number '))
b = int(input('enter the second number '))
i = 1
while(a >= i and b >= i):
if(a%i==0 and b%i==0):
gcd = i
i = i+1
print( gcd ) |
2e86e6d499de5d51f19051728db135aac6b36044 | avisek-3524/Python- | /oddeven.py | 260 | 4.1875 | 4 | '''write a program to print all the numbers from
m-n thereby classifying them as even or odd'''
m=int(input('upper case'))
n=int(input('lower case'))
for i in range(m,n+1):
if(i%2==0):
print(str(i)+'--even')
else:
print(str(i)+'--odd') |
3d3513f1520a98a06f7047699c4bee78d6e4a00f | carolinesekel/caesar-cipher | /caesar.py | 361 | 4.34375 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
#shift by 5
cipher = "fghijklmnopqrstuvwxyzabcde"
input_string = input("What would you like to encrypt? ")
print("Now encrypting ", input_string, "...")
encrypted = ""
for letter in input_string:
position = alphabet.index(letter)
new_char = cipher[position]
encrypt... |
d52653878c95ab7502a7f1a7a97e3d38040951aa | Athul8raj/Main-Repo | /Deep Learning/Tensorflow tutorials/Tensorflow with mnist data.py | 2,354 | 3.609375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data/',one_hot=True)
n_nodes_hl1 = 512
n_nodes_hl2 = 1024
n_nodes_hl3 = 512
n_classes = 10
batch_size = 100
x = tf.placeholder('float',[None,784])
def neural_network(data):
hidden_layer_1 ... |
b39dc36b9df1aba9fed2f1958c4f73e79c152ac9 | geforcexfx/arrayDub | /exercise1.py | 903 | 3.671875 | 4 |
def eliminate( numbers,n ):
endLoop = False
num = 0
new_number = []
#dictionary to store the time of a number appears in the array
dictionary = dict([])
for i in range(0,len(numbers)):
#if the number found in dictionary, increase the count
if numbers[i] in dictionary.keys():
... |
8c6e920238d869d8a98aee888acec584a95dc6d9 | tomduhourq/p4e-coursera | /src/Week05/min.py | 159 | 3.75 | 4 | from src.Week05.list_helper import create_list
min = None
for elem in create_list('min'):
if min is None or elem < min:
min = elem
print 'smallest is ',min |
1286812346feeb6a75e2ff7ecd5f265c851690af | tomduhourq/p4e-coursera | /src/DictPractice/examples.py | 807 | 3.578125 | 4 | __author__ = 'tomasduhourq'
import string
from src.FilePractice.file_helper import choose_file
# Sorting the keys of a dict
counts = {'chuck': 1, 'annie': 42, 'jan': 100}
# Create a list of the keys in the dict
def sort_keys(d):
keys = d.keys()
keys.sort()
for key in keys:
print key, d[key]
sort... |
b06ea463ef5033368b8f97c0097b09a16a76adef | saloni2805/Assignment-Submission | /ASS1/Ass1Q2.py | 66 | 3.515625 | 4 | x=5
y=((x^2+5*x+6)/(2*x+5))
print('Result= ',y)
#Result= 2.4 |
b1dd62f0e1927d1fb553f3426eac22a79ad655d1 | voidbeast6/voidbeast6 | /comps209fproject/comps209fprojectV1.1/comps209fproject/MC.py | 9,939 | 3.515625 | 4 | #
#created by Lewis
#finished on 3rd May 2021
#
import tkinter as tk
import random, string
class MultipleChoice(tk.Tk):
def __init__(self, *args, file = "words.txt"):
tk.Tk.__init__(self, *args)
self.width=800
self.height=600
self.geometry(str(self.width)+"x"+str(self.... |
8ffef9d61aeb24f3348195bc09b765ed61262f67 | AyseErdanisman/PythonProgramlamaKursu | /6.8_uygulama-sayi-tahmin.py | 1,006 | 3.765625 | 4 | """
1 - 100 arasında üretilecek bir sayıyı aşağı yukarı ifadeleri ile bulmaya çalışınız:
* 'random' modülü için rangom araştırması yapınız.
** 100 üzerinden puanlama yapınız. Her sor 20 puan olacaktır.
*** Hak bilgisini kullanıcıdan alın ve her soru belirtilen can sayısı üzerinden hesaplansın.
"""
import random
sayi... |
b4bcc71a567588ce3a87f18f75846f2cc3631c40 | AyseErdanisman/PythonProgramlamaKursu | /3.18_uygulama-dictionary-demo.py | 1,871 | 3.5 | 4 | """
ogrenciler ={
"120": {
"ad": "Ali",
"soyad": "Yılmaz",
"telefon": "1231 231 23 12"
},
"125": {
"ad": "Can",
"soyad": "Korkmaz",
"telefon": "1231 123 12 12"
},
"128": {
"ad": "Volkan",
... |
1fdb39656d8df970aab30707d5dfcfc08bbb1486 | AyseErdanisman/PythonProgramlamaKursu | /4.5_matiksal-operatorler.py | 536 | 3.828125 | 4 | x = 6
hak = 5
devam = 'e'
result = 5 < x < 6
# and
result2 = (x > 5) and (x < 10)
# koşulun her iki durumu da doğru olursa ture değerini döndürür
print(result2)
result3 = (hak > 0) and (devam == 'e')
print(result3)
# or
result4 = (x > 0) or (x % 2 == 0)
# true deger için ifadelerden sadece birinin true olması yeter... |
5b05a8ac8d51f8e784eda8064088dfcf5cf877dc | AyseErdanisman/PythonProgramlamaKursu | /3.11_uygulama-string-metotlari.py | 3,167 | 4.0625 | 4 | website = "http://www.sadikturan.com"
course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 Saat)"
# 1- " Hello word " karakter dizisinin baştaki ve sondaki boşluk karakterlerini silin
# result = " Hello word "
# result = result.strip()
# result = result.lstrip() --> left stript
# result = result.rstri... |
a0ac1bd7ae21e0cc2bbe1cb66425903ec03fea6d | AyseErdanisman/PythonProgramlamaKursu | /4.2_uygulama-atama-operatoleri.py | 785 | 3.875 | 4 | x, y, z = 2, 5, 107
numbers = 1, 5, 7, 10, 6
# 1- kullanıcıdan aldığınız 2 sayının çarpımı ile x,y,z nin toplamı kaçtır?
a = input("ilk degeri giriniz: ")
b = input("ikinci degeri giriniz: ")
c = int(a) * int(b) + (x+y+z)
print(c)
# 2- y'nin x'e kalansız bölümünü hesaplayınız
print(y // x)
# 3- (x,y,z) toplamının ... |
f9a87ecc31ca17ed6bbeda260a84ea5a60e59937 | Thyrvald/MinimaxAlgorithm | /main.py | 3,772 | 3.609375 | 4 | from functions import *
import timeit
def main():
tic_tac_toe_tree = make_tree()
minimax_search_depth1 = 2
minimax_search_depth2 = 4
minimax_search_depth3 = 6
minimax_search_depth4 = 10
x = []
o = []
d = []
for i in range(6):
x.append(0)
o.append(0)
d.append... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.