blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ff96730fd2863c392f87d93e3dbd842ad063e88d | jhd/nntest | /sigmoid.py | 981 | 3.609375 | 4 | import itertools
import math
class Sigmoid():
weights = []
bias = []
weighedInput = None
activation = None
activationPrime = None
error = None
def __init__(self, startWeights=None, startBias=None):
self.weights = startWeights
self.bias = startBias
def sig(self,... |
8fbfdaca1191359762e5b2cb142b19de0ceb7a9a | noobcoderr/python_spider | /alien_invasion/bullet.py | 1,057 | 3.984375 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""a class that manage how a ship fire"""
def __init__(self,ai_settings,screen,ship):
"""create a bullet where ship at"""
super(Bullet,self).__init__()
self.screen = screen
#creat a bullet rectangle at (0,0) t... |
5b7ddd980eef5d63cc7cda3da0a9504a4a969a76 | MateusdeOliveira15/IFCE-PYTHON | /Lista/q9.py | 421 | 3.96875 | 4 | #Faça um programa que receba do usuário uma string e imprima a string sem suas vogais.
string = input('Digite uma string: ')
lista = list(string)
string_nova = []
for i in range(len(lista)):
if lista[i] != 'a' and lista[i] != 'e' and lista[i] != 'i' and lista[i] != 'o' and lista[i] != 'u':
string_nova.append(lis... |
034d4f75912f5e1a3e85ea3d83c28938d5fdaa2d | MateusdeOliveira15/IFCE-PYTHON | /Lista/q10.py | 451 | 4 | 4 | #Faça um programa em que troque todas as ocorrências de uma letra L1 pela letra L2 em
#uma string. A string e as letras L1 e L2 devem ser fornecidas pelo usuário.
string = input('Digite uma string: ')
letra1 = input('Digite uma letra: ')
letra2 = input('Digite outra letra: ')
string = list(string)
for i in range(l... |
98cf462c49a5227c9af6638e2589de8202bd961a | ajorve/pdxcodeguild | /objects/valet/valet.py | 857 | 3.875 | 4 | """
Create a car for color, plate # and doors.
Create a parking lot that will only fit to its capacity the cars created.
"""
class Vehicle:
def __init__(self, color, plate, doors):
self.color = color
self.plate = plate
self.doors = doors
def __str__(self):
ret... |
28192ec1a2ff45eab9f27fe8b1227a910adaba93 | ajorve/pdxcodeguild | /warm-ups/string_masking.py | 1,364 | 3.953125 | 4 | """
# String Masking
Write a function, than given an input string, 'mask' all of the characters with a '#' except for the last four characters.
```
In: '1234' => Out: '1234'
In: '123456789' => Out: '#####6789'
"""
# def string_masking(nums_list):
# """
# >>> string_masking([1, 2, 3, 4, 5, 6, 7, 8... |
f81cd655babcadec3b45696091a852a56b8ccd92 | ajorve/pdxcodeguild | /warm-ups/wall-painting.py | 564 | 4 | 4 | """
This is a Multiline Comment. THis is the first thing in the file.
AKA 'Module' Docstring.
"""
def wall_painting():
wall_width = int(input("What is the width of the wall?"))
wall_height = int(input("What is the height of the wall?"))
gallon_cost = int(input("What is the cost of the gallon"))
... |
dfd38f505944aeb4fee6fa57bda110fa84952084 | ajorve/pdxcodeguild | /json-reader/main.py | 1,131 | 4.5 | 4 | """
Objective
Write a simple program that reads in a file containing some JSON and prints out some of the data.
1. Create a new directory called json-reader
2. In your new directory, create a new file called main.py
The output to the screen when the program is run should be the following:
The Latitude/Longi... |
dbfe81b01a012a936086b78b5344682238e88ea5 | ajorve/pdxcodeguild | /puzzles/fizzbuzz.py | 1,145 | 4.375 | 4 | """
Here are the rules for the FizzBuzz problem:
Given the length of the output of numbers from 1 - n:
If a number is divisible by 3, append "Fizz" to a list.
If a number is divisible by 5, append "Buzz" to that same list.
If a number is divisible by both 3 and 5, append "FizzBuzz" to the list.
If a number meets none ... |
cbb5dfcd92d734e476075cc01b063ce611826b92 | ajorve/pdxcodeguild | /warm-ups/sum_times.py | 1,245 | 3.890625 | 4 | """
Weekly warmup
Given a list of 3 int values, return their sum.
However, if one of the values is 13 then it does not count towards the sum and values to its right do not count.
If 13 is the first number, return 0.
In: 1, 2, 3 => Out: 6
In: 5, 13, 6 => Out: 5
In: 1, 13, 9 => Out: 1
"""
import time
de... |
5733f941bb23cec0470a41d4bb6ab1f78d86bd73 | ajorve/pdxcodeguild | /warm-ups/pop_sim.py | 2,021 | 4.375 | 4 | """
Population Sim
In a small town the population is 1000 at the beginning of a year.
The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town.
How many years does the town need to see its population greater or equal to 1200 inhabitants?
Write a fun... |
df1f704b954ec8d3d0680b2776a7afaf3ba4357f | redashu/augmenu2018 | /day2.py | 351 | 4 | 4 |
import time
print "Hello world "
x=10
y=20
time.sleep(2)
print x+y
# taking input from user in python 2
n1=raw_input("type any number1 : ")
n2=raw_input("type any number2 : ")
z=int(n1)+int(n2)
time.sleep(2)
print "sum of given two numbers is : ",z
'''
take 5 input from user and make a tuple with o... |
a8ae1110868b0bd4845ac1ee59fc4b3c27ccbc1e | Lite-Java/KNN | /KNN.py | 789 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 21:46:15 2018
@author: 刘欢
"""
import numpy as np
class NearestNeighbor:
def _init_(self):
pass
def train(self,X,y):
"""X is N X D where each row is an example.y is 1-dimension of size N"""
self.Xtr=X
self.ytr=y
def predict(se... |
d13b5bdd1b380482a8ee433c8b513a830a01bb4d | tangmingsheng/Python_Learn | /20190611_语言元素.py | 435 | 3.859375 | 4 | # f=float(input("请输入华氏温度"))
# c=(f-32)/1.8
# print("%.1f华氏温度 = %.1f摄氏度"% (f,c))
# import math
# radius = float(input("请输入圆周半径:"))
# perimeter = 2 * math.pi * radius
# area = math.pi * radius * radius
# print("周长:%.2f" % perimeter)
# print("面积:%.2f" % area)
year = int(input("请输入年份:"))
is_leap = (year % 4 == 0 and ye... |
fd2a8b080bd4435fc8229279b5bbce26f782c677 | lahwaacz/Scripts | /pythonscripts/misc.py | 2,184 | 3.71875 | 4 | #! /usr/bin/env python
"""
Human-readable file size. Algorithm does not use a for-loop. It has constant
complexity, O(1), and is in theory more efficient than algorithms using a for-loop.
Original source code from:
http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
... |
1058223566e7c3af49e5df00ff6d6754b4d9088c | onwayWalk/aaa | /day02/xiaoyouxi.py | 294 | 3.796875 | 4 | import random
print("请输入一个数")
a=int(input())
b=random.randint(0,10)
while a!=b:
if a>b:
print("猜大了噢,再猜一次吧")
a=int(input())
else:
print ("猜小了哦,再猜一次吧")
a=int(input())
print ("太棒了,猜对了!")
|
5ec0e7fec324bb65eeb8484c83c50180db82d595 | onwayWalk/aaa | /day02/test06.py | 473 | 3.796875 | 4 | # 实现登陆系统的三次密码输入错误锁定功能(用户名:root,密码:admin)
print("qing shu ru zhang hao mi ma")
a,b=input().split()
i=1
username="root"
password="admin"
while 1:
if username==a and password==b:
print("deng lu cheng gong ")
break
elif i==3:
print("yong hu suo ding !")
break
else:
print(... |
b5f8bc0b3e61470c6bc6d779e470244f5a52a508 | onwayWalk/aaa | /day10_thread/test03.py | 1,459 | 3.6875 | 4 | from threading import Thread
import time
box=500
boxN=0
cus=6
class cook(Thread):
name=''
def run(self) -> None:
while True:
global box,boxN,cus
if boxN<box:
boxN+=1
print("%s做了一个蛋挞!,现在有%s个"%(self.name,boxN))
else:
if... |
4d6ce6a41f6ba8d94f67fc4e63a0d2b09cfd6eb7 | AyngaranKrishnamurthy/Python-Simple-Programs | /Single swap.py | 668 | 4.0625 | 4 | def swapstr(str1, str2):
len1 = len(str1)
len2 = len(str2)
if (len1 != len2): #Checks for if both the strings are of same length
return False
prev = -1
curr = -1
count = 0
i = 0
while i<len1: #Compares string for resemblence of elements
if (str1[i] != str2[i]): #Count... |
8b4fcea87d0a7ac318a2f9c0b0ae019175d7e291 | juan6630/MTIC-Practice | /Python/clase11.py | 1,273 | 4.15625 | 4 | def dos_numeros():
num1 = float(input('Ingrese el primer número'))
num2 = float(input('Ingrese el segundo número'))
if num1 == num2:
print(num1 * num2)
elif num1 > num2:
print(num1 - num2)
else:
print(num1 + num2)
def tres_numeros():
num1 = float(input('Ingrese el prime... |
b46ee7847c7fc4045af1a79fd52efc0616f8a616 | YoungWoongJoo/Learning-Python | /list/list1.py | 666 | 3.875 | 4 | """
리스트 rainbow의 첫번째 값을 이용해서 무지개의 첫번째 색을 출력하는 코드입니다. 3번째줄이 first_color에 무지개의 첫번째 값을 저장하도록 수정해 보세요.
rainbow=['빨강','주황','노랑','초록','파랑','남색','보라']
#rainbow를 이용해서 first_color에 값을 저장하세요
first_color =
print('무지개의 첫번째 색은 {}이다'.format(first_color) )
"""
rainbow=['빨강','주황','노랑','초록','파랑','남색','보라']
#rainbow를 이용해서 first_color... |
24442d594ecf27a0df3058aff922011d6953e8dc | YoungWoongJoo/Learning-Python | /bool/bool2.py | 733 | 4.46875 | 4 | """
or연산의 결과는 앞의 값이 True이면 앞의 값을, 앞의 값이 False이면 뒤의 값을 따릅니다. 다음 코드를 실행해서 각각 a와 b에 어떤 값이 들어가는지 확인해 보세요.
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format(a, b))
"""
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format... |
55757b84c56e85cee15ca08b313294a7919b8564 | YoungWoongJoo/Learning-Python | /random/random1.py | 474 | 4 | 4 | """
https://docs.python.org/3.5/library/random.html#random.choice 에서 random.choice의 활용법을 확인하고, 3번째 줄에 코드를 추가해서 random_element가 list의 element중 하나를 가지도록 만들어 보세요.
import random
list = ["빨","주","노","초","파","남","보"]
random_element =
print(random_element)
"""
import random
list = ["빨","주","노","초","파","남","보"]
random_ele... |
f7b72f1287d5a2b3c61390235c41b2fd81681a5b | YoungWoongJoo/Learning-Python | /function/function2.py | 705 | 4.3125 | 4 | """
함수 add는 매개변수로 a와 b를 받고 있습니다. 코드의 3번째 줄을 수정해서 result에 a와 b를 더한 값을 저장하고 출력되도록 만들어 보세요.
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요.
result =
print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요.
add(10,5)
"""
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 resul... |
cc2af962b0a91dfe357a9cee79571bff2e7449a6 | YoungWoongJoo/Learning-Python | /bool/bool1.py | 716 | 3.984375 | 4 | """
다음 코드를 실행해서 어느 경우 if문 안의 코드가 실행되는지 확인해 보세요.
if []:
print("[]은 True입니다.")
if [1, 2, 3]:
print("[1,2,3]은/는 True입니다.")
if {}:
print("{}은 True입니다.")
if {'abc': 1}:
print("{'abc':1}은 True입니다.")
if 0:
print("0은/는 True입니다.")
if 1:
print("1은 True입니다.")
"""
if []: #false
print("[]은 True입니다... |
b4f5e679116a4a68c30846b2128890f0bc53d8f5 | leeonlee/misc | /euler/5.py | 152 | 3.953125 | 4 | def isDivisible(number):
for i in range(20,1,-1):
if number % i != 0:
return False
return True
i = 2
while not isDivisible(i):
i += 2
print i
|
b5a4db5c966000f3b3126d5a75e4e33eba5793b8 | leeonlee/misc | /euler/4.py | 299 | 3.765625 | 4 | def palindrome(number):
return str(number)[::-1] == str(number)
def largest():
i = 999 * 999
j = 999
while i >= 100000:
if palindrome(i):
while j >= 100:
if i % j == 0 and len(str(j)) == 3 and len(str(int(i/j))) == 3:
print i
return
j -= 1
j = 999
i -= 1
largest()
|
7dfacf5c92af0747086f799b21abe106acd9b185 | 0x464e/comp-cs-100 | /8/pistekirjanpito_a.py | 988 | 3.765625 | 4 | """
COMP.CS.100 pistekirjanpito_a.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
counted_scores = {}
try:
file = open(input("Enter the name of the score file: "), "r")
except OSError:
print("There was an error in reading the file.")
return
scores = []
for line in file:... |
2036aac98dd7e9ff312100e3625ce12d35b44bb6 | 0x464e/comp-cs-100 | /3/tulitikkupeli.py | 1,129 | 3.59375 | 4 | """
COMP.CS.100 tulitikkupeli.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
total_sticks = 21
player = 0
# oli vissii ok olettaa et sielt
# tulee inputtina aina intti
sticks = int(input("Game of sticks\n"
"Player 1 enter how many sticks to remove: "))
while True:
... |
281d096877dfa31bad260fab583c547d4c70ca68 | 0x464e/comp-cs-100 | /3/yogi_bear.py | 702 | 3.90625 | 4 | """
COMP.CS.100 Old MacDonald Had a Farm -laulu.
Tekijä: Otto
Opiskelijanumero:
"""
# en usko et tätä joku manuaalisesti kattoo, mut
# jos kattoo, nii meni moti variablejen nimeämisen
# kaa, ne nyt on mitä sattuu :'_D
def repeat_name(name, count):
for _ in range(1, count+1):
print(f"{name}, {name} Bear... |
1e07d223937d4701534d7e5d0ead745167344c62 | 0x464e/comp-cs-100 | /6/tekstintasaus.py | 3,798 | 3.875 | 4 | """
COMP.CS.100 tekstintasaus.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
print("Enter text rows. Quit by entering an empty row.")
inp = read_message() # "moro mitä kuuluu :D:D :'_D :-D"
max_length = int(input("Enter the number of characters per line: ")) # 12
# "list comprehension"
# l... |
80318b9873859647862039df26e805d293d16d18 | 0x464e/comp-cs-100 | /11/murtolukulista.py | 4,737 | 3.96875 | 4 | """
COMP.CS.100 murtolukulista.
Tekijä: Otto
Opiskelijanumero:
"""
class Fraction:
"""
This class represents one single fraction that consists of
numerator (osoittaja) and denominator (nimittäjä).
"""
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the n... |
d749af202a4ee42fa4f5f79548febcab1b46e95e | vvvaish/Book-My-Movie | /mod1.py | 4,234 | 3.8125 | 4 | class operations:
def __init__(self,row,col):
self.row = row
self.col = col
self.cinema = []
for i in range(self.row + 1):
x = []
for j in range(self.col + 1):
if i == 0:
if j == 0 and j == 0:
... |
41ffebc58f2c3f35520955e2bdec311c4f103bf0 | NazguaL/UFOs | /game_functions/create_fleet.py | 1,744 | 3.734375 | 4 | from alien import Alien
def get_number_rows(ai_settings, ship_height, alien_height):
"""Определяет количество рядов, помещающихся на экране."""
available_space_y = (ai_settings.screen_height - (5 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_row... |
902271740940425156907021aecdd1d4c8b05d9e | visajkapadia/huffman-coding-python | /huffman.py | 2,951 | 3.671875 | 4 | start = None
class Node:
def __init__(self, letter, probability):
self.letter = letter
self.probability = probability
self.next = None
class LinkedList:
LENGTH = 0
def insertAtEnd(self, letter, probability):
node = Node(letter, probability)
global start
... |
8523f0d7a6dd5773e2b947e5302906f1f385187d | kevinwei666/python-projects | /hw1/solution1/Q4.py | 634 | 4.625 | 5 | """
Asks the user to input an integer. The program checks if the user entered an integer,
then checks to see if the integer is within 10 (10 is included) of 100 or 200.
If that is the case, prints ‘Yes’, else prints ‘No’.
Examples:
90 should print 'Yes'
209 should also print 'Yes'
189 should print 'No'
"""
#Get use... |
ec555598b456c810f86a0948aff0073e49bb2077 | kevinwei666/python-projects | /hw1/Q10-3.py | 387 | 3.84375 | 4 | #Given the following coefficients: 1, 3, 1
#Solve the quadratic equation: ax^2 + bx + c
#Here's a reminder of the quadratic equation formula
#https://en.wikipedia.org/wiki/Quadratic_formula
d = b^2 - 4ac
if d < 0:
print('no solution')
elif d = 0:
print(-b/2*a)
else:
solution1 = -b + d^0.5 / 2*a
solution... |
768be2ffc01f8e2e3dc1fd9e6971f63258d4e17d | ZombiMigz/Adventure-Rooms- | /startup.py | 1,273 | 3.78125 | 4 |
#player framework
class player:
def __init__(self):
pass
player = player()
player.maxhealth = 100
player.health = 100
#startup
def startup():
import framework
import main
framework.printunknown("Hello, what's your name?")
framework.guide('Type your name, then hit ENTER')
player.name... |
146b320e4fd906f1e9a40f63512007ccb6cbd836 | jemtca/Python-Development | /Scripting/email_sender/email_sender_static.py | 595 | 3.515625 | 4 | import smtplib # to create a SMTP server
from email.message import EmailMessage
email = EmailMessage()
email['from'] = '' # email (from)
email['to'] = [''] # email/emails (to)
email['subject'] = '' # email subject
email.set_content('') # email message
with smtplib.SMTP(host = '', port = 587) as smtp: # param1: SMTP ... |
cd4362ab4eb9b4521ffcd45b4355837d80ff6683 | HaaaToka/HUPROG19 | /final/Jenga/solveOkan.py | 1,090 | 3.5625 | 4 |
"""
1 <= Q <= 10
1< N <= 10^7
"""
q=int(input().strip())
# if not 1 <= q <= 10:
# print("1Constraints")
for _ in range(q):
n=int(input().strip())
# if not 1 < n <= 10**7:
# print("2Constraints")
txt=[]
tam,yarim=0,0
"""
yarim -> *-- , --*
tam -> -*-
"""
for __ in ra... |
56b8dad133fe4f9c472136e6a35dbd903625710c | creator-123/Sorting-Algorithm | /sort.py | 13,125 | 4.28125 | 4 | # -*- encoding: UTF-8 -*-
# 冒泡排序
def bubbleSort(nums):
"""
冒泡排序:每次与相邻的元素组成二元组进行大小对比,将较大的元素排到右边,小的元素排到左边,直至迭代完数组。
备注:将排好序的元素,放到最后面
"""
for i in range(len(nums) - 1): # 遍历 len(nums)-1 次
for j in range(len(nums) - i - 1): # 已排好序的部分不用再次遍历
... |
dd6c1d03c8a15228d5892ef94e20636941f989f8 | cjd1884/pyLectureMultiModalAnalysis | /classification/preprocessing.py | 1,674 | 3.578125 | 4 | from sklearn import preprocessing as pp
import pandas as pd
def do_preprocessing(df, categorical_columns=None):
df = standardize(df)
if categorical_columns is not None:
df = categorical_2_numeric(df, categorical_columns)
return df
def standardize(df):
'''
Standardizes the provided data... |
276a75d07f610dfad18575d23dcc26ba843be9aa | cjd1884/pyLectureMultiModalAnalysis | /old/av_merge.py | 1,958 | 3.59375 | 4 | '''
Short description: Script for merging associated video and audio files into a single medium using FFMPEG.
It expects that audio files are stored as `in_dir/audio/audio_k.mp4`
(and similarly for video) and stores the newly created file as `out_dir/media/medium_k.mp4`
'''
import ffmpy
import os
def main(in_dir='.... |
e61e9a0dd1533eca20ca131949e683b0d87aba71 | krisgrav/IN1000 | /3. oblig/lister.py | 2,125 | 3.9375 | 4 | #1
'''Programmet lager en liste med tre verdier. Deretter blir en fjerde verdi lagt til
i programmet. Til slutt printes den første og tredje verdien i listen.'''
liste1 = [1, 5, 9]
liste1.append(11)
print(liste1[0], liste1[2])
#2
'''Programmet lager en tom liste. Deretter brukes .append og en input-funksjon
til å sam... |
cc94647d2b34d67d0feea3bc0dca72a928b2fd61 | tsg-ut/esolang-battle-archive | /komabasai2018-day1/python3.py | 79 | 3.65625 | 4 | y=int(input())-2
x=int(input())
print("*"*x+("\n*"+" "*(x-2)+"*")*y+"\n"+"*"*x) |
21d842412724f3144975448a20ce0dc91e92d2fa | LuckyQingke/myrepository | /pythontest/test.py | 418 | 3.71875 | 4 | #dict
d={'cc':22,'bb':11,'mm':'00'}
if('cc' in d):
print(d['cc'])
print(d)
d['dd'] = 90
print(d)
d.pop('mm')
print(d)
def appendL(d):
d['ee']=99
appendL(d)
print(d)
#python迭代对象
for x in 'asdfg':
print(x)
for value in enumerate([1,2,3]):
print(value)
for i,value in enumerate([1,2,3]):
print(i,value)
L1 = ['Hel... |
cfa8167b3df46123ee695b344e9025d91dad2673 | kaido89/General | /tools_API/ldap/ldap_api.py | 1,186 | 3.515625 | 4 | #!/usr/bin/env python3
from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
def main():
ldap_server = input('LDAP SERVER url (eg. example.com): ')
# it should be the ldap_server
server = Server(ldap_server, get_info=ALL)
# it should have the login user
ldap_user = ... |
9cc7bbd72c1e4a79e101815dd46b4964c2d7306d | wflosin/Code-Portfolio | /Python/combatgame.py | 18,018 | 3.953125 | 4 | import time
import random
def main():
#[a,b,c, d]
#[0] is the monster's health,
#[1] is its speed,
#[2] is its damage,
#[3] is its armour class
goblin = [8, 2, 4, 2]
spider = [12, 5, 6, 4]
dragon = [30, 7, 10, 7]
smiley = [21, 6 , 8, 1]
weapon = None
print("This is a combat simulator")
time.sleep(1)
... |
291afaa5eb6a3a5e8a87f945826cf9b93d872d7e | jgjefersonluis/python-pbp | /secao02-basico/aula27-lacorepeticao/main.py | 188 | 3.84375 | 4 | # Faça um laço de repetição usando o comando while começando com o valor 50
# até 100
a = 50 # variavel
while a <= 100: # condição
print(a) # instrução
a = a + 1
|
7a4ce4b010222efd9670600554c384f40fc040fc | jgjefersonluis/python-pbp | /secao01-introducao/variaveis/main15-time.py | 387 | 3.640625 | 4 | import time
#declarando as variaveis
num = 2
num1 = 3
data_hota_atual = time.asctime()
num2num = 5
#Usando os valores das variaveis para produzir texto
print("variavel com apenas letras %i" %num)
print("variavel com letras e numero no final %i" %num1)
print("variavel com caractere especial uderline ", data_hota_atual... |
ace87f462bb896fa3a87a0a89c71569ef676e01f | jgjefersonluis/python-pbp | /secao02-basico/aula02-variaveis-comandos/float.py | 82 | 3.53125 | 4 | # Float
# Ponto Flutuante
a = float(input('Digite um valor decimal: '))
print(a) |
d37b7a9f7bbfbc9b2a247ccb2988c220d802bf95 | jgjefersonluis/python-pbp | /secao01-introducao/operadoreslogicobooleanos/main.py | 222 | 3.828125 | 4 | # AND = Dois valores verdades
# OR = Um valor verdade // Dois falsos
# NOT = Inverte o valor
a = 10
b = 5
sub = a - b
print(a != b and sub == b)
print(a == b and sub == b)
print(a == b or sub == b)
print(not sub == a)
|
5dfecf790c2ed3a9623301cdf7c1d112e76cbc25 | jgjefersonluis/python-pbp | /secao02-basico/aula23-aumentosalarial/main.py | 444 | 3.78125 | 4 | # Escreva um programa para calcular aumento salarial, se o valor do salario for maior que R$ 1200,00
# o percentual de aumento será de 10% senao sera de 15%.
salario = float(input('Digite o seu salario: '))
# condições
if salario > 1200:
pc_aumento = 0.10
aumento = salario * pc_aumento
if salario <= 1200:
... |
6002c33a5aa29c39155830b6b9f066f5d21c0a1b | AbhilashMathews/gp_extras | /examples/plot_gpr_manifold.py | 4,013 | 3.75 | 4 | # Authors: Jan Hendrik Metzen <janmetzen@mailbox.org>
#
# License: BSD 3 clause
"""
==============================================================================
Illustration how ManifoldKernel can exploit data on lower-dimensional manifold
==============================================================================... |
572a81171d108cd73f3ea478253c06b442eeef51 | kyhuudong/Learn-Algorithm | /MatrixKeanuReeves/MatrixCheckTriangleTopAndBot.py | 478 | 3.53125 | 4 | M1 = [
[2,3,4],
[0,5,7],
[0,0,7]]
M2 = [[7,0,0],
[7,5,0],
[4,3,2]]
def TriangleTopMatrix(M):
for i in range(1,len(M)):
for j in range(i):
if(M[i][j] != 0):
return False
return True
def TriangleBotMatrix(M):
for i in range(len(M)):
for j... |
c4003359c66806d171bc8d22855e75c40bb854a1 | isotomurillo/Programacion | /Python/Pila/forma lista parcial.py | 304 | 3.75 | 4 | def formarList(num):
if isinstance (num,int) and (num>0):
return pares(num)
else:
return "Número Incorrecto"
def pares(num):
if num==0:
return[]
elif (num%10)%2==0:
return Lista[num%10]+pares(num//10)
else:
return pares(num//10)
|
e19fc7953dc495fef5987d49d2a6febb41042ef5 | igorsobreira/playground | /problems/notifications.py | 1,151 | 4.1875 | 4 | '''
Eu tenho um objeto da classe A que muda muito de estado e objetos das classes
B e C que devem ser notificados quando o objeto da classe A muda de estado.
Como devo projetar essas classes?
'''
class Publisher(object):
def __init__(self):
self.status = "FOO"
self._subscribers = []
... |
474203b4cfbb1ebb634431a2eed392f539a98f6e | igorsobreira/playground | /problems/project_euler/20.py | 258 | 3.90625 | 4 | #-*- coding: utf-8 -*-
'''
n! means n × (n − 1) × ... × 3 × 2 × 1
Find the sum of the digits in the number 100!
'''
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print sum( [ int(n) for n in str(factorial(100)) ] )
|
d4f45f0640ce0cd0e066ce92db1c3be386570eed | jmorton89/Portfolio | /Code Golf- Fizzbuzz.py | 111 | 3.71875 | 4 | for i in range(1,101):
if i%3==0 and i%5==0:i='FizzBuzz'
elif i%3==0:i='Fizz'
elif i%5==0:i='Buzz'
print(i) |
e095d54de54855fbf5c006b6fe47ee93e51fd5ba | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/11.Top View of Binary Tree .py | 1,394 | 4.28125 | 4 | """
Top View of Binary Tree
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 ... |
feedbf88435af6b186da9dcd85041587edcee515 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/6.Inorder Tree Traversal – Iterative and Recursive.py | 1,406 | 3.921875 | 4 | """
Inorder Tree Traversal – Iterative and Recursive
Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
output = 4 2 1 7 5 8 3 6
... |
7629f38b20e5dd43ceda19cceb9e68a7386adee0 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/18.K-th element of two sorted Arrays.py | 1,027 | 4.25 | 4 | """
K-th element of two sorted Arrays
Given two sorted arrays arr1 and arr2 of size M and N respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array.
Example 1:
Input:
arr1[] = {2, 3, 6, 7, 9}
arr2[] = {1, 4, 8, 10}
k = 5
Output:
6
Explanation:
The... |
90c36140e441af6d4d68bc6b4199e42038ae31d2 | DinakarBijili/Data-structures-and-Algorithms | /Algorithms/Sorting_Algorithms/5.Quick_sort.py | 930 | 4.0625 | 4 | # Quick Sort using Python
# Best = Average = O(nlog(n)); Worst = O(n^2)
#Quick sort is divide-and-conquer algorithm. it works by a selecting a pivot element from an array and partitionong the other elements into two sub-array.
# according to wheather their are less that or greaterthan the pivot. the sub-arrays are t... |
6d66d78b7774086fa047257b28fd2d3d83c7d7ca | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/10.min_no._of_jumps_to_reach_end_of_arr.py | 1,639 | 4.1875 | 4 | """
Minimum number of jumps
Given an array of integers where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Exa... |
ecc51e9f138f6e8d3cfeeb04fab9a9c45edc2ce8 | DinakarBijili/Data-structures-and-Algorithms | /STACK AND QUEUE/2.Queue(FIFO).py | 2,870 | 3.9375 | 4 | """
Queue (First<-In First->Out )
Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.
The difference... |
4bd049da90d733d69710804afaa9b5352667caf3 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/7.Majority Element.py | 900 | 4.40625 | 4 | """
Majority Element
Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
Example 1:
Input:
N = 3
A[] = {1,2,3}
Output:
-1
Explanation:
Since, each element in
{1,2,3} appears only once so t... |
07c39032e44ce00d6df3d3b1306ebb5e0fbb0ce5 | DinakarBijili/Data-structures-and-Algorithms | /STRING/Edit Distance.py | 1,182 | 4.0625 | 4 | """
Edit Distance
Given two strings s and t. Find the minimum number of operations that need to be performed on str1 to convert it to str2. The possible operations are:
Insert
Remove
Replace
Example 1:
Input:
s = "geek", t = "gesek"
Output: 1
Explanation: One operation is required
inserting 's' between two 'e'... |
a6b70b95e2abd954adf5c0ef7884792630fc1e5e | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Rotate Doubly linked list by N nodes.py | 2,692 | 4.1875 | 4 | """
Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.
N = 2
Rotated List:
Examples:
Input : a b c d e N = 2
Output : c d e a b
Input : a b c ... |
6fc2e1d949f0bfaa8b60947c38faf8e435a41a73 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/1.Level order traversal.py | 1,352 | 4.125 | 4 | """
Level order traversal
Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree.
Example 1:
Input:
1
/ \
3 2
Output:1 3 2
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output:10 20 30 40 60 N N
"""
c... |
1c32e5e226de7d4f2d1e3711911554730b406f9a | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Check if Linked List is Palindrome.py | 2,064 | 4.21875 | 4 | """
Check if Linked List is Palindrome
Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not.
Example 1:
Input:
N = 3
value[] = {1,2,1}
Output: 1
Explanation: The given linked list is
1 2 1 , which is a palindrome and
Hence, the output is 1.
Example 2:
... |
af1eae902cacf9c3bbf7f609e763f01dc286edf0 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/8.Postorder Tree Traversal – Iterative and Recursive.py | 3,014 | 4.0625 | 4 | """
Postorder Tree Traversal – Iterative and Recursive
Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
output:4 2 7 8 5 6 3 1
... |
dcd5db7c301734d0b7406153043d6e89ece94997 | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Reverse a Linked List in groups of given size.py | 2,665 | 4.3125 | 4 | """
Reverse a Linked List in groups of given size
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed f... |
34da084f0c7ec038a9502cf05bfeb9d56baca684 | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/Palindromic Array.py | 431 | 3.75 | 4 | """
Example:
Input:
2
5
111 222 333 444 555
3
121 131 20
Output:
1
0
"""
def palindromic(arr, n):
rev = (arr[::-1])
if rev == arr:
return True
else:
return False
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int,inpu... |
da2f6f83dca1a4776eba5777e39cb41676e29f2a | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/4.Sort_arr-of_0s,1s,and,2s.without_using_any_sortMethod.py | 971 | 4.375 | 4 | # Sort an array of 0s, 1s and 2s
# Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.
# Example 1:
# Input:
# N = 5
# arr[]= {0 2 1 2 0}
# Output:
# 0 0 1 2 2
# Explanation:
# 0s 1s and 2s are segregated
# into ascending order.
# Example 2:
# Input:
# N = 3
# arr[] = {... |
11960b0f8caeafeda8c4cffcfa4d90bf087ad4bd | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/5.Create a mirror tree from the given binary tree.py | 1,605 | 4.375 | 4 | """
Create a mirror tree from the given binary tree
Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.
Examples:
Input:
5
/ \
3 6
/ \
2 4
Output:
Inorder of original tree: 2 3 4 5 6
Inorder of mirror tree: 6 5 4 3 2
Mirro... |
1c01d4fdc49e7addb4a02b1e32959abfb4df5377 | GBXXI/LucidProgramming | /Algorithms/Look_n_Say_Sequence.py | 1,326 | 3.90625 | 4 |
# %% [markdown]
# ## String Processing: Look and Say Sequence.<br>
# The sequence starts with the number 1:<br>
# 1<br>
# We then say how many of each integer exists in the sequence to
# generate the next term.<br>
# For instance, there is "one 1". This gives the next term:<br>
# ... |
fc8c3b2a5970f408d17c0f2b89be8add746f63f4 | pronyushkin/learn1 | /l1l2/test2.py | 2,328 | 3.90625 | 4 | '''Еще набор тестовых заданий с интенсива.'''
from math import sqrt
def do_nothing():
'''Делаем ничего, возвращаем ничто.'''
return None
def test_info():
'''Тест работа со словарем.'''
user_info = {'first_name':'fn', 'last_name':'ln'}
print(user_info['first_name'], user_info['last_name'])
pr... |
1665a5752794a64a0de7e505e172a814c9b32e8f | andrewsanc/pythonFunctionalProgramming | /exerciseLambda.py | 282 | 4.15625 | 4 | '''
Python Jupyter - Exercise: Lambda expressions.
'''
# Using Lambda, return squared numbers.
#%%
nums = [5,4,3]
print(list(map(lambda num: num**2, nums)))
# List sorting. Sort by the second element.
#%%
a = [(0,2), (4,3), (9,9), (10,-1)]
a.sort(key=lambda x: x[1])
print(a)
#%%
|
3ee8c523fd80d72e388a4fe972ea834745909b28 | andrewsanc/pythonFunctionalProgramming | /lambda.py | 427 | 3.875 | 4 | '''
Python Jupyter - Lambda. Lambda expressions are one time anonymous functions.
lambda param: action(param)
'''
#%%
myList = [1,2,3,4]
print(list(map(lambda item: item*2, myList)))
print(myList)
#%%
words = ['alcazar', 'luci', 'duncan', 'sam']
print(list(map(lambda name: name.title(), words)))
#... |
4717d68b14a296bc895da87ff083cb2db711e551 | vik407/holbertonschool-interview | /0x10-rain/0-rain.py | 538 | 3.625 | 4 | #!/usr/bin/python3
""" 0_rain.py
"""
def rain(walls):
""" Return rainwater trapped with array of wall heights.
"""
i, j = 0, len(walls) - 1
lmax = rmax = res = 0
while i < j:
if walls[j] > walls[i]:
if walls[i] > lmax:
lmax = walls[i]
else:
... |
e38e2d771340ac0843aef8cb25dd0b6fa960755b | pascee/physics_learning_app | /velocity/calculations.py | 1,239 | 3.71875 | 4 | from sympy import *
x = Symbol('x')
#takes in an equation for displacement as a string and derives it to find velocity
def differentiate(your_equation):
your_equation = your_equation.replace("^", "**")
f_prime = diff(your_equation)
f_prime = str(f_prime)
if "x" not in f_prime:
f_prime = 'y=' +... |
025e4b39d4981efa90b2414fa3a5e59276d83012 | crunchypi/Sudoku-Solver | /sudoku_helper_GUI.py | 8,717 | 3.765625 | 4 | import tkinter as tk
from tkinter.ttk import Separator, Style
import sudoku_tools
class GUIInterface():
""" A GUI interface for a Sudoku solver.
Requires:
- Tkinter.
- Sudoku loader and solver.
Has two main views/frames:
- Top for loading a Sudoku board.
... |
cb77261c3c3db53f0a7067e749f1b10a06fbeb63 | DandyCV/SoftServeITAcademy | /L07/L07_HW1_4.py | 306 | 4.0625 | 4 | def season(month):
"""Returns - string (season of year).
Argument - integer from 1 to 12 (number of month)."""
if 0 < month < 3 or month == 12: return "Winter"
if 2 < month < 6: return "Spring"
if 5 < month < 9: return "Summer"
if 8 < month < 12: return "Autumn"
print(season(7)) |
3a6fa89d2f42f9b264fc509e02c13c8222e8d76c | DandyCV/SoftServeITAcademy | /L07/L07_HW1_3.py | 321 | 4.15625 | 4 | def square(size):
"""Function returns tuple with float {[perimeter], [area], [diagonal]}
Argument - integer/float (side of square)"""
perimeter = 4 * size
area = size ** 2
diagonal = round((2 * area) ** 0.5, 2)
square_tuple = (perimeter, area, diagonal)
return square_tuple
print(square(3))... |
97d0ccc3d5c0bd1f9d84c1201695309d49c09fb9 | DandyCV/SoftServeITAcademy | /L07/L07_HW1_1.py | 473 | 4.5 | 4 | def arithmetic(value_1, value_2, operation):
"""Function makes mathematical operations with 2 numbers.
First and second arguments - int/float numbers
Third argument - string operator(+, -, *, /)"""
if operation == "+": return value_1 + value_2
if operation == "-": return value_1 - value_2
if ope... |
80c45c7f70d8f318b41146d4d8ec521cff44b331 | DandyCV/SoftServeITAcademy | /L08/L08_HW2_4.py | 1,302 | 3.578125 | 4 | #Задано символьний рядок,. Розробити програму, яка знаходить групи цифр, записаних підряд, і вилучає із них всі
# початкові нулі, крім останнього, якщо за ним знаходиться крапка. Друкує модифікований масив по сорок символів у рядку.
from random import randint
random_string = "000.001jh000.550opk00023.000dfe70000.0001"... |
cf22428c9b7c74168b938c045c472490fcdd777e | DandyCV/SoftServeITAcademy | /L06/L06_HW1_8.py | 394 | 3.640625 | 4 | from random import randint
random_list = []
for number in range(10):
random_list.append(randint(-100, 100))
print("Random list 1:", random_list)
index_max = random_list.index(max(random_list))
index_min = random_list.index(min(random_list))
temp = random_list[index_min]
random_list[index_min] = random_list[index... |
5a3e85770875b03396a7a0f19fcd53dfdab290df | devangi2000/HacktoberFest2020-1 | /Interview Based/Anagram.py | 1,315 | 4.09375 | 4 | """ Given two strings a and b consisting of lowercase characters.
The task is to check whether two given strings are anagram of each other or not.
An anagram of a string is another string that contains same characters,
only the order of characters can be different. For example, “act” and “tac” are anagram of each ot... |
4aea4fa53d3b15c6535d109b58eaa36840778e95 | devangi2000/HacktoberFest2020-1 | /Interview Based/Longest Palindrome in a String.py | 805 | 3.984375 | 4 | """ Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least ... |
c5c25d3d8be7abf375018cdfa1e6a75ac48438e1 | devangi2000/HacktoberFest2020-1 | /Interview Based/Missing number in array.py | 763 | 3.796875 | 4 | """ Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing,
the missing number is to be found.
Input:
The first line of input contains an integer T denoting the number of test cases.
For each test case first line contains N(size of array). The subsequent line contains N-1 ... |
3de63dc10bf4adab4fca2f8da4704652a2e1a3cf | jasonjiang001/LeetCode | /1TwoSum.py | 780 | 3.734375 | 4 | """
1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
def getTowSum(nums, target):
sum = []
for i in range(len(nums)):
for j in range(len(nums)-1, -... |
aa33cf7e6eca200e41c461c00a48a7f3bafde728 | aaherrera3/Lab-3- | /Binary_Tree.py | 3,838 | 4.09375 | 4 | # Code to implement a binary search tree
# Programmed by Olac Fuentes
# Last modified February 27, 2019
class BST(object):
# Constructor
def __init__(self, item, left=None, right=None):
self.item = item
self.left = left
self.right = right
def Insert(T, newItem):
if T ... |
8a05ce56e01f8c822283574871f22ec5ea5fe1dc | chengyaojun/FindDuplicateFile | /find_duplicate_file.py | 1,498 | 3.8125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
find duplicate file
"""
import os
from collections import Counter
import sys
def get_all_files(abspath):
"""
@abspath: get all files from path of 'abspath'
@return: get list of all files
"""
all_files = []
for _, _, files in os.walk(abspath):
... |
9fe71b923d902d03dab882fe161d38d3bd122d81 | albornoz440/trabajo-informatica | /programacion 2/punto 3.py | 117 | 3.828125 | 4 | name = input("¿Cómo te llamas?: ")
num = input("Introduce un número entero: ")
print((name + "\n") * int(num))
|
97a4605437a98334fb3b356944b504f2ca457588 | natemago/advent-of-code-2019 | /day-2-program-alarm/solution.py | 1,331 | 3.5625 | 4 | def exec(program):
pc = 0
while True:
if pc < 0 or pc >= len(program):
print('PC outside range')
break
instr = program[pc]
if instr == 99:
print('Normal HALT')
break
a = program[pc + 1]
b = program[pc + 2]
dest = pr... |
bc23a915700dd7c8f593f9e27e17035e59987e7b | Percy-Cucumber/IND3156 | /homework_7/parabola.py | 314 | 3.5625 | 4 | #import
import random
#code
random.seed(42)
total=1000000*1000
out = 0
for i in range(total):
x = random.random()
y = random.random()
if ((-x)*x) + x > 1:
out = out + 1
#print
print( 4.0*(1.0-float(out)/float(total)))
#referenced https://pythonprogramming.net/monte-carlo-simulator-python/ |
b7f773a51b49ad7512c4dee4a860c49d2e600ba7 | ramalho/modernoopy | /examples/tombola/ibingo.py | 814 | 4.34375 | 4 | """
Class ``IBingo`` is an iterable that yields items at random from
a collection of items, like to a bingo cage.
To create an ``IBingo`` instance, provide an iterable with the items::
>>> balls = set(range(3))
>>> cage = IBingo(balls)
The instance is iterable::
>>> results = [item for item in cage]
... |
d77391b2a500f484e0438d722b683f76077610e5 | ramalho/modernoopy | /examples/countries/countries.py | 287 | 3.859375 | 4 | import dataclasses
@dataclasses.dataclass
class Country:
"""Represents a country with some metadata"""
name: str
population: float
area: float
def density(self) -> float:
"""population density in persons/km²"""
return self.population / self.area
|
3a8597f3280a8a10dff9731e090596fc79e0b67c | SLongofono/Python-Misc | /multiprocessing/multiprocessing_pools.py | 2,446 | 3.640625 | 4 | """
This demonstrates the use of asynchronous pools of workers using the multiprocessing
module. Due to some unfortunate choices on the back end, anonymous functions and
closures will not work. Similar constraints apply to the pool.map() construct. Things
like logging and shared queues are built in to the module, b... |
53bd12eb151b9514575a8958560352ddb44bd941 | SLongofono/Python-Misc | /python2/properties.py | 1,250 | 4.125 | 4 | """
This demonstrates the use of object properties as a way to give the illusion of private members and
getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other
programmers that they should be changing them directly, but there really isn't any enforcement. There are
still... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.