blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e033c04fefdebc2bfec367b3b97456c504dba801 | AndrewAct/DataCamp_Python | /Introduction to Deep Learning with Keras/2 Going Deeper/10_The_History_Callback.py | 1,150 | 3.578125 | 4 | # # 8/9/2020
# The history callback is returned by default every time you train a model with the .fit() method. To access these metrics you can access the history dictionary parameter inside the returned h_callback object with the corresponding keys.
# The irrigation machine model you built in the previous lesson is l... |
93cee3a5f9b2bc7b6282fa9533a74bb00bc29846 | maq-622674/python | /廖Py教程/py/10.错误,调试和测试/1.错误处理.py | 8,465 | 4.21875 | 4 | '''
1.错误处理
在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。在操作系统提供的调用中,返回错误码非常常见。比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1。
用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错:
'''
def foo():
r = some_function()
if r==(-1):
return (-1)
# do something
return r
def bar():
r =... |
76b8803b49b982dc6cd087d76eb66f038c0de1fc | EljEnoch/highma | /0x0B-python-input_output/2-read_lines.py | 690 | 4.4375 | 4 | #!/usr/bin/python3
"""This module defines a function the reads and prints n lines from file"""
def read_lines(filename="", nb_lines=0):
"""Read and print n lines from file
Arguments:
filename: file to read from
nb_lines: number of lines to read/print
"""
line_count = 0
with open(fi... |
6c9d2230d49f674f16a3d014fcebb4eece182a5b | pchudzik/mocked-http-server | /server.py | 2,924 | 3.515625 | 4 | import argparse
from http.server import BaseHTTPRequestHandler, HTTPServer
from random import random
import json
arg_parser = argparse.ArgumentParser(
description='Simple http server which will to serve request with specified ratio and errors')
arg_parser.add_argument(
"--port",
help="Port on which server... |
61c85785fdd5422b9fb1f96aa20b6f36b7aae974 | hhgman/beakjoon | /2442.py | 114 | 3.921875 | 4 | num = int(input())
for i in range(1,num+1):
star = "*"*(2*i-1)
space = " "*(num-i)
print(space+star)
|
622b7b4ed8286cf999b2033b92fedca9f350579f | Phantomn/Python | /study/ch1/if/grade.py | 162 | 3.9375 | 4 | print("Input score : ",end="")
score=int(input())
if(score>=90 and score<=100):
print("A")
elif(score>=80 and score<90):
print("B")
else:
print("F")
|
2cc1f6dc22158f8ac72c4fdfbdb7566347775c74 | arzzon/PythonLearning | /PythonInbuilts/Advanced/Map/map.py | 644 | 4.71875 | 5 | '''
Map is used to generate another iterable from the iterable provided to it along with
the lambda function, where each element of the generated iterable is mapped/modified
to some value based on the lambda function logic provided to it.
It returns a map object which contains all those filtered element... |
5cabb228233f3c2d3034e105e49525dda46f2e07 | a0927024706/second_hight | /second_hight.py | 428 | 3.96875 | 4 | students = [['a', 123], ['b', 211], ['c', 100], ['d', 101]]
def second_highest(students):
grades = [s[1] for s in students] # 只把成績拿出來
grades = sorted(grades, reverse = True)
second = grades[1] # grades[0]是最高,grades[1]是第二高
second_high_students = [s[0] for s in students if s[1] == second]
for st... |
6971d5c611639fce1ef4f3ed413fd89c93ded218 | AlisonWonderland/Scripts | /litte_caesars/litte_caesars.py | 5,733 | 3.6875 | 4 | #! /usr/bin/env python
import time, sys
#For the delay at the end to close the browser after its done
from selenium import webdriver
#To launch browser
from selenium.webdriver.common.by import By
#Helps us find things on a page. Like a login
from selenium.webdriver.support.ui import WebDriverWait
#To wait ... |
d6a0a8a6394786d17df066026c24b1bdbfc0db2c | patrisor/4.2-Twitter-Challenges | /hangman/src/Auxiliary.py | 1,500 | 3.59375 | 4 | # **************************************************************************** #
# #
# ::: :::::::: #
# Auxiliary.py :+: :+: :+: ... |
725fd692f388cc86cce9e1ac623c3ca9c1c83b31 | eltechno/python_course | /Functions.returning-multiple-values.py | 1,388 | 4.0625 | 4 |
def raise_both(value1, value2):
"""Raise value 1 to the power of value2 and vice versa"""
new_value1 = value1 ** value2
new_value2 = value2 ** value1
new_tuple = (new_value1, new_value2)
return new_tuple
a, b = raise_both(2,4)
print(a)
print(b)
# Define shout with parameters word1 and word2
de... |
c7f0a9a643fa6300b50a959885569908b2ee98ea | rohan-1998/Assignment9 | /Assignment9.py | 547 | 3.9375 | 4 | #Question 1
try:
a=3
if a<4:
a=a/(a-3)
print(a)
except ZeroDivisionError:
print("You Cannot Deivide By Zero")
#Question 2
INDEX ERROR
#Question 3
'''AN execption'''
#Question 4
-5.0
a/b result in 0
#Question 5
#import Error
try:
import xyz
except ImportError:
print("P... |
c93db938347d451f22ffe804dd670788b2f30d57 | MitsurugiMeiya/Leetcoding | /leetcode/Tree/107. Binary Tree Level Order Traversal II(反层序遍历).py | 1,151 | 4 | 4 | """
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
"""
# class TreeNode(object):
# def __init__(self, x):
# self... |
61a70603e5444aee66217a3fa69152db5a82f8fe | meta-omega/formal-system-library | /utils/get_leaves.py | 514 | 3.515625 | 4 | from tree.functions.to_node import to_node
from tree.alphabets.logic import get_logic_alphabet
def get_leaves(node):
if len(node.children) == 0:
return [node]
alphabet = get_logic_alphabet()
leaves = []
def to_logic_node(string):
return to_node(string, alphabet)
for chi... |
b8e07a5c22a0aea8faa07368250b48ffd10858c5 | Jiadalee/storm-swarm | /StormSwarm/controller.py | 837 | 3.59375 | 4 | import numpy as np
class controller:
"""
Class for representing the policy of workers
"""
def __init__(self,
constant_action,
policy,
exploration,
action_space):
self.exploration = exploration
self.action_space = action... |
17124d60f1087e7fd49adbab87952b9af2eb2f65 | g2g2g2g2/PedraPapelTesoura | /PedraPapelOuTesoura_.py | 4,003 | 3.59375 | 4 | from tkinter import *
import tkinter as tk
from random import randint as r
from time import sleep as s
voce = 0
pc = 0
def pedra1():
s(0.5)
if r(1, 3) == 1:
output = Label(Tela, width=18, text='Empatou!!\n Também escolhi Pedra')
output['bg'] = 'red'
output.place(... |
083af068fb5d9189133547341dceb277d00feb36 | FreddieMercy/leetcode | /Python/_2017/July2017/July25th2017/_41FirstMissingPositive.py | 253 | 3.578125 | 4 | class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 1
while True:
if not ans in nums:
return ans
ans+=1 |
f9e4fbd42dda1e022200917e0529faaa64eaf425 | t3miLo/lc101 | /Unit_1/assignments/country_code.py | 947 | 4.3125 | 4 |
# Write a function that will return a string of country codes from an argument that is a
# string of prices (containing dollar amounts following the country codes).
# Your function will take as an argument a string of prices like the following:
# "US$40, AU$89, JP$200".
# In this example, the function would return the... |
edb34c6f5f7ba0b38f519ff0dc427c2ab6a9b637 | ericgarciadv/aulas | /9-retanguloQuadrado[1].py | 209 | 3.859375 | 4 | print("Informe as dimensões do retângulo")
base = int(input("Base: "))
altura = int(input("Altura: "))
print("Área calculada: %dcm²" % (base * altura))
if base == altura:
print("Área de um quadrado!") |
5513f4f3c6a2936037c66b42938900386aaa01b7 | DustyQ5/CTI110 | /P4T2_BugCollector_ChazzSawyer.py | 634 | 4 | 4 | # Loop counter that then displays the total number
# Date
# CTI-110 P4T2 - Bug Collector
# Chazz Sawyer
#
total = 0.0
#Greets user and introduces the priogram concept
print ('I heard you like bugs! Lets count how many you can catch in five days!')
#loop asks user how many bugs caught that day
for day i... |
02439a8abc67f5efbb1e261f81b8caa11c2cb26c | skilldrick/event | /test.py | 292 | 3.828125 | 4 | class Dave:
x = 1
def __init__(self, y):
self.y = y
monkey = Dave(5)
bob = Dave(100)
print monkey.x, monkey.y
print bob.x, bob.y
monkey.x = 2
monkey.y = 3
print monkey.x, monkey.y
print bob.x, bob.y
bob.x = 1001
bob.y = 1002
print monkey.x, monkey.y
print bob.x, bob.y
|
d0d82e564bc58f3b02ca584836f6d7eef70af8c5 | pbarton666/learninglab | /begin_advanced/solution_python2_chapter07_logging.py | 3,057 | 4.25 | 4 |
#solution_python2_chapter07_logging.py
import sqlite3
import csv #python's library for reading csv files
import logging
DB='beer'
TABLE='brewpub'
FILE='py_log_english_brewery_data.csv'
LOG_FILE='brewery.log'
LEVEL=logging.DEBUG
logging.basicConfig(filename=LOG_FILE,
level=LEVEL)
logger=logg... |
90fbdca408fd2288ddb12e22b39cb986a6a01019 | laboyd001/python-crash-course-ch3 | /guest_list2.py | 361 | 3.90625 | 4 | #this program demos a list and a way to add and remove items
guest_list = ['Jenn', 'Kathy', 'BT']
cannot_attend = guest_list.pop(0)
print(cannot_attend + " is unable to attend.")
new_guest = guest_list.append('Salty')
print(guest_list[0] + ", you're invited!")
print(guest_list[1] + ", you're invited!")
print(g... |
b2aa6e45e47ed0c767515fb2b930a4eb6ee27476 | sanjay2610/InnovationPython_Sanjay | /Python Assignments/Task3/ques1and2.py | 427 | 3.984375 | 4 | #quesion 1
#Create a list of the 10 elements of four different types of Data Types like int, string, complex, and float
list1=[1,2,3,'hello', 'world', 1+2j, 3+6j, 1.23, 3.45]
print(list1)
# lst contains all number from 1 to 10
lst =list(range(1, 11))
print (lst)
# below list has numbers from 2 to 5
lst1_5 =... |
7cc6b4d73c667f59b7bed96ad39dab143cd2a099 | ekohilas/comp2041_plpy | /examples/3/tetrahedral.py | 231 | 3.796875 | 4 | #!/usr/local/bin/python3.5 -u
n = 1
while n <= 10:
total = 0
j = 1
while j <= n:
i = 1
while i <= j:
total = total + i
i = i + 1
j = j + 1
print(total)
n = n + 1
|
43394a3d3571947a6a61fdddf1ba011cbbfb5ddf | bYsdTd/Leetcode | /python/690.员工的重要性.py | 1,158 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=690 lang=python3
#
# [690] 员工的重要性
#
# @lc code=start
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
... |
1d204736ae60d0d946e4cd8bbbff364a7d491e21 | Abreu-Ricardo/IC | /clivar.py | 872 | 3.578125 | 4 | # Programador: Ricardo Abreu
# Inicio da clivagem de algoritmos
from LCS import LCS
arquivo = open("entrada.txt", "r")
# Criando objetos
pept1 = LCS()
pept2 = LCS()
resultado = None
for aux in arquivo:
try:
if aux[0] == '>':
continue
else:
pept1.string = aux
if... |
bdc95e5ee56ef4279161f0bfdb6f5091dcc0a484 | bsivavenu/Machine-Learning | /Advanced python 7 - 8/Demo12.py | 417 | 3.734375 | 4 | class A:
def calc(self,no1,no2):
print(no1,no2,"sum = ",(no1+no2))
class B(A):
def calc(self,no1,no2):
A().calc(no1,no2)
super().calc(no1,no2)
print(no1,no2,"sub = ",(no1-no2))
#----------------
a1 = A()
print("Enter 2 No's")
a1.calc(int(input()),int(input()))
#-------... |
65eb98fcdfecaa8f2e1c049d500737ccb5fbcc6c | Jmoore1127/aoc2018 | /day2/challenge2.py | 535 | 3.59375 | 4 | #!/usr/local/opt/pyenv/shims/python
def solve():
with open("input.txt", "r") as f:
lines = f.readlines()
for i in range(0, len(lines)):
currentLine = lines[i]
for j in range(i+1, len(lines)):
difference = 0
commonLetters = []
comparedLine = lines[j]
for k in range(0, len(currentLine)):
i... |
b8f0acecdb1cbf1951af64498ba6948bb43a33c4 | Pretty-19/Coding-Problems | /array-stack.py | 238 | 4.09375 | 4 | arr = [1,2,3,4]
arr3 = []
arr2 = []
for i in range (len(arr)):
#print(i)
for j in range (i, len(arr)):
#print(j)
arr2.append(arr[j])
arr3.append(arr2)
print(arr2)
print(arr3) |
37e2423b4f3fff9972a2558849c38adb1651c1c6 | Cubesnail/nasaspaceapps | /materials.py | 3,439 | 3.796875 | 4 | # MATERIALS
class Material:
"""Currently unused class
"""
def __init__(self, name, mass, cost, density):
"""
:param name:
:param mass:
:param cost:
:param density:
:return:
"""
self.name = name
self.mass = mass
self.cost = ... |
a5f64edaede8218e9ec9281a81b43a1e27449c33 | diofelpallega/unittests | /tests/account.py | 606 | 3.6875 | 4 |
class Account(object):
def __init__(self, account_number, balance):
if type(account_number) == str and type(balance) == int:
self.account_number = account_number
self.balance = balance
else:
print "error inputs"
class AccountWithdraw(object):
def __init__(s... |
5c0c2c9ce36a8b2b507328dc678fa1f77ae7503f | PyBeaner/DiveIntoPython3 | /7.Classes & Iterators/fibonacci.py | 779 | 3.828125 | 4 | __author__ = 'PyBeaner'
class Fib:
"""
Iterator that yield numbers in the Fibonacci sequence
"""
def __init__(self,max):
self.max = max
def __iter__(self):
"""
called manually by you or automatically by a for loop
:return:an iterator should always return an object ... |
1f0be79876c5409237e819e809f2009f3a5288db | lindsim/exercise03 | /our_calculator.py | 1,150 | 3.84375 | 4 | from arithmetic import *
from sys import exit
def main():
while True:
cal = raw_input(">")
if cal == "q":
exit()
else:
cal_split = cal.split(" ")
cal_split[:] = [x for x in cal_split if x != ""]
a = float(cal_split[1])
... |
6910585c042ef9d5b052c497c98db12aad618371 | YLin-Z/CXCDATAUPDATE | /Include/main.py | 819 | 3.59375 | 4 | import pandas as pd
import os
def updaterow(row,numofcol):
i=1
print('-----------------------------------------------------------------')
# print(type(row))
while i<numofcol:
# print(row[1][i])
if row[1][i] =='-':
# print('-')
row[1][i]=0
i=i+1
return... |
00837ace4be4dc33f4445a0b707cb431d765918b | raiyansayeed/ProgLangData | /add_field.py | 653 | 3.703125 | 4 | import json
import os
filename = 'data_copy.json'
field = input("Enter a field name: ")
val = int(input("String (1) or String array (2)?: "))
def add_string(lang):
tmp = lang
tmp[field] = "Not updated"
return tmp
def add_array(lang):
tmp = lang
tmp[field] = ["Not updated"]
return tmp
with ... |
21801e8041c3d26c4f0b17b562e685d004e69ed0 | elchic00/leetcode | /reverse.py | 124 | 4.09375 | 4 | def reverse(s):
str = ""
for c in s:
str = c + str
return str
s = "string"
print(s)
print(reverse(s))
|
dc38ac93aa069e4f5f0ba37c03b61b6b14f5dea7 | Onac8/X-Serv-14.2-Variaciones | /servidor-http-simple.py | 1,689 | 3.640625 | 4 | #!/usr/bin/python3
"""
Simple HTTP Server
Jesus M. Gonzalez-Barahona and Gregorio Robles
{jgb, grex} @ gsyc.es
TSAI, SAT and SARO subjects (Universidad Rey Juan Carlos)
"""
import socket
# Create a TCP objet socket and bind it to a port
# We bind to 'localhost', therefore only accepts connections from the
# same mac... |
f10bf8ad5cd324c8880eec233fb852b86150564d | alsimoes/mao-na-massa | /lista1/peso_ideal.py | 137 | 3.546875 | 4 | # -*- coding:utf-8 -*-
altura = float(raw_input('\nQual a sua altura? '))
print '\nSeu peso ideal é %3.1f kilos.\n' % ((72.7*altura)-58) |
30db04329ab776355e05a3e84af563a6e0c62eb1 | yavord/hmm | /test/backward.py | 901 | 3.625 | 4 | def backward(X,A,E):
"""Given a single sequence, with Transition and Emission probabilities,
return the Backward probability and corresponding trellis."""
allStates = A.keys()
emittingStates = E.keys()
L = len(X) + 2
# Initialize
B = {k:[0] * L for k in allStates} # The Backward trellis
... |
6535916cfb74a4c43c6f5310433f5910289200cd | guyuzhilian/Programs | /Python/project_euler/problem34.py | 698 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: lidajun
# date: 2015-08-30 17:02
factorial_cache = [1, 1]
def init_factorials():
for i in range(2, 10):
factorial_cache.append(factorial_cache[i-1] * i)
def get_n_digit(num, n):
return int(num // pow(10, n-1) % 10)
def is_the_curious_number(num)... |
83dd5f49bd102c81b6b9b6c2bace7c4845b5a8fd | sametatabasch/Python_Ders | /ders11.py | 772 | 4.03125 | 4 | kullanicilar = {
"samet": {
"sifre": "1234",
"adı": "Samet",
"soyadı": "ATABAŞ"
},
"ahmet": {
"sifre": "ahmet61",
"adı": "Ahmet Can",
"soyadı": "ATABAŞ"
},
"vecihi": {
"sifre": "hürkuş",
"adı": "Vecihi",
"soyadı": "hürkuş"
}... |
5695083e8f8516d9e03224af1093d759e4beee61 | Jennymason24/CNS210.60.WN2020 | /oldfib.py | 233 | 3.890625 | 4 | def fibonacci(n):
F0=0
F1=1
if n < 0:
print("Incorrect input")
elif n == 0:
return F0
elif n == 1:
return F1
else:
return
Fibonacci(n-1)+Fibonacci(n-2)
print(fibonacci(9))
|
ebdac5ff1b71d920337598f9bb87e2e7b64c5970 | bopopescu/imfree | /venv/Lib/site-packages/base64_util/__init__.py | 2,260 | 3.859375 | 4 | import re
def get_only_base64_characters(arg):
'''
Returns only the base64 characters from the string, preserving order.
Args:
arg: The string that will have the non-base64 characters removed
Returns:
A string containing only base64 characters
'''
if not ar... |
e40cead6611db94806ea78ffa79bfbc170cc4cbb | vsdrun/lc_public | /co_uber/621_Task_Scheduler.py | 3,263 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/task-scheduler/description/
https://leetcode.com/problems/task-scheduler/discuss/104507
Given a char array representing tasks CPU need to do.
It contains capital letters A to Z where different letters represent
different tasks.
Tasks c... |
f710b4cbbe9fa66ede7e8a0c3059e36c937945ea | CodeProgress/misc | /TheGame.py | 4,584 | 3.59375 | 4 |
import random
import cProfile
class Rating(object):
def __init__(self):
self.lowRating = 0
self.highRating = 10
self.averageRating = 5
self.standardDeviationRating = 2
def get_rating(self):
'''
Returns a random float between low and high using a gaussian distri... |
bf28dd80c9b1b50a5a5afbec1d30abfe2e08991f | Sandhie177/CS5690-Python-deep-learning | /ICP1/ICP1_letter_digit.py | 427 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 16:50:28 2018
@author: farid
"""
sentence = input("write down the sentence: ")
length = len(sentence)
digit = 0
letter = 0
for i in range(length):
temp=sentence[i]
if temp.isdigit():
digit +=1
if temp.isalpha():
letter +=1
print ("Number... |
7c13480c2ee6b7a83d7bb2bcdffde4b2d16d62f7 | yifengw95/Python-Programming | /Assignment1/6_yifeng_wang.py | 619 | 4.15625 | 4 | import random
random_number = random.randint(1,10)
count = 0
while(True):
guess = input('input your guess')
try:
guess = int(guess)
count = count + 1
if guess > random_number:
print('your guess is larger than the real number')
elif guess < random_number:
p... |
65ecded6b62f037f2a669401fa59f584c09ea04d | alephist/edabit-coding-challenges | /python/test/test_find_the_falsehoods.py | 683 | 3.53125 | 4 | import unittest
from typing import Any, List, Tuple
from find_the_falsehoods import find_the_falsehoods
test_values: Tuple[Tuple[List[Any], List[Any]]] = (
([0, 1, 2, 3], [0]),
(["", "a", "ab"], [""]),
([None, 1, [], [0], 0], [None, [], 0]),
([], []),
([[]], [[]]),
([[[]]], []),
(["0", 1,... |
983f9a055d15113587c9a1c72ab6b83982a1099a | elainecao93/projecteulerstuff | /30.py | 457 | 3.546875 | 4 | # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
# Let f(x) be the sum of the fifth powers of the digits of x, then f(x) < x for all x > 999999 (trivial upper bound)
# brute forcing from 2 to 999999 is inelegant, but isn't too bad and I don't see a cleaner solution
out... |
9bcb96f0ea058bb7063f14c0f973d969c10968a9 | NurRahmawatiSubuh/tugas1strukturdata | /R.1.7.py | 103 | 3.875 | 4 | def squares_odd_sum(n):
return sum(x*x for x in range(0,n) if x%2==1)
print(squares_odd_sum(7))
|
360faed1ed6efd03c82f23a4466b87adbab732e0 | chrispeabody/Class-Assignments | /Fall-2016/cs5401/as3/sokoban.py | 2,404 | 3.5625 | 4 | # Chris Peabody cgpzbd@mst.edu
# Sokoban puzzle
# CS 5400, Artificial intelligence, F16
# Assignment 2 (MAIN FILE)
import sys
import grbefgs
import copy
from datetime import datetime
if __name__ == '__main__':
### --- CONFIGURATION --- ###
# Make sure a file was specified
if len(sys.argv) > 1:
in... |
4097b12369dd9d797f09ec97c8dd9a62eed973e9 | tonyvu2014/algorithm | /tree/same_tree.py | 1,063 | 4.125 | 4 | # Given the roots of two binary trees p and q, write a function to check if they are the same or not.
# Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=Non... |
a4f5b84fa617b97f13631784b5ae25cb6beeca1c | JulienZe/mega-spark | /megaspark/sql/megaframe.py | 5,044 | 3.546875 | 4 | from pyspark.sql.types import ByteType, ShortType, \
IntegerType, LongType, FloatType, DoubleType, BooleanType, StringType
class MegaFrame(object):
def __init__(self, df):
self._df = df
self.feat_info = [(field.name, field.dataType)
for field in self._df.schema.field... |
549a8d52a043e83c8d60fdcccd2429156ad814c2 | Imhotep504/PythonCode | /twenty.py | 796 | 4.09375 | 4 | #!/usr/bin/python
#import for system exit
import sys
#prompt user for equation
print("Enter in your equation to be calculated and spit out back at you")
#create vars to accept values and operand from console
line = raw_input()
split = line.split() #just like in Ruby
left = int(split[0])
op = split[1]
ri... |
a467f4915cc4c7b08de934152b37693efb2025e3 | abhaykatheria/cp | /HackerRank2/SOS.py | 297 | 3.625 | 4 | def Search(S):
l=len(S)
p=len(S)/3
count=0
string=S
for i in range(0,l):
if string[i:i+3]=="SOS":
count +=1
string=S[i+3:]
else:
continue
return abs(p-count)
S=str(input())
result=Search(S)
print(int(result))
|
b4c3c4e5b56b152efb7f8de400c80c6315879e07 | rwang249/ops435 | /lab3/lab3e.py | 1,240 | 4.46875 | 4 | #!/usr/bin/env python3
# Create the list called "my_list" here, not within any function defined below.
# That makes it a global object. We'll talk about that in another lab.
my_list = [ 100, 200, 300, 'six hundred' ]
def give_list():
# Does not accept any arguments
# Returns all of items in the glob... |
c6af4647c3afc85bf095b6d072f0f735f7c81cb8 | margosukharenko/GB | /Python/lesson_01/task_04.py | 580 | 4.09375 | 4 | # 4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.
num = int(input("Введите целое положительно число >>> "))
max_num = 0
while True:
if num == 0:
break
one_num = num % 10
num = num // 10
if on... |
c7f1f984b58ecaaa68680b187d9261a5b6f40624 | cookies5127/algorithm-learning | /leetcode/default/13_roman_to_int.py | 1,618 | 3.734375 | 4 | '''
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman nu... |
9ee750e469732516f7bcc991d2b9c736bf29d216 | Yuchen112211/Leetcode | /problem79.py | 1,841 | 3.9375 | 4 | '''
79. Word Search
Medium
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A... |
14dbd083366da64b867da1a9eafc48008a57c069 | AllanTumu/PythonBasics | /BreakAndContinue.py | 617 | 3.890625 | 4 | name = "Tumuhimbise"
# using the break Key word
for i in name:
print(i)
if i == "h":
break
print("----------------------")
# using the continue Key word
for i in name:
print(i)
if i == "h":
continue
print("----------------------")
# using break and continue for lists
str = ["python... |
8ca17ff327ee0a3c7a1ead8654e8364da938fa27 | hermanholmoy/TDT4109 | /Oppgaver/fibtall.py | 745 | 3.515625 | 4 | import time
def fib_performance(func, inp):
start = time.time()
func(inp)
end = time.time()
print(f"Runtime for n={inp} : ", (end - start))
def fib1(a):
n = 1
m = 1
fibs = [0, 1]
i = 0
while i < a - 3:
fibs.append(n)
temp = n
n = m + n
m = temp
... |
4444c33f44eefa46c0fec2bf556e90e88bcb511d | williampsmith/algorithms | /largest_subsequence_sum.py | 662 | 3.515625 | 4 |
def largest_suybsequence_sum(array):
if not array:
return
largest_interval = (0,0)
largest_sum = array[0]
length = len(array)
for i in range(length):
for j in range(i, length):
new_sum = sum(array[i: j + 1])
if new_sum > largest_sum:
largest_sum = new_sum
largest_interval = (i,j)
return lar... |
9cc512ff71b43e8a79735ba57bbed05d5eaa189c | B-urb/generic_object_tracking | /python/Vector2.py | 588 | 3.578125 | 4 |
class Vector2:
def __init__(self,x=0,y=0, vec_as_list= None):
if vec_as_list is not None:
if len(vec_as_list) != 2:
raise Exception("List not length 2")
else:
self.x = vec_as_list[0]
self.y = vec_as_list[1]
else:
... |
eb17a354ccbd1e96a31a526bdef9a182bc357404 | gengletao/learn-python | /1.download/ex6.py | 690 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: letao geng <gengletao@gmail.com>
# Copyright (C) alipay.com 2011
'''
'''
import os
import sys
def main():
''' main function
'''
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those ... |
6279da46807be37a13e6e8c8c89b7916bbcdf8ac | Jiezhi/myleetcode | /src/496-NextGreaterElementI.py | 1,372 | 3.515625 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2021/10/19
Des:
https://leetcode.com/problems/next-greater-element-i/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
Tag:
See:
"""
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
... |
31e84e989ae7b1e87347e251028cb941ba1a82d0 | Gabrri/LOGICA2_CC | /Codificacion_y_escritura_formulas/codificacion.py | 1,613 | 3.75 | 4 | # Codificacion y decodificacion de una tabla de Nf filas y Nc columnas
def codifica(f, c, Nf, Nc):
# Funcion que codifica la fila f y columna c
assert((f >= 0) and (f <= Nf - 1)), 'Primer argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nf) - 1 + "\nSe recibio " + str(f)
assert((c >= 0) and (c ... |
9fbc6f63d84f7c3b74c24ff638bb00bd476f6ffe | MaleehaBhuiyan/pythonBasics | /notes_and_examples/h_functions.py | 853 | 4.0625 | 4 | #Funtions
#a collection of code that performs a specific task
#its good to break up your code into dddifferent functions
#how to create a function
def say_hi():
print("Hello User")
#to execute the code you need to call it
say_hi()
#the flow of functions
print("Top")
say_hi()
print("Bottom")
#making t... |
2201673292c7f16222c9a8f659345d9e618bc218 | ChrisJHatfield/Python | /Fundamentals/Functions Intermediate I/Functions_Intermediate1.py | 1,875 | 4.3125 | 4 | # If no arguments are provided, the function should return a random integer between 0 and 100.
# If only a max number is provided, the function should return a random integer between 0 and the max number.
# If only a min number is provided, the function should return a random integer between the min number and 100
# If... |
b7d6485ac153e2500cc40914af1c15c040032a39 | AnkitSrma/PythonWorkshop | /Assignment 2/Conditional/Question 4.py | 224 | 4.25 | 4 | numbers = (1,2,3,4,5,6,7,8,9)
odd = 0
even = 0
for i in numbers:
if not i % 2:
even+=1
else:
odd+=1
print("Number of even numbers :",even)
print("Number of odd numbers :",odd)
|
68f7efd311dedd4b50dfb2d2a24035c85ae5674e | legeannd/codigos-cc-ufal | /APC/AULA 7/Fatores.py | 104 | 3.546875 | 4 | n = int(input())
fator = []
for i in range(1, n+1):
if n%i==0:
fator.append(i)
print(fator)
|
2c79df67506a066a8a88280bb4b93fcb06ced64a | ihatetoast/lpthw | /ex6.py | 746 | 3.875 | 4 | x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." %(binary, do_not)
print x
print y
print "I said: %r." %x
print "I also said: '%s'." %y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation %hilarious
w = "This is... |
18b25c5920e3570e78ce1ca7182da44aea47bdf9 | rahulpandey-rp/bootcamp_2021 | /Python_Bootcamp/python_day3/fivezeros.py | 161 | 3.875 | 4 | list_zero = [0]*5
print(list_zero)
list_zero = []
for i in range(5):
list_zero.append(0)
print(list_zero)
list_zero = [0 for i in range(5)]
print(list_zero)
|
806f10606548b573fdf8029ba8882b90ebe7bb93 | rj8928/pycharm-master | /base_study/13-变参.py | 220 | 3.703125 | 4 | sums = 0
def sum_num(a,b,*args):
print(args)
sums = a+b
for temp in args:
global sums
print(temp)
sums = sums+temp
return sums
sums_s = sum_num(1,2,3,4,5,6,7,8,9)
print(sums_s)
|
c1f8d6ef44c79c33c6e6d617baae7244eb683e62 | japarker02446/BUProjects | /CS677 Data Analysis with Python/Homework3/JparkerHw3Helper.py | 5,934 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Jefferson Parker
Class: CS 677
Date: April 1, 2022
Homework Problem 3.*
Support functions for Homework 3.
WARNING: IF you are running this in an IDE you need to change the path of the
working directory manually below. The __file__ variable is set when running
python as a script... |
7428dd35e2ac792bf5c0b51bc1d8832f2afe869f | AnthonyWaddell/Automating-The-Boring-Stuff-with-Python | /pdfEncrypter.py | 1,384 | 3.734375 | 4 | #! python3
''' Simple python script that goes through a folder and all subfolders and encrypts
all .pdf files with password provided by command line'''
import PyPDF2
import os
import sys
# Get the password and create list for
password = sys.argv[1]
# Start from current working directory and iterateover all files/(... |
2647f4412f371e605d0cac08a4ec44b16843e591 | jrainbolt/jrainbolt.github.io | /CS421/Assignments/2/hw2-master/q1.py | 4,303 | 3.640625 | 4 | import argparse
# Class definition for Hidden Markov Model (HMM)
# Do not make any changes to this class
# You are not required to understand the inner workings of this class
class HMM:
"""
Arguments:
states: Sequence of strings representing all states
vocab: Sequence of strings representing all ... |
e494aaeea0077a5e3af83129a112a6104ed185cb | henryfang1989/ctci | /1_7_rotate_matrix.py | 208 | 3.609375 | 4 | # question: Given an image represented by N*N matrix, which each pixel in the image of 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
def rotate_matrix(pixels):
pass |
5eeb3108769f7d4aff575a02b01e8457166992e2 | diamondtron24/code_guild | /lab03.py | 3,579 | 4.34375 | 4 | # Lab 3: Grading
# Let's convert a number grade to a letter grade, using if and elif statements and comparisons.
# Concepts Covered
# input, print
# type conversion (str to int)
# comparisons (< <= > >=)
# if, elif, else
# Instructions
# Have the user enter a number representing the grade (0-100)
# Convert the number... |
a06a3cab846b812f8ad96003b8bfe7a49324b9dc | chenchaojie/leetcode350 | /binary/x的平方根-69.py | 472 | 3.671875 | 4 | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
s, e = 0, x
while s <= e:
mid = (s + e) // 2
if mid ** 2 > x:
e = mid - 1
elif mid ** 2 < x:
if (mid + 1) ** 2 > x:
... |
a5de46349a25f682daba5dd36ff76a2b79a4db78 | sijmenw/schatzoeken | /treasure_map.py | 1,138 | 3.9375 | 4 | # created by Sijmen van der Willik
# 03/02/2018 18:08
import random
class TreasureMap(object):
def __init__(self, width, height, length=10, max_step_size=10):
self.width = width
self.height = height
self.no_instructions = length
self.max_step_size = max_step_size
self.star... |
00dcbd1070459b6ff5a63b3f15e65786dae17667 | RobertMcCutchen/DigitalCrafts_Assignments | /July/July 3rd/Remove_Duplicate_Emails.py | 472 | 3.515625 | 4 | file_name = "Email_List.txt"
duplicate_free_emails = []
with open(file_name) as file_object:
contents = file_object.read()
emails = contents.replace("\n", "").split(', ')
for email in emails:
if email not in duplicate_free_emails:
duplicate_free_emails.append(email)
print(duplicate_free_emails)
str... |
a051928d9d4616c4028811ae9df5afc4cdc6a32f | ixe013/mongolito | /src/transformations/renameattribute.py | 948 | 3.546875 | 4 | import re
import utils
from transformations import BaseTransformation
class RenameAttribute(BaseTransformation):
'''Takes a key name and renames it, keeping values intact.
Uses Python's re.sub(), so fancy renames with expression
groups can be used.
'''
def __init__(self, attribute, replacement... |
cd7e628b59612809eaf829627d2602643c551255 | carpben/fizzbuzz | /fizzbuzz.py | 1,223 | 4.53125 | 5 | import sys
print "Welcome to the Fizzbuzz Game!"
# defining n.
# first option command line argument. command line can have: 0 argument (no n), 1 arguments (n) or more than 1 arguments (mistake/error)
# In case of 1 arguments, the second argument is n. otherwise we will ask user to provide input (n).
#possible prob... |
24a029f1f20505e3a2ac7aab520d775c67898103 | sarahlevendoski/Coursera | /assigment 2.py | 2,791 | 4.3125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA seq... |
7fda9a14b791318477218fb01769e2768a2159f4 | ThiagoLiraRosa/Python_Projects | /AULA 08.py | 316 | 3.875 | 4 | #from math import sqrt
#num=int(input('Digite um Número: '))
#raiz=sqrt(num)
#print('A raiz quadrada de {} é {:.2f}.'.format(num, raiz))
import random
num=random.randint(1, 100)
print('O Número aleatório é: {}'.format(num))
#import emoji
#print(emoji.emojize('Ola Mundo :earth_americas:', use_aliases=True))
|
326195a3b3a25e409bc62a64f6b388a250dd3c46 | UPSD1/Temperature-Conversion-on-Python | /BaseTwotoBaseSixteen David Akinboro.py | 570 | 4.3125 | 4 | # Python Program - Convert Binary to Hexadecimal and Octal
print("This is a program converting BASE 2 to BASE 16");
print("Enter 'x' for exit.");
binary = input("Enter a number in Binary Format (1's AND 0's): ");
if binary == 'x':
exit();
else:
# converting binary to Hexadecimal using the hex built-in func... |
b850858449ed09d6b118867a3dc4fb215f74a86f | jizefeng0810/Databases_Learning | /MySQL/mysql_basic.py | 966 | 3.609375 | 4 | # 导入pymysql
import pymysql
if __name__=='__main__':
# 连接mysql数据库的服务
connc = pymysql.Connect(user='root',password='***',database='person',charset='utf8')
# 创建游标对象
cur = connc.cursor()
# 编写sql语句
sql = 'select * from info;'
# 使用游标对象去执行sql
cur.execute(sql)
# 获取结果
result = cur.fetcha... |
2a1d994692654fbfb6293db7d9cc12e6816d0bbc | glenonmateus/ppe | /secao20/intro_unittest.py | 1,425 | 4.28125 | 4 | """
Introdução ao módulo Unittest
Unittest -> Testes Unitários
O que são testes unitários?
Teste unitário é a forma de se testar unidades individuais de código fonte.
Unidades individuais podem ser:
- funções, métodos, classes, módulos, etc.
# OBS: Teste unitário não é específico da linguagem Python.
Para cri... |
d81e3b07ff05d5801d18172210504e15282aafcc | aashi0707/matplotlib-module-plot-graph | /bar-plot.py | 287 | 3.765625 | 4 | #!/usr/bin/python3
import matplotlib.pyplot as plt
x=[1,2,9]
y=[3,5,7]
y1=[3,6,8]
x1=[4,8,13]
plt.title("simple")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.bar(x,y,label="water",color='g')
plt.bar(x1,y1,label="soil",color='r')
plt.legend()
plt.grid(color='y')
plt.show()
|
509830792d354d964b557217424b2f4711123dd0 | tylersmithSD/Multipurpose_Calculator-Python | /unitObject.py | 2,187 | 3.984375 | 4 | #Developer: Tyler Smith
#Date: 11.06.16
#Purpose: Unit Converter class where the user can
# enter in amount of feet and it is
# converted to different types of
# measurements used.
class unitConverter(object):
def __init__(self, feet): # Constructor of the class ... |
e25569ee58806eac2980f5c2263a63e407dc97f7 | ccsreenidhin/100_Python_Problems | /Learning_Python_100_problems/python32.py | 668 | 3.90625 | 4 | ###############################################################################################################
###################################################SREENIDHIN C C##############################################
################################################################################################... |
f019a020f145b61da9f45df3dbae1130654baf91 | darya-ver/ERSP201819 | /additionalFiles/getLists.py | 1,034 | 3.5625 | 4 | def main():
fp = open('pythonLists.txt')
minsT = []
onesT = []
twosT = []
threesT = []
maxsT = []
minsB = []
onesB = []
twosB = []
threesB = []
maxsB = []
for i, line in enumerate(fp.readlines() ):
# do something here
#print( i )
#print( line )
split = line.split( ',', -1)... |
a79498a88843e8ba49b5c8068ae9855205ebd28e | dixoncox/6.00.1x | /Old/ps7/TEST.RectangularRoom.py | 5,892 | 4.21875 | 4 |
import math
import random
class Position(object):
"""
A Position represents a location in a two-dimensional room.
"""
def __init__(self, x, y):
"""
Initializes a position with coordinates (x, y).
"""
self.x = x
self.y = y
def getX(self):
ret... |
320f2feba29602afc508e5aaf74a852f63858add | gaj995/Random | /momoization/can_construct.py | 795 | 3.71875 | 4 | def can_construct(target, array, memo={}):
if target in memo:
return memo[target]
elif target == '':
return True
for word in array:
if target[:len(word)] == word:
suffix = target[len(word):]
if can_construct(suffix, array, memo) == True:
memo[... |
3631ba69951dca1f801724c33dfda70921d6f1f7 | Mdmorshadurrahman/Python_Programming | /try_your_luck.py | 1,932 | 4.09375 | 4 | import random
colorDict = {
1: "Red" ,
2: "Black" ,
3: "White" ,
4: "Blue" ,
5: "Green"
}
print('\n\t***Welcome to Our game of Luck by Chance:***\n\n\n ||-> (Rules: Choose your color and check if it match with your luck or not)')
print("\n 1: TEST your luck\t\t\t\t2: Exit\n\n")
j = int(inpu... |
9a4d54c568c8570d638b20aca55ae43c4d3474b1 | frclasso/CodeGurus_Python_mod2_turma1 | /Cap02_Classes/script4-special-methods.py | 2,235 | 3.984375 | 4 | #!/usr/bin/env python3
# special methods
class Empregados:
num_emps = 0
aumento = 1.04
def __init__(self, nome, sobrenome, salario, empresa): # construtor
self.nome = nome
self.sobrenome = sobrenome
self.salario = salario
self.empresa = empresa
self.email_pro = ... |
95ab62e93f9257945f059e4a66ddc96846e26d8c | dhineshns/reinvent_the_wheel | /algorithms/arrays.py | 164 | 3.859375 | 4 | list_apples = ["malgudi", "kansas", "kashmir"];
i = 0;
while (i<len(list_apples)):
print (list_apples[i]);
i=i+1;
for item in list_apples:
print (item); |
39c295ad23fa6398a5de3e952fe285d30c59f834 | j18r1L/Algorithms_analysys | /lab_01/main.py | 2,784 | 3.71875 | 4 | import time
import tests
import PIL
def main():
word1 = enter()
word2 = enter()
if len(word1) < len(word2):
word1, word2 = word2, word1
print()
result_mtr = levenshtein(word1, word2)
print('result levenshtein: ', result_mtr, '\n')
mtr = demerau_levenshtein(word1, word2)
print('demerau_levenshtein: ', mtr,... |
edfc9ea820f0ef77924fcf58fbcda1f721e7c5c0 | nmoore32/coursera-fundamentals-of-computing-work | /1 An Introduction to Interactive Programming in Python/Week 1/1 Functions/exercise-9.py | 163 | 3.890625 | 4 | def name_and_age(name, age):
'''Returns a string giving someone's name and age'''
return f"{name} is {age} years old."
print(name_and_age('Joe Warren', 52))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.