blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d740fee3ec9d099fea72ed5f1306dcb0718f7160 | childofthefence/ucsd-algo-python | /venv/fibonacci.py | 698 | 3.828125 | 4 | fib_nums = [0, 1]
# place is how many fib numbers, starting at 1. The 10th fib number is thus 34
# indices in fib_nums stars at 0 so to get F19 would use something like fib_nums[19]
# and would be the 20th fib number (despite 19 being the index)
def calc_fib(place):
if place == 0:
return 0
elif place == 1:
... |
c6fd8cbfe4a6dca8fb433135460f25980a5f1798 | dilawarm/TDT4171 | /assignments/assignment5/neural_network_skeleton.py | 10,061 | 4.125 | 4 | # Use Python 3.8 or newer (https://www.python.org/downloads/)
import unittest
# Remember to install numpy (https://numpy.org/install/)!
import numpy as np
import pickle
import os
class NeuralNetwork:
def __init__(self, input_dim: int, hidden_layer: bool) -> None:
"""
Initialize the feed-forward n... |
db9f8f1535075c51e4eff02bb8c428eeb14a1d34 | saurabh-pandey/AlgoAndDS | /leetcode/arrays/remove_duplicate_sorted_a2.py | 990 | 3.5625 | 4 | from typing import List
def _shift_left(nums: List[int], index: int, shift_by: int) -> None:
for i in range(index, len(nums) - shift_by):
nums[i] = nums[i + shift_by]
def remove_elements_1(nums: List[int]) -> int:
new_len = len(nums)
end_marker = len(nums)
dup_count = 0
i = 1
while i <... |
e79f4bc6a33ba7b4959aa50291042e0843ae9705 | Ompragash/python-ex... | /Simple_calculator.py | 680 | 4.15625 | 4 | #Python program to make a simple calculator
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
print("Select Operation.")
print("1.Add")
print("2.Subtrac")
print("3.Multiply")
print("4.Division")
choice = input("Enter the choice(1/2/3/4)... |
dca2eaa44133561cb48d950eab7983ad4efd3041 | jordymcm/learning-to-code | /python/Stories/hamsterV1.0.0.py | 889 | 3.84375 | 4 | #!/usr/bin/python3
from getch import getch
import os
answer=0
name=0
answer = input ('You are a hamster what\'s your name? A: Fred B: doggy C: Zoof ')
os.system('clear')
if answer == 'a' or answer == 'A':
name=('fred')
print ('Fred, that is a good choice')
getch() == ' '
os.system('clear')
answ... |
cc6d93c6c4e4027c457d294031e08f8d3ca0f035 | edu-athensoft/stem1401python_student | /py200912f_python2m7/day04_201003/file_5_read.py | 352 | 3.6875 | 4 | """
open a file in read mode
"""
f = open("file5_mode_r.txt",'r')
# read the specified length of data in the file
print(f.read(8),end="==")
print(f.read(8),end="==")
# print(f.read(1),end="==")
# print("EOF",end="==")
# print(f.read(1),end="==")
# print("EOF")
print(f.read(8),end="==")
print(f.read(8),end="==")
prin... |
b7a9979f6dfb368954ac3a53a37e2e8d9eb99d91 | dongyingname/pythonStudy | /Data Science/np/numpyTrial.py | 5,135 | 4.40625 | 4 | # %%
# Numpy is the core library for scientific computing
# in Python. It provides a high-performance multidimensional
# array object, and tools for working with these arrays.
# If you are already familiar with MATLAB, you might find
# this tutorial useful to get started with Numpy.
# %%
# A numpy array is a grid of v... |
e3c52f6189d7d4d20c845cd0a4e4d791d88e6076 | superniaoren/fresh-fish | /python_tricks/dictionary/test_dict_craziest_expression.py | 2,542 | 3.828125 | 4 | #
class AlwaysEqual:
def __eq__(self, some):
return True
def __hash__(self):
return id(self)
class AlwaysConflict:
def __hash__(self):
return 1
class AlwaysSame:
def __eq__(sefl, some):
return True
def __hash__(self):
return 1
if __name__ == '__main__':
... |
0d2bbfe07ddb86cb74eade29586cf9b903e28058 | gtxmobile/leetcode | /151. 翻转字符串里的单词.py | 162 | 3.5625 | 4 | class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
return ' '.join([w for w in s.strip().split() if w][::-1])
|
7586c98142cc7445da911f2a9fa4bf5f988ea699 | Aasthaengg/IBMdataset | /Python_codes/p02880/s118793555.py | 154 | 3.5625 | 4 | N=int(input())
resurt=''
for i in range(1,10):
if N%i ==0 and N//i<=9:
result='Yes'
break
else:
result='No'
print(result) |
eb708e1ca365e7cde1a32cc0ca71a063d9d67f56 | EngineerToBe/python-labs | /008_loops.py | 1,308 | 4.53125 | 5 | # with loops we can perform the set of task for n number of times
# for loop
pandavas = ['Yudhisthir', 'Arjun', 'Bhim', 'Nakul', "Sahdev"]
for pandav in pandavas:
print(pandav)
# break and continue
# The break statement terminates the loop containing it. Control of the program flows to the statement immediatel... |
9e5d145529906ea80fa4d575cc9f43a4e72fcc47 | Leo-hw/psou | /anal_pro4/deep_learn1/keras2.py | 2,106 | 3.625 | 4 | # Keras 를 이용해 OR gate 논리 모델을 생성한 후 분류 결과 확인
import numpy as np
from tensorflow.keras.models import Sequential # 선형 네트워크 스텍을 정의
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import SGD, Adam, RMSprop
# 순서 1 : 데이터 수집 및 가공
x = np.array([[0,0], [0,1],[1,0],[1,1]])
... |
e239afa4753e67cf501dcb1ad80117f912fca612 | kriti-banka/ml-workshop-wac-1 | /day_1/even_odd.py | 236 | 3.9375 | 4 | # If Condition
"""
if condition_1:
code
code
code
elif [optional] condition_2:
code
...
...
...
else [optional]:
code
code
"""
number = int(input())
if number % 2 == 0:
print('even')
else:
print('odd')
|
1ad42b305455d60ccda9ddd450d79ca2b83b719f | AmandaRH07/PythonUdemy | /1. Básico/26- Exercicio2.py | 409 | 4 | 4 | hora = input("Digite a hora:")
if hora.isdigit():
hora = int(hora)
if hora < 0 or hora > 23:
print("Por favor, digite um horário entre 0 e 23 horas")
else:
if hora <= 11:
print("Bom dia, dia")
elif hora <= 17:
print("Boa tarde, Brasil,Boa noite Itália")
... |
2d57899fae3d3036f3cd7adc0931c5a84d89bc23 | boliluce/CodingTest | /programmers/짝수와 홀수.py | 134 | 3.671875 | 4 | def solution(num):
#return "Even" if num%2==0 else "Odd"
return ["Even", "Odd"][num&1]
print(solution(3))
print(solution(4))
|
27502b0d82a9c38962a414f9e2276e537d300215 | zhengfuli/leetcode-in-python | /n044_wildcard_matching.py | 954 | 3.828125 | 4 | class WildCardMatching(object):
def wildCardMatching(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
# sp, and pp are pointers for s and p, star for storing the star position
# ss for storing the letter in s corresponding to star in p
sp, p... |
6637ba5feb7e64e4bb6812e88fb0b6721d1e7bf7 | UmaAnantharaman/Python_Matplotlib_Numpypandas_ML | /openpyxl_worksheet_aceesscells.py | 632 | 4.09375 | 4 | #Create a workbook using openpyxl library
from openpyxl import Workbook
wb = Workbook()
#Make the current worksheet from the workbook active
ws = wb.active
#Changing the default title of the worksheet
ws.title = "Sample worksheet"
#Iterating through the workbook and printing the sheet names
for sheet in w... |
28259266de63cee34702478653c332fe1dc4be84 | archu333/python | /list slicing.py | 3,382 | 3.84375 | 4 | Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 16:30:00) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list1=[2,4,6]
>>> print(list1[:])
[2, 4, 6]
>>> print(list1[-1])
6
>>> list=["Ajay","Baby","Mommy","Anil","Roshan","Ammu"]
>>> print(list... |
d994b636467ff4908e1daa64a31b4ce302a14154 | leilin-research/Link-Travel-Time-prediction | /filterTaxiDataset.py | 1,646 | 3.59375 | 4 | import dataToGraph
def isWithinRange(latitude,longitude,max_suitable_latitude,min_suitable_latitude,max_suitable_longitude,min_suitable_longitude):
return (latitude > min_suitable_latitude and latitude < max_suitable_latitude
and longitude > min_suitable_longitude and longitude < max_suitable_longitude)
d... |
6f695b3482fbf84bf4813b1cbc48989e94963d67 | MarkLyck/Learning-Python | /for.py | 102 | 3.625 | 4 | foods = ['bacbon', 'tuna', 'ham', 'sausages', 'beef']
for f in foods:
print(f)
print(len(f))
|
880e6fd13ed49921215c97107b7aa2681424f863 | ricardomartinez4/python | /orientadoObjetos/practica070.py | 2,842 | 3.96875 | 4 | # -*- coding: utf-8 -*-
'''
'''
class Rectangulo():
#
def __init__(self, base, altura, color='white'):
# Ahora en vez de iniciar los atributos se utilizan los métodos getter
self.base = float(base)
self.altura = float(altura)
self.color = color
def __str__(self):
... |
b8b6ef37b7dab583decfb4ab22d149d58191b494 | HaoLIU94/lpthw | /Pratice-exos/ex2.py | 281 | 3.671875 | 4 | import random
cont=1
while cont==1:
dice=[1,2,3,4,5,6]
res = random.randint(1,6)
print 'The result is',res
print 'Would you like to play again'
s = raw_input('yes/no\n')
if s =='yes':
cont=0
elif s=='no' :
cont=1
else:
pass
|
171e9b7299ddb13c6e7bb55bdf2889be39d83421 | sacki123/django_training | /Python test/thêm pt vào tuple.py | 380 | 3.796875 | 4 | tpl1 = ('a', 'b', 'c', 'd')
tpl2 = ('e',)
tpl3 = tpl1 + tpl2
print(tpl3)
lst = [1,2,3,4]
print(tuple(lst))
print(list(tpl3))
lst2 = ["Google",(10,20), 15, (40, 50, 60), ["a", "và", "e"], (70, 80, 90, 100)]
for index, value in enumerate(lst2):
if isinstance(value, tuple):
lst1 = list(lst2[index])
lst... |
302930c6fe8b8e3a2deda19a132e839ba981961c | RoshaniPatel10994/-ITCS1140---Python--Practices- | /My Practice/rock collected in loop.py | 383 | 4.1875 | 4 | rocksdays = int()
weeks = 0
total = int()
days = 0
rocks = int()
for weeks in range(0, 2):
for days in range(0, 7):
rocks = int(input(" Enter the rocks you collected todays: "))+rocks
print("You collected: ", rocks, " rocks today")
weeks = weeks+ days
print(" You collected:... |
15609b2c5898686febdb31ac2dcfd0b19fa251d7 | bernardwija/Sir-Jude-Exercise | /1st Semester/Sir Jude's Exercise 7/No.1.py | 1,460 | 4.09375 | 4 | print('Welcome to List Converter!')
def removekeys(mydict,keylist):
print('Here are your datas: ')
print('Your dictionary:',mydict)
print('Your List:',keylist)
for i in keylist:
if i in mydict:
del mydict[i]
print('Here is your new dictionary:')
a=mydict
return a
def di... |
dac58ea7588cf42c7397afc380f37b748f9032a0 | tata-LY/python | /python-100-days/08.面向对象编程基础/1.py | 853 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021-1-12 16:08
# @Author : liuyang
# @File : 1.py
# @Software: PyCharm
class Student(object):
def __init__(self, name, age):
"""
__init__是一个特殊方法用于在创建对象时进行初始化操作
:param name: 初始化学生名字
:param age: 初始化学生年龄
"""
... |
51863239e93ebea22250aecd50d49d5856b577db | Monzillaa/practices-python | /conditionals.py | 943 | 4.3125 | 4 | """ print("ingresa color")
color = input()
if color == "red" :
print("the color is red")
elif color == "blue":
print("the color is blue")
elif color == "yellow":
print("the color is yellow")
else:
print("any color bitch!!") """
""" print("ingresa tu nombre")
name = input()
print("ingresa tu apellido")... |
49dc7f4165e15937be90a09bd1a04d2cfe79ceb9 | daniel-reich/ubiquitous-fiesta | /JmyD5D4KnhzmMPEKz_12.py | 511 | 3.734375 | 4 |
def constraint(txt):
letters = [i.lower() for i in txt if i.lower().isalpha()]
words = txt.split()
if len(set(letters)) == 26:
return 'Pangram'
if len(set(letters)) == len(letters):
return 'Heterogram'
if len({i.lower()[0] for i in words}) == 1:
return 'Tautogram'
s = se... |
c40b13afae5d363d1ec2e976f9af5ad667db1f78 | blue0712/blue | /demo65.py | 287 | 3.703125 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
pass
def calculate_area(self):
return self.width * self.height
r1 = Rectangle(5, 7)
r2 = Rectangle(2, 9)
print(r1.calculate_area(), r2.calculate_area()) |
12daa5790ccfb0f8a00f66c39d74866112acb4a8 | marcosihe/Python_basico | /strings.py | 2,145 | 4.53125 | 5 | # MÉTODOS
# upper() --> convierte a mayúsucla
# capitalize --> convierte a mayúscula la primera letra de la palabra
# strip() --> elimina los espacios que están de más
# lower() --> convierte a minúscula
# replace('a', 'b') --> reemplaza todas las letras 'a' de la cadena por la letra 'b'
# Índices --> si nombre == 'Mar... |
4566be4d35f74f7876c10fafdba860feee95379f | ashkhi/Python | /Week1/PrintBasics.py | 461 | 3.875 | 4 | # print can have multiple messages as arguments
print("Hello India !", "Hello World !", "Hi from Python class..")
# print can have numbers
print(5)
# print can have decimal values
print(20.5)
# print can also have multiple different types of messages
print("Hello", 5, 20.5)
# print accepts only the round brackets
#... |
2bf6151c76f8189b83eedebde63f40ee4a37a843 | VineetAhujaX/Team-Automated-Chatbot | /Bonus.py | 2,276 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 04:02:34 2021
@author: USER
"""
import requests
def getWeather():
# Enter your API key here
api_key = "9c9623d2c835fb356931d3b0b8d19c4a"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
... |
f7deec37c47814d6208f670682dffdbc174b34eb | KrolMateusz/Crypto | /Alghoritms/vigenere_cipher.py | 1,583 | 3.796875 | 4 | import pyperclip
import string
LETTERS = string.ascii_uppercase
def main():
file = open('C:\\Users\\Mateusz\\PythonProjects\\Aplikacja_szyfrowanie\\Alghoritms\\message_vigenere.txt')
message = file.read()
file.close()
key = 'ASIMOV'
encrypted = encrypt_message(message, key)
decrypted = decryp... |
772e6d23d7a4428c788e3bb08974e78f1d62ad25 | Kirankumar76k/my-python-programs | /OOPS/PolyGit.py | 1,168 | 4.03125 | 4 | class Artillery():
def __init__(self):
self.className = "Artillery Class constructor"
def showName(self):
shootingRange = "aprox. 1-30 km"
return "Artillery" + " " + shootingRange
class Mortar(Artillery):
def showName(self):
shootingRange = "1 km"
retur... |
ce4e23ef1c0489bf2d97487416c87e64b1c67b2c | Najoj/advent-of-code | /2022/5/Stack.py | 681 | 3.8125 | 4 | class Stack:
def __init__(self):
self._stack = []
self._height = 0
def push(self, item, bottom=False):
if item and item.strip():
self._height += 1
if bottom:
self._stack = [item] + self._stack
else:
self._stack = self._... |
bf35a78850c08000f95a857195d42c1ffdc9050b | surimLee/Python_study_ | /0315_4.py | 181 | 3.59375 | 4 | from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
canvas.create_polygon(10, 10, 150, 110, 250, 20, fill="blue")
window.mainloop() |
1da3eaaae1aa570c05e330396cc49276fcb3a586 | thewritingstew/lpthw | /ex11.py | 2,135 | 4.09375 | 4 | #============================================================
# beginning of original exercise
#============================================================
print "How old are you?",
age = raw_input() # accepts input with no prompt
print "How tall are you?",
height = raw_input('--> ') # accepts input with '--> ' promp... |
5122e3c1a8bc3853bee181705c6efc3664e7e1a4 | kennedy0597/projects | /Python/fileHandling.py | 874 | 3.9375 | 4 | # writing a file
# testtext = "aiosdjioasjodoajdjaso x,comaolsmdokqwokek,samocmoaskdoqmeo"
# file_handler = open("test1.txt", "w")
# file_handler.write(testtext)
# file_handler.close()
# reading file method 1
read_handler = open("test1.txt", "r").read()
print(read_handler)
# reading file method 2 line splitting
read... |
e0d63f680849e7c642a5e14a7fab2bfe7c6772ba | nigelgomesot/ml | /statistical_methods/random_numbers.py | 1,028 | 3.765625 | 4 | # generate random numbers
from random import seed
from random import random
from random import randint
from random import gauss
from random import choice
from random import sample
from random import shuffle
print('\nseed ensures random function is deterministic')
seed(1)
print(random(), random(), random())
seed(1)
p... |
dbd7d68b55411336bc308c6cd28112e2c6c133c0 | lvraikkonen/GoodCode | /leetcode/561_array_partition_I.py | 428 | 3.6875 | 4 | """
给定一个长度为2n的整数数组,将数组分成n组,求每组数的最小值之和的最大值。
整个数组的最小值x和下一个值的min等于x,所以每组值的和最大,应该等于按顺序排列后偶数位置的数之和
"""
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2]) |
c20138e40ec60d554c2ba8d7094812df3117c6e8 | prachipatel2509/Sample- | /Assesment/n.py | 279 | 3.8125 | 4 |
def sequence(x):
l = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
l.append(x)
return l
if __name__=="__main__":
n=int(input("Enter a no. :"))
print(sequence(n))
|
5dc798779edd0f61d1b47a8dabe6149bea9d602d | ducoendeman/Introduction-to-Functional-Programming | /scripts/python/lab2.py | 1,514 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 14:25:16 2019
@author: duco
------------------------------------------------------------------------------------------------------------------------------
-- Lab 2: Validating Credit Card Numbers
-------------------------------------------------... |
e4adb3621d03f1de0345f03086279ea58941b15b | hemapython/2ndnewlife | /40.py | 904 | 3.9375 | 4 | # writing program for exception handling
#fox=[34,2,1,45,76,45,22,45]
#print(fox[1:5])
#fox=(46,45,[45,12,34,21])
#print(fox.count(45)) # it will give output of how many times 45 present in tuple
#print(fox.index(45)) #it will provide the index number of tuple
#print(fox[2][3])
H=8
J=4
try:
print(H/J... |
fcdcbaffddc3c6caa7a14a05faadba16c7456f00 | ththanhbui/dangerously-raw | /sort_rides.py | 478 | 3.515625 | 4 | def get_distance(row1,col1,row2,col2):
return abs(row1-row2) + abs(col1-col2)
def get_ride_length(ride):
return get_distance(ride["start_col"], ride["start_row"], ride["fin_col"], ride["fin_row"])
def get_latest_possible_start_time(ride):
return ride["latest_finish"] - get_ride_length(ride)
# Take in a list of... |
06d318e6e265aa5c8cd77e233d4f8dd884dda706 | KristianMSchmidt/Algorithms-specialization-stanford- | /Course_1/week3_quick_sort/quick_sort.py | 3,203 | 4.28125 | 4 | """
Implementation of Quick Sort with different strategies for chosing pivots. Random pivots are provably best, though.
In particular, this exercise is about counting the number of comparisons when doing quick_sort.
"""
def partition_l(my_list, l, r):
"""
Partition subrutine to be used by quick sort.
Partit... |
3245cd7599855b8e7fb391c3eef760395bd6c354 | frclasso/CodeGurus_Python_mod2_turma1 | /Cap01-sintaxe_especifica/dict_comprehension/script3.py | 653 | 3.890625 | 4 | dict1 = {
'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
}
dict1_comp = {k:v for(k,v) in dict1.items() if v > 2}
print(dict1_comp)
# for k, v in dict1.items():
# if v > 2:
# print(k,':', v)
dict2_comp = {k:v for(k, v) in dict1.items() if v > 2 if v % 2 == 0}
print(dict2_comp)
# for k,... |
957dbff70c969826eca5cc9ad954a7cdd7c98e3b | divyavani-gmail/ASSIGNMENT2 | /9.py | 263 | 3.65625 | 4 | # 9. Select the rows the age is between 2 and 4(inclusive)
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["divya_db"]
mycol = mydb["vani_data"]
myquery = mycol.find({"age":{"$gte":2 ,"$lte":4}})
print(list(myquery)) |
6022befaf5be41b18bf0219cd41afba79e533af0 | Franklin-Wu/project-euler | /p109.py | 3,883 | 3.875 | 4 | # Darts
# Problem 109
#
# In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.
#
# (Only 1 of 20 sectors is shown.)
#
# +--------------------+
# \ [1 - 20] /
# +----------------+
# \ double /
# +---... |
b8690eefe5eae06ad8683af44c4408f9a828f17d | alondavid/Self.Py | /ex535.py | 509 | 4.15625 | 4 | #ex 535
def distance(num1, num2, num3):
'''int,int,int > Bool
the Function return True if:
(num2 - num1 or num3 - num1 = abs(1))
and (num2 - num1 or num2 - num3 or num3 - num1 > abs(2)).
>>> distance(1, 2, 10)
True
>>> distance(4, 5, 3)
False
... |
dc9cb6cd006928b9923b0016dfd45a1925a996e3 | siimkollane/programm | /uusaastalubadus.py | 324 | 3.5 | 4 | import tkinter as tk
def write_slogan():
print("Saan geo perioodihinde positiivse.")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button()
slogan = tk.Button(frame,
text="Vajuta minu peale!",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainlo... |
68392a4a749bc340fa76b447ab93cd63fcdecf0b | praveenkumarsrivas/Python-3_Programming | /Hackerrank-Python3/mean_varr_std.py | 592 | 3.921875 | 4 | # Output Format
# First, print the mean.
# Second, print the var.
# Third, print the std.
# Sample Input
# 2 2
# 1 2
# 3 4
# Sample Output
# [1.5 3.5]
# [1. 1.]
# 1.11803398875
import numpy
n, m = input().split()
n = int(n)
m = int(m)
l = list()
arr = list()
arr = []
x = 0
i = 0
for x in range(n):
l = input(... |
5a2fa7376d2a2ca37f4d29194f5e40a67fb83025 | xiasiliang-hit/leetcode | /island_num.py | 1,705 | 3.65625 | 4 | ## now work !
import pdb
import Queue
#visited = []
#matrix = []
#X = 0
#Y = 0
#num = 0
class Solution(object):
def __init__(self):
global X, Y, visited, num
X = len(matrix[0])
Y = len(matrix)
visited = [[False for x in range(X) ] for y in range(Y)]
self.num = 0
... |
b0322a6833f1563300b1b02745d458b6cdbc1462 | fedhere/StatisticalCompass | /main.py | 1,156 | 3.6875 | 4 | import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over qu... |
3cd369cc0526d0f81349961ce3150c0ef97f83e8 | tartaponei/URI | /iniciante/1064positivosmedia.py | 165 | 3.640625 | 4 | p = 0
s = 0
for i in range(6):
n = float(input(""))
if(n > 0):
p += 1
s = s + n
print(p, "valores positivos")
print("{:.1f}" .format(s / p))
|
c7c75378f36e39183bd6a9510e405951cfd1c805 | CeruleanOwl/Python-Practice | /RockPaperScissors.py | 2,612 | 4.0625 | 4 | '''Global Variables'''
rockC = False
scissorsC = False
paperC = False
rockU = False
scissorsU = False
paperU = False
#computer logic
def computer_choice():
#import random module
import random
#request global variables
global rockC
global paperC
global scissorsC
#Random int generator betwee... |
a9aded09b71a15dc2be4deabeb1bbd5655c88a27 | calvar122/EXUAGO2021-VPE-L1 | /0929/jose.benavides/serieFub.py | 712 | 3.90625 | 4 | #!/usr/bin/env python3
# c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil
# vi: set shiftwidth=4 tabstop=8 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
#
# SPDX-License-Identifier: GPL-3.0-or-later
#fn = fn-1 + fn-2
#Funcion recursiva para la serie de Fibonacci
def fibo(num):
if num == 0:
return... |
ac3420ed1d71fbab98b8155a84e77c68262290af | amarinas/algo | /chapter_1_fundamentals/final_countdown.py | 396 | 3.796875 | 4 | # given 4 params
# print the multiples of param 1 starting at param 2 and extending to param 3
# if a multiple is equal to param 4 then skip
#given( 3,5,17,9) expected (6,12,15)
def final_count(param1,param2,param3,param4):
count = param3
while count > param2:
if count % param1 == 0 and count != param4... |
c30f6563e12403ce7de4281da1d7a25e2cad3c58 | MsDiala/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/array_reverse/array_search.py | 317 | 3.921875 | 4 | def binary_search(arr, key):
low = 0
high = len(arr)
while len(arr) > 0:
middle = (low+high) // 2
if arr[middle] == key:
return middle
if arr[middle] < key:
low= middle
if arr[middle] > key:
high= middle
if middle == 0 or middle == len(arr) - 1:
return -1
return -1 |
4b85eb0e9e1462ab0bd1728f4ed1fba33ee99179 | ngpark7/deeplink_public | /2.ReinforcementLearning/MCTS/mcts.py | 9,222 | 3.5 | 4 | # For more information about Monte Carlo Tree Search check out our web site at www.mcts.ai
# http://mcts.ai/about/index.html
from math import *
import random
def upper_confidence_bounds(node_value, num_parent_visits, num_node_visits):
""" the UCB1 formula """
return node_value + sqrt(2 * log(num_parent_visit... |
589a566083cb9ffa0f331aed0930d7b0bfae4bdb | Clanrat/adventofcode | /day9.py | 1,017 | 3.953125 | 4 | import sys
import itertools
def shortest(cities, dest):
travel_plans = itertools.permutations(cities, len(cities))
return [calc_distance(travel_plan, dest) for travel_plan in travel_plans]
def calc_distance(travel_plan, dest):
distance = 0
for i in range(1, len(travel_plan)):
distance += int... |
be4022313e80f64fab6e48bbdfb59b439e177bbe | CodedBrackets/python_cricket | /hello.py | 685 | 3.875 | 4 | print("Hello World!")
for i in range(10):
print("\t",i)
print("\tBananazzzzz")
mylist=[]
mylist.append("Apple")
mylist.append("Banana")
mylist.append("Grapes")
print(mylist)
print("Square of 5 is : ",5**2)
x = object()
y = object()
# TODO: change this code
x_list = [x] * 10
y_list = [y] * 10
... |
6d935feba24dec9ef75a85a4e9d81e47419fdbe4 | gauravdhmj/Project | /Tuples.py | 2,546 | 4.09375 | 4 | t = "a", "b", "c"
print(t)
print("a", "b", "c")
print(("a", "b", "c"))
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975
bad = "Bad Company", "Bad Company", 1974
budgie = "Nightflight", "Budgie", 1981
imelda = "More Mayhem", "Imelda May", 2011
metallica = "Ride the Lightning", "Metallica", 1984
print... |
d1882c89bbfb5505bc97fb43f841e902398461ca | LordVendrik/Python-Bot | /Automation/s.py | 270 | 3.6875 | 4 | import pyperclip
import re
text = str(pyperclip.paste())
ph = re.compile(r'#write what you want to find',re.I)
mo = ph.findall(text)
if len(mo) > 0:
for i in range(len(mo)):
print('Mobile NUmber (' +str(i) +')' +mo[i])
else:
print('No NUmber found')
|
593ca9ac9ce2fb37c8b6422acd7b33ba116fd613 | CDeividi/CDeividi | /exercicio 2.py | 417 | 3.875 | 4 |
while(True):
try:
codigo=int(input('Insira o código que deseja emitir digito verificador: \n'))
except ValueError:
print('São válidos somente números inteiros !')
continue
if(codigo < 10000 or codigo > 30000):
print('Suportad... |
5f693a4306f1583f247405d8e551f15ebdff81ac | tcanfield/web | /sudoku/board.py | 5,920 | 4.03125 | 4 | import math
class sudoku_board:
#Initialize the board by passing in a string representing the board
#positions in order top to bottom, left to right. Use 0 to represent
#empty spaces
#
#arg board: String representation of the board.
#Positions listed in order left to right, top to bott... |
b7942016a2fc747501a19583d7e239063cac29de | flame4ost/Python-projects | /additional tasks x classes/Fraction.py | 1,106 | 3.953125 | 4 | class Fraction:
# numerator: int
value = 0
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
print(str(self.numerator) + ' | ' + str(self.denominator))
def calculateSum(self):
sum = self.makeSum(self.numerator, self.den... |
d2dd0e571bfa6da3e1b693fdb54dee89ec8252a1 | danae678/techx-appliedds | /Associative Arrays/firstNonrepeated.py | 577 | 4.28125 | 4 | # Find the first non-repeated character in a string.
# Some things you can reason from the example:
# The return value is the non-repeated character itself, as opposed to the index or some other value
# Example:
# Input: input_string = "supercalifragilisticexpialidocious"
# Output: "f"
import collections
def... |
b85971cf4844976a2469e693f4d15098afc7b3ad | mk270/dot-home | /bin/newmonth | 583 | 3.71875 | 4 | #!/usr/bin/env python
import datetime
import sys
import calendar
def run():
try:
_, month, year = sys.argv
except:
print >>sys.stderr, "Usage: newmonth month year"
m = int(month)
y = int(year)
print "\n%s %d\n" % (calendar.month_name[m].upper(), y)
for day in xrange(0, c... |
965b9effdbebe69659fb6418c06c998fca135c23 | damodardikonda/Python-Basics | /core2web/Week5/patt.py | 308 | 3.609375 | 4 | '''
Program 4: Write a Program to Print following Pattern.
A
B A
C B A
D C B A
'''
ch="A"
for i in range(4):
for j in range(4):
if j<3-j:
print("",end="\t")
else:
print(ch,end="")
ch=(chr(ord(ch))-1)
print()
ch=(chr(ord('A'))+j+1)
|
c02abd392e2efc34120880783b208efcdadd3afe | sihyeonn/Sunday | /Python/모두의 파이썬/13B-walk.py | 735 | 3.890625 | 4 | import turtle as t
import random
MOVE = 10
def turn_right():
t.setheading(0)
t.forward(MOVE)
def turn_up():
t.setheading(90)
t.forward(MOVE)
def turn_left():
t.setheading(180)
t.forward(MOVE)
def turn_down():
t.setheading(270)
t.forward(MOVE)
def blank():
t.clear()
def c... |
afc73f4034232443ae0551f480e34983fef334ba | andrea2910/c4v2020 | /code/indicators/dialysis_indicator.py | 5,353 | 4.03125 | 4 | import pandas as pd
def dialysis_indicator(df):
"""
dialysis.py
------------------
This Function calculates the dialysis indicator, a metric that measures
whether or not dialysis can be performed in the hospital in that particular state
Logic
-----
First, the function cleans the variab... |
51d7e6c3f0965fae518a2a346f1f5e9ab555b9e0 | SINHOLEE/Algorithm | /python/프로그래머스/방금그곡.py | 1,417 | 3.5625 | 4 | from datetime import datetime
def string_to_minute(start, end):
temp1 = datetime.strptime(start, '%H:%M')
temp2 = datetime.strptime(end, '%H:%M')
temp3 = temp2 - temp1
return temp3.seconds // 60
def string_to_list(string):
# 검증완료
lis = []
for s in string:
if s == "#":
... |
198c7baf4e32bfeaf82f75bc7449871c7a72d325 | mandeep-codetresure/python-study1 | /classpractise.py | 506 | 3.75 | 4 | class Calculator:
def __init__(self, number):
self.number = number
@staticmethod
def greet():
print("welcome user")
def square(self):
print(f"square of {self.number} is {self.number **2}")
def cube(self):
print(f"Cuberoot of {self.number} is {self.number ... |
918ec59032e9302215f4458b8db0166cd228a5c1 | danyalsaqib/Machine-Learning-Basics | /Code Files/Python, Matlab, and Pandas/exportFile.py | 449 | 3.625 | 4 | # Import Pandas using its common nickname
import pandas as pd
# Reading test_data.csv as a dataframe
df = pd.read_csv('test_data.csv')
# Adding another column for average scores
df['Average Score'] = (df['Math Score'] + df['Physics Score'] + df['Chemistry Score'] + df['English Score']) / 4
# Short Method
df['Short Me... |
c0f8adb7cb46ad9e9d258e2458f3c2ee8db75382 | Cassio-4/URI-Online-Judge | /python/Begginer/1017.py | 108 | 3.703125 | 4 | hours = int(input())
speed = int(input())
fuelSpent = (hours * speed)/12.0
print('{:.3f}'.format(fuelSpent)) |
b71c4eb4ca4ab67e9d230c0a00c2c584bb8426d1 | benny83324/c_to_f | /c_to_f.py | 110 | 3.796875 | 4 | c = float(input("What is the temperature in C so far:"))
f = c * 9 / 5 + 32
print("temperature F is mow:",f)
|
ab01b29943909262c37078c6769fc5fcf256da66 | santhosh-kumar/AlgorithmsAndDataStructures | /python/test/unit/common/test_linked_list.py | 1,366 | 3.8125 | 4 | """
Unit Test for binary_tree
"""
from unittest import TestCase
from common.linked_list import LinkedList
from common.linked_list import Node
class TestLinkedList(TestCase):
"""
Unit test for LinkedList
"""
def test_construct(self):
"""Test for construct
Args:
self: Test... |
f93ae3b67ce53447ec7528f0b37b3670895d8ae5 | antrijuzar/DDU-sem-4-programs | /SP/Lab 1/P5.py | 633 | 4.1875 | 4 | # first
a=-5
if a>0:
if a%2==0:
print(str(a) + " is positive even number")
else:
print(str(a) + " is negative number")
# Output is : -5 is negative number because the outer if statement is evaluated
# and the condition is false so the else statement gets executed.
# second
a=5
if a>0:
if a%2==0 :
... |
258ccc665fe6922754b0f692476d60d3024f1e03 | julianestebanquintana/ladrillos | /videojuego.py | 6,356 | 3.515625 | 4 | import sys
import time
import pygame
ancho = 640
alto = 480
color_azul = (0, 0, 64)
color_blanco = (255, 255, 255)
pygame.init() # Es necesario para poder usar las fuentes en un juego
# pygame.font.init()
class Bolita(pygame.sprite.Sprite):
# Los objetos que se ven en la pantalla en pygame, son sprites
d... |
56079c8d71e50abb6f0a10da94512d4bd36957b4 | olgaamp/python | /venv/1.py | 738 | 3.515625 | 4 | from math import *
nsDict = {'global': None}
varDict = {}
def create(a, b):
nsDict[a] = b
def add(a, b):
varDict[a] = b
def get(prostr, per):
# x = varDict.get(a)
# print(x)
res = False
for k in varDict:
if (k == prostr and varDict[k] == per):
res = True
pr... |
3a5242bd6e7dba591b4d0158ed05c236ea01ffc1 | heidarinejad/MyNests | /Integrate_and_fire_neuron.py | 2,027 | 3.765625 | 4 | # iaf (integrate_and_fire) neuron example
import nest
import pylab # for plotting
# in this program a DC current is injected to neuron using a current generator device and V_m is recorded by 'spike_detector'
# to do so the best way is define a function so called ' build_network'
# this function take the resoulti... |
f70f99dbaa4b1574b75ec698a909d2ed8f34a465 | mdalton87/python-exercises | /solutions.py | 1,504 | 4.1875 | 4 | # 1.
#
# Write a function named isnegative.
# It should accept a number and return a boolean value
# based on whether the input is negative.
def isnegative(x):
return x < 0
# 2.
# Write a function named count_evens. It should accept a list and return the number of even numbers in the list.
def count_evens(n... |
2eb514c8cb7d5f90ee35fe62631fa2e35d35dd81 | jose-ramirez/project_euler | /problems/p19.py | 1,384 | 4.03125 | 4 | #You are given the following information, but you may prefer
#to do some research for yourself.
#
#1 Jan 1900 was a Monday.
#Thirty days has September, April, June and November.
#All the rest have thirty-one, Saving February alone,
#Which has twenty-eight, rain or shine.
#And on leap years, twenty-nine.
#A leap year oc... |
5bfa906b00b190ec1f28f9e2c586e39704207c77 | nishantchaudhary12/w3resource_solutions_python | /Strings/uppercase_str.py | 539 | 4.40625 | 4 | #Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters
# in the first 4 characters.
def upper_str(sample_string):
count = 0
new_string = ''
for each in range(0, 4):
if sample_string[each].isupper():
count += 1
if count > 1... |
c914d570a0fad439482cb03a94c1fba136724e5e | MattAnderson16/Algorithms | /stack.py | 1,306 | 4.21875 | 4 | class stack:
"""Stack class"""
def __init__(self):
self.items = []
self.max_size = None
self.stack_pointer = None
def is_empty(self):
if len(self.items) == 0:
return True
else:
return False
def push(self,item_to_add):
if... |
85d0abb36fa69b7b6dcbf05634daf2613baeb308 | mizhi/project-euler | /python/problem-55.py | 1,784 | 4.15625 | 4 | #!/usr/bin/env python
# If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
#
# Not all numbers produce palindromes so quickly. For example,
#
# 349 + 943 = 1292,
# 1292 + 2921 = 4213
# 4213 + 3124 = 7337
#
# That is, 349 took three iterations to arrive at a palindrome.
#
# Although no one has proved ... |
ab9d571dbb0ce77c6c86ae9588e678c7ea134b68 | shrishtydayal2304/python | /hackerrank/Sets/Symmetric Difference.py | 270 | 3.71875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import print_function
a=int(input())
x=set(map(int,input().split()))
# print(x)
b=int(input())
y=set(map(int,input().split()))
w=sorted(x.symmetric_difference(y))
print(*w,sep='\n')
|
1551c6af7432a330e266cf243dc79de8aa785800 | MartaCortes/Repository | /Coding_and_Visualization_Projects/Sklearn Python/sklearn.py | 16,673 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Assignment 3 Advanced Programming
# ### Authors: Rafaela Becerra & Marta Cortés
# #### Part I Scikit-Learn
#
# #### Preprocess
#
# Some libraries are imported and the solar dataset is read (in cvs format) into a Pandas dataframe
# In[1]:
import numpy as np
from numpy.ran... |
cd22c86f74b78705397305900b50b8dbbfa36fc0 | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom04/mock.py | 2,043 | 3.734375 | 4 | """
Går igenom Mock i unittest.
https://docs.python.org/3/library/unittest.mock.html
"""
from unittest import mock
# https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock
# Vi kan antingen skapa ett Mock eller MagicMock objekt.
# För att använda Mock objektet behöver vi i förväg specificera vilka att... |
1d7ebc1b65ba02e23c43c2750360a2b7d9367cb0 | jadamsowers/arc-reactor | /Python/breathe.py | 2,174 | 3.625 | 4 | # breathe.py by J. Adam Sowers
# Generates an array of RGB values to make a NeoPixel device appear to
# 'breathe', similar to the sleeping MacBook LED indicator.
import math
import sys
import colorsys
r,g,b = 0x40,0xD0,0xFF # blue-ish glow
numSteps = 128
#colorsys expects RGB values in the range [0,1]
r,g,b = [ x ... |
8052a046ff59c1bee411e1fe0f6f640ed3eb9eba | goareum93/K-digital-training | /01_Python/18_OOP/01_클래스구현.py | 5,795 | 4.0625 | 4 | ####
## 클래스 구현 : 메서드, 필드 정의, 생성자 이용
# 클래스 선언
# class 클래스이름 [(슈퍼클래스명)] :
# 필드(속성)1
# 필드(속성)2
# def method1(self):
# ...
# def method2(self):
# ...
# 빈 클래스 정의
# class Car:
# pass
#
# car1 = Car()
# print(car1)
# # <__main__.Car object at 0x0000020491E4F1F0>
#
# class Car:
# # 메소... |
8bf0d7d753ff517a7547f06698343d2f182f7285 | thedeveshpareek/random-simple-polygon-generation | /src-generate/main_naive.py | 1,837 | 3.703125 | 4 | # -----------------------------------------------------------------------------
# Naive polygon generation algorithm
# -----------------------------------------------------------------------------
from src.Edge import Edge
from src.Polygon import Polygon
from src.Math import quickhull
import sys
import matplotlib.p... |
05bf5dfee32b157e534466d0533ffd571c075561 | JongSeokJang/Sogang_ConputingThinking | /p3_2.py | 168 | 3.734375 | 4 | a = input();
c_temp = float(a);
f_temp = ((9/5) * c_temp) + 32
print ("===============")
print ("Celsius : %.1f" %(c_temp) );
print ("Fahrenheit : %.2f" %(f_temp) );
|
c4528607c93d78a0f7eb730ef62562c5a0ff2cef | piraog/PacketPrioritizing | /Simulation.py | 14,869 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from Network import *
class Simulation:
'''This class runs scheduling algorithms for emergency flows over a given network.
Args:
* network (Network): a network we want to run the simulation on
Kwargs:
* eFlowDeadLine (i... |
e06e4705afbeb7ba916cb22c5728ea8fbf91cea9 | yejinee/Algorithm | /Algorithm Concept/Union_Find.py | 1,521 | 3.890625 | 4 | """
[ 서로소 집합 자료 구조 ]
- 연산
1) 합집합 (Union)
- 동작과정
1. Node 갯수 크기의 부모테이블 초기화 (자기 자신)
2. Union하려는 node들의 루트노드 찾기 (부모테이블 거슬러 올라갈 것)
3. 2개 node의 루트노트 중 더 작은 번호의 루트를 가진 노드의 루트노드가 다른 노드의 부모노드 됌
=> 연결성 통해 집합의 형태 확인 가능( 재귀함수로 루트노드 확인해보아야함 )
2) 찾기 (Find)
: 경로 압축 방법(Find함수 재귀호출 뒤에 부모table 값 바로 갱신... |
f13e0a842e4b301ac52a671b1b43b850e0cfd64c | JesusMartinezCamps/programacion | /python/yatzy_Refactoring_TDD_Kata/yatzy.py | 3,573 | 3.5625 | 4 | class Yatzy:
@staticmethod
#Un metodo static no puede recibir un objeto
def chance(*dice):
total = 0
for die in dice:
total += die
return total
@staticmethod
def yatzy(*dice):
if dice.count(dice[0]) == 5:
return 50
return 0
... |
70fce8052217feb51feb2c40eea8e11c04d69688 | gabriellaec/desoft-analise-exercicios | /backup/user_348/ch44_2020_04_08_17_26_59_480524.py | 304 | 3.859375 | 4 | #usando dicionário
meses = {'janeiro': 1, 'fevereiro': 2, 'março': 3, 'abril': 4, 'maio': 5, 'junho': 6, 'julho': 7, 'agosto': 8, 'setembro': 9, 'outubro': 10, 'novembro': 11, 'dezembro': 12}
numero = input('digite o nome do mes: ')
mes = meses[numero]
print("O mes de {0} é: {1}".format(numero, mes)) |
f06d6151b50b2c7508a79ffa22a2d97986266d69 | Vinograd17/Python | /HW 6/hw6_task_3.py | 595 | 3.5625 | 4 | # Task 3
class Worker:
def __init__(self, name, surname, position, income):
self.name = name
self.surname = surname
self.position = position
self.income_wage = income['wage']
self.income_bonus = income['bonus']
class Position(Worker):
def get_full_name(self):
r... |
b9f5bfbeed0832d2a48d43e07735e8b6bf41efde | catliaw/berkeleyext_intro_computers_programming | /Module7/sort_and_mean.py | 917 | 4.40625 | 4 | #!/usr/bin/python3
# This program consists of a user-defined function called sort_and_mean
# which takes a list of numbers as an argument and sorts and PRINTS that
# list of numbers. The function also calculates and RETURNS the mean value
# numberse in the list.
# Test input: [3,9,7,4,0,2]
def sort_and_mean(nums_list... |
f5c403e3a80a030d8459377563aaf10d8fbaca04 | BThacker/codingbatPYTHON | /list2/List2.py | 3,192 | 4.0625 | 4 | # @Brandon Thacker
# www.codingbat.com PYTHON List2 Problems and Solutions
# Max of 1 Loop
'''COUNT_EVENS
Return the number of even ints in the given array.
Note: the % "mod" operator computes the remainder,
e.g. 5 % 2 is 1.
count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0
'''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.