blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
494772ce01dc269ae05814a6669d2a5638b49e4d | alesamv/Estructura-de-Datos-y-Algoritmos-I | /Practicas/Practica13/ejercicio3.py | 377 | 4.25 | 4 | #Serie de Fibonacci Iterativa
"""Programa que calcula la serie de Fibonacci, utilizando una función Iterativa."""
def FibonacciIterativo(numero):
f1=0
f2=1
for i in range(1, numero-1):
f1,f2=f2,f1+f2
return f2
print("Ingresa la posicion para obtener el correspondiente numero de la serie:")
num... |
298d4980ed2959c7be84981595db0e3d77518175 | larry-dario-liu/Learn-python-the-hard-way | /ex2.py | 566 | 3.53125 | 4 | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_per_car=passengers/cars_driven
# hahahahahah#
print "there %s are",cars,"cars %s available."
print "there are only",drivers,"drivers av... |
19d8299b8356915d1b62b5c655dbc28779626da1 | harryw1/cs_python | /CS121/rainfall_database_v2.py | 8,920 | 4.375 | 4 | """
Harrison Weiss
homework_02
Program that implements a class called RainfallTable that builds
a dictionary of years and rainfall totals from njrainfall.txt.
Implements different functions that allow the user to determine
different traits of this data.
"""
import statistics
class RainfallTable():
... |
45a2e63632863c04d8b351b5c850f8b551cbd36c | siddalls3135/cti110 | /Functions.py | 1,709 | 4.9375 | 5 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 12:00:03 2019
@author: sidda
"""
# In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
# To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello fro... |
5c1d627e827fcada39f7975cfb45894a9aa6312c | ashwiniwagh2296/python | /add3.py | 270 | 3.734375 | 4 | a = int(input("Enter your no a : "))
b = int(input("Enter your no b: "))
c = a+b
d = int(input("Enter your no d : "))
e = int(input("Enter your no e : "))
f = d+e
g = int(input("Enter your no g: "))
h = int(input("Enter your no h: "))
i = g+h
print(c)
print(f)
print(i) |
bbc1ce0a0a7f88f06f2efcd3b0575a9af9d3287c | dreamroshan/Code_examples | /if Elif Example.py | 216 | 4.125 | 4 | '''
@author :CreativeCub
'''
z = 3
if z == 1:
print 'z is equal to 1'
elif z == 2:
print 'z is equal to 2'
elif z == 3:
print 'z is equal to 3'
else:
print 'z is not equal to 1 or 2 or 3' |
60f674124d4a480fe0c334229594cd9036cbadc7 | gaurav1116/Practicing-Python | /stringreverser.py | 175 | 4.40625 | 4 | entered_string = raw_input("Please enter a string: ")
reversed = ""
for item in range(len(entered_string) -1, -1, -1):
reversed += entered_string[item]
print(reversed)
|
dd922f28ae272b938183d247db66f512c1e404b2 | panscoding/leetcode | /4.Top K Elements/findKthSmallest.py | 2,190 | 3.96875 | 4 | """
iven an unsorted array of numbers, find Kth smallest number in it.
Please note that it is the Kth smallest number in the sorted order, not the Kth distinct element.
Note: For a detailed discussion about different approaches to solve this problem, take a look at Kth Smallest Number.
Example 1:
Input: [1, 5, 12, ... |
5c5d4c52e327b9ea67205ea8be00bca97619214c | MatheusEwen/Exercicios_Do_CursoDePython | /ExPython/CursoemVideo/ex113.py | 951 | 3.890625 | 4 | def leiafloat(msg):
while True:
try:
n = float(input(msg))
except (ValueError, TypeError):
print('\033[0;31mERRO, por favor, digite um numero interio valido\033[m')
continue
except(KeyboardInterrupt):
print('\033[0;31mO usuario preferiu não dig... |
cade7b92d7fee6c28b6226475c77f8c356d19991 | schlerp/schlerpnn | /NENNN.py | 18,696 | 3.984375 | 4 | #!/usr/bin/python
# Patty's neural network
# ----------------------
#
# a bunch of shit for me to fuck around with and learn
# neural networks.
# currently idea is:
# * pick a non linear
#
# * initialise a network with the amount of input,
# hidden, and output nodes that you want for the
# data
#
# * tr... |
2ac4da68f38bd5f8a22d67a22ada09f50085f7dd | sharonLuo/LeetCode_py | /longest-valid-parentheses.py | 3,665 | 4.03125 | 4 | """
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has len... |
507acf567b8442d7c9200bacad0037f0b01f7f6c | daniel-reich/ubiquitous-fiesta | /zgu7m6W7i3z5SYwa6_3.py | 177 | 3.578125 | 4 |
def is_equal(lst):
num1=str(lst[0])
num2=str(lst[1])
total1=0
total2=0
for i in num1:
total1+=int(i)
for i in num2:
total2+=int(i)
return total1==total2
|
5cee3bccc5d9546d6f24a330f6e389af4e82e161 | horeilly1101/naive-fibonacci | /fib.py | 286 | 4.03125 | 4 | '''
contains a naive recursive implementation of
the fibonacci sequence
'''
def fib(num):
'''
returns the ith element of the fibonacci
sequence
kw args:
num -- an integer greater than or
equal to zero
'''
return 1 if (num == 1 or num == 0) \
else fib(num-1) + fib(num-2) |
c2257f3ed88f15d9f4628d08e168abe86b36e20a | mihaeladimovska1/interview_practice | /problem_01_01.py | 427 | 3.90625 | 4 | '''ord(character) returns an integer between 0...127 from a single unicode character'''
def are_all_chars_unique(s):
all_chars = [0 for i in range(128)]
for character in s:
if not all_chars[ord(character)]:
all_chars[ord(character)]=1
else:
return False
return True
... |
71b2c875306a0164af9fb93af75f02b84c23a0a1 | kowshik448/python-practice | /python codes/factorial.py | 294 | 4.0625 | 4 | n = int(input())
def recursive_factorial(n):
if n==1:
return n
else:
return n*recursive_factorial(n-1)
if n < 0:
print('invalid nmber , please enter positive num ber')
elif n==0:
print('factoeial of 0 is 1')
else:
print(recursive_factorial(n)) |
a1624a983b6adf49330a7ac3a3af64903d958e80 | Gilbert-van-Lierop/Python | /09_dictionaries.py | 823 | 3.53125 | 4 | #word= key(dit is de unieke identifier in de dicttionairy) en value is de echte definitei
#wij gaan een programma maken die een maand van 2 letters omzet naar de volle maand naam
#dus jan => Januery | feb omzet naar FEbruaie
#dicttionairy wordt altijd gemaak met open en closing{}
maand_conversie = {
"Jan"... |
72b8c72b69d1ca360c3beaf56edca08526724752 | suraj1ly/AI-Vs-2048 | /Programming_Assignment/Assignment2/pa2.py | 8,684 | 3.59375 | 4 |
import copy
import math
countz=0
def check(tic):
if (tic[0]==tic[1] and tic[1]==tic[2] and tic[0]=='X') or (tic[3]==tic[4] and tic[4]==tic[5] and tic[4]=='X') or(tic[6]==tic[7]and tic[7]==tic[8]and tic[8]=='X'):
return -1
if (tic[0]==tic[1] and tic[1]==tic[2] and tic[0]=='O') or (tic[3]==tic[4] and tic... |
3de4fe8558dd71a29a9d01b62f3263265dd4d1d6 | osamadel/Hacker-Rank | /Implementation/designer_PDF_viewer.py | 1,115 | 3.953125 | 4 | '''
PROBLEM LINK:
https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
'''
import math
import os
import random
import re
import sys
# Complete the designerPdfViewer function below.
def designerPdfViewer(h, word):
alphabet = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e'... |
c1c2fe07ea583801d28cb1746b587900e9e5ba6f | BICpen12/pihat | /hat_message.py | 388 | 3.5625 | 4 | #!usr/bin/env python3
#needs to run on python3
from sense_hat import SenseHat
sense = SenseHat()
color= (255, 0, 0)
speed = 0.05
x = input('Enter your name: ') #imput allows for input from user
message = ('Hello, ' + str (x) ) #str converts x into a string
print (message)
sense.show_message(message, speed, text... |
00e0a5b9c2cfc41a06f1de0fd50e2d4ac5669719 | nightjuggler/puzzles | /dragon.py | 1,277 | 3.5625 | 4 | #!/usr/bin/python
# Is minMoves = 2 * (numCaves - 2) for all numCaves > 2? (True at least for numCaves = 3 thru 7)
numCaves = 5
allCaves = range(numCaves)
maxCave = numCaves - 1
moves = []
prevStates = set()
minMoves = None
def solve(dragonCaves):
global minMoves
if minMoves is not None and len(moves) >= minMoves:... |
f12a1255662029cde2f4371c8b190d466dbb2961 | RunhuaGao/LeetCode | /75_SortColors/75_version1.py | 694 | 3.6875 | 4 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
size = len(nums)
if size < 2:return
red,white,blue = 0,0,0
for n in nums:
if n==0:red+=1
elif n==1:white+=1
... |
77d96d49aaf351f4b057b81eafbb3ef079022cd5 | Nimisha-V-Arun/Interview-Prep | /Arrays/Python/numForm.py | 569 | 3.828125 | 4 | def factorial(no):
f = 1
if(no == 0 or no == 1):
return 1
else:
return(no*factorial(no-1))
def getSum(n):
arr = [4,5,6]
fact = factorial(n)
digSum = 0
for i in range(len(arr)):
digSum += arr[i]
digSum = digSum * (fact // n)
i =1
k =1
res = 0... |
03d2efe25e91d4fc3ba16bdf5bd9e598405d684e | diligentaura/oldpypractice | /pracTrue.py | 244 | 3.796875 | 4 | import random
number = input ("Your Number:")
x = 0
while True:
num = random.randint (1,100000)
print (num)
x=x+1
print
if num == int (number):
break
print ("Number of Times:")
print ("")
print (x)
|
41354043ffe2349f4915d3e5fb1cafc0603a3892 | Etv500/Python-Basics-to-make-and-break | /max of a column numpy.py | 223 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 27 17:59:11 2017
@author: elvis
"""
import numpy
a = numpy.array([[10, 2], [3, 4], [5, 6]])
xmax = numpy.max(a[0:-1,0])
ymax = numpy.max(a[0:-1,1])
print(xmax, ymax) |
8f1895d912bbe0a8c8c8c3b442445d501ea10bc2 | Vasyl0206/orests_homework | /cw28.py | 320 | 3.65625 | 4 | class Ball(object):
def __init__(self,ball_type = None):
self.ball_type = ball_type
if self.ball_type is None:
self.ball_type = 'regular'
elif:
self.ball_type = ball_type
ball1 = Ball()
ball2 = Ball("super")
ball1.ball_type #=> "regular"
ball2.ball_type #=> "super"
|
be3eb151487e790ba5cd9da8c81888e0601cfec7 | Doldge/MyFirstGame | /tree_span.py | 2,936 | 3.59375 | 4 | #! /usr/bin/python
#Tree spanning Alg
# Currently unused.
# Could be used for generating efficient connections between points.
# And navigating units around the map / etc
import sys
import heapq
class Vertex(object):
def __init__(self, node):
self.id = node
self.adjacent = {}
# Distance... |
592f40b5ac73a601cc2178815ab9e72df45dde6c | Jane620/fluentPython | /tests/ut/chapter2/test_nametuple.py | 449 | 3.6875 | 4 | # -*- coding:utf-8 -*-
from src.chapter2.nametuple_list import exec_city_info, make_city_info
def test_city():
"""
function main 我是函数说明
"""
detail = exec_city_info()
assert detail.name == "HZ"
def test_make():
"""
nametuple._make(iterator) == nametuple(*iterator)
:return:
"""
... |
a6e06759e894d7b9607175e1b84377b5f9255c35 | bmarkwalder/csc594 | /hw_01/text_pre_processing.py | 8,741 | 4 | 4 | """
Brandon Markwalder
CSC 594
Spring 2018
Homework 01 Text pre-processing
This program will tokenize a corpus such that words, leading and trailing
punctuation and expanded contractions are converted to tokens. Punctuation
found in the middle of a word is ignored. The program outputs the number of:
Sentences, paragra... |
c3856fcea61038a17abd456c2f343576de95fb8b | DanielRJohnson/Neural-Networks-From-Scratch | /main.py | 3,752 | 3.78125 | 4 | '''
# Name: Daniel Johnson
# File: main.py
# Date: 1/3/2021
# Brief: This script creates uses neural_network to train
# and evaluate the network using XOR as an example
'''
import numpy as np
import matplotlib.pyplot as plt
from neural_network import Neural_Network
def main():
#make a neural network with ... |
19a72e26387fe2b6887657361ba27443a9113461 | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk18/008_sequenceOfNumbers.py | 1,416 | 3.984375 | 4 | def sequenceOfNumbers(m, n):
'''
sequenceOfNumbers()=counts off numbers between m and n recursively
@param m=starting number
@param n=ending number
prints m
'''
try:
if m==n:
print(m)
else:
print(m)
sequenceOfNumbers(m+1, n)
except:
print("Unha... |
b09649e263977e8648c5f8f7477d394d32a7314e | Gexeg/lessons | /OOAP/second course/InheritanceCategory(3)11.py | 4,037 | 3.875 | 4 | """
Задание 20.
Приведите пример кода, где выполняется наследование реализации и льготное наследование.
Отправьте выполненное задание на сервер.
"""
# Наследование реализации (implementation inheritance)
# вернемся к классу "Существо".
class Creature():
def __init__(self, hp):
self.hp = hp
self... |
15424d868853c0d3bc18d4d299239ce4742bfe65 | robertruhiu/learn | /slices.py | 252 | 3.984375 | 4 | nums=[1,2,3,4,5,6]
# for i in range (1,len(nums),2):
# print(nums[i])
print(nums[3:6:2])
print (nums[::-2])
print (nums[::-1])
print (nums[5:0:-1])
#they itterate on the index that starts from 0 not the numbers
# in the list[start:stop:incriment]
|
42f5b50cac004ddb4c8cd35ed68062283db41083 | amelia98/level3_NCEA | /auction.py | 1,447 | 3.984375 | 4 | def get_reserve(reserve):
print("Auction Manager")
print("Reserve must be greater than or equal to $0.00")
reserve = (read_int("What is the auction reserve?"))
def get_bids(names, bids):
print("\nAuction has started")
name=""
while name.upper() !='F':
print("Highest bid is ${:.2f}".form... |
f5d53ae2aeee2dd7ecf33207533c514c0df62f63 | Javed69/Python | /HackerRank-30DaysofChallenge/day-3-Conditional-Statement.py | 185 | 3.84375 | 4 | #!/bin/python3
import sys
N = int(input().strip())
if N % 2 == 1:
print('Weird')
elif N < 5:
print('Not Weird')
elif N <= 20:
print('Weird')
else:
print('Not Weird')
|
1307ce915f4021a60aeeea1ab0b385b8bbd433b7 | zzcbetter01/pythonProject | /python学习/python编程从入门到实践/第五章、用户输入和while循环.py | 3,709 | 4.4375 | 4 | #### 5.1 函数input的工作原理
## input接受一个参数,即要向用户显示的提示和说明,让用户知道该如何做
# message = input('Tell me somthing, and I will repeat it back to you: ')
# print(message)
## 如果提示超过一行,可能需要将提示储存在一个变量中
# prompt = "If you tell us who you are, we can personalize the messages you see."
# prompt += "\nWhat is your first name?"
# name = input(p... |
771e8e3d343396f78454e15bc028c07b6c72608e | pigmonchu/Earth_Mars | /inputs.py | 574 | 3.921875 | 4 | def Input(message, options):
result = input("{}: ".format(message)).upper()
while result not in options:
print("Opción incorrecta")
result = input("{}: ".format(message)).upper()
return result
def valida_number(value):
try:
float(value)
return True
except Valu... |
15178eb8f498369c6e101a7737fa7b68733feaf7 | sontaku/learning_python | /01_basic/a_datatype_class/Ex07_tuple.py | 986 | 3.546875 | 4 | """
#----------------------------------------------------------
[튜플 자료형]
1- 리스트와 유사하지만 튜플은 값을 변경 못한다.
2- 각 값에 대해 인덱스가 부여
3- 변경 불가능 (*****)
4- 소괄호 () 사용
"""
# (1) 튜플 생성
print('------------------- 1. 튜플 생성-----------------')
t = (1,2,3)
print(t)
print(t[0])
t2 = 1,2,3
print(t2)
print(t[0])
# (2) 튜플은 요... |
fb4abda6554847c4d35c0a0d4ccb57b7c03b457b | RBEGamer/HACK4TK_HACKATHON_2018 | /src/Case_Class_structure.py | 2,258 | 3.59375 | 4 | from enum import Enum
class Passengers_Together:
def __init__(self, num=0, list_passenger = [], time_stamp=0, start_point = [0,0], end_point = [0,0] ):
self.id = id
self.time_stamp = time_stamp
self.num = num
self.list_passenger = list_passenger
self.start_point = start_poin... |
26f5f7f18cc166d95bb17aabc6dd4706fab16e16 | mthlongwane/plylexerandparser | /parser.py | 2,388 | 3.578125 | 4 | # ------------------------------------------------------------
# Parser.py
# MT Hlongwane 2021
# Compilers Assignment 3
# Adapted from PLY Documentation https://ply.readthedocs.io/en/latest/ply.html#lex-example
# ------------------------------------------------------------
import sys
import lex as lex
import yacc as ... |
b978890cb86092e1218d315e3769951b91f94250 | snake1597/Leetcode | /Array/MonotonicArray.py | 612 | 3.625 | 4 | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
flag = True
current = A[0]
if A[-1] > A[0]:
for i in range(1,len(A)):
if A[i] >= current:
current = A[i]
flag = True
else:
flag... |
9c865434188c07ef269d126e15bb1669909f719f | mschae94/Python | /Day13/Ex01.py | 376 | 4.34375 | 4 | # 리스트는 인덱스의 표현이 정수로만 가능하다
lst = ['a' ,'b' , 'c']
print(lst[0])
#반면 , 딕셔너리는 대부분의 타입이 적용가능하다.
dic = {1:"hello" , 2:"world" , "python" : 3}
print(dic)
print(dic[1])
print(dic["python"])
dic = {"first": ['a', 'b' , 'c']}
print(dic["first"])
dic[3] = "하이"
print(dic)
|
ddf815ac376e981b53ddb5f2936c51aab4324e1f | vimiix/scripts | /yaml_to_json.py | 768 | 3.609375 | 4 | #!/usr/bin/python2
#coding=utf-8
'''
usage: yaml_to_json.py [-h] [-f FILE]
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE input yaml filename(include path)
'''
__author__ = 'Vimiix'
import json
import yaml
import argparse
def yaml_to_json(path):
with open(pat... |
71a7cdd76b470450b44fd410eecf61915ca29d28 | m8ko/BlackjackAnalysis | /Deck.py | 661 | 3.671875 | 4 | '''
Creates a standard deck of 52 playing cards
'''
import Card
import random
class Deck:
def __init__(self, size=1):
self.all_cards = []
for _ in range(size):
for suit in Card.suits:
for rank in Card.ranks:
created_card = Card.Card(suit, rank)
... |
38ec990466f4834fb573ae7f9b25a4d1fff81042 | PJ71194/DSA | /Graph/charOrderInAlienLang.py | 1,105 | 3.578125 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.vertices = set()
def addEdge(self, u, v):
self.graph[u].append(v)
self.vertices.add(u)
self.vertices.add(v)
def topoUtil(self, node, visited, stack):
visited[node] = 1
for child in self.graph[no... |
f8dcb0c0759911bd479cc8ccc02ef36b6dbdcdf2 | KacperKubara/hackerrank_sols | /common_child.py | 873 | 3.609375 | 4 | def commonChild(s1, s2):
result = []
result_string = ""
word_length = len(s1)
for i in range(0, word_length):
result.append(0)
last_found = -1
for count1, char1 in enumerate(s1):
if count1 >= i:
for count2, char2 in enumerate(s2):
... |
685259aac8726bd49a4c91644b0ec0028707ddfe | marikaswanberg1/CS-591-Privacy-In-Machine-Learning- | /Hw1_reconstruction_attack.py | 5,908 | 3.703125 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
def generate_data(n):
'''
n : int specifying the size of the dataset
returns a uniformly random bit vector of size n (which will be the data)
'''
data = np.random.randint(low=0, high=2, size=n)
return data
def generate_noise(n):
'''
n : int sp... |
63e5b343f49cbe174dfc3f9e1d35722aeb7739c8 | yeasellllllllll/bioinfo-lecture-2021-07 | /0708_theragenbio/bioinformatics_4_4.py | 1,791 | 3.734375 | 4 | #! /usr/bin/env python
# Op1) Read a FASTA format DNA sequence file
# and make a reverse sequence file.
# Op2) Read a FASTA format DNA sequence file
# and make a reverse complement sequence file.
# Op3) Convert GenBank format file to FASTA format file.
a = "sequence.nucleotide.fasta"
# Op1) Read a FASTA form... |
c7a501881504bebcd33e345a031495ac183e160c | YeeyingTan/Workspace | /rtest.py | 546 | 3.640625 | 4 | def check_productID(isbn):
remainingDigits = isbn[3:]
#print(remainingDigits)
assert len(remainingDigits) == 9
sum = 0
for i in range(len(remainingDigits)):
number = int(remainingDigits[i])
value = i + 1
sum += value * number
#print(sum)
result =... |
1f3c72902e27a7bc81fb367823f78941836cbfa9 | naivor/PythonPractice | /ifelse.py | 137 | 4.09375 | 4 | #!/usr/bin/env python3
age=3
if age>=18:
print('your age is',age)
print('adult')
else:
print('your age is',age)
print('teenager')
|
cfb0a1e40fa0c15c1001bb54f781bbb547f62aa4 | tohkyr/daily-practice | /Python/Day 1/program2.py | 484 | 4.125 | 4 | while True:
try:
a = int(input("Enter a number for variable A: "))
b = int(input("Enter a number for variable B: "))
except ValueError:
print("The value you entered is not valid, please enter a number.")
continue
else:
break
def compare(x, y):
if x <... |
08d700d8ca20ad4ecbc328295e5bc1d27d92d2d5 | kelva99/sudoku_solver | /code/generate.py | 4,622 | 3.90625 | 4 | # reference Creating a Sudoku Puzzle in https://www.sudokuwiki.org/Sudoku_Creation_and_Grading.pdf
import random
from validate import validate
from Solver import Sudoku_Solver, Sudoku_Solver_1
class Level(object):
EASY = 0 # 35-40
MIDDLE = 1 # 30-36
HARD = 2 # 25-33
EXPERT = 3 # 20-28
class Generator(objec... |
04e9e4fb09c851d37c5d660d0a16562f04a87549 | jrussell416/Rock-Paper-Scissors | /game.py | 1,330 | 4.59375 | 5 | #importing random module for ability to randomize computer's choice
import random
winner = ""
#How a "random" choice is selected
randomChoice = random.randint(0,2)
#Assigning the numbers from the random choice into a string so it can be used for a comparison to the user's choice
if randomChoice == 0:
computerChoice... |
09528b41d584e20bf47d2f48595367e08743d41f | yusheng88/RookieInstance | /Rookie073.py | 1,370 | 4.1875 | 4 | # -*- coding = utf-8 -*-
# @Time : 2020/8/16 21:21
# @Author : EmperorHons
# @File : Rookie073.py
# @Software : PyCharm
"""
https://www.runoob.com/python3/python-heap-sort.html
Python 堆排序
堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。
堆积是一个近似完全二叉树的结构,
并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
堆排序可以说是一种利用堆的概念来排序的选择排序。
"""
import pysno... |
c41d7a60fca8f163e5eb49142dbe79045e17fdd2 | lkhphuc/HugoLarochelle_NN_Exercises | /Restricted Boltzmann Machine/nnet.py | 16,610 | 3.71875 | 4 |
from mlpython.learners.generic import Learner
import numpy as np
class NeuralNetwork(Learner):
"""
Neural network for classification.
Option ``lr`` is the learning rate.
Option ``dc`` is the decrease constante for the learning rate.
Option ``sizes`` is the list of hidden layer sizes.
O... |
f5a36c40c96e7060925076784fddea7763508056 | ursulenkoirina/courses | /homework3/issue3_3.py | 211 | 3.78125 | 4 | # 3.1
a = 0
while a <= 10:
print(a)
a += 1
# 3.2
a = 20
while a >= 1:
print(a, end=' ')
a -= 1
# 3.3
a = 1024
i = 0
while a%2 == 0:
a = a//2
i += 1
print('\nNumber of divisions: ', i)
|
3b8b712736790baacbc46b1ecadd27993df6939f | mohsinz99/Password_Generator | /userInterface.py | 1,849 | 3.796875 | 4 | import tkinter
from tkinter import *
from algorithms import algorithms
class user_interface:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.labelUpper = Label(frame, text = "How many uppercase letters:")
self.labelUpper.grid(row = 0, column = 0, padx = 20, pady = 20)
self.ent... |
2f5b25b48921e2b131fd2fdc88f1a7b4a724f2c6 | dudrill/Coursera_ML | /1 неделя/task11.py | 400 | 3.59375 | 4 | import pandas
import re
from scipy import stats
df = pandas.read_csv("C:\Users\Adele\Desktop\\titanic.csv")
# 1. Какое количество мужчин и женщин ехало на корабле? В качестве
# ответа приведите два числа через пробел.
male = df[df['Sex'] == 'male']
female = df[df['Sex'] == 'female']
print(len(male), len(female)) |
5a57de98f121623b6e0937ee4a2cb7939c98d0b1 | marcelovca90-inatel/C210 | /search-puzzle-python/algorithms/greedy_search.py | 3,514 | 4.25 | 4 | import heapq
class GreedySearch(object):
'''
This class implements the greedy search algorithm.
'''
def __init__(self, problem):
'''
Constructor
Any instance of this class must receive a ``problem`` parameter that is responsible
for controlling the problem evaluation an... |
2a7effa0f6e9bc9551bfa017bb3ef99f42e7a70a | ruchi2ch/Python-Programming-Assignment | /week 3/3.4.py | 1,570 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 12:18:24 2020
7/17/2016
@author: HP FOLIO 9480M
"""
'''Problem 3_4:
Write a function that is complementary to the one in the previous problem that
will convert a date such as June 17, 2016 into the format 6/17/2016. '''
def problem3_4(mon, day, year):
mo... |
8115ebe869bb82ec14aa65892d8e70894297504c | weguri/python | /oop/curso_2/Polimorfismo/audiofile.py | 664 | 3.640625 | 4 | class AudioFile:
def __init__(self, filename):
if not filename.endswith(self.ext):
raise Exception('Formato invalido')
self.filename = filename
class MP3File(AudioFile):
ext = 'mp3'
def play(self):
print('Tocando arquivo MP3')
class WavFile(AudioFile):
ext = 'wa... |
a20eb4910dd9a7478a5d30647b82826e647afdff | marshall1996/-Python-for-Beginners-Giraffe-Course | /For loops.py | 389 | 4.03125 | 4 | for letter in "Giraffe Academy":
print(letter)
friends = ["May", "Minnie", "Marshall"]
for friend in friends:
print(friend)
for index_of_list in range(len(friends)):
print(friends[index_of_list])
for index in range(3, 10):
print(index)
for i in range (5):
if i == 0:
print(... |
3e40d70060e2ad8d4b829db6d30b80a79ff6f998 | brrcrites/PySchool | /56_dictionary.py | 74 | 3.828125 | 4 | numbers = {1: "one", 2: "two", 3: "three"}
for x in numbers:
print(x)
|
74cf7ac6bb03854966d18c70471e3bf4d01962c3 | acse-jt321/modern-programming-methods | /lectures/lecture04/tests/unittest_example.py | 821 | 3.5 | 4 | import unittest
import foo
def expensive_function():
"""Pretend this uses a lot of resources."""
return (1, 0, -1)
def make_safe(val):
"""This might clean up memory or free up resources"""
pass
class TestSolveQuadratic(unittest.TestCase):
def setUp(self):
"""Runs first."""
# Can... |
f01385b155b89ff04d71f8fb290bfe295d754d16 | kapil23vt/Python-Codes-for-Software-Engineering-Roles | /unique characters in string.py | 297 | 3.515625 | 4 | def unique(s):
d = dict()
for i in range(len(s)):
d[s[i]] = 0
for i in range(len(s)):
d[s[i]] += 1
print(d)
if (len(s) == len(d)):
return True
else:
return False
s = 'xyzw' #prints False
print(unique(s)) |
552b859596cd8e05861b632ef16de633477a30f5 | Jeetendranani/yaamnotes | /os/introduction.py | 52,709 | 3.796875 | 4 | """
1. Introduction
A modern computer consists of one or more processors, some main memory, disk, printers, a keyboard, a mouse, a display,
network interfaces, and various other input/output devices. All n all, a complex system.oo if every application
programmer had to understand how all these things work in detail, n... |
83257bb8fb0e2147f534752fbdfb373b67717acc | zakircuet/Python | /if.py | 327 | 3.9375 | 4 |
indian=["somosa","dal","naan"]
chinese=["soup","fried rice","egg role"]
italian=["pizza","pasta","risotto"]
dish=input("Please enter a dish name:")
dish=str.lower(dish)
if dish in indian:
print("indian")
elif dish in chinese:
print("chinese")
elif dish in italian:
print("italian")
else:
print("No know... |
ddfeddb6a76f082e3c408d980860e2f4e964eba0 | davidokun/Python | /fundamentals/5-methods-and-functions/7-homework-exercises.py | 3,289 | 4.09375 | 4 | import string
# Write a function that computes the volume of a sphere given its radius.
print("# VOLUME OF A SPHERE\n")
def vol(rad):
volume = (rad**3 * 3.141592) * (4/3)
return "Volume of Sphere with radius {1} is = {0:1.5f} m3".format(volume, rad)
print(vol(2))
print(vol(8))
# Write a function that chec... |
861b5f91f88f313e2425b6675dea3625a4f6ba63 | sunnystory/Algorithm_2021 | /algory lecture/multi_algori/06큐1.py | 393 | 4.0625 | 4 | queue=[None for _ in range(3)]
front=rear=-1
rear+=1;queue[rear]='A'
rear+=1;queue[rear]='B'
rear+=1;queue[rear]='C'
print(queue)
front+=1;print(queue[front]);queue[front]=None #안해되 되는데 확실히 하려고
front+=1;print(queue[front]);queue[front]=None
front+=1;print(queue[front]);queue[front]=None
print(queue)
rear+=1;queue[rear... |
86fef75ec95e68e5a9ed49c0696ea2c1b92fee1e | IceMIce/LeetCode | /Array/485_Max Consecutive Ones.py | 494 | 3.59375 | 4 | class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
max_num_list = []
for num in nums:
if num == 1:
i = i + 1
max_num_list.append(i)
else:
... |
5f1d92406f44e20655686f2380c9db195bb87a73 | WWTprojects/Python | /School/Lab 1 by Wesley Thomas.py | 1,716 | 4.15625 | 4 | # Wesley Thomas
# Lab 1
#Declare variables for grocery item
item1 = ""
item2 = ""
item3 = ""
item4 = ""
item5 = ""
item6 = ""
item7 = ""
item8 = ""
#Declare variable
# s for the price for each item
price1 = 0.0
price2 = 0.0
price3 = 0.0
price4 = 0.0
price5 = 0.0
price6 = 0.0
price7 = 0.0
price8 ... |
90d4aec5f7ccc48bad55bb2d9d8ffc2330478007 | edmanf/Cryptopals | /src/cryptopals/convert.py | 861 | 4.1875 | 4 | """ This class contains methods for converting from one format to another """
import base64
def hex_string_to_bytes(hex_str):
""" Convert the hex string to a bytes object and return it.
Keyword arguments:
hex_str -- a String object comprised of hexadecimal digits
"""
return bytes.fromhex(h... |
171b998e32a6fde1dd5b037ee117c863026c12e8 | josedoneguillen/python-profesional | /anotaciones/comprehension.py | 457 | 3.640625 | 4 | #lista = []
#
#for x in range(0, 101):
# lista.append(x)
#
#print(lista)
estructura_lista = [ "indice-" + str(x) for x in range(0, 100) ]
print(estructura_lista)
estructura_tupla = tuple(( x for x in range(0, 100)
if x % 2 == 0) )
print(estructura_tupla)
estructura_d... |
d3c421b81e2347ba608153664d399c906a1a0b53 | arsaltariq/Detailed-Assignment-3.17-3.44 | /3.33.py | 92 | 4.15625 | 4 | #Exercise 3.33:
#Reverse string:
x=input("Input three letter string:")
print(x[::-1])
|
9e979cfaa7e3ca1bc5a7a25d5dba1ddb19868838 | edubd/uff2020 | /progs/p14_normalizacao.py | 761 | 4.0625 | 4 | #P14: Normalização
import pandas as pd
#(1)-Importa a base de dados para um DataFrame
df_lojas = pd.read_csv('lojas.csv')
#(2)-Normaliza o “salario”
sal_max = max(df_lojas['salario'])
sal_min = min(df_lojas['salario'])
df_lojas['sal_norm'] = (df_lojas['salario'] - sal_min) / (sal_max - sal_min)
#(3)-Nor... |
11526f44e85f59ddcb204482a70d08faf5b88dd6 | 1cedsoda/py-equalculator | /solve.py | 14,778 | 3.65625 | 4 | from type import getType
import re
def replaceVars(equasion_as_list, variables={}):
equasion = equasion_as_list.copy()
# >>> replace vars <<<
for n in range(len(equasion)):
if equasion[n] in variables:
equasion[n] = variables[equasion[n]]
return equasion
def solveEquasion(equasio... |
c369e076ba5d2b3764a0040238c6c7631d439eff | akashrai80/python-programs | /question-5.py | 726 | 4.21875 | 4 | file = input("enter file name :")
# function for word count
def count_word(file_name):
# open file
f = open(file_name, "r")
total_words = 0
# reterive lines from file
for line in f:
word = True
# reterive letters from line
for letter in line:
# co... |
d59e88f4e83a44b12b1cf0a4e9bde20cd13093ac | pellungrobe/SimulatedPrivacyAnnealing | /PSA/datetime_util.py | 3,644 | 3.640625 | 4 | from datetime import datetime, timedelta
def weekend_weekdays(zero_at_day=0, number_of_days=31):
day_dict = {1: "Monday", 2: "Tuesday", 3: "Wednesday",
4: "Thursday", 5: "Friday", 6: "Saturday", 0: "Sunday"}
day = 24
day_num = zero_at_day
weekdays, weekend = list(), list()
for i in... |
ae34bc98b1af2b240f325c7b2f0a0aa84adbf924 | YaminiNarayanan-359/guvi | /codekata/printnearest.py | 57 | 3.640625 | 4 | h=int(input())
if(h%2==1):
print(h-1)
else:
print(h)
|
ebdd4a56abd2702ee5a120be792b35a56fb0b340 | ko9ma7/cse_project | /coding practice/Judge/1114.py | 1,154 | 3.515625 | 4 | '''
1114. 나무 쌓기 1
초등학교에 입학한 한기대는 격자 모양의 바닥에 나무 쌓기 놀이를 하고 있습니다.
정육면체 도형을 격자 모양에 쌓으면서 놀던 기대는 문득 바라보는 방향에 따라서 쌓인 나무의 모양이 달라 보인다는 걸 깨달았습니다.
쌓인 나무를 위에서 볼때, 오른쪽에서 볼때, 앞쪽에서 볼 때의 개수가 서로 다르다는 걸 깨달은 기대는 그 총 합을 구하고 싶어졌습니다.
한기대를 도와서 각각의 면에 보이는 나무의 개수의 총합을 구하는 프로그램을 구현해 주세요.
'''
X, Y = map(int, input().split()... |
fa072e45b87e2330046453538d7c894110414ae4 | ThomasBrouwer/project_euler | /problem_42.py | 714 | 3.84375 | 4 | import string
def calc_triangle(n):
return n*(n+1)/2
def calc_number(word):
result = 0
for char in word:
result += string.lowercase.index(char.lower())+1
return result
# First we establish the longest word, and then compute the triangle 4
# numbers until that length * 26
words = open('words.txt','r').read().sp... |
fdf955064f3567b583963be2126b369fca6e9120 | madeibao/PythonAlgorithm | /PartB/Py两个有序数组的中位数.py | 2,729 | 3.625 | 4 |
# nums1 = [-1,1,3,5,7,9]
# nums2 = [2,4,6,8,10,12,14,16]
思路:
这道题如果时间复杂度没有限定在 O(log(m+n))O(log(m+n))O(log(m+n)),我们可以用 O(m+n)O(m+n)O(m+n) 的算法解决,用两个指针分别指向两个数组,比较指针下的元素大小,一共移动次数为 (m+n + 1)/2,便是中位数。
首先,我们理解什么中位数:指的是该数左右个数相等。
比如:odd : [1,| 2 |,3],2 就是这个数组的中位数,左右两边都只要 1 位;
even: [1,| 2, 3 |,4],2,3 就是这个数组的中位数,左右两边 1 位;
... |
d53608043488ec1046245376194e78732ab2945e | pyvista/pyvista | /examples/02-plot/vector-component.py | 1,303 | 3.625 | 4 | """
Plot Vector Component
~~~~~~~~~~~~~~~~~~~~~
Plot a single component of a vector as a scalar array.
We can plot individual components of multi-component arrays with the
``component`` argument of the ``add_mesh`` method.
"""
import pyvista as pv
from pyvista import examples
######################################... |
67f47a10fa00d30d42cf8408055a4664edc24532 | bnitish101/Python-Practice | /OOPs In Python/inheritance single, multilevel, multiple.py | 1,025 | 4.1875 | 4 | # Type of Inheritance
# 1. Single Inheritance
# 2. Multiple Inheritance
# 3. Multiple Inheritance
class A: # Super/Parent Class
def feature1(self):
print('Feature One is working.')
def feature2(self):
print('Feature Two is working.')
class B(A): # Sub/Child Class of class A [Multilevel I... |
b8da0b84656533024918762e17b2e2cec4469926 | fabriciogonzalez06/cursos-practicas-old | /Ejemplos python/cicloFor.py | 806 | 3.859375 | 4 | for i in [1,2,3,4,5,6,7,8,9,10]:
lista=["hola"]
print("1)Agregar 2)Buscar 3)eliminar 4)Ver lista 5)Ver tamaño")
opc=int(input("\n Ingrese una opción a realizar >"))
if opc==1:
agregar=input("\n Ingrese una cadena a agregar >")
lista.extend([agregar])
print(lista)
elif opc==2:
buscar=input("\n Ingrese la ca... |
b617c60b700d4243d79158fbe9ab8c5ddddec6d8 | yunieyuna/Solutions-for-Leetcode-Problems | /python_solutions/155-min-stack.py | 1,096 | 3.8125 | 4 | # https://leetcode.com/problems/min-stack/
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
# 数据栈
self.data = []
# 辅助栈
self.helper = []
def push(self, x: int) -> None:
self.data.append(x)
if len(self.helpe... |
4fe3e1725b8431e00cd05676e39c3d96ab73db3e | NecmettinCeylan/Py_Works | /0_Completed_Introduction_to_Computer_Science_and_Programming_in_Python_MIT_6.0001/10.1.py | 1,008 | 3.6875 | 4 |
# import time
# def c_to_f(c):
# return c*9/5 + 32
# t0 = time.clock()
# c_to_f(100000)
# t1 = time.clock() - t0
# print("t = ", t, ":", t1, "s,")
# linear search on unsorted list
# def linear_search(L, e):
# found = False
# for i in range(len(L))
# if e == L[i]
# found = True
# return found
# # li... |
e048db29d3e2fe3211048a104afef3c28c98f728 | Joydata/Opteeq | /Google_vision.py | 5,369 | 3.59375 | 4 | import io
import os
import math
import pandas as pd
# Imports the Google Cloud client library
from google.cloud import vision
# Environment variable must be set before the function can be used
# Terminal command : set GOOGLE_APPLICATION_CREDENTIALS=<KEY_FILE_PATH>
def generate_annotations(input_file, output_file):
... |
12360595d0f0a842be33984f347e43b1d3af01ff | tazbingor/learning-python2.7 | /python-exercise/1-number-and-string/py021_multiplication_table.py | 598 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17/11/7 下午4:08
# @Author : Aries
# @Site :
# @File : py021_multiplication_table.py
# @Software: PyCharm
'''
for循环打印9*9乘法表,要求输出格式如下。
1 2 3 4 5 6 7 8 9
-----------------------------------
1|1 2 3 4 5 6 7 8 9
2|2 4 ... |
e730561d74f73604381fe9b8c9bb03520863c755 | lightmen/leetcode | /python/tree/maximum-depth-of-binary-tree.py | 535 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def depth(self,root,cur_h):
if root is None:
return
cur_h += 1
if cur_h > self.max_h... |
5b510b36ac0e341283429abcb4e235a9ae9c0127 | chenglinyue/Maplestory | /MapleStory.py | 37,186 | 3.78125 | 4 | '''Author: Cheng Lin
Date: June 5th, 2012
Description: This program is a mini version of the 2D game Maplestory.
It is a one player game and will be using the same images and similar
sprites as the original but the game will be implemented differently
overall. The game will be both keyboard and mouse controlled.... |
cf4e927ed359f1c3ac0bcc95620167773077052d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2153/60870/248216.py | 362 | 3.78125 | 4 | num_str = input()
if(num_str[0] == '-'):
num_str = (num_str[1:])[::-1]
for i in range(0, len(num_str) - 1):
if num_str[i] is not '0':
print('-' + num_str[i:])
break
else:
num_str = num_str[::-1]
for i in range(0, len(num_str) - 1):
if num_str[i] is not '0':
... |
6380f3d5afda61376b3aceffd9e382c35fa8562e | mbocaneg/Leetcode-Submissions | /88_merge_sorted_array/main.py | 665 | 3.671875 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
m -= 1
n -= 1
tail = len(nums1) - 1
while tail >= 0:
if m < 0:
nums1[tail] = nums2[n]
n -= 1
elif n < 0:
nums1[tail] = nums1[m]
m -= 1
... |
f6c5a155a4cfba766364d0487eec012aa9c99bef | mkhalil7625/capstone-week1 | /greetings.py | 317 | 4.40625 | 4 | from datetime import date
name = input("What is your name? ")
birth_month=input("What month were you born in? ")
print(f"Greetings, {name}")
if birth_month == 'August':
print("Happy birthday month!")
# today = date.today()
# current_month = today.month
print(f"There are {len(name)} letteres in your name")
|
a630b0d37d77dce7f7f65ac9661211aa19dd9e8a | suvrajeet01/python | /04.26.51_1920.1080_421M/15.py | 578 | 3.9375 | 4 | #Return Statement
#using return statement in python functions
#return keyword allows the program to return information from a function
#after return keyword no new code can be added too the next line as the interpreter will skip it since return breaks back out of the function
#parameter is used to give information to t... |
fc116dc7c14e3582cdeb570c15a6d1253be36299 | jmmedel/Python-Reference | /11_Python_Conditions/02_Conditions.py | 867 | 4.25 | 4 |
"""
Author: Kagaya john
Tutorial 10 : Conditions
"""
"""
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then do this condition"."""
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
"""
In this example a is equal to b, so... |
66fbe59a2102452774343b58fd393f4525853191 | ivanCodegod/guess-the-number-game | /game.py | 1,096 | 4.03125 | 4 | from text import *
from colorama import Fore
intro() # How to play
low, high = None, None # tmp values
attempt = 5 # Default value
level = int(input(" Choose complexity of the game:\n\t1 - easy\n\t2 - medium\n\t3 - hardcore\n"))
print(f'You chose the <<{level}>> level of complexity, GOOD LUCK')
if level == 1: low,... |
0df1decfba15bde489e1ecbc428e1d6d3ba819f4 | matt-fielding8/ODI_Cricket | /src/data/gather_data.py | 4,400 | 3.5625 | 4 | """
All the scripts required to gather missing data from
https://www.espncricinfo.com/
"""
from bs4 import BeautifulSoup
import requests
import numpy as np
def getSoup(url):
'''
Returns soup for url response object.
'''
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
return... |
f2c1a4a31264c21388b83b973f13bae8aeb426cd | ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python | /trees/avl-tree.py | 9,015 | 3.71875 | 4 | class TreeNode:
def __init__(self, key=None, value=None, parent=None, left=None, right=None,
left_subtree_height: int = 0, right_subtree_height: int = 0, balance_factor: int = 0):
self.key = key
self.value = value
self.parent = parent
self.left = left
self.ri... |
8c3384bc99b200394f11505904f39b2b8c4ea60f | ILiterallyCannot/script-programming | /script-programming/task9.py | 279 | 4 | 4 | list1 = [1,2,3,5,4] #the function should return 5
list2 = [1,4,9,2] #the function should return 9
def listmax(numList):
theMax = 0
for i in numList:
if i > theMax:
theMax = i
return theMax
print(listmax(list1))
print(listmax(list2))
|
a9a79c5f2036fa97ff964241b14e9015f522446e | MinasMayth/BitsandBobs | /Maze Game.py | 1,089 | 4.34375 | 4 | # program written by Sue Sentance
import time
def main():
print("You are trying to find your way through a maze to the centre where ")
print("there is a pot of gold!")
print("What you don't know is that this is a dangerous maze with traps and hazards.")
print()
print("Starting maze game .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.