blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1fa6a0c73d34d55016eb66aeca0e8a7ecd3bb375 | bobby20180331/Algorithms | /LeetCode/python/_338.CountingBits.py | 325 | 3.6875 | 4 | # 原来列表也有加法![a]+[b]=[a,b].思路L:利用位移运算
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = [0]
for x in range(1, num + 1):
ans += ans[x >> 1] + (x & 1),
return ans
|
9a0fdd2226aa51129d3f5e409dfdd29ece33810c | beggerss/algorithms | /Sort/merge.py | 1,425 | 3.96875 | 4 | #!/usr/bin/python2
# Author: Ben Eggers
import time
import numpy as np
import matplotlib.pyplot as plt
# Implementation of mergesort written in Python.
def main():
base = 1000
x_points = []
y_points = []
for x in range(1, 20):
arr = [np.random.randint(0, base*x) for k in range(base*x)]
start = int(round(time... |
f7f98b782810ea91307db96d7c212fd2f0106a8c | nyucusp/gx5003-fall2013 | /ke638/Assignment 1/Problem 2.py | 434 | 3.75 | 4 | import sys
def absvalue(i,j):
return abs(int(sys.argv[i]) - int(sys.argv[j]))
n = int(sys.argv[1])
diff = []
for i in range(2,len(sys.argv)-1):
value = absvalue(i,i+1)
diff.append(value)
for i in range(1,n):
found = False
for element in diff:
if(i == element):
found = T... |
0f82a6b3dbce734db750187ab3fe34513ec4388d | LuisPalominoTrevilla/CompetitiveProgramming | /Competition1/primalSport.py | 540 | 3.734375 | 4 | import math
def sieve(primes):
real_primes = []
for i in range(2, x2+1):
if primes[i]:
real_primes.append(i)
for j in range(i*2, x2+1, i):
primes[j] = False
return real_primes
def getX0(x2):
hash_primes = [True]*(x2+1)
primes = sieve(hash_primes)
l... |
d8dadc4a84dff70cac6fa482f7c739e4fb92e51d | Natalshadow/Learning-Python | /Main.py | 1,835 | 3.8125 | 4 | import random
import sys
import datetime
import time
#fake authentication function
def authenticate():
for attempts in range(5):
print("Enter ID: ")
ID = input()
ID = ID.upper()
if ID == 'EXIT':
print('Exiting...\n')
sys.exit()
elif ID == 'JOE':
... |
e9857632937fe32da7a587d056c6fa53b3b41257 | YuudachiXMMY/Python-Challenge | /1.py | 990 | 3.671875 | 4 | '''
# 1
http://www.pythonchallenge.com/pc/def/map.html
'''
def decry(input):
return chr(((ord(input)+2) - ord('a')) % 26 + ord('a'))
def main(txt):
result = ''
for i in txt:
if ord(i)>=ord('a') and ord(i)<=ord('z'):
result += decry(i)
else:
result += i
print res... |
43ff9e7c419b90ba17eead1e2eb81d88c022e0e7 | luamnoronha/cursoemvideo | /ex.055.py | 373 | 4.125 | 4 | maior = 0
menor = 0
for c in range(1, 6):
numero = float(input('Digite um numero: '))
if numero == 1:
maior = numero
menor = numero
else:
if numero > maior:
maior = numero
if numero < menor:
menor = numero
print('O maior numero lido é {}'.format(maior)... |
2c3e69d8ca5a14247555da07a1989ab292c561b0 | eufmike/wu_data_bootcamp_code | /homework/w04_HeroesOfPymoli/code.py | 10,033 | 3.65625 | 4 | '''
# Unit 4: Assignment - Pandas, Pandas, Pandas
## Project: Heroes of Pymoli
Heroes Of Pymoli Data Analysis
* Of the 1163 active players, the vast majority are male (84%). There also exists, a smaller, but notable proportion of female players (14%).
* Our peak age demographic falls between 20-24 (44.8%) with secon... |
5959c1c0d5751792deac3dbab234604e96439cb7 | punpraphanphoj/Project-1 | /A3dataStatistics.py | 1,680 | 3.515625 | 4 | """
Created on Thu Jan 14 16:02:20 2016
A3 Data statistics function
"""
import numpy as np
import math
def dataStatistics(data, statistics):
if statistics == "Mean Temperature":
temperature = data[:,0]
result = np.mean(temperature)
elif statistics == "Mean Growth rate":
gr... |
c07ab9b61466ac38b6f893b4bb6f604c9c901d5a | jinjiangliang/pythonLearner | /PythonResearch/221NumPy.py | 757 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 19:36:30 2018
@author: 1000877
2.2.1: Introduction to NumPy Arrays
Learn how to import NumPy
Learn how to create simple NumPy arrays, including vectors and matrices of zeros and ones
n-dimentional;
C, C++
linear algebra
numpy.org;
"""
import numpy as np
zero_vector... |
2cd06ee91417cff3f075f252431fca211f612c26 | SurajSarangi/Python | /Python/school_salary.py | 334 | 3.765625 | 4 | """Displaying salary in tabular format depending on years of experience"""
s=eval(input("Enter starting salary:\n"))
p=eval(input("Enter percentage increase:\n"))
y=eval(input("Enter number of years:\n"))
print("{0:<8} | {1:<8}".format("Years:","Salary:"))
for i in range (1,y+1):
s+=(p/100)*s
print("{0:>8} | {1:^.2f}... |
fc5acf6505e90ff4f7016a432f53c01a1abcff7d | hansinla/Qualtity_Code | /Lesson code/Palindrome.py | 221 | 4 | 4 | def is_palindrome(s):
"""(str)->bool
This fundction should return True if
and only if the string s is a palindrome.
>>> is_palindrome('noon')
True
>>> is_palindrome('racecar')
True
>>> is_palindrome('ented')
False
"""
|
b9941081bfa0d9e429467c515d0f1aa23d25bcfe | cathalhughes/data-mining | /nn.py | 1,254 | 3.53125 | 4 | # Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
# fix random seed for reproducibility
numpy.rand... |
d98b84de7d8e9d28715d7da26869eda4e4125c91 | samanthaWest/Python_Scripts | /AlgoDaily/TwoStackQueue.py | 952 | 3.671875 | 4 | # import functools
# import math
# import numpy
# Two Stack Queue
# Stack LIFO
# Queue FIFO
# Implementing Queue using 2 stacks
#
class TwoStackQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def en(self, e):
self.s1.append(e)
def de(self):
if n... |
5ead8e1accb928c42ef3f18674536e443ae6f072 | frclasso/1st_Step_Python_Fabio_Classo | /Cap12_Estruturas_de_dados/9.3_Dicionarios/2020/dicionarios_2020.py | 2,602 | 4.03125 | 4 | #!/usr/bin/env python3
#dicionario vazio
al = {}
aluno = {'ID': 1223,
'Nome':'Fabio',
'Sobrenome':'Classo',
'Idade': 45,
'Curso': 'Sistemas de Informação',
'Turno':'Noturno'
}
print(f"ID: {aluno['ID']}")
print(f"Nome: {aluno['Nome']}")
print(f"Idade:{aluno['Idade... |
ce567f6ddc62685dc7f18f760af4446a6c349a8c | Amathlog/MTH6412B | /TP1/unionFind.py | 935 | 3.96875 | 4 | # -*- coding: utf-8 -*-
class UnionFind(object):
def __init__(self):
self.__parent = dict()
self.__rang = dict()
def make_set(self, item):
self.__parent[item] = item
self.__rang[item] = 0
def find(self, item):
""" Compression des chemins. Le parent de chaque noeud... |
7f698dd9c19fe40b1e895b20938ff096c4f9720e | dschoonwinkel/NetworkingPGCourse | /Activity1BashPrimer/python_populator.py | 293 | 3.515625 | 4 | import time
file1 = open("some_text.txt", 'w')
file1.close()
write_count = 0
while(True):
file1 = open("some_text.txt", 'a')
print("Writing to std_out %d" % write_count)
file1.write("Writing to file %d \n" % write_count)
write_count += 1
time.sleep(3)
file1.close()
|
d22f0806ec754c0aedca4cd5e09ded9b61dca7e7 | Ewa-Gruba/Building_AI | /Scripts/C1E1_Optimalization.py | 710 | 3.8125 | 4 |
import math
import random
import numpy as np
import io
from io import StringIO
portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
def permutation(start, end=[]):
if len(start) == 0:
if end[0] == 0:
print(' '.join([portnames[i] for i in end]))
else:
for i in range(len(sta... |
bfa65d91ff23f2c5c291ba4a6450c2acb279d838 | dmil/raspberrypi | /main2.py | 535 | 3.625 | 4 | #!/usr/bin/env python
"""
main.py - turns light red if I might need an umbrella today, and green if I won't
"""
from weather import rain
import rgbled
import RPi.GPIO as GPIO
import time
import rgbled
from weather import rain
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
... |
eca2f753aacff678567625016d7e98882478ab20 | gautamsreekumar/tictactoe | /tictactoe.py | 3,032 | 4.125 | 4 | from numpy import *
from os import *
def markPosition(canvas, playername, n):
moves = int(raw_input("Enter position "))
x = int(moves/10)-1
y = int(moves%10)-1
if x > n-1 or y > n-1:
print "Invalid position"
temp = markPosition(canvas, playername, n)
elif canvas[x, y] == 2*n:
... |
cdbb1dc82dac13f36383f179e2df457c3bf5a1b1 | reshmaladi/Python | /1.Class/Language_Python-master/Language_Python-master/LC25_1_IPaddressChecking.py | 751 | 3.640625 | 4 |
import re
def checkip(ip):
pattern = re.compile("(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})")
k=re.match(pattern,ip)
type=k.group(1)
print(type)
type = int(type)
if(int(k.group(2))<256 and int(k.group(3))<256 and int(k.group(4))<256):
if(type<127 and type>0):
print("Class A")
elif(type<192 and type>127):... |
46b6e19cee41566551164635cb3daca26a6a396d | HiCitron/PythonOftenUsed | /chars.py | 1,422 | 3.75 | 4 | # -*- coding: utf-8 -*-
def IsNumber(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 48 and k <= 57 ):
return False
return True
def IsUpper(s):
for i in range(len(s)):
k = ord(s[i])
if not(k >= 65 and k <= 90 ):
return False
r... |
dca811d735a4d086641730c3537c30a9240fb1d0 | brisa123/palindrome | /practice.py | 147 | 3.53125 | 4 |
a="i am a girl"
b=a.capitalize()
print(b)
c=a.split()
print(c)
'''wkejfnwjiefjnf
sdfkfjnsalkgm
wlggknwrlg
woekfowkenmf
ewlkfnwrg
weflkwng'''
|
efec61863383cf738f3ff00e6e8ffc0441232a54 | jeromejohnenriquez1121/SJSU_CMPE130_Project | /school_content.py | 7,488 | 3.890625 | 4 | # a module with the information and functions about the students and assignments
'''
The school_content module has a 'student' class. The student has a full name, an email
address, an ID number, and a list of grades. The students can be sorted by their names
or their ID numbers; their grades can also be sorted from low... |
945b7bfbdf8e92a61122fb4fe18c40c55df4e98e | dbarella/ArrowLanguage | /datatypes.py | 7,220 | 3.625 | 4 | import numbers, functools, evaluator, inverter, shared
@functools.total_ordering
class Num:
"""
Because floating-point numbers lead to irreversibility, infinite-precision
rational numbers are used in Arrow.
"""
def __init__(self, top, bottom=None, sign=None):
"""
Nums store a numera... |
7f0afe650638d180d15316bf2d203d74d3273dce | GregBlockSU/iSchool | /ist652/Week8/twitter_hashtags.py | 3,266 | 3.71875 | 4 | '''
This program processes a DB collection of tweets and returns the top frequency hashtags.
The Mongod server must be running.
The number parameter is the number of top frequency hashtags to print.
Usage: python twitter_hashtags.py <DBname> <DBcollection> <number>
Example: python twitter_... |
de761230b22c343cde9f22d47e84345128d717b8 | noamoalem/intro | /ex7/ex7.py | 6,776 | 4.46875 | 4 | #################################################################
# FILE : ex7.py
# WRITER : noa moalem , noamoa , 208533554
# EXERCISE : intro2cs ex7 2019
# DESCRIPTION: we asked to write 10 recursive function
# #################################################################
def print_to_n(n):
"""This function ... |
01a0e26ada1e183ff9d65d4e2196177cb0ad8863 | daniel-reich/ubiquitous-fiesta | /sDvjdcBrbHoXKvDsZ_24.py | 114 | 3.625 | 4 |
def anagram(name, words):
name = name.replace(" ","").lower()
return sorted("".join(words)) == sorted(name)
|
18ae81b7575762b250afdc7035ae8483ab6f8f4a | lakshmipraba/New-two | /search.py | 457 | 4.0625 | 4 | def search(sorted_list,n):
i=0
while(i<=int(new)):
if(sorted_list[i]==n):
print "ur element in the %r position of the list"%i
exit(0)
else:
exit
i=i+1
print "-1"
sorted_list=[]
i=0
new=raw_input("enter the no.of elements in ur list:")
while(i<=int(new)):
print "the %r element in the list"%i
a=r... |
4dedf03cb9ef479426f56d4206a2192afae54ab2 | jessiditocco/interview_prep | /hackerrank/problem_solving/algorithms/diagonal_difference.py | 1,116 | 4.03125 | 4 | def diagonal_difference(matrix, num):
diagonal1 = 0
diagonal2 = 0
for i in range(num):
diagonal1 += matrix[i][i]
diagonal2 += matrix[i][(num - 1) - i]
return abs(diagonal1 - diagonal2)
print diagonal_difference([
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
], 3)
... |
30b6660dc1a038d117e6adb5d3a32754a78f4099 | yenwel/DAT256x | /Module03/excercises.py | 165 | 3.84375 | 4 | def magnitude(x):
return sum([i**2 for i in x])**(1/2)
print([i**2 for i in [3 ,5]])
print(sum([9, 25]))
print(34**(1/2))
print(magnitude([3 ,5]))
print(2*4+5*3) |
8e89364bc15157166dc4fa6cab299a76d4483b82 | mike111452/code-practice | /code/elenen.py | 467 | 3.71875 | 4 | while True:
n=str(input())
if n == '0':
break
sum1=0
sum2=0
for i in range(1,len(n),2):
sum1=sum1+int(n[i])
for j in range(0,len(n),2):
sum2=sum2+int(n[j])
if sum2>sum1:
sum1,sum2=sum2,sum1
if (sum1-sum2)==0:
print(n,"is a mu... |
6d3c055b12c84936c9cbe99849021b3da64273ec | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4081/codes/1643_869.py | 306 | 3.625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
preço=float(input("sem desconto:"))
desc=(preço*5/100)
sub=(preço- desc)
if(preço>=200):
print(round(sub, 2))
else:
print(round(preço, 2)) |
5d624f375d637476c7601d16ea9ab915a0f8b776 | malyar0v/UVa-solutions | /543/543 - Goldbach's Conjecture.py | 717 | 3.625 | 4 | UPPER_BOUND = 1000000
def generate_primes():
table = {boolean: True for boolean in range(UPPER_BOUND)}
root = int(UPPER_BOUND ** 0.5)
for i in range(2, root):
index = i * 2
while True:
if index > UPPER_BOUND:
break
table[index] = False
index += i
return table
if __n... |
1502853316e915aee5615901940ef65c321de075 | baothais/Practice_Python | /lambda.py | 938 | 4.21875 | 4 | # thislist = list(filter(lambda x: x%2==0, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# for i in thislist: print(i)
# thisdict = dict(brand = "Ford", model = "Everest", price = "50,000$")
# l = list(map(lambda x: x[0], thisdict.items()))
# for i in l: print(i)
# syntax
"""lambda arguments : expression""" # The expression is exe... |
f96d62b329f857259e0ebb8c144dd01f51c993dc | prolaymukherjee/PythonBasicToAdvance | /python/py12.py | 174 | 3.875 | 4 | x=int(input("Enter The First Number:"))
y=int(input("Enter The First Number:"))
z=int(input("Enter The First Number:"))
print(max(x,y,z))
input("Please press enter to exit")
|
a7f3f2529a637643e5a8e68779b0e6ff8e28f3e0 | tom-henderson/dotfiles | /scripts/num2words | 2,705 | 4.125 | 4 | #!/usr/bin/python
import sys
def bigNumbers( n, lowerBound, theWord ):
if n % lowerBound == 0:
return numberAsWords( n / lowerBound ) + ' ' + theWord
elif n - ( n / lowerBound * lowerBound ) < max( lowerBound / 1000, 100 ):
return numberAsWords( n / lowerBound ) + ' ' + theWord + ' and ' + num... |
662c83ad2bdd231e9296ff70e80b026dd686c465 | mrgsfl/Python-OOP-course | /python_task_2.py | 143 | 3.578125 | 4 | objects = [1, 2, 1, 2, 3, True, False, "true", '1', True]
ans = 0
s = set()
print("set: ", s)
for obj in objects:
s.add(id(obj))
print(s)
|
3ec14b058b49c2526452378dd85d02733e398c1d | allankeiiti/Python_Studying | /SoloLearn_Scripts/Strange_Root.py | 1,133 | 4.375 | 4 | # Strange Root
# A number has a strange root if its square and square rot share any digit. For example, 2 has a strange root because
# the square root of 2 equals 1.414 (consider the first three digits after the dot) and it contains 4 (which is the square
# of 2).
#
# Examples:
# Input: 11
# Output: True
# (The square ... |
19c5cc14784451d9169eefa0f825cd9d702c5e1f | rambling/algo-study | /userspace/mitkim123.kim/week01/mercy_mitkim123_01.py | 321 | 3.578125 | 4 | # -*- conding: utf-8 -*-
'''
Created on 2016. 5. 16.
@author: mitkim123
'''
def main():
print("Input number ...")
a = input()
count = int(a)
if(count>0):
print("Hello Algospot!\n" * count)
else:
print("[Warning]Input number should be > 0")
if __name__ == "__main__":
main()... |
7d98ad6bcd6d6652a37386cdda2f3033933bda69 | LarsiParsii/Smarthus.gruppe9 | /Python/print_func.py | 202 | 3.5625 | 4 | import datetime as dt
def TimePrint(msg):
'''Takes an input and combines it with a timestamp, then prints it.'''
now = dt.datetime.now().strftime('%x %X')
print(f"[{now}] {msg}") |
e82c06d2dfbf9ed4590f27513dc89e58ee3322fa | sgscomputerclub/tutorials-python | /Week 2/Tutorial Walkthrough/6-Slicing.py | 1,845 | 4.34375 | 4 | '''
More Advanced Slicing Techniques
'''
l = [0,1,2,3,4,5,6,7]
print l[4:5] # Gets 5th item from the list (indexing starts from 0)
'''
Important to Note: Slicing isn't choosing the items in the list, it's about dividing the list or slicing the list. In l[4:5], imagine a cursor is placed four items in, then it's m... |
9d9d58a9dd4f54e232d0ff346c0de9e234704ed1 | PARKJUHONG123/turbo-doodle | /ALGOSPOT/7_2_FENCE.py | 1,605 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 14:59:58 2020
@author: elin9
"""
def biggest_rectangle(left, right):
if left == right:
return fences[left]
mid = int((left + right) / 2)
ret = max(biggest_rectangle(left, mid), biggest_rectangle(mid + 1, right))
lo = mid
hi = mid ... |
b3e9a8000f72208d59493eb01b3cba1a55231f2c | Flor246/PythonFlor | /Modulo2/scripts/triangulo.py | 202 | 3.96875 | 4 | # %%
altura = int(input('Ingrese la altura del triangulo: '))
# %%
print(altura)
# %%
for i in range(1,altura+1):
print('#'*i)
# %%
for i in range(1,altura+1):
print(' ' * (altura-i) + '#' * i)
|
f7c64163adb1191c131b8862c5b343d303d5aa00 | nilanjanchakraborty87/py-learn | /introduction/hello.py | 367 | 3.578125 | 4 |
#! /usr/bin/python
import sys
from utils import power, repeat
"""
Hello python
"""
def main():
# print("Hello ", sys.argv[1])
print("Square of 9: ", power(9, 2))
print("Docstring of power: ", power.__doc__)
print("power type: ", type(power))
print(repeat("Python", 3))
print(repeat("-", 100))... |
cd88028fbc09d312f34e66cec2f21509d0020634 | BIGWangYuDong/Algorithm | /1.sort/sort_count.py | 436 | 3.796875 | 4 | def sort_count(array):
n = len(array)
num = max(array)
count = [0] * (num+1)
for i in range(n):
count[array[i]] += 1
arr = []
for i in range(num+1):
for j in range(count[i]):
arr.append(i)
return arr
if __name__ == '__main__':
x1 = [4, 2, 1, 5, 7, 3, 9, 6, 8... |
1cdfd84bea0f3eda7a72aaf8224883c5977d9e23 | Billl000/gotit-intership | /Chap4.py | 1,740 | 3.515625 | 4 | from utils.display import display_chap_result
class chap4():
def practice1(self):
print ('Computer' + 'Science')
print ('Darwin\s')
print ('H2O' * 3)
print ('CO2' * 0)
def practice2(self):
print("They'll hibernate during the winter.")
print('"Absolutely not," he... |
fe9eba66c854ffd380037e9e211adc5b693be440 | biljiang/pyprojects | /Badbuy_NN/.ipynb_checkpoints/Car_predict1-checkpoint.py | 6,850 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 10:15:43 2018
Build Neural network from perceptron,treating biases as part of weights and use
matrix computation to optimize the stochastic gradient descent method.
@author: Feng
"""
#### Libraries
import random
import numpy as np
class NeuralNetw... |
86089a27a146fa9f673458f71e563dd9e31975e9 | spencerbertsch1/IOT-Raspberry_Pi | /web_led_communication_test.py | 960 | 3.796875 | 4 | # Spencer Bertsch
# Dartmouth College - Winter 2018
# IOT Short Course, R-Pi Programming Demo
# This program blinks an LED pseudo randomly
#
# Import needed modules
import time
import RPi.GPIO as GPIO
import random
#### o_o
import web
#### -_-
led = 4 # connect the LED to this pin on the GPIO
pir = 17 # conn... |
727e95470fa7f79947831e4b2f577365f81ba387 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/443a8b38e1c74b13b3a060c20bc57613.py | 395 | 3.828125 | 4 | def square_of_sum(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x
total_holder = total_holder ** 2
return total_holder
def sum_of_squares(number):
total_holder = 0
for x in range(1,number+1):
total_holder += x**2
total_holder = total_holder
return total_holder
def differe... |
ba7eb01fbe6edd7b1498ddd4d0e64b686343ff12 | wkcn/leetcode | /0001-0100/0070-climbing-stairs.py | 320 | 3.578125 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2: return n
one = 2
two = 1
for i in range(3, n):
old_one = one
one = two + one
two = old_one
return one + two
print(Solution().climbStairs(2))
print(Solution().climbStairs(3))
|
63c16911a2de926b882ee6f5b550a4895fceec7e | manusia1932/Praktikum-STEI-IF-ITB | /Dasar-Pemrograman/PRAKTIKUM-5/berat.py | 873 | 3.53125 | 4 | # NIM/Nama : 16520299/Malik Akbar Hashemi Rafsanjani
# Nama file : berat.py
# Topik : Pengulangan dan Pemrosesan Array
# Tanggal : 9 April 2021
# Deskripsi : Program yang digunakan untuk membaca masukan berat tubuh mahasiswa dan menampilkan beberapa statistik
# KAMUS
# total, N, i, kurang, lebih : integer
# arr : arr... |
2a024b3a118d5fef6ec7acfaf8a610e78808d248 | Dustyposa/goSpider | /python_advance/about_pyhton/simple_interpreter/interpreter_1.py | 1,573 | 3.59375 | 4 | class Interpreter:
def __init__(self):
self.stack = []
def LOAD_VALUE(self, val) -> None:
self.stack.append(val)
def PRINT_ANSWER(self) -> None:
answer = self.stack.pop()
print(answer)
def ADD_TWO_VALUES(self) -> None:
total = self.stack.pop() + self.stack.pop(... |
c17a27d6d704102b2929f8c0cc347c06bf549b94 | piyushkaran/old-python | /prev Python/pyt25.py | 208 | 3.9375 | 4 | year=int(input())
if(year%100==0):
if(year%400==0):
print("leap year")
else:
print("not a leap year")
elif(year%4==0):
print("leap hai")
else:print("bewakkof nahi h leap")
|
827040c9fa87434546df9f8365c41ece8cdd527d | Kuldeep28/Satrt_py | /zipinffuntion.py | 922 | 4.21875 | 4 | string="kuldeepop"
tup=[1,2,5,7,8,8,9,89,90]
print(list(zip(string,tup)))# in zip function the length of the zip list is depending on the value of the shortest listt
zipped=list(zip(string,tup))
for entity,num in zipped:# that cool we are using tupple assingnment to iterate over it as we are confirmed that there
... |
c94816c68324c76fdd4b223980fdfb47a5fe6634 | tanlangqie/coding | /二叉树/98二叉搜索树.py | 1,088 | 3.53125 | 4 | # -*- coding: utf-8 -*-#
# Name: 98二叉搜索树.py
# Author: tangzhuang
# Date: 2021/7/20
# desc:
"""
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处... |
c828b1de74e770642ab4b6bedce0244bead4e745 | Sunsetjue/python | /多线程/多线程_3.py | 1,079 | 3.90625 | 4 | import time
import threading
def loop1():
print('Start loop1 at:',time.ctime())
time.sleep(4)
print('End loop1 at:',time.ctime())
def loop2():
print('Start loop2 at:',time.ctime())
time.sleep(1)
print("End loop2 at:",time.ctime())
def loop3():
print('Start loop3 at:',time.ctime())
time... |
baec963ba0762ddff463147c2445fec2fe2b47a1 | belaidabdellah/databricks | /04-Working-With-Dataframes/1.Describe-a-dataframe.py | 4,084 | 3.640625 | 4 | # Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Describe a DataFrame
# MAGIC ### Tuto à suivre en détail
# MAGIC
# MAGIC Your data processing in Azure Databricks is accomplished by defining Dataframes to read and process the Data.
# MAGIC
# MAGIC This notebook will introduce how to read your data using Az... |
0a50346b59d640e568e92bc3ad21f5ae5b7099f5 | vinobc/UGE1176 | /scope.py | 650 | 3.546875 | 4 | def main():
type = "hot"
def mix_and_heat():
print("prepare ingredients")
print("heat milk/water in a bowl")
print("put sugar")
def make_coffee(param1):
global type
mix_and_heat()
print("put coffee powder")
coffee='{} coffee ready'.format(type)
... |
77660f9dad44fc30b1094c63aba74842f8f45ddd | ralphbean/ms-thesis | /__old_stuff/src/1_over_f_visualization.py | 369 | 3.53125 | 4 | #!/usr/bin/python
import pylab
from math import log
def frange(start, stop, step):
return [ start + float(i)*step for i in range((stop-start+step)/step)]
T = frange(0.01,1,0.01)
X = [1.0/(ele) for ele in T]
pylab.subplot(2,1,1)
pylab.title('1/x')
pylab.plot(T,X)
pylab.subplot(2,1,2)
pylab.title('log(1/x)')
pyl... |
1405df871cd8674ab1f6c1896dcf8f81bb242ca7 | PKNU-IT-ALGORITHM2019/pa-04-alsgur1368 | /programming4-1.py | 2,350 | 3.546875 | 4 | #-*- coding : utf-8 -*-
import random
import sys
import time
def input_random(size):
sort_list=[]
for i in range(0, size):
sort_list.append(random.randint(1, size))
return sort_list
def input_reverse(size):
sort_list=[]
for i in range(size, 0, -1):
sort_list.append(i)
return ... |
bbebeb8648ba561b5c0660b775ee9e348d0c8977 | maverick13m/correletion | /meme.py | 1,000 | 3.96875 | 4 | import plotly.express as px
import csv
"""
#ice cream vs temp
with open("./Ice-Cream vs Cold-Drink vs Temperature - Ice Cream Sale vs Temperature data.csv")as f:
df1 = csv.DictReader(f)#₹
figure1 = px.scatter(df1,x = "Temperature",y = "Ice-cream Sales( ₹ )")
figure1.show()
"""
#coffee vs sleep
w... |
e5748150fe6b2333ee0c35fb8626c813e1e03661 | gerisd/Path_Planning | /Breadth First Search/main.py | 1,773 | 3.875 | 4 | from BFS import BreadthFirstSearch as BFS
import numpy as np
#10x10 grid
grid = [[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,... |
636931f6c8b05e09e52c35ace3b1ed4c29eca811 | HaoPham1912/ML_gradient-boosting | /GradientBoostingRegressor.py | 2,231 | 3.53125 | 4 | #tham khao tai https://acadgild.com/blog/gradient-boosting-for-regression-problems
#import các thư viện cần dùng
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.metrics import mean_squared_error, r2_sco... |
cab5908306224830d26c969dc89f71e883819a37 | JacobAAnderson/Python | /Templates/Textfile.py | 669 | 3.984375 | 4 | # .txt template
# This script will create a text file and read and write to the text file
# The read comands return a list object containing the text from the file.s
with open("Desktop/testfile.txt",'w') as file:
file.write('Hello World\n')
file.write('This is a test\n')
file.write('This is line 3\n')
... |
128de0e1c7170501e9fcd130e0f464a3c6481094 | ramlaxman/cisco-feb2020 | /mytest.py | 194 | 3.734375 | 4 | #!/usr/bin/env python3
def hello(name: str) -> str:
greeting = 3
greeting = 'Hello'
return f'{greeting}, {name}'
print(hello('world'))
print(hello(5))
print(hello([10, 20, 30]))
|
09de478578b5a67f5401f75ab7cf2e7d6ed19e43 | angel-robinson/carrion.chancafe.trabajo7 | /rango02.py | 167 | 3.5625 | 4 | # imprimir los n numeros enteros
import os
#input
n=int(os.sys.argv[1])
#inicio_rango
for n in range(n):
print(n+1)
#fin_rango
print("fin del bucle")
|
bc7cf8151bb8d8556600ce95222128a9f9a38a98 | Nikitushechka/mipt_python_1sem | /1/1.7.py | 727 | 3.734375 | 4 | import turtle
import numpy as np
import math
turtle.shape('turtle')
R = 30
x = 1
n = 3
turtle.up()
turtle.goto(R,0)
turtle.down()
def ok(x):
... |
76fa058c4bfb8b4ef1bd3b0d41610ca0845be809 | ujjwalshiva/pythonprograms | /Replace 0 with 5.py | 465 | 3.875 | 4 | number = int(input("Enter a number: "))
def convertFive(n):
lst_num = list(str(n))
if '0' not in lst_num:
return n
else:
updated_number = 0
for items in lst_num:
if items == '0':
index = lst_num.index('0')
lst_num[index] = '5'
... |
5be8e772ab21e22f7660c9bdd9697685764428fb | dineshpazani/algorithms | /src/com/python/ReverseStringRecursive.py | 396 | 3.8125 | 4 |
def reverse(s, k):
if k == len(s):
return;
reverse(s, k+1);
print(s[k])
def reverseNby2(s):
if len(s) == 0:
print(s)
ls = list(s)
l = len(s)-1
for i in range(len(ls)//2):
t = ls[i]
ls[i] = ls[l-i]
ls[l-i] = t
... |
3fa87b39fbff52cb2c76e44f9d3b7c1eede2cd6e | tywins/TC1014 | /funWithNumbers.py | 415 | 4.15625 | 4 | x=int(input("Enter a number: "))
y=int(input("Enter another number: "))
summ=x+y
difference=x-y
product=x*y
division=x/y
remainder=x%y
print ("the sum of ", x, " + ", y, " = ", summ)
print ("the difference of ", x, " - ", y, " = ", difference)
print ("the product of ", x, " x ", y, " = ", product)
print ("the division ... |
7b7f1e18492c29217ff0162770af9b0065292af9 | codebubb/python_course | /Semester 1/Week 1/maths.py | 215 | 4 | 4 | # What do the different symbols do?
print 2 + 2 # Add
print 12 - 2 # Subtract
print 3 * 3 # Multiply
print 3 ** 3 # To the power of
print 12 / 3 # Divide
print 12 % 3 # Remainder
|
5ba74cdd0f08689e4c74a784f8d56df5f5d0ba56 | luisandre69/python-programming-course | /syntax_errors.py | 299 | 3.59375 | 4 | # %% IndexError
L=[1,5,8]
L[3]
# %% KeyError
x={"a":1,"b":2,"c":3}
x["d"]
# %% TypeError
L=[1,2,3,4]
L["a"]
# %% AttributeError
L=[1,2,3,4]
L.add(5)
# %% NameError
z
# %% ZeroDivisionError
y=10/0
y
# %% IndentationError
def greet():
print("Hello")
# %% OverflowError
a=24583**2456.1245
a |
2561c8aafdd87bf22d67be444ed45e9e9f2b389d | gaTarr/PythonasaurusRex | /Module8/more_fun_with_collections/assign_average.py | 603 | 3.890625 | 4 | """CIS189 Python
Author: Greg Tarr
Created: 10/14/2019"""
def switch_average():
""" This prompts a user to select from a set of Keys
and returns the value associated with that key.
:returns the value of the selected key, or a message
if an invalid key is selected
"""
try:
search_value ... |
d0986444945a96db564f2cdda08b9e0dcffdf373 | JoJaJones/leetcode_solutions | /SameTree.py | 548 | 3.5625 | 4 | class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return self.BFS(q) == self.BFS(p)
def BFS(self, node):
queue = [node]
res = []
while len(queue) > 0:
cur ... |
d8b4cb3cc121e48a4e8d2b35c19f790892db8119 | MattB17/ComputerNetworks | /Networking/UDPPinger/udp_server.py | 2,561 | 3.953125 | 4 | """The UDPServer class implements a server using the UDP protocol.
"""
import socket
from Networking.Base.network_server import NetworkServer
from Networking.UDPPinger import utils
class UDPServer(NetworkServer):
"""Implements a UDP Server of a given `reliability`.
UDPServer is a dervived class of the gener... |
41afd55e7130037e9c77fa03b832ace16cbaae5e | chanthony/Oregon-112 | /TP3 Test/characters.py | 4,391 | 3.5625 | 4 | #characters.py
import random
def generateCharacters(data):
data.characterList = []
for char in range(4):#four people per party
character = Character("",char)
data.characterList.append(character)
class Character(object):
def __init__(self,name,index):
self.name = name#k... |
d1eca227b49239da04226bc6c8f66fc434babe0c | hosankang/AI_Class | /Classification_2.py | 437 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
def ActivationFunction1(n):
return 1/(1+math.e**(-n))
def ActivationFunction2(n):
return n
w11=10
w12=10
b1=-10
b2=10
w21=1
w22=1
b3=0
p=np.arange(-2,2,0.01)
p1=ActivationFunction1(w11*p+b1)
p2=ActivationFunction1(w12*p+b2)
p3=ActivationFunction2((p... |
de871b56ca8cc3cb5930520a1a55efbf73186ba8 | Akashmallareddy/mini-tool | /generator.py | 764 | 3.96875 | 4 | import random
def pwd_generator(name, mail):
#name=input('Enter your name:')
#mail=input('Enter your mailid:')
symbol=['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>',
'*', '(', ')']
#print(name, mail)
n=[]
n[:]=name
m=[]
m[:]=mail
final=n+m+symbol
password=[]
z=''
t1 = len(... |
1afc3c225159031d26cb695863e698d82d494b32 | thetruejacob/CS166 | /pycx-0.32/misc-fileio.py | 371 | 3.984375 | 4 | # Simple file I/O in Python
#
# Copyright 2008-2012 Hiroki Sayama
# sayama@binghamton.edu
# writing to file
f = open("myfile.txt", "w")
f.write("Hello\n")
f.write("This is a second line\n")
f.write("Bye\n")
f.close()
# reading from file
f = open("myfile.txt", "r")
for row in f:
print row,... |
3f22d80169b7776fb5d159cbab04aaa28038add2 | MalyshkinMike/Gubar | /3.py | 2,837 | 3.625 | 4 | # 3 лаба
import numpy as np
from numpy import fabs
import matplotlib.pyplot as canvas
def f(x):
return (np.pi * x - 3) / (x - 1) ** 2
def f2(x):
return 2 * (x - 1) - 5 * (np.pi * (x ** 2 + x - 2) - 9 * x + 9) # 2⋅(x−1)−5⋅(π⋅(x2+x−2)−9⋅x+9)
def f4(x):
return 24 * ((x - 1) ** -7) * (np.pi * (x * (x + ... |
ce3207a74b696e47c3349e4817cabcae55a4649a | ogarnica/Compumaticas | /progresiones.py | 151 | 3.5 | 4 | a1 = int(input('primer numero: '))
d = int(input('desplazamiento: '))
n = int(input('ultimo termino: '))
an = a1+(n-1)*d
suma = (a1+an)/2*n
print(suma) |
68fe05c07018b0dab716f70b94febaedc60e988e | romulovieira777/Programacao_em_Python_Essencial | /Seção 05 - Estruturas Lógicas e Condicionais em Python/Exercícios da Seção/Exercício_31.py | 1,044 | 4.21875 | 4 | """
31) Faça um programa que receba a altura e o peso de uma pessoa.
De acordo com a tabela a seguir, verifique e mostre qual a classificação
dessa pessoa.
| Altura | Peso |
| |Até 60 | Entre 60 e 90 (Inclusive) | Acima de 90 |
|Menor que 1,20|... |
0c197f957465b229407a753d8e95d9154976eb04 | andres4423/Andres-Arango--UPB | /Numpy/Ejercicio14.py | 954 | 4.1875 | 4 | print("Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array.")
print("Sample Array [0, 12, 45.21 ,34, 99.91] Expected Output: Values in Fahrenheit degrees: [ 0. 12. 45.21 34. 99.91] Values in Centigrade degrees: [-17.77777778 -11.111... |
2a28b5fc1d2aacf435be44ab848b76a981d5860c | whjr2021/G11-C3-V1-SAA1-Solution | /C3_SAA1_Solution.py | 694 | 4.15625 | 4 | # Define a variable "num1" and assign a value to it
num1 = 90
# Define a variable "num2" and assign a value to it
num2 = 50
# Define a variable "choice" and assign any one value between 1 to 4
choice = 3
# Check if "choice" is equal to 1, then print the sum of "num1" and "num2"
if choice == 1:
print(num1 + nu... |
5fe95ba0f69683028a95ff2a976c464c7c4ec33b | zidarsk8/aoc2019 | /test_aoc_20.py | 12,848 | 3.515625 | 4 | import string
import collections
import heapq
class Vertex:
def __init__(self, name, pos=None, dl=0):
self.pos = pos
self.name = name
self.adjacent = {}
self.distance = 100000000
self.previous = None
self.dl = dl
def __str__(self):
return (
... |
d6da3d1dc564c45307cc28a419e904c3bab9bcba | AndresERojasI/ClaseJS | /Python/First Class/3_Operators.py | 1,696 | 4 | 4 | #------------------ Arithmetic: ------------------#
x = 15
y = 4
# Output: x + y = 19
print('x + y =', x+y)
# Output: x - y = 11
print('x - y =', x-y)
# Output: x * y = 60
print('x * y =', x*y)
# Output: x / y = 3.75
print('x / y =', x/y)
# Output: x // y = 3
print('x // y =', x//y)
# Output: x ** y = 50625
print... |
a535b84f63b71526ec980926a847574d4a0dc5a9 | mrsingh3131/Foobar | /Some other foobar gits/xslittlegrass/solutions/Q41.py | 1,984 | 3.796875 | 4 | import itertools
def calculate_graph_distance_matrix(weight_mtx):
"""calculate shortest graph distance matrix"""
num_vertex = len(weight_mtx)
dist = [[0 for i in range(num_vertex)] for j in range(num_vertex)]
for i in range(num_vertex):
for j in range(num_vertex):
dist[i][j] = we... |
9f36d102f754864e405354fa1dd86c970eec5f76 | ahd3r/some_code_python | /Cat.py | 2,414 | 3.5625 | 4 | from random import randint
class Cat:
def __init__(self, name):
self.name = name
self.mood = 100
self.fulness = 50
self.home = None
self.sleep = 100
def __str__(self):
if self.home is None:
if self.sleep >= 75:
return f'I am a {self.name}, I am {self.mood}% good, I am full... |
4a081e1427d0562c4ca9a6d57fc003355e93278d | wljave/subentry | /test/module.py | 767 | 3.796875 | 4 | a = '我是模块中的变量a'
def hi():
a = '我是函数里的变量a'
print('函数“hi”已经运行!')
class Go1: # 如果没有继承的类,class语句中可以省略括号,但定义函数的def语句括号不能省
a = '我是类1中的变量a'
@classmethod
def do1(cls):
print('函数“do1”已经运行!')
class Go2:
a = '我是类2中的变量a'
def do2(self):
print('函数“do2”已经运行!')
... |
66976de4fdaa47fb3986cc9ca06751dbb4868ba9 | AndrewDuncan/Doublecoset | /python/genfold/hd.py | 499 | 3.53125 | 4 | from graph import *
G=Graph()
a=G.addVertex()
b=G.addVertex()
c=G.addVertex()
d=G.addVertex()
e=G.addVertex()
f=G.addVertex()
G.addEdge(a,b,'x')
G.addEdge(a,b,'y')
G.addEdge(b,c,'x')
G.addEdge(b,c,'y')
G.addEdge(c,d,'x')
G.addEdge(c,d,'y')
G.addEdge(d,a,'x')
G.addEdge(d,a,'y')
G.addEdge(a,e,'w')
G.ad... |
828879ec7bbfeb56f44b558e961fdc4017d59c7f | akimi-yano/algorithm-practice | /lc/1814.CountNicePairsInAnArray.py | 3,029 | 3.609375 | 4 | # 1814. Count Nice Pairs in an Array
# Medium
# 103
# 11
# Add to List
# Share
# You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all... |
7b4f974b6893ef01ea389b5665d6158c5b2d168b | SuryaGowrisetti/War_game | /game_logic.py | 1,996 | 3.578125 | 4 | import deck
import player
a_deck = deck.Deck()
a_deck.shuffle() # shuffling the deck
player1 = player.Player('Surya')
player2 = player.Player('Chandu')
for i in range(int(len(a_deck.cards)/2)):
player1.cards.append(a_deck.deal_one())
player2.cards.append(a_deck.deal_one())
game_on = True
rou... |
455c50d52518d02c67c1095fd2ed087f8909e8f4 | alexhla/programming-problems-in-python | /remove_duplicates.py | 667 | 3.71875 | 4 | class Solution:
def removeDuplicates(self, nums): # remove duplicate numbers from a sorted list
if not nums: # an empty list has zero duplicates
return 0
i = 0 # 1st pointer
for j in range(1, len(nums)): # loop with 2nd pointer to avoid index overflow
if nums[i] != nums[j]: # IF nums at 1st and 2nd p... |
5ee59d3cf66f8cea47d1d32cb3ba1ddc667dff41 | amandeep1991/data_science | /ai/nlp/udemy/1/Section 4 - Regular Expression/regex6_groups.py | 405 | 3.796875 | 4 |
import re
# Regex Groups using or '|'
###### OR is represented by |
###### You can a group using ()
###### explicit character range using []
# Few patters
r"[A-Za-z]+" # upper or lowercase English alphabet
r"[0-9]" # numbers from 0 to 9
r"[A-Za-z\-\.]+" # upper or lower case English alphabets with - or .
r"(a-z)" #... |
a9f066966368df9c51ebea91a1cbfff8b06bb8c5 | Neha-kumari31/Intro-Python-II | /src/player.py | 413 | 3.578125 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
from room import Room
class Player:
def __init__(self, current_room=None):
self.current_room = current_room
self.player_items= []
def add_inventory(self,item):
self.player_items.append(item)
... |
721aee08db14cd87e44347ab075b48c4706b942e | kunalt4/AlgorithmsandDataStructuresCoursera | /Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py | 1,456 | 3.625 | 4 | # Uses python3
import sys
import collections
def fast_count_segments(starts, ends, points):
l_label = 1
point_label = 2
r_label = 3
cnt = [0] * len(points)
points_dict = collections.defaultdict(set)
tuples = []
for start in starts:
tuples.append((start, l_label))
for end in... |
5eed55109def2c21809d4178fdfd5567bbd32797 | CesaireTchoudjuen/programming | /week03-Variables/Lab3.2.2-absolute.py | 246 | 4.28125 | 4 | # Author: Cesaire Tchoudjuen
# Program takes in number and give its absolute value (ie -4 or 4 would both output 4)
number = float(input("Enter a number: "))
absoluteValue = abs(number)
print("The absolute value of {} is {}.".format(number, absoluteValue)) |
161ef8932c1a6c2be3e188b8e3ba01a014255d69 | anirudh1808/Python | /python_tut/concept_in.py | 102 | 3.640625 | 4 | word="anirudh is a good boy"
for letter in word :
print (letter)
if ("good" in word) :
print ("hello")
|
1b4ce7373f79c139354d9c65b7fc6654c47c44bc | shijia-listen/python-basic-exercises | /python基础知识练习/user-password.py | 324 | 3.59375 | 4 | import getpass
n=0
while n <3:
name = raw_input('û: ')
pwd = getpass.getpass(': ')
if name=='listen' and pwd=='admin123':
print('ӭɹ,listen')
break
else:
print('û!')
n+=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.