blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6e853af8f5c029a4c5843cb0c6f6de451bfcc3ed | lcbm/cesar-is-cool | /matemática-discreta/main.py | 3,520 | 3.65625 | 4 | import sympy as sp
import random
import sys
import os
import time
## OK ##
def newton_raphson():
os.system('cls')
print("Zero da função: Método de Newton-Raphson\n")
x = sp.Symbol('x')
fx = sp.sympify(input("digite f(x): "))
x0, erro = [float (x) for x in input("Digite x0 e erro (separados por vir... |
5654828bd965177fc7ef341aecaf1fb897e59a1e | weekswm/cs162p_week8_lab8 | /Car.py | 1,291 | 4.25 | 4 | #Car class
class Car:
'''Creates a class Car
attributes: make, color, and year
'''
def __init__(self, make = 'Ford', color = 'black', year = 1910):
'''Creates a car with the provided make, color, year.
Defaults to Ford black 1910.
'''
self.make = make
self.color =... |
2034276de5f99ed60e9ab3fd0d3e8d667c3e5ba0 | mugwch01/Trie | /Mugwagwa_Trie_DS.py | 2,267 | 4.21875 | 4 | #My name is Charles Mugwagwa. This is an implementation of a Trie data structure.
class Trie:
def __init__(self):
self.start = None
def insert(self, item):
self.start = Trie.__insert(self.start, item+"$")
def __contains__(self,item):
return Trie.__contains(self.sta... |
c12e3911332c165f3159f17f08f16a399a1400f9 | binayokbhowmikxp/python-short-code | /random_password_generator.py | 222 | 3.546875 | 4 | from random import choice
len_of_password=8
valid_chars_for_password='abcdefghijklmnopqrstuvwxyz!@#%^&*()?1234567890'
password = []
for each_char in range(len_of_password):
password.append(choice(valid_chars_for_password))
print("".join(password))
|
cfa646e3ef8ed2b29640e494e392ac60e5463b90 | captain-kirk/datascience | /homework/a1.py | 1,038 | 3.96875 | 4 | def product(values):
result = 1
for v in values:
result = result * v
return result
def shortest(words):
result = words[0]
for w in words:
if len(w) < len(result):
result = w
return result
def average(numbers):
sum = 0;
i = 0;
for n in numbers:
sum = sum + n
return sum/len(numbers)
import random
d... |
7bd99c14dcc43ad0dacc7fb1959885a5c5ba1269 | impractical101/LeetCode-30-June-Challenge | /day22.py | 276 | 3.546875 | 4 | #Submitted by thr3s0ld
#Logic: Use counter to check the occurences.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
count = Counter(nums)
for elements in count.elements():
if count[elements] == 1:
return elements |
b13e9172a451090480793a0f8d90782bdad25c68 | impractical101/LeetCode-30-June-Challenge | /day12.py | 1,307 | 3.96875 | 4 | #Submitted by thr3sh0ld
#Logic: Use dictionary operations.
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
self.lis = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the... |
9cbe2efb3a247ee760532f717d73c5edaa043c5d | impractical101/LeetCode-30-June-Challenge | /day6.py | 381 | 3.625 | 4 | #Submitted by thr3sh0ld
#logic: sorting both the indexes and inserting based on the no of people before. Using insert as it is faster.
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key=lambda x: (-x[0], x[1]))
ans = []
for p i... |
4e8d07e4ae1b2560b3fedb1ccc908602fa8cf90e | JuliusNM/AboutPython | /kamau.py | 289 | 3.6875 | 4 | # def find_age(b, c):
# y = c - b
# print("Kamau born in %d : %d Years" % (b, y))
# return y
# find_age(2000, 2017)
def get_age(born, current):
years = current - born
print("hello I was born in %d and that has been %d years ago"% (born, years))
get_age(2000, 2017)
|
366005e6b40e57b8dd76f0be587559d1c7f5893e | konstantinaagraniti/python | /exercise9.py | 438 | 3.953125 | 4 | noumero =int(input("enter noumero:")) # noumero = 10
while noumero >= 10:
noumero = noumero*3 + 1 # noumero = 31
def digit_sum(noumero):
num_str = str(noumero)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
print(num_str[i])
return sum
noumero = digit_sum(noumero... |
a6c45c82588dd8dc5f6211d277ae2fe6a4689d17 | patrickbucher/python-crash-course | /ch09/dice.py | 227 | 3.578125 | 4 | from random import randint
class Die:
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
return randint(1, self.sides)
die = Die()
for i in range(0, 10):
print(die.roll_die())
|
4984ef6694f634ff87215abd4d82d332dfc3262a | patrickbucher/python-crash-course | /ch08/user-albums.py | 610 | 3.921875 | 4 | def make_album(artist, title, number_of_songs=None):
album = {'artist': artist, 'title': title}
if number_of_songs:
album['number_of_songs'] = number_of_songs
return album
def is_quit_input(entered):
return entered.strip().lower() == 'quit'
quit_message = 'Enter «quit» to finish'
while True:... |
27845f58cee3c88a8e9ab3da0853d796c4194bd8 | patrickbucher/python-crash-course | /ch10/addition.py | 196 | 3.78125 | 4 | a = input('First Number: ').strip()
b = input('Second Number: ').strip()
try:
c = int(a) + int(b)
print(f'{a} + {b} = {c}')
except ValueError:
print('You entered an invalid number.')
|
80e2a092b5a6d56cd137ebba96d26e55f3edb3d2 | patrickbucher/python-crash-course | /ch10/guest-book.py | 198 | 3.703125 | 4 | with open('guest_book.txt', 'w') as f:
while True:
name = input('What is your name, please? ').rstrip()
if name:
f.write(f'{name}\n')
else:
break
|
c1940693fd3eface908ff33ad53698b00bccba0a | patrickbucher/python-crash-course | /ch07/pizza-toppings.py | 294 | 4.125 | 4 | prompt = 'Which topping would you like to add to your pizza?'
prompt += '\nType "quit" when you are finished. '
topping = ''
active = True
while active:
topping = input(prompt)
if topping == 'quit':
active = False
else:
print(f'I will add {topping} to your pizza.')
|
cd59c41b072bd046b739d48e00b8506f258e6dab | patrickbucher/python-crash-course | /ch08/sending-messages.py | 304 | 3.53125 | 4 | def show_messages(messages):
printed_messages = []
for message in messages:
print(message)
printed_messages.append(message)
return printed_messages
messages = ['Hi', 'Hello', 'How are you', 'Nice weather!']
printed_messages = show_messages(messages)
print(printed_messages)
|
accefe593ecbe5aff02fd7a6bb3d374df47e992f | patrickbucher/python-crash-course | /ch11/city_functions.py | 253 | 3.796875 | 4 | def city_country(city, country, population=0):
"""Generate a neatly formatted location string."""
if population:
return f'{city}, {country}'.title() + f' ‒ population {population}'
else:
return f'{city}, {country}'.title()
|
9dbd18cac1fa64121cac0493556b93df6bf464fd | patrickbucher/python-crash-course | /ch10/addition-calculator.py | 346 | 4 | 4 | def input_number(prompt):
x = ''
while x == '':
number = input(prompt).strip()
try:
x = int(number)
except ValueError:
print(f'You entered an invalid number "{number}".')
return x
a = input_number('first number: ')
b = input_number('second number: ')
c = a ... |
612190f98c2cea1e2fa49adefea568f97c0690f8 | sushovanisalive/python_codes | /speed_test.py | 1,103 | 4 | 4 | # Python program to test
# internet speed
import speedtest
st = speedtest.Speedtest()
# option = int(input('''What speed do you want to test:
# 1) Download Speed
# 2) Upload Speed
# 3) Ping
# Your Choice: '''))
# if option == 1:
# print('Download Speed: ' + str((float(st.down... |
4f02eaf1a3c64792db5a7c468936ca267481634a | sushovanisalive/python_codes | /rand5_rand7.py | 623 | 3.6875 | 4 | import random
from collections import Counter
def rand7():
return random.randint(1, 7)
def rand5():
# Implement rand5() using rand7()
out_put = rand7()
if out_put <= 5:
return out_put
else:
rand5()
test_list = []
for _ in range(100):
# print('Rolling 5-si... |
501f711e78c2b2cf2cc1af161524ac9c3c5c1d60 | sushovanisalive/python_codes | /SingleNumber.py | 205 | 3.765625 | 4 | num_dict = {}
provide_list = [2,3,4,2,4]
for element in provide_list:
if num_dict.items == element:
num_dict[element] += 1
else:
num_dict[element] = 1
print(num_dict)
|
7894c996e9ddeb8cc376a9382a4d8e0175b0d1d4 | sushovanisalive/python_codes | /testing_file.py | 781 | 3.96875 | 4 | import timeit
# def mean_list(in_list):
# sum=0
# for entry in in_list:
# sum = sum + entry
# return (sum/len(in_list))
# print(mean_list([2,5,8,0,8,7]))
def read_file_text(filename):
with open(filename, "r") as myfile:
data = myfile.read()
return data
def reverse... |
3562c127d8f30c5d3cf544bb6076a46ea245b85b | ElektroNeo/100-days-of-code-python | /Day-011/Shape-Calculator/shape_calculator.py | 1,788 | 3.984375 | 4 | import math
class Rectangle:
# Init class function
def __init__ (self, w, h):
self.h = h
self.w = w
# Class string representation
def __str__(self):
return "Rectangle(width={}, height={})".format(self.w, self.h)
# Set width of rectangle
def set_width(self, w):
se... |
5c2a4fdd82fd27d20ad31e76b27e4448dd2b7ac7 | hethune/leetCode | /python/surroundedBoard/solution.py | 1,181 | 3.578125 | 4 | from pprint import pprint
class Solution:
# @param board, a 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
l = len(board)
if l == 0:
return
w = len(board[0])
if w == 0:
retu... |
f682470849955a595115419b10a5c33427345893 | BGCX261/zhengxinxing-svn-to-git | /trunk/Money/Money.py | 2,895 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class MoneyError(Exception): pass
class NoRateError(MoneyError): pass
class NeedListError(MoneyError): pass
class Money:
def __init__(self, currency='USD', amount=0):
self.amount = amount
self.currency = currency
def __eq__(self, mon... |
35fd8ca058887c3f58fa5f2ae6b46402c573d17f | B-Ricey763/Python-Snake | /field.py | 1,622 | 3.796875 | 4 | from pygame import display, draw
from enum import Enum
from collections import namedtuple
WHITE = 255, 255, 255
SIZE = 16
class FieldState(Enum):
EMPTY = 0
SNAKE = 1
APPLE = 2
Point = namedtuple("Point", ("x", "y"))
class Field:
def __init__(self, width: int, height: int):
self.width = width... |
05a6e73545aba94442b52eb8cfcced8225292cad | qmisky/python_fishc | /3-3 斐波那契数列-递归.py | 372 | 4.21875 | 4 | def factorial(x):
if x==1:
return 1
elif x==2:
return 1
elif x>2:
result=int(factorial(x-1))+int(factorial(x-2))
return result
elif x<0:
print ("WRONG NUMBER!")
number=int(input("please enter a positive number:"))
result=factorial(number)
print("the %d'th mont... |
bd06e7dba5e61c75fdb9172fb23fe5228ee4ef2a | qmisky/python_fishc | /3-12 按一定的规律打印字符串.py | 144 | 4.03125 | 4 | temp=input("please enter a positive number:")
number=int(temp)
for i in range(0,number):
print(" "*(7-i), end="")
print("*"*(8-i))
|
679f7f7f099d851e1a63beca3be61c3dfa50a7f8 | zl0bster/BubblesProject | /transform_decart_ang.py | 2,186 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#
# functions for coordinates transformation from angular to decart and back
import math
import simple_draw as sd
def angular_to_decart(distance: int, angle: int):
x = int(distance * sd.cos(angle))
y = int(distance * sd.sin(angle))
return x, y
def vector_length(x: int, y: int):... |
fa74d50eb1dd4ab11d49c66a62a3a3cc7acdd059 | rstjh/python_MTA | /class_examples/computepay.py | 550 | 3.734375 | 4 | def get_input():
while True:
inp_hr = input('Enter Hours: ')
inp_rate = input('Enter Rate: ')
try:
hours = float(inp_hr)
rate = float(inp_rate)
except ValueError:
continue
else:
break
return hours, rate
def... |
7d998a3059c71b8ae52ebeea0be30f73c3dfe0b1 | IEEE-ComSoc-UnB/PENTEST_PROJECT | /IOT/Virtual/Sec_iot/procedural/socket_server.py | 1,113 | 3.8125 | 4 | #!/usr/bin/python3
import socket
import os
HOST = "127.0.0.1" # Configuracao da variavel de ambiente do endereco do host utilizado pelo servidor
PORT = 6789 # A porta que sera utilizada pelo servidor
# Inicializacao de um socket com a funcao socket
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
... |
af65459d645f6c00e9b18b3bf9f38e9282e4e6d7 | amangarg8279/PythonL | /Day 4/tales or head.py | 118 | 3.953125 | 4 | import random
number=random.randint(1,2)
if(number==1):
print("its head")
elif(number==2):
print("its Tail")
|
54c529943319ebdda6e98448f48d29485b69536e | amangarg8279/PythonL | /Day 5/average height challenge.py | 286 | 3.953125 | 4 | #we will have average height of number of student and after that we have to calc the avearge height
total_of_height=0
height=[180,124,165,173,189,169,146]
for values in height:
total_of_height+=values
print("Average height will "+str(round(total_of_height/len(height),2))+" cm !") |
0b97bad2fc0adf54957ed3cbb269590a3e8dde04 | amangarg8279/PythonL | /Day 2/bmi calc.py | 179 | 4.0625 | 4 | height=input("Please enter your height in meter")
weight=input("please enter your weight in kg")
f_height=float(height)
f_weight=float(weight)
print(f_weight/(f_height**f_height)) |
905976bf6c4a48cb5e3a9a10f8bf8dd4179f17da | AKArrow/AllPracticeProblemInPython | /week.py | 289 | 4.15625 | 4 | n=input("Enter A Week Day:")
if n==1:
print "monday"
elif n==2:
print "tuesday"
elif n==3:
print "wednesday"
elif n==4:
print "thursday"
elif n==5:
print "friday"
elif n==6:
print "saturday"
elif n==7:
print "sunday"
else:
print "There Is No Such Week Day!" |
4201b574397318cf1d12da42a8d119754ade21e9 | AKArrow/AllPracticeProblemInPython | /unit.py | 263 | 3.75 | 4 | n=input("Enter A Number:")
if n==1:
print "one"
elif n==10:
print "ten"
elif n==100:
print "one hundred"
elif n==1000:
print "one thusand"
elif n==10000:
print "ten thusand"
elif n==100000:
print "one lakh"
else:
print "Out Of Bounds!" |
8976d4ecfd44c63a7eb2517625af7924a6892833 | UDTechLLC/python-ml-research | /research/tensorflow/src/crash/pandas/pandas3.py | 576 | 3.921875 | 4 | import numpy as np
import pandas1
import pandas2
if __name__ == '__main__':
print(pandas1.city_names.index)
print(pandas2.cities)
print(pandas2.cities.index)
cities = pandas2.cities.reindex([2, 0, 1])
print(cities)
print(cities.index)
random_cities = cities.reindex(np.random.permutation(... |
c429b6220cb9d706bbb84e98e68c6d207d5a4809 | RaveenaHebbar/march-training | /18.py | 734 | 3.96875 | 4 | bracket=input("enter the string of the bracket")
ocf=0
ccf=0
ocp=0
ccp=0
flag=True
stk=[]
for i in range(len(bracket)):
if bracket[i]=="{":
stk.append("}")
ocf+=1
elif bracket[i]=="(":
stk.append(")")
ocp+=1
elif bracket[i]=="}":
if bracket[i]!=stk[... |
0bfc634f9122b7cf9e627a43167f4389b8a1f295 | guanglin-kuang/div_mod | /by_packages/src/div_mod_pkg/div_mod_script.py | 649 | 3.53125 | 4 | #!/usr/bin/python
"""
A custom divide/modulo script.
Example usage:
div_mod_script.py 10 3
"""
import sys
from div_mod_pkg.div_mod import div_mod
def div_mod_example():
"""
For testing `console_scripts` only.
"""
print(__doc__)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Pl... |
fdd3407811accf169529cd73467a49580ab791b6 | Lambdanaut/Drawrawr | /system/betaGenerator.py | 288 | 3.625 | 4 | import random
def intsToString(numbers):
string = ""
for number in numbers:
string += chr(number)
return string
def generatePassword(length):
pos = 0
password = []
while pos < length:
password.append(random.randint(97,122))
pos+=1
return intsToString(password) |
92c966450b58c178090dffa9688931fc219d7469 | moustapha-ramadan/Test | /calculator.py | 233 | 3.8125 | 4 | #!/usr/bin/env python
def add(num1,num2):
print("%s+%s=%s"%(num1,num2,num1+num2))
return num1+num2
def sub(num1,num2):
print("%s+%s=%s"%(num1,num2,num1-num2))
return num1-num2
if __name__=='__main__':
sub(add(2,6),sub(3,1))
|
35dd288697bfe404b8f069973f4ca4e79091d445 | Shivanshu17/DS-Algo | /Insertion_Sort.py | 291 | 4.1875 | 4 | def insertionsort(arr):
l = len(arr)
for i in range(1,l):
j= i-1
key = arr[i]
while(j>=0 and key<arr[j]):
arr[j+1] = arr[j]
j = j-1
arr[j+1] = key
arr = [3,5,1,6,3,8,2,9]
insertionsort(arr)
for k in arr:
print(k) |
806d552645bd0773a43bad8d5e71731c35e42fc3 | pratimasakinala/python | /python/loop_list.py | 385 | 3.859375 | 4 | def censor(text, word):
result = []
lists = text.split()
print( lists )
for item in lists:
if item == word:
string = ""
for char in item:
string += "*"
result.append(string)
else:
result.append(item)
result = " ".join... |
3dfb4913f950a02de3690c0ed5d832720497805a | AlphaHMJ/JinritoutiaoWebScraping | /into_sql.py | 2,788 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 14:05:42 2019
@author: Holmes
sqlite>.header on
sqlite>.mode column
"""
import sqlite3
def get_news():
read_file=open('news.txt','r')
news_data=read_file.readlines()
news_title=[]
for title in news_data:
element=ti... |
5cd54222648f5cce408e3f8eb343d1c821cf3c36 | archanasbharath/Cryptocurrencies-Price-Prediction-and-Analysis-System | /FinalProjLTCPred.py | 6,000 | 3.546875 | 4 | '''
Project : CryptoCurrencies Prediction and Analysis System
Author : Archana Subramaniyan
Course : ITMD 513 Open Source Programming
File : FinalProjLTCPred.py
About : This is the module that builds LSTM prediction model for predicting future prices of litecoin data
'''
import numpy as np
import matplotlib.p... |
09940d45fdeee5b2198010f9ecb8da9eb3a0d89e | bryanl5/ctci | /string_to_int.py | 1,140 | 4.0625 | 4 | """
Given a number in string format, return it in number format
>>> print(stringToInt("123"))
123
>>> print(stringToInt("+123"))
123
>>> print(stringToInt("-1"))
-1
"""
def stringToInt(numStr):
if not numStr or type(numStr) is not str or len(numStr) < 1:
return None
digits = {
"0": 0,
... |
382e6f84c3680ad1c4a651502b5f134f22390c4e | bryanl5/ctci | /ch8/2robot.py | 736 | 4.09375 | 4 | def robot(maze):
path = []
if get_path(maze, len(maze) - 1, len(maze[0]) - 1, path):
return path
return "no path"
def get_path(maze, r, c, path):
if (r, c) == (0, 0):
path.append((r,c))
return True
if r < 0 or c < 0 or maze[r][c] == False:
return False
if get_pat... |
6e30c74c5f381ba9ddbb69cce62089bee2ceef98 | Yourens/OS2016springgrading | /stat.py | 416 | 3.515625 | 4 | #!/bin/env python2
studlist = open("finallist")
scorefile = open("summary.txt")
score = {}
miss =[]
for line in scorefile:
scoreline = line.split()
score[scoreline[0]] = scoreline[2]
for line in studlist:
stud = line.split()
if stud[2] in score:
print line.strip() + " " + score[stud[2]]
e... |
36b0399789e23a682cf5c23cd5896c1b67f4fb7e | DanWade3/belhard_8_tasks | /tasks/easy/incapsulation/game_obj.py | 748 | 3.65625 | 4 | """
Напишите класс GameObject, в котором будут храниться координаты объекта.
- x int
- y int
Координаты должны быть доступны для чтения, а их изменение должно происходить в методе
move(delta_x, delta_y)
реализовать через property
"""
class GameObject:
def __init__(self, x: int = 0, y: int = 0):
self.__... |
0165c1a06718db569cd1f53a94956a1508b5959e | DanWade3/belhard_8_tasks | /tasks/easy/inheritance_polimorphism/duck_typing.py | 745 | 4.34375 | 4 | """
Создать 3 класса:
Cat, Duck, Cow
в каждом классе определить метод says()
Cat.says() - кошка говорит мяу
Duck.says() - утка говорит кря
Cow.says() - корова говорит муу
Написать функцию animal_says(), которая принимает объект и вызывает метод says
"""
class Cat:
def says(self):
print("кошка говорит ... |
9b6df81a3c997aea23bcf91585c136e3ca8f307f | DevAbdullah7/Mine-Univaresity | /test.py | 6,422 | 3.734375 | 4 | import os
import time
from datetime import datetime
#from typing_extensions import Required
# varibles
time_now = datetime.now()
weekend = ('Fri', 'Sat')
print('Welcome ^_^\n\n')
def plans():
print('road map: 1')
print('required tasks: 2')
plansUser = int(input('choice: \t ( To Exit prees E ): '))
tr... |
47f626777c3b36be151c05ca7a604fd976437788 | nash-sanshi/test | /pytest/mypython/amusitel.py | 548 | 4.03125 | 4 | # Python 检测用户输入的数字是否为阿姆斯特朗数
# 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 例如1^3 + 5^3 + 3^3 = 153。
# 获取用户输入的数字
num = int(input("请输入一个数字: "))
# 初始化变量 sum
sum = 0
# 指数
n = len(str(num))
print(n)
# 检测
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
# 输出结果
if num == sum:
print(num,"是阿姆斯特朗... |
196f190a75bfd938cbc166ff2111b1a5790ece6d | nash-sanshi/test | /pytest/mypython/str2float.py | 793 | 3.609375 | 4 | '''
Created on 2020-9-8
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
@author: zhangsanshi
'''
from functools import reduce
def str2float(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
#去除小数点
s1 = s.repla... |
5e86d3968b563d852e0dd68b67f48d12b37036d3 | psgeisa/python_eXcript | /Excript - Aula 01 - Concatenar.py | 698 | 4.28125 | 4 | # Concatenando numero inteiro e str
num_int = 5
num_dec = 7.3
val_str = "qualquer texto"
# %d é um marcador padrão
print("1ª forma - o valor é:", num_int)
print("2ª forma - o valor é:%i" %num_int) # %i de "inteiro"
print("3ª forma - o valor é:" + str(num_int)) # Essa concatenação necessita de conversão int >... |
05b28091468dd9b14d054bc1c090b9cb5a73291a | psgeisa/python_eXcript | /Excript - Aula 06 - Operadores Relacionais.py | 255 | 3.53125 | 4 | # Operadores de igualdade
print(10 == 10) #É verdade que os valores são iguais
print(10 == 11) #É falso que os valores são iguais
print(10 != 10) #É falso que os valores são diferentes
print(10 != 11) #É verdade que os valores são diferentes
|
3c647ea21a894256099a43bf1835c741ca6aea32 | bhuiyanmobasshir94/haker-rank | /Problem-Solving/stair_case.py | 341 | 4.15625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
def staircase(n):
for i in range(1,n+1):
str=''
for k in range(1,((n-i)+1)):
str +=' '
for j in range(1,i+1):
str += '#'
print(str)
if __name__ == '__main__':
n = int(raw_input(... |
52fc3b10eddc233d193457e9ad001434b4d5d4a4 | Taratay/Project1 | /hello.py | 1,175 | 3.625 | 4 | import sqlite3 as db
from tkinter import *
root = Tk()
con = db.connect('Hospital.db')
cur = con.cursor()
'''
deletetables()
'''
cur.execute('SELECT * FROM JOBPOSITION')
for i in cur.fetchall():
print(i)
cur.execute('SELECT * FROM PATIENT')
for i in cur.fetchall():
print(i)
cur.execute('S... |
2e8aa2f002fc756362092ca4dec4318670207608 | dhruuuuuv/mlalgorithms | /linearreg.py | 849 | 3.53125 | 4 | import csv
import math
import operator
import matplotlib.pyplot as plt
import numpy as np
def linear_regression(filearg):
# load data from file passed as arguement
data = np.loadtxt(filearg, delimiter=' ')
a = np.matrix(data)
print(a)
# split input into x and y
x = a[:,0]
y = a[:,1]
o... |
b21ff9ac11afeff8e73430b6ff62edb8e4c4e4be | Icogerard/chat_simple_bot_1 | /chat_1.py | 1,140 | 4.0625 | 4 | # checked code | Yum
print('Hola. Soy Yum')
print('Fui creado en el año 2020.')
print('Dime tu nombre.')
name = input()
print('Un placer conocerte, ' + name + '!')
print('Ahora adivinare tu edad.')
print('Dime cual es el residuo de dividir tu edad entre 3, 5 y 7.')
residuo3 = int(input())
residuo5 = int(input())
re... |
2f06d3b2145228e69a5a9b95bf46d09f3cec6a85 | mneesemann/GameProject | /SplashScreen.py | 1,727 | 4.03125 | 4 | import tkinter as tk
class SplashScreen(object):
"""docstring for SplashScreen
Boilerplate for all Screens:
The Screen classes are self-contained view that only require their controller to pass the
appropriate callback functions upon instantiation. They should only added to and removed
from the sc... |
510fc9eb56fa86afea6291700870f4a3236d49bf | terryinfcco/sqlite3_codemy | /db_app.py | 1,506 | 3.65625 | 4 | import db_template
not_done = True
# Loop until x is menu choice
while not_done:
# Create a menu so we can use the database
print ()
print ("Menu - Select an Option")
print ("-----------------------")
print ("S - Show All Records")
print ("A - Add a Record")
print ("D - Delete a Record")
... |
3c2fa232fc4349e7eb7b63254c73088a6c10f06a | adrianoviana/algoritmos | /recursividade/fatorial.py | 265 | 3.671875 | 4 | def fatorial(n):
print("calculando fatorial(%s)\n" % n)
if n == 0:
print("terminou fatorial(0) = 1\n")
return 1
else:
f = n*fatorial(n-1)
print("terminou fatorial("+str(n)+") = "+str(f)+"\n")
return f
fatorial(4) |
2083a17e6a704cfa7fe0964189337ace738869a5 | jasonwsvt/Python-Projects | /web_generator/web_generator_func.py | 1,877 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Python Ver: 3.5.1
#
# Author: Daniel A. Christie
#
# Purpose: Phonebook Demo. Demonstrating OOP, Tkinter GUI module,
# using Tkinter Parent and Child relationships.
#
# Tested OS: This code was written and tested to work with Windows 10.
import ... |
c3fbdb921f822e4d6ebfeeeb8c11459af4f8af50 | jasonwsvt/Python-Projects | /db_sub.py | 1,389 | 4.375 | 4 | """
Use Python 3 and the sqlite3 module.
Database requires 2 fields: an auto-increment primary integer field and a field with the data type “string.”
Read from fileList and determine only the files from the list which end with a “.txt” file extension.
Add those file names from the list ending with “.txt” file extension... |
b5e8d024a2f319a3a08661fa4006265fb17303bd | reybalgs/keyword-generator | /csv_reader.py | 620 | 3.8125 | 4 | """
Module for reading CSVs from files or passed into the reader itself.
"""
import csv
class CSVReader(object):
"""
The actual reader class.
"""
def __init__(self):
pass
@classmethod
def read_file(cls, filename):
"""
Reads a file from a given filename and passes it b... |
bdf21e232926951c456a4ddbbb11799289ea3f27 | osho-sunflower/python_session_snippets | /console_io.py | 489 | 4.15625 | 4 | # Python2 ----> Python3
# input() ----> eval(input())
# raw_input() ----> input()
# Python3
string = input('Enter a string: ')
print('Got:', string)
number = int(input('Enter a number: '))
print('Got:', number)
expression = eval(input('Enter an expression: '))
print('Evaluated:', expr... |
807c92e198c28a7c7dce5766c99ef8d7ef99c36d | MG-98/AI-lab-assignments | /lab4/Lab requirement 4 .py | 5,457 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[65]:
class Game:
'''
Abstract game class for game formulation.
It declares the expected methods to be used by an adversarial search algorithm.
All the methods declared are just placeholders that throw errors if not overriden by child "concrete" classes!
... |
5d5676ab2d75343f36fa37a80a1505ab709fa4bb | Hoxtygen/Graphs | /projects/ancestor/ancestor.py | 1,628 | 4.0625 | 4 | from util import Stack, Queue
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex):
"""
Add a vertex to the graph.
"""
if vertex not in self.vertices:
... |
b3e59177b9643c9ab377afbc9ada1a5043f07501 | arbboter/wits | /app/comm/stime.py | 1,872 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import time
# 当前模块主程序
def main():
print(timestamp())
class CTimeCount:
def __int__(self):
self.beg = time.time()
self.end = self.beg
self.cost = 0
def cost_time(self):
return self.cost
def beg_time(self):
return tim... |
28cc501b831850a59865209d4e6a8a31a50cf3fc | luzap/intro_to_cs | /cs016/particles.py | 2,264 | 3.828125 | 4 | """Particles: main event + additional practice."""
import os
import time
from random import randint
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Pair(self.x + other.x, self.y + other.y)
def __str__(self):
return "{},{}".for... |
d8ab89b7385cb57feee9f39e0bc6d1d03ac3ee3a | luzap/intro_to_cs | /cs003/exer04.py | 488 | 4.09375 | 4 | """Exercise 4: Dice game."""
import random
outcomes = ['one', 'two', 'three', 'four', 'five', 'six']
bool_outcomes = ['wrong', 'right']
guess = int(input("What is your guess? "))
value = random.randint(1, 6)
print("Your guess was", bool_outcomes[guess == value])
print("The value was", outcomes[value - 1])
side_of... |
43feb2a790674e0c4b64bb62bb6ca5e2ca74b658 | luzap/intro_to_cs | /cs007/exer2.py | 492 | 3.90625 | 4 | """Exercise 1.2: Friend book."""
friends = []
while True:
name = input("Enter your friend's name or `stop` to finish: ")
if name == 'stop':
break
else:
friends.append(name)
print("You have {} friends. They are:".format(len(friends)))
for friend in friends:
if friends.index(friend) == ... |
a73c3092eff51d68042dce6d9afd50f8ff48ec5c | luzap/intro_to_cs | /cs010/exer1.py | 2,098 | 3.828125 | 4 | """Exercise 1.1: CSV Dragons."""
def breakdown_by_property(members: list, prop: str) -> dict:
"""Shortening of the breakdown process."""
breakdown = {}
for member in members:
if member[prop] not in breakdown.keys():
breakdown[member[prop]] = []
else:
breakdown[membe... |
fb42b8f08dfafd00fb9f98f9a27e3907a6865931 | luzap/intro_to_cs | /cs005/exer9.py | 899 | 3.84375 | 4 | """2.2 Making the band."""
print("Enter coordinates row first (column, row)")
first_coord_text = input("What's the first coordinate?").split(",")
second_coord_text = input("What's the second coord?").split(",")
first_coord = list(map(lambda x: int(x), first_coord_text))
second_coord = list(map(lambda x: int(x), secon... |
c526f0b569465e0e1a3cd10674793bff1debd6bf | luzap/intro_to_cs | /cs013/lab.py | 1,389 | 4.21875 | 4 | import random
import helpers
#
# Each of the following functions have an arbitrary return value. Your
# job is to edit the functions to return the correct value. You'll
# know it's correct because when you run test.py, the program will
# print "PASS" followed by the function name.
#
# Any code you add outside of these... |
43a2b5f160ae5950b7fc5a883a092d72002e8a3a | luzap/intro_to_cs | /cs018/exer1.py | 1,206 | 3.96875 | 4 | """Exercise 1: Practice."""
import pygame
import sys
pygame.init()
display = pygame.display.set_mode((640, 480))
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
mouth = pygame.Rect(display.get_width() // 2 - 30,
display.get_height() // 2 + 30, 60, 10)
while True:
for event... |
bc27e2f2a7608ac3f2fd61169f67aa42b4e6ea38 | luzap/intro_to_cs | /cs015/exer3.py | 1,859 | 4 | 4 | """Exercise 1.3: Rock-paper-scissors."""
import random
class Rock:
def __init__(self):
self.name = "rock"
def __gt__(self, other):
if other.name == "scissors":
return True
else:
return False
def __lt__(self, other):
if other.name == "paper":
... |
0231e36fd7b15310e8cea9bca567d710fca47494 | tohichoi/adventofcode | /2015/day9/day9-pn.py | 1,722 | 3.546875 | 4 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import random
import time
import itertools
import urllib
import csv
import functools
from statistics import mean, stdev
def alltours_tsp(cities):
"Generate all possible tours of the cities and choose the shortest tour."
return shortest_tour(alltours(c... |
c890d124aa3ad5ca01a684e01a6ba2e1111559f4 | Jacob124/SOKOBAN | /solve.py | 2,426 | 3.703125 | 4 | from time import time
from copy import deepcopy
from queue import Queue
def print_solve(name, board, gen, rep, exp, dur):
print(name)
print("Solution: " + board.getDirections())
print("Nodes Generated: " + str(gen))
print("Nodes Repeated: " + str(rep))
print("Nodes Explored: " + str(exp))
print... |
4278581c7d6e1ae55f461023ecf95992cbc21c67 | Sakshi-1819/Assignment-14 | /Assignment 14.py | 3,913 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Q1. Write a function to find the longest common prefix string amongst an array of strings.If there is no common prefix, return an empty string "".
# In[5]:
def longestCommonPrefix( a):
size = len(a)
if (size == 0):
return ""
if (size == 1):
... |
7503727b0a9c88dc803c3e14b761229899230e5b | dzf0023/wbd | /SoftwareProcessCA01/Navigation/test/testAngle.py | 1,380 | 3.984375 | 4 | import Navigation.prod.Angle as Angle
angle1 = Angle.Angle()
angle2 = Angle.Angle()
angle3 = Angle.Angle()
def setDegrees(degrees):
if (not(isinstance(degrees,(int,float)))):
raise ValueError("degrees should be int or float")
if 0 <= degrees <= 360:
return degrees
else:
R = deg... |
2fb1c1486be92415aa8e2ec0141b5dbcf69a851c | Sagar-VV/Patterns | /star2.py | 246 | 3.890625 | 4 | # *
# **
# ***
# ****
# *****
n = int(input("Enter the Row height : "))
for i in range (n, 0, -1):
for s in range(i):
print(' ', end='')
for t in range (n-i+1):
print('*', end='')
print('')
|
abe456f87835c8737eb3463672abe9d124141bd0 | Zolor/adventofcode2020 | /day21/part1.py | 2,023 | 3.53125 | 4 | from typing import NamedTuple
from copy import deepcopy
data = open("input.txt").read().split("\n")
allergens_dct = {}
all_ingredients = set()
for line in data:
tmp_set = set()
tmp_lista = []
ingredients, allergens = line.split(" (contains ")
ingredients = [i for i in ingredients.split()]
allerge... |
5b89da60e714f8cec79aa0486fb9a82b8f0cb3b3 | Zolor/adventofcode2020 | /day03/part1.py | 406 | 3.609375 | 4 | map = []
counter = 0
tree_count = 0
first = True
with open('input.txt') as input:
for i in input.readlines():
map.append(i.rstrip()*len(i*2))
for line in map:
if first == True:
first = False
continue
counter += 3
if line[counter] == "#":
tree_count += 1
if counte... |
8b9a40622e61762a3fdc03ff24672d4ef6b00af1 | Zolor/adventofcode2020 | /day02/part1.py | 683 | 3.671875 | 4 | import re
import time
start_time = time.time()
valid_passwords = 0
with open('input.txt') as input:
for i in input.readlines():
bigger_than = int(re.search("^[0-9]{1,2}", i).group(0))
less_than = int(re.search("(?<=-)\\d{1,2}", i).group(0))
match = re.search("(?<!:)[a-zA-Z]", i).group(0)
... |
ee0051ae5668bb372c6e3d260b77f3656e8eb8bf | carlosfajardor/Python-cardio | /Reto 2/Yankenpo.py | 2,661 | 3.59375 | 4 | import random
def juego(intentos):
x = 0
tu = 0
pc = 0
while str(x) != intentos:
print("Piedra, Papel o Tijera?")
opcion = input()
opcion = opcion.lower()
azar = random.choice(["piedra","papel","tijera"])
if opcion == azar:
print("La PC ... |
2e80c07065e96f7ebecc17ba799a26f34388aad3 | Roger-Mei/EECS-592 | /Project_1/code/mysearch.py | 2,750 | 3.859375 | 4 | import csv
import math
import mygraph
from functionfile import *
"""
Define Main function
"""
def mysearch(obj):
"""
Read the CSV files
"""
f = open('route_planning.txt', 'r')
reader1 = csv.reader(f)
g = open('coordinate_map.txt', 'r')
reader2 = csv.reader(g)
"""
Construct Graph a... |
65e403f05d4963065c8354ee2a13c30d4ede24d9 | PPTaa/python_self_study | /programmers/같은 숫자는 싫어.py | 361 | 3.75 | 4 | def solution(arr):
answer = []
for i in range(len(arr)-1):
# print(arr[i])
if arr[i] != arr[i+1]:
answer.append(arr[i])
answer.append(arr[len(arr)-1])
return answer
arr1 = [1,1,3,3,0,1,1]
arr2 = [4,4,4,3,3]
arr3 = [1,1,1,3,3,3,4,4,4,8,8,8,8,2,2,2,2,2,2,3,3,3,3,3]
arr4 = [1,0... |
4521bdb9bea307dc705f5a35e0ca4ee05d33a803 | PPTaa/python_self_study | /programmers/서울에서 김서방 찾기.py | 390 | 3.5625 | 4 | def solution(seoul):
Kim = "Kim"
print(seoul.index(Kim))
answer = ""
for i in range(len(seoul)):
print(seoul[i])
if seoul[i] == Kim:
answer =f"김서방은 {i}에 있다"
return answer
seoul = ["J","a","ne","Kim"]
print(solution(seoul))
## 모범 답안
def findKim(seoul):
return "김서방은 ... |
2a63d8f2a73f066c9a6ab6d20fa4d0d81e8a217a | noodlemaster/EPQ_StackingSpheres | /3D-sphere packing.py | 2,428 | 4.09375 | 4 | import math
import os
print('-----Regular sphere 3D packing-----')
print('Please enter three parameters of a cubic:')
print('*Note: Length/diameter needs to be an integer and h >= d.*')
l=int(input('Length:'))
w=int(input('Width:'))
h=int(input('Height:'))
d=int(input('Diameter:'))
def hex(d,l,w,h):
... |
05f02174029e72f410f52517576d655cd297e8ab | chin269/proyectos-ie | /cli/cli_simple.py | 1,572 | 4.4375 | 4 | """
Argumentos de linea de comandos
Modulo recibe argumentos de linea de comandos
Módulo sys proporciona funciones y variables que se usan
para manipular diferntes partes de Runtime de python y
acceso a ciertas partes del interprete.
"""
import sys
class Calc:
"""Provee metodos para operaciones basicas"""
... |
6466da4e06bc55be7f9a40ea422e81d18890c3cc | feng-yu/daily_python_practice | /complicatethreadexample.py | 662 | 3.640625 | 4 | """
This is a complicate thread example, using queue, threading, etc
"""
import threading
from queue import Queue
import time
"""
get a lock first
"""
print_lock = threading.Lock()
q = Queue()
def exampleJob(worker):
time.sleep(0.5)
with print_lock:
print(threading.current_thread().getName(), worker... |
7d9a3ab299ff38313227a4b04a0cfe6cc1585487 | feng-yu/daily_python_practice | /may19.py | 1,549 | 4.09375 | 4 | """
The question is the following:
return a new sorted merged list from K sorted lists, each with size N
For example, if we had [[10, 15, 30], [12, 15, 20], [17, 20, 32]],
the result should be [10, 12, 15, 15, 17, 20, 20, 30, 32]
"""
import heapq
def merge_sorted_list(list_sorted_lists):
merged_list = list_sorted_... |
58ee4037fac188e297b8108d6b4923c95dca4660 | feng-yu/daily_python_practice | /may25.py | 1,554 | 4.03125 | 4 | """
[medium]
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
"""
import fu... |
04b7921cc6d7a4afaf9b7f5b0d38525b4676d43a | amey-joshi/am | /optim/or-tools/mip/basic-mip.py | 779 | 3.5625 | 4 | #!/bin/python
from ortools.linear_solver import pywraplp
# We solve the following problem.
# Maximize x + 10y subjec to:
# x + 7y <= 17.5; x <= 3.5; x, y >= 0
# where x, y are integers.
solver = pywraplp.Solver.CreateSolver('basic-mip', 'CBC')
# Integer decision variables
x = solver.IntVar(0, solver.infinity(), 'x'... |
e1aa0d79222e7c2ba32a07f3d17db4089485ad94 | liuyi-CSU/learn-python | /liuyi/day001/20171029字典.py | 545 | 3.875 | 4 | #!/usr/bin/env python
#-*-coding:utf-8-*-
#字典浅复制
x = {'user': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
y['user'] = 'mlh'
y['machines'].remove('bar')
print('keys方法:', x.keys())
#print('iterkeys:', x.iterkeys) #iterkeys不能直接print
for i in iter(x.keys()):
print('%s:%s', (i, x[i]))
#print(y)
#print(x) ... |
9b6e659c0c9882957dab0c689f476402e035b749 | liuyi-CSU/learn-python | /liuyi/day001/test007.py | 838 | 3.9375 | 4 | """
题目描述
写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。例如:
输入描述:
输入N个字符
输出描述:
输出该字符串反转后的字符串
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print st... |
6e47977259e6e3ef8cfab1671844839496a7cb31 | talaikis/videogrep | /videogrep/tools/getyoutubecc.py | 7,026 | 3.59375 | 4 | import urllib.request, urllib.parse, urllib.error
import html.parser
from re import search, DOTALL
import codecs
class getyoutubecc():
""" This class allows you to download the caption from a video from you tube
Example:
>>> import getyoutubecc
#import the library
... |
4606b37475901e917518a03f64b24811fc92eae5 | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Valid_parenthesis.py | 460 | 4 | 4 | """ Program to validate the parenthesis with correct order """
def validparenthesis(string) -> bool:
brackets = {')': '(', '}': '{', ']': '['}
stack = []
for i in string:
if i in brackets:
if stack and stack[-1] == brackets[i]:
stack.pop()
else:
stac... |
ecddeb829aa78cd91843859c3e72093580f00279 | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Count_occurrences.py | 485 | 4.28125 | 4 | """ Program to count number of occurrences of each element in a list.
Asked in Precisely interview for Software Engineer-I """
def count_occurrences(ourlist):
# return dict((i, ourlist.count(i)) for i in ourlist) # List comprehension approach
dicx = {}
for j in ourlist:
dicx.__setite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.