blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5cdf628644e7b70b84559de0a8cec6b58cb3df58 | Israelfluz/Tensorflow-e-Deep-learn-com-python | /redes neurais artificiais/rna classificação regressão/mnist.py | 4,351 | 3.890625 | 4 | # ====== Construção de uma rede neural para fazer a classificação dos dígitos de 0 até 9 =====
# Importando para o tensorflow
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('mnist/', one_hot = True)
# Carregando os dados da pasta mnist/
x_treinamento = mnist.train.ima... |
cbe8c45e8b2524afdf228819cef51ee154d111c7 | saikhurana98/dist_search | /src/search/search.py | 648 | 3.765625 | 4 | import sqlite3
import json
with open ('../src/Data/index.json') as f:
index = json.load(f)
def main():
filepath = os.path.join('../src/Data/Movie.db')
conn = sqlite3.connect(filepath)
c = conn.cursor()
c.execute("SELECT id FROM Movie;")
data = c.fetchall()
def lookup_tags(output):
output ... |
97cd293823ba4efda41d404e553f495f754662dd | senorhimanshu/Machine-Learning | /simple_perceptron.py | 1,013 | 4.3125 | 4 | # Single Layer Perceptron Learning Rule : OR Gate Example
# https://blog.dbrgn.ch/2013/3/26/perceptrons-in-python/
from random import choice
from numpy import array, dot, random
from pylab import plot, ylim
# unit step as an activation function by using lambda
unit_step = lambda x: 0 if x < 0 else 1
# training d... |
093805341f15883a14f84aa573e67e426fbba5f4 | shivhudda/python | /29_Writing_And_Appending.py | 597 | 3.984375 | 4 | # write mode
f = open('29_myfile.txt', 'w')
a = f.write('lorem ipsum dollar sit amet.\n')
f.write('shivhudda')
'''There is a certain limitation to the write mode of the opening file that it overrides the existing data into the file.'''
print (a) #its return number of written characters
f.close()
# append mode ... |
9b9752def360e0c4b010c3b10923e76eb942a52e | dlrgy22/Boostcamp | /2주차/2021.01.27/예제/data_selection.py | 499 | 3.53125 | 4 | import pandas as pd
import numpy as np
df = pd.read_excel("./excel-comp-data.xlsx")
print(df.drop("name", axis=1))
print(df.head(2).T)
print(df[["account", "street", "state"]].head())
account_series = df["account"]
print(df[account_series > 200000])
df.index = df["account"]
print(df[["name", "street"]].iloc[:2])
m... |
a3b1d6f474ae20024f776352b448b260c509578c | gx20161012/leetcode | /easy/MajorityElement.py | 700 | 3.9375 | 4 | '''
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
'''
class Solution:
def majorityElement(self, nums):
"""
:type nums: List... |
ad52a9db50b57d5d97b7ce78c8ab652658971b43 | addriango/curso-python | /sintaxis-basica/12.bucles-for.py | 827 | 4 | 4 | ## los bucles nos ayudan a ejecutar codigo repetitivo en pocas lineas
##esto no es eficiente
print ("hola mundo")
print ("hola mundo")
print ("hola mundo")
print ("hola mundo")
print("")
##esto si es eficiente
##bucle determianado (sabemos cuantas veces se va a realizar)
for cadaNumero in range(4):
print (cadaNu... |
4e5fddbf7083e669b03145877ccc7160a1834c08 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.4C.py | 515 | 4.3125 | 4 | # Write list functions that carry out the following tasks for a list of integers. For each
# function, provide a test program.
# c. Replace all even elements with 0.
# FUNCTIONS
def replaceEven_with_Null(list):
for i in range(len(list)):
if list[i] % 2 == 0:
list[i] = 0
return list
#... |
d6fdf35d255b315fbf9bb85495feff0ff6c42d45 | petrooha/NLP-notes | /Computing with NL/All Preprocessing in one function (HTML tags, lowerase, non-letters, stopwords, stem, tokenize).py | 1,092 | 3.75 | 4 | # BeautifulSoup to easily remove HTML tags
from bs4 import BeautifulSoup
# RegEx for removing non-letter characters
import re
# NLTK library for the remaining steps
import nltk
nltk.download("stopwords") # download list of stopwords (only once; need not run it again)
from nltk.corpus import stopwords # im... |
f0c1934711d886f6221b0fdf7b4f22fd412305bb | Achyu02/20176081 | /String matching 2 - Copy.py | 2,102 | 4.03125 | 4 | import os
class stringM(object):
'''
class stringM consists of multiple methods used to calculate plagiarism
for multiple files
'''
def __init__(self,arg):
'''Initializer automatically calls when you create a new instance of class'''
self.arg=arg
def pieces(p1):
'''
Input : files
funct... |
a4cb7edd17e6954a1dc7d383d5a96d835379d1d3 | shannonmlance/leetcode | /solved/removeLinkedListElements.py | 3,271 | 3.96875 | 4 | # Remove all elements from a linked list of integers that have value val.
# Example:
# Input: 1->2->6->3->4->5->6, val = 6
# Output: 1->2->3->4->5
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
# set the front... |
163ceba2642904c3f169c0ce9b0fec77af58265b | m-j-hacker/Data-Structures | /doubly_linked_list/doubly_linked_list.py | 3,818 | 4.40625 | 4 | """Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this no... |
e74da0c57f093e3799de94d741e8c2e098a39b54 | graphql-python/graphql-core | /tests/utils/gen_fuzz_strings.py | 378 | 3.59375 | 4 | from itertools import product
from typing import Generator
__all__ = ["gen_fuzz_strings"]
def gen_fuzz_strings(allowed_chars: str, max_length: int) -> Generator[str, None, None]:
"""Generator that produces all possible combinations of allowed characters."""
for length in range(max_length + 1):
yield... |
55630d6a3badf0e38d4fadba96a646aa11059733 | voitenko-lex/leetcode | /Python3/30-day-leetcoding-challenge/week-6/Trie.py | 3,909 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns tru... |
8d8abd496e64a683dd12d2e0ab8f48e8c863be03 | Iftikhar-Shams-Niloy/URI-Python-Solutions | /URI 1116.py | 204 | 3.625 | 4 | N = int(input())
i = 0
while i < N :
X,Y = list(map(int,input().split(" ")))
if Y == 0:
print("divisao impossivel")
else:
result = X/Y
print(result)
i += 1 |
f52cb677fa25db780c5c10eb36bfcf9207846ed5 | yahaa/Python | /basis/com/zihua/test5.py | 266 | 3.671875 | 4 | import datetime
time=raw_input('Enter a date (mm/dd/yyyy):')
moth=['January','February','March','April','May','June','July','August','Septemper','October','November','December']
t=time.split('/')
print ' The converted date is: '+moth[int(t[0])-1]+' '+t[1]+', '+t[2]
|
b77661631958f0470fa7edc41158aff28de06489 | yw9142/Solving-algorithmic-problems | /Programmers/Level1/나누어 떨어지는 숫자 배열.py | 323 | 3.609375 | 4 | def solution(arr, divisor):
possible_divide = []
for i in arr:
if i % divisor == 0:
possible_divide.append(i)
if len(possible_divide) == 0:
possible_divide.append(-1)
return possible_divide
else:
possible_divide.sort()
return possible_divid... |
e4af45c0d40bbb305fe35f2eeceeedc45ef579ec | aminhp93/python_fundamental | /strings.py | 589 | 4.4375 | 4 | print "this is a sample string"
name = "Zen"
print "my name is " + name
first_name = "Zen"
last_name = "coder"
print "My nameis {} {}".format(first_name, last_name)
my_string = 'hello world'
print my_string.capitalize()
my_string = "HELO WEOflD"
print my_string.lower()
my_string = "Hello WORLD"
print my_string.swapc... |
d4723e2fdeff34b0646f42985161b592d35c8493 | ananthuk7/Luminar-Python | /Django tut/functionalprograming/lamdafunction.py | 1,554 | 3.640625 | 4 | # lamda function
# def add(num1,num2):
# return num1+num2
#
# print(add(5,6))
#
# add = lambda num1, num2: num1 + num2
# print(add(5,6))
# lst = [1, 2, 3, 4, 5, 6, 7]
# sq=[]
# for i in lst:
# sq.append(i**2)
# print(sq)
# map(function,itreatable)
# def square(num1):
# return num1 ** 2
#
#
# squares ... |
dd2213bf157aaebd1207803e0db0e0ba75bc54c4 | caimimao/project-euler | /200/112.py | 1,396 | 3.5 | 4 | # -*- coding: utf-8 -*-
__title__ = "Bouncy numbers"
def solve():
from common import log
def get_non_bouncy_number(n):
ff = [0] + range(9, 0, -1)
gg = [9] + range(9, 0, -1)
s = 99 # 1-99 are non bouncy
m = 3
while m <= n:
# f(m, 0) = 0
... |
873818b49699745fdbc4cfd161f583f811d19833 | RafaelBuchser/Chess-AI | /WeakMiniMaxEngine.py | 1,041 | 3.734375 | 4 | from MiniMaxEngine import MiniMaxEngine
from King import King
""" This class is a subclass of the MiniMax-engine. The only difference between the other engine is the
evaluation function. To evaluate a position it just adds up the values of the pieces. The more pieces from the opposite
player are missing the higher ev... |
30f05b9424ba6455656abb0265b3227546e4980b | Sjaiswal1911/PS1 | /python/functions/basics.py | 928 | 4.15625 | 4 | # functions
# is a block of organised, reusable code to perform a single , related action
# syntax
# def functionname( parameters ):
# "function_docstring"
# function_suite
# return [expression]
# Defining a function
def printme( str ):
"This prints a passed string into this function"
print (str)
r... |
c99641bcb8fcd5093dcc2e5d8bf6523b515f7bea | rahul-gopinath-datapsych/python_coursera | /Python/asgn11_dictionary.py | 1,430 | 3.546875 | 4 | # Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates
# a Python dictionary that maps the sender's mail address to a coun... |
547668609a94be048112b0545b96416d76a799a6 | surajbnaik90/devops-essentials | /PythonBasics/PythonBasics/PickleAndShelves/pickle1.py | 1,349 | 4 | 4 | #Using 'Pickle' to write binary files
#Imp Note : Pickle make use of protocols while dumping and reading data.
import pickle
tupleObject = ('Microsoft', 'Azure', 'Satya Nadella')
with open("testfile.pickle","wb") as pickle_file:
pickle.dump(tupleObject, pickle_file)
#Read the binary file
with open("testfile.pi... |
6ab06c31c438166533c8b96c098041c8de516328 | tellefs/ML-projects | /project3/src/neuralnetwork.py | 6,686 | 3.75 | 4 | import numpy as np
from .activation_functions import *
class NeuralNetwork:
def __init__(
self,
X_data,
Y_data,
n_hidden_layers = 1,
n_hidden_neurons=[50],
n_categories=1,
epochs=1000,
batch_size=5,
eta=0.00... |
5e8f51f22f2b539125dbab79cc3c0c55cb9ec763 | Rlizaran/python-challange | /PyPoll/main.py | 2,346 | 3.96875 | 4 | import os
import csv
# main function
def main():
# This path goes to the directory Resources and select the budget_data.csv file
filepath = os.path.join('Resources', 'election_data.csv')
totalVotes = []
candidates = []
votes = [0, 0, 0, 0]
# Opens csv file as read mode
with open(filepath, '... |
e8ddec968c9ccf4fff6913d9cbd579cdd9ad3587 | djaychela/playground | /codefights/arcade/python/drilling_the_lists/math_practice.py | 204 | 3.671875 | 4 | import functools
def mathPractice(numbers):
return functools.reduce(lambda acc, x: (acc + x[1] if x[0] % 2 else acc * x[1]), enumerate(numbers), 1)
print(mathPractice(numbers=[1, 2, 3, 4, 5, 6]))
|
f9e6c2763170012b96dedc094e95fd1d29e80892 | krishnadhara/my-programs | /krishna/Reddy/python/function_utilities.py | 1,540 | 3.765625 | 4 | #map,filter,reduce
#map(function_object,iterable1,iterable2)
def mul(x):
return x*2
c=mul(4)
print(c)
a=map(lambda x:x*2, [1,2,3,4])
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(list(map(lambda x:x*2, [1,2,3,4])))
dict=[{'name':'python','points':10},{'name':'java',"points... |
3dd24143907bf4ca535d5d96c22eb812705ed693 | MaryanneNjeri/pythonModules | /.history/repeated_20200903104547.py | 520 | 3.890625 | 4 | def repeated(s):
# soo umm we supposed to check if the string can be
# made from its substring
if len(s) == 0:
return False
n = len(s)
for i in range(n// 2,0,-1):
newStr = s[0:i]
print(new)
count = 1
while len(newStr) <= n:
newStr = s[0:... |
8729f7ed2327a1a9b47466aa749ea7e7d235badc | prathammehta/interview-prep | /SumOfIntegers.py | 354 | 4.125 | 4 | # https://www.geeksforgeeks.org/ways-to-write-n-as-sum-of-two-or-more-positive-integers/
def sum_of_integers(num):
possibilites = [0 for _ in range(num + 1)]
possibilites[0] = 1
for i in range(1,num):
for j in range(i, num+1):
possibilites[j] = possibilites[j] + possibilites[j - i]
pass
return possibilite... |
e7cf1b9bc1fe5ee8bb6aff718c325abe51c58695 | banana-galaxy/challenges | /challenge4(zipcode)/PinkFluffyUnicorn.py | 282 | 3.6875 | 4 | def validate(zipCode):
if isinstance(zipCode,int) and len(str(zipCode)) == 5:
s = str(zipCode)
temp = [a for a, b in zip(s, s[2:]) if a == b]
if len(temp) == 0:
return True
else:
return False
else:
return False |
4583b4a5c68b8611fb890659847fa3b649ebee8f | AAliAbidi/Python-Code | /01_Welcome.py | 100 | 3.78125 | 4 | # print("Hey now brown cow")
x = input("Enter name: ")
print ("Hey " + x)
input("Press<enter>")
|
ca80ac09b2bc16e7b996ef0210b6115a5585a0db | MysteryMS/tpa-lista5 | /ex07.py | 221 | 3.828125 | 4 | n1 = int(input("Insira o primeiro número: "))
n2 = int(input("Insira o segundo número: "))
inter = []
count = n1+1
while count < n2:
inter.append(str(count))
count += 1
print(f"Resultado: {' '.join(inter)}")
|
0eebdf5a25bac022805349f549c6a5cdac5e521b | mcwills-clemson/Darknet | /CityScapes_Conversion/scripts/pyscript.py | 1,396 | 3.578125 | 4 | #Pseudo Code for Python OpenCV Bounding Boxes
# Courtesy of Carlos Piza-Palma
import cv2
import numpy as np
#import image
#note: you may wish to make copies of the original image as
# some functions are destructive.
################Part I Masks#############################################
#Use masks to extract onl... |
d941a98bcaae0dc7d40d0ec6fce1b84c382267b5 | FreddyBarcenas123/Python-lesson-2- | /Excercise2.py | 215 | 4.15625 | 4 | #FreddyB-Exercise 3: Write a program to prompt the user for hours and rate per hour to compute gross pay.
print("Enter hours:")
print("Enter Rate:")
print("Pay:")
Hours = "35"
Rate = "2.75"
Pay = "96.25"
|
625414b6cab5f9919c4a89c7e82bff7a77853c36 | mkd/uic_cli | /main.py | 4,291 | 3.953125 | 4 | #!/usr/bin/python
# Valeriy Volodenkov, Eva Rio, Claudio M. Camacho
# T-121.5300 User Interface Construction
# Aalto University, School of Science
import sys
import sqlite3
ERROR_OPTION_DOES_NOT_EXIST = 991
DB = "products.db"
# keep the number of items in the current cart
items = [ ]
shopping_cart = { }
#goods fetc... |
c5fc5a6b6a323f1857703c975e6aaf4aaa2b427b | Distributed-SLSH/Distributed-SLSH | /distributed_SLSH/middleware/utils/generate_data.py | 2,081 | 3.53125 | 4 | '''
File containing the methods to generate datasets and store them into files.
'''
import numpy as np
import sys
def generate_identity(D, folder, prediction=False):
"""
Generate identity matrix.
:param D: dimensionality
:param folder: folder to store the dataset to
:return: nothing
"""
... |
5c246326341f131f989831cd5c69f7e1308d89dd | poojaisabelle/python-challenge | /PyBank/main.py | 3,081 | 4 | 4 | # Import modules
import os
import csv
# Set the path to input the budget_data.csv
budget_data = os.path.join("Resources", "budget_data.csv")
# Open input csv and read
with open(budget_data, "r", encoding="utf-8") as input_csv_file:
csvreader = csv.reader(input_csv_file, delimiter = ",")
# Skip the header r... |
f7133938af39b35af3692bff0b98a7f962d7863e | mfguerreiro/Python | /Introdução/ex1Aula6.py | 275 | 4.03125 | 4 | n = int(input("Digite um número:"))
while n >= 0:
if n == 0:
print("1")
else:
fatorial = n
i = n - 1
while i > 1:
fatorial = fatorial * i
i -= 1
print(fatorial)
n = int(input("Digite um número:"))
|
f0388e36939ac32be0300373efba7a1bcaa350c1 | Built00/Leetcode | /Populating_Next_Right_Pointers_in_Each_Node_II.py | 1,503 | 4.3125 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# Follow up for problem "Populating Next Right Pointers in Each Node".
# What if the given tree could be any binary tree? Would your previous solution still work?
# Note:
# You may only use constant extra space.
# For example,
# Given the following binary tree,
# ... |
8622bb61191de9577b9544e9485393e9e8283b1b | tcoln/NowCoder | /阿里链表中间元素2.py | 733 | 3.796875 | 4 | class Node(object):
def __init__(self, val):
self.data = val
self.next = None
def print_middle_element(head):
if not head:
return None
p1 = None
p2 = head
while p2 and p2.next:
if not p1:
p1 = head
else:
p1 = p1.next
p2 = p2.next.next
if p2... |
a74696e2da9b0d16c4630b3ca96f3bd8de69aea8 | waitingliu/notes | /python/using_dict.py | 288 | 3.53125 | 4 |
ab = {
'liu':'huantian',
'yang':'peng',
'wang':'binghua'
}
xing = raw_input('input a xing:')
if xing in ab:
print ab[xing]
else:
print 'not exists..'
ab['li'] = 'bian'
print 'add li:',ab
del ab['wang']
print 'del wang:',ab
for xing,ming in ab.items():
print '%s-%s' %(xing,ming)
|
de89c0be8b3461e0292f51aed71f898df9d3d9f1 | spametki/web3py | /web3py/storage.py | 920 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`, and setting obj.foo = None deletes item foo.
>>> o = Storage(a=1)
>>> print o.a
1
>>> o['a']
1
... |
0b953fa66505720a02408992fd0785089aed4295 | facu2279/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 258 | 3.53125 | 4 | #!/usr/bin/python3
""" my_int"""
class MyInt(int):
"""Class MyInt"""
def __init__(self, xd):
"""iniciar"""
self.xd = xd
def __eq__(self, xd):
return self.xd != xd
def __ne__(self, xd):
return self.xd == xd
|
052f2f2133ece64fe3a78041fc1731e65fbcba9b | gordonli08/Exercism-python | /perfect-numbers/perfect_numbers.py | 411 | 3.578125 | 4 | import math
def classify(number):
if number < 1:
raise ValueError("Not a natural number")
maxfactor = math.floor(math.sqrt(number))
aliquot = 0
for i in range(1,maxfactor + 1):
if number % i == 0:
if i * i == number:
aliquot += i
else:
aliquot += i + (number/i)
aliquot -= number
if aliquot ... |
e30be62bc9c2b884bdaae8bd821e210d914a729c | bluerosinneo/Three-Fair-Dice | /threeFairDice.py | 2,558 | 3.765625 | 4 | # python 2.7
# This code explores the likelihood of repeated results when rolling three fair sixe-sidded dice four times
rolls = {}
for x in range(3,19):
rolls[x]=0
for i in range(1,7):
for j in range(1,7):
for k in range(1,7):
result = i+j+k
rolls[result]=rolls[result]+1
print "Probabilities of rolling r... |
0e56874eb80d811e80cd528da495c265949d4250 | toshi09/algorithms | /Determine_string_has_unique_characters.py | 308 | 3.84375 | 4 | def unique(input_string):
sort_input = sorted(input_string)
unique_found = True
for idx in range(len(sort_input)-1):
if sort_input[idx] == sort_input[idx + 1]:
unique_found = False
else:
continue
return(unique_found)
unique('ashwani')
|
e384ed2670512ff1840e2ecd207dc26edb0dc253 | RoyMcCrain/Mastering-Vim | /Chapter06/animal_farm.py | 753 | 3.921875 | 4 | #!/usr/bin/python3
"""Our own little animal farm."""
import sys
from animals import cat
from animals import dog
from animals import sheep
import animal
import farm
def make_animal(kind):
"""Create an animal class."""
if kind == 'cat':
return cat.Cat()
if kind == 'dog':
return dog.Dog()
... |
93da8269b535c894a7c685c65107551da3baa692 | pytutorial/samples | /_summary/2.if/s21.py | 215 | 3.515625 | 4 | # Nhập vào 2 số, in ra số lớn hơn
a = input('Số thứ nhất:')
b = input('Số thứ hai:')
a = float(a)
b = float(b)
if a > b:
print('Số lớn hơn:', a)
else:
print('Số lớn hơn:', b) |
a0176c0ca1e9626eb18cfccc5304198eb9a96dac | k-yama007/python3 | /Myclass.py | 1,133 | 4.1875 | 4 | class Myclass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
class Dog:
kind = 'canine' #class variable shared by all instances
#dell_k_yama007 tricks = []
def __init__(self,name):
self.name = name #instance variable unique to each... |
2fd34cd90ae558c49d3c03b2da62e0757c00a08e | harvey345/B-S | /BS.py | 206 | 3.9375 | 4 | num1=float(input("請輸入數字 : "))
num2= float(input("請輸入數字 : "))
if num1>num2:
print(num1,">",num2)
if num1<num2:
print(num1,"<",num2)
if num1==num2:
print(num1,"=",num2) |
16c20c578c9a0f464bf687e7080857082c0e0fad | felixkiptoo9888/Cafe | /frontend/lesson3.py | 633 | 4.34375 | 4 | # dictionary stores data using key/ value approach
# mostly used to store an object data in json format: ie car details
person = {'name': 'Ken',
'age': 22,
'residence': 'nairobi',
'weight': 72.5,
'height': 1.5,
'email': 'ken@gmail.com',
'marks': 410}
print(per... |
ba1175394d2562d42e4d73631debba07c4ab18b7 | Beardocracy/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py | 6,769 | 3.609375 | 4 | #!/usr/bin/python3
''' This module tests the rectangle class '''
import unittest
import sys
from models.rectangle import Rectangle
from models.base import Base
class TestRectangle(unittest.TestCase):
''' This is a unittest for class rectangle '''
def setUp(self):
''' Resets the class variable'''
... |
2516a933b33775fdc298d7ff208bd549331d650b | ChineseKawhi/Data-Structures-and-Algorithms | /LinkList/SkipList.py | 4,563 | 4.09375 | 4 | """
A skip list implementation.
Skip list allows search, add, erase operation in O(log(n)) time with high probability (w.h.p.).
"""
import random
class Node:
"""
Attributes:
key: the node's key
next: the next node
prev: the previous node
bottom: the bottom node in skip l... |
db85f9a280842c3c641bd5d77e55b8b7a6f0469c | smithajanardan/janardan_python | /CalcSqrt.py | 692 | 3.96875 | 4 | # File: CalcSqrt.py
# Description: Determining the square root of a poistive integer.
# Student Name: Smitha Janardan
# Student UT EID: ssj398
# Course Name: CS 303E
# Unique Number: 52220
# Date Created: 09-29-10
# Date Last Modified: 09-29-10
def main():
n = input ("Enter a positive... |
d301d8b7c002bf4a0e13825d9ef08f45594dd7a4 | Frky/p-euler | /src/p61.py | 4,130 | 3.9375 | 4 | #-*- coding: utf-8 -*-
from p import Problem
from toolbox import is_triang, is_square, is_pent, is_hexa, is_hepta, is_octa
class p61(Problem):
"""
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal
numbers are all figurate (polygonal) numbers and are generated by the
fo... |
0fc5d9365d0c7af606aca1b95b9d8f9664dcb818 | frclasso/FCGurus_python1_turma_novembro2019 | /Cap09_estruturas_de_dados/9.4_tuplas/script1.py | 2,397 | 3.5 | 4 |
# tuplas
# tupla vazia
tupla_vazia =()
print(f'Tipo: {type(tupla_vazia)}')
# tupla de um elemento
tupla_de_um_elemento = (50, ) # <====
print(f'Tipo: {type(tupla_de_um_elemento)}')
# ou
tupla_de_um_elemento_sem_parenteses = 50,
print(f'Tipo: {type(tupla_de_um_elemento_sem_parenteses)}')
# Acessando valores
curso... |
02bc2eb8476f2dc28cf62865c08741b2087e8c94 | oliverralbertini/euler | /003/solution.py | 560 | 3.953125 | 4 | """Problem 3: Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"""
import sys
import math as m
sys.path.append('../modules')
from isprime import is_prime
from prime_factorization import prime_factorization
"""find out the largest prime f... |
39358e75284d42b875ef5809e50838561e18af96 | AdrienGuille/EGC-Cup-2016 | /ciprian/utils.py | 878 | 3.53125 | 4 | # coding: utf-8
__author__ = "Ciprian-Octavian Truică"
__copyright__ = "Copyright 2015, University Politehnica of Bucharest"
__license__ = "GNU GPL"
__version__ = "0.1"
__email__ = "ciprian.truica@cs.pub.ro"
__status__ = "Production"
import csv
import codecs
#author field parse
def getAuthorName(text, ch = ','):
... |
b4b00c410bacf2f1aaa7c969670245c13d241e7a | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_156/828.py | 1,848 | 3.6875 | 4 | f = open('input.txt', 'r')
def function(pancakes, t):
# a = 6
# if t == a:
# print(pancakes)
# # print('pancakes',pancakes)
biggest = pancakes[-1]
indexOfBiggest = pancakes.index(biggest)
numberOfBiggestPancakes = len(pancakes)- indexOfBiggest
time = 0
# print(numberOfBiggestPancakes)
while pan... |
6000a48c25d77b6e671d02904460008ae9384761 | EB-coder/simple-game | /main.py | 2,754 | 3.6875 | 4 | from tkinter import *
import random as rdm
class Main(Frame):
def __init__(self, root):
super(Main, self).__init__(root)
self.startUI()
def startUI(self):
btn = Button(root, text="Rock", font=("Times New Roman", 15),
command=lambda x=1: self.btn_click(x))
... |
1f2995c3a905f25a3a07afb533a298ed289d551d | sreerajch657/internship | /practise questions/split list.py | 340 | 3.828125 | 4 | #Take a list of 10 elements. Split it into middle and store the elements in two dfferent lists.
n=int(input("enter the limit of the list : "))
lst=[]
for i in range(0,n):
x=int(input("enter the elements to list : "))
lst.append(x)
middle=int(n/2)
print("the array after spliting : ")
print(lst[ :middle])
print... |
815c9475d75a29e92c168a85bb01ebeaa345b987 | jayhebe/w3resource_exercises | /Dictionary/ex11.py | 130 | 3.609375 | 4 | my_dict = {'data1': 100, 'data2': -54, 'data3': 247}
result = 1
for value in my_dict.values():
result *= value
print(result)
|
6c3df315649dd506d43ee913a8ee11775798d5a7 | enderst3/challenges | /swap_cases.py | 261 | 4.15625 | 4 | """
Swap the cases of a a given string
"""
def swap_case(s):
swapped = ''
for char in s:
if char.isupper():
swapped = swapped + char.lower()
else:
swapped = swapped + char.upper()
return swapped |
91e79442027d3f90c9dc7876a7b2e06946150428 | JFaruk/Py_basics | /tuple.py | 500 | 3.828125 | 4 | #Tuples
t1=(1,23,4)
print(t1[2])
# can hold mix data type
t2=(1,'faruk','ccc',4)
print(t2[3])
# slicing
print(t2[-3])
#tuples are immutable means cant assign or change index after assigning them to something
# t2[0]='faruk'
# print(t2)
#this will through a error call 'tuple' object does not support item assign... |
1fb7248ef64295f0c01972afbad658ce87e8976a | myhelloos/concurrency-python | /app/thread/helloSemaphore.py | 781 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: alfred_yuan
# Created on 2019-01-28
"""using a semaphore to synchronize threads"""
import threading
import time
import random
semaphore = threading.Semaphore(0)
def consumer():
print("consumer is waiting")
semaphore.acquire()
print("Consumer notify : co... |
9d46754114c4c7f28062e6ff6f257c49f1bb7dab | Northwestern-CS348/assignment-3-part-2-uninformed-solvers-maxine1444 | /student_code_game_masters.py | 12,211 | 3.640625 | 4 | from game_master import GameMaster
from read import *
from util import *
class TowerOfHanoiGame(GameMaster):
def __init__(self):
super().__init__()
def produceMovableQuery(self):
"""
See overridden parent class method for more information.
Returns:
A Fact... |
588f284b0c8cd0ee80f3210430ea7486f6fcebb9 | SensorEducation/workshop_programs | /Loop.py | 1,380 | 3.828125 | 4 | #SensorEd Workshop V0.1
#Author - Jacob Ulasevich
#Loop Introduction
"""
A loop in programming is a certain area of code that gets ran over
and over again until something tells it to stop. Think of it like Newtons
A loop in execution will stay in execution until another bit of code stops it.
"""
"""
Just as we discu... |
1fb0a0e05dc6fd3fc714cdc56023954aedb99e40 | jogusuvarna/jala_technologies | /read_file.py | 225 | 3.8125 | 4 | #Write a program to read text from .txt file using Input Stream
#In the python we don’t have Input Stream instead of this we have ‘r’ mode to read the file
f = open("c:\\information\\test.txt", 'r')
f.read()
f.close()
|
eeb4159a61fb206cef8ee5ada76a86d292ff2841 | patrik-nilsson/Python | /2.3.py | 1,162 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
""" In the main function
-sets variables for use in gameend
-randomises a number
-initiates the gamestart function
"""
def main():
c="Correct"
w="Wrong"
r=random.randrange(1,11)
gamestart(r, c, w)
return 0
""" In the gamestart function
-asks the use... |
15fb8dbeb14662c4bd58f148a262934e7b16cca9 | sidxlfc/practice | /google_question.py | 1,066 | 3.671875 | 4 | def find_neighbors(m, g, n, visited) :
l = []
if g[0] < n and g[1] < n and g[0] > 0 and g[1] > 0 :
if m[g[0]][g[1]] < m[g[0] + 1][g[1]] :
l.append([g[0] + 1, g[1]])
if m[g[0]][g[1]] < m[g[0]][g[1] + 1] :
l.append([g[0], g[1] + 1])
if m[g[0]][g[1]] < m[g[0] - 1][g[1]] :
l.append([g[0] - 1, g[1]]... |
cd9643d689811a2ed90b436068e229656e4054aa | elchuzade/gamerl | /games/Racing/core/core.py | 9,112 | 3.8125 | 4 | """In this file we present all the classes that are used in Race game"""
from common.constants import constants as common
from games.Racing.constants import constants
from common.core import core
from games.Racing.helpers import helpers
import pygame
import numpy as np
class MyCar:
"""Instance of this class bec... |
9002befb024258a18d693bcf477d404963b02594 | DanielPramatarov/Python-Data-Structures-Implementation | /Stack/Stack.py | 555 | 3.796875 | 4 | class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return self.stack == []
def push(self, data):
self.stack.append(data)
def pop(self):
if self.size_stack() < 1:
return None
data = self.stack[-1]
del self.stack[-1]
... |
a915a80bcbf624e40df7deb604c90ba2baee56ee | akshaytolwani123/gci-2019 | /not-so-fast-gci/not-so-fast-gci.py | 477 | 3.578125 | 4 | #Not so fast task gci
#By:- Akshay Tolwani
#Username for gici:- akshayprogrammer
#Loop to check if the input from user is valid
while True:
o = input('Please input n: ')
if o:
if o.isdigit():
n = int(o)
break
#Check if the number is more than 0 and less than or equal to 1024
if ... |
2f3a7767919b8a83e6662ecf5a04174f3f4c3b7a | akshays-repo/learn.py | /files.py/Machine Learning/K MEAN/k means_1.py | 1,734 | 3.984375 | 4 | # importing required libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# read the train and test dataset
train_data = pd.read_csv('/home/akshays/Desktop/learn.py/files.py/K MEAN/train-data.csv')
print(train_data)
test_data = pd.read_csv('/home/akshays/Desktop/le... |
dc2f5c784de252f1f06d04effd6b7264c12cb124 | shridharkapshikar/python_ | /unique_list.py | 387 | 4.1875 | 4 | # **Write a Python function that takes a list and returns a new list with unique elements of the first list.**
#
# Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]
# Unique List : [1, 2, 3, 4, 5]
def function_list(lst):
unique_lst = []
for i in lst:
if i not in unique_lst:
unique_lst.append(... |
6e59bf3b6576bc8c9b697ce6bd9ee0860ddaeaa7 | jsaraviab12/Exercism-Python | /isogram/isogram.py | 236 | 4.09375 | 4 | def is_isogram(string):
string = string.lower()
for letter in string:
if letter == "-" or letter == " ":
continue
if (string.count(letter) > 1):
return False
return True
|
caeb4b7cc1f20905b7cd5d4506ebc9fb8ff61e43 | yangzongwu/leetcode | /20200215Python-China/0394. Decode String.py | 1,857 | 4.03125 | 4 | '''
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, squar... |
e28269d4d872492ed3133fd2b8c9a7a96e34c62b | sabina2/DEMO3 | /Hurray.py | 138 | 3.953125 | 4 | num1 = int(input("Enter your 1st number"))
num2 = int(input("Enter your 2nd number"))
if num1==num2 or num1+num2==7:
print("Hurray")
|
afbd90d2f107bb7572ef03507b921fc3a8532a8f | N-Verma/Beginners-Python-Examples | /Percentage.py | 753 | 3.90625 | 4 | # Percantage Increase , Percentage Decrease
def increasePercent(increase , origValue):
iPercent = increase / origValue * 100
return(str(iPercent) + '%')
def decreasePercent(decrease , origValue):
dPercent = decrease / origValue * 100
return(str(dPercent) + '%')
print('Hello\n')
print('Pres... |
1806cc48d7388d25aef3a2f7a5008dae4a6cbe9e | ayssel-uct/random_scripts | /search_pattern.py | 924 | 3.609375 | 4 | #this script searches for a specific input patterns (provided in Pattern_in.txt) in a fasta file, and outputs fasta sequences with matching patterns to the output fasta
#!/usr/bin/env python
import sys
import os
from collections import defaultdict
import re
_INPUT_FILE1 = 'Pattern_in.txt'
_INPUT_FILE2 = 'Digitaria.tra... |
4156231e0ebeed6a8378d1bf9d98960286375fd0 | seongbeenkim/Algorithm-python | /Programmers/Level2/폰켓몬(poncketmon).py | 303 | 3.6875 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/1845
def solution(nums):
n = len(nums) // 2
nums = set(nums)
if len(nums) >= n:
return n
else:
return len(nums)
print(solution([3, 1, 2, 3]))
print(solution([3, 3, 3, 2, 2, 4]))
print(solution([3, 3, 3, 2, 2, 2]))
|
591c8c0a1622fa897f18d347705d1ef709536266 | WinterBlue16/Function-for-work | /Data Structure/time/02_get_month_last_day.py | 276 | 3.703125 | 4 | import calendar
def get_month_last_day(year: int, month: int):
month_last_day = calendar.monthrange(year, month)[-1]
print("{}년 {}월의 마지막 날은 {}일입니다.".format(year, month, month_last_day))
return month_last_day
get_month_last_day(2022, 6)
|
dfa58188b8063dded851616fcff5ada026607767 | Reikonz/PythonLearning | /Basic Tutorial/dictionaries.py | 553 | 4.28125 | 4 | # python dictionaries - arrays indexed by objects (ex. strings, numbers, lists)
# defining dictionaries
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 94766... |
90a29f9eeece05b94f0d30551d2e06a3015a21e8 | mistryvatsal/Leetcode-Problems | /Remove_Nth_Node_From_Linkedlist/Solution.py | 739 | 3.71875 | 4 | #
# Created on Fri Apr 18 2021
#
# Title: Leetcode - Remove Nth node from end of linked list
#
# Author: Vatsal Mistry
# Web: mistryvatsal.github.io
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
... |
19e587f4258feabdd91bea5c338431ed404a22a6 | agaitanis/deep_learning_with_python | /6_deep_learning_for_text_and_sequences/one_hot_encoding.py | 2,214 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Deep Learning with Python by Francois Chollet
6. Deep learning for text and sequences
6.1 Working with text data
6.1.1 One-hot encoding of words and characters
"""
# Word-level one-hot encoding (toy example)
import numpy as np
samples = ['The cat sat on the mat.', 'The dog ate my homework.'... |
7607700d6806d2fc27e5bb467ef0f3f5932552b8 | lchoward/Practice-Python | /Graphs/LongestConseqSeq.py | 1,283 | 3.734375 | 4 | # # Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
# # Your algorithm should run in O(n) complexity.
# Example:
# Input: [100, 4, 200, 1, 3, 2]
# Output: 4
# Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].
# Therefore its length is 4.
class... |
8f2eb6138629a1161090adf2363cad09c0593b66 | Vivek-abstract/NCSIT-Journal-Tracking-System | /login.py | 16,732 | 3.546875 | 4 | import os
from tkinter import *
from tempfile import NamedTemporaryFile
import tkinter.messagebox
import datetime
import shutil
import csv
def Login():
"""This function creates the Login window and displays it"""
def validate():
"""Validates the user_name and password"""
user_name = user_name... |
0d78ea7a584497039342b9c62e0290f84bbfd4db | BangAbe88/modul_python | /grade.py | 803 | 3.640625 | 4 | import math
def grade1(nilai):
if nilai<50:
print("Nilai Anda E"+" __Maaf, anda tidak lulus mohon coba kembali")
elif nilai>=50 and nilai<=59:
print("Nilai Anda D"+" __Maaf, anda masih belum lulus mohon coba kembali")
elif nilai>=60 and nilai<=74:
print... |
cad1a97fe56016e1d9fe2523ed526eec0d44a28b | Dodilei/uncertainty_propagation | /calculator_sphere.py | 265 | 3.671875 | 4 | from math import pi
i = True
while i:
print("\nDescribe your measures: \n")
D = float(input("D: "))
_D = float(input("δD: "))
v = (1/6)*pi*(D**3)
_v = (1/6)*pi*(3*(D**2)*_D)
print(v, " +- ", _v)
if input("Next? [y]/n\n") == "n":
i = False
|
b998b5e7c529270d46c77e709552dfc0b349c67d | raghavbabbar/Learning-Python | /Basic/01_python.py | 304 | 3.828125 | 4 | num = 100
num2 = 100/3
print(num2)
#it will print 33.33333333___
num3=100//3
print(num3)
#but the num3 will be 33
num = 5*3
print(num)
#it prints 15
num=5**3
print(num)
#it prints 125
pth="C:Raghav\name\m"
print(pth)
#by inserting r no special character will b included
pth=r"C:Raghav\name\m"
print(pth)
|
f6ec843df6a4ad2fb5daca6b9ed95913a14352b7 | emnsen/locale-direction-detect | /index.py | 158 | 3.625 | 4 | import json
with open('data.json') as json_file:
data = json.load(json_file)
for locale in ['en', 'ar', 'fa', 'he', 'tr']:
print(data[locale])
|
770a5baa4731aa0c5dd66312b9adb211bfce147b | y471n/algorithms-n-ds | /ds/stack-balanced-paranthesis.py | 476 | 4.03125 | 4 | from stack import Stack
def paranthesis_check(symbols):
balanced, s = True, Stack()
for symbol in symbols:
if symbol == "(":
s.push(symbol)
else:
if s.is_empty():
balanced = False
break
s.pop()
if not s.is_empty():
... |
38784a0dc5809b3ddd73d5f0a706f2d58f781757 | fucongcong/ssos | /php/AI/资料/Perceptron.py | 1,425 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
import numpy as np
x = np.array([[2,1],[3,1],[1,1]])#创建数据集,共3个实例
y = np.array([1,1,-1]) #创建标签
history = [] #存储迭代学习过程中的w,b值,便于可视化绘图
#x.T是转置矩阵
gramMatrix = x.dot(x.T)
#计算得到对称矩阵
alpha = np.zeros(len(x)) #初始化alpha为零向量
b = 0 #b为回归直线截距... |
6fdf07478e56de9f8880ddb6f4d8027f1303a8e1 | volodinroman/py-flow-based-programming | /PyFBP/nodeGraph.py | 6,189 | 3.578125 | 4 | from port import Port
from connection import Connection
from node import Node
from loop import NodeLoop, Loop
class NodeGraph(object):
"""
NodeGraph controlls the way how connected nodes interract with each other
"""
def __init__(self):
"""[Constructor]"""
self.nodesList = []... |
c1bc3f1eeca79cb89fc9be98951490fdc58b2b40 | Lyasinkovska/BeetRootPython | /lesson_22/task_2.py | 521 | 4.21875 | 4 | """
Checks if input string is Palindrome
is_palindrome('mom')
True
is_palindrome('sassas')
True
is_palindrome('o')
True
"""
def is_palindrome(looking_str: str, index: int = 0) -> bool:
if len(looking_str) < 2:
return True
if looking_str[0] != looking_str[-1]:
return False
retur... |
085f147fd7a754440c7fa2796902ef505867bc87 | KIKUYA-Takumi/Python_basic | /small_large_equal.py | 154 | 3.890625 | 4 | InputNum = input().split()
a = InputNum[0]
b = InputNum[1]
if a < b:
print("a < b")
elif a > b:
print("a > b")
elif a == b:
print("a == b")
|
e75b23fbb630281d61509aed04b9e49e289fde3f | NateScheidler/ProjectEuler | /euler29.py | 605 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 28 09:56:56 2014
@author: nscheidler
"""
# Calculates number of distinct factors of an integer
# Does not count the integer itself and 1 as factors
def countFactors(n):
numFactors = 0
for i in range(2,n/2+1):
if n%i == 0:
numFactors += 1
... |
111fb653b1104c7c40dee8422845f6cf3838deac | Rsj-Python/project | /test/python.py | 1,015 | 3.578125 | 4 | #coding=utf-8
# 标识符
# 变量
a = 10
# 行和缩进
if True:
print("正确")
# 数据类型
# 1.浮点型
n = 3.14
#2.字符串
strl = 'This is Tom'
# print(strl)
# print(strl[8])
# print(strl[5:7])
# 格式化字符串 %s 格式化整数%d
# x = 1.112
# y = 1.2210
# print(y-x)
print(f'My name is 卢吊 and my age is {18}')
# 3.列表
list1 = [1,'hello',T... |
5f61b241f012ac728ef30fdda48380841bdda93e | entropyofchaos/QLearning | /originalPython/grid.py | 2,100 | 3.6875 | 4 | import qLearning
class Grid:
def __init__(self):
self.world = []
self.cols = 0 #added by yuksel
self.rows = 0 #added by yuksel
self.walls = [] #added by yuksel
self.weights = {} #added by yuksel
def readFile(self, path):
with open(path, "r") as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.