blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
aae78a1e1218f831fcb47fda26413f9705393c56 | RichieSong/algorithm | /算法/分治/pow.py | 1,088 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
#
# 示例 1:
#
# 输入: 2.00000, 10
# 输出: 1024.00000
#
#
# 示例 2:
#
# 输入: 2.10000, 3
# 输出: 9.26100
#
#
# 示例 3:
#
# 输入: 2.00000, -2
# 输出: 0.25000
# 解释: 2-2 = 1/22 = 1/4 = 0.25
#
# 说明:
#
#
# -100.0 < x < 100.0
# n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
#
# Related ... |
74b8ad12cda25ee78b388d59be7aa22645e23550 | rpsmith77/PythonForEverybody | /CH10_Exercise1.py | 1,160 | 4.59375 | 5 | # Ryan Smith
# Python for Everybody Coursera
# Exercise 1: Revise a previous program as follows: Read and parse the
# “From” lines and pull out the addresses from the line. Count the number of
# messages from each person using a dictionary. After all the data has been
# read, print the person with the most commits by ... |
ab8b31b22d065b834ae9e8e3ee33548202553428 | gustmtofoli/DeepLearning | /lesson1/softmax.py | 507 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Using python3.6
scores = [3.0, 1.0, 0.2]
# transforms the scores into probabilities
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis = 0)
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
# print("scores: ", ... |
02cfe8d62938103c0bcb88873f128bc43f1c89d6 | THUEishin/Exercies-from-Hard-Way-Python | /exercise3/ex3.py | 302 | 4.15625 | 4 | '''
This exercise is to show easy operations between numbers.
Nmaely, +, -, /, *, %, <, >, <=, >=
'''
print("I will now count my chickens:")
print("Hens",25+30/6)
print("Roosters",100-25*3%4)
print("How I will count the eggs:")
print(3+2+1-5+4%2-1/4+6)
print("Is it true that 3+2 < 5-7?", 3+2<5-7) |
4bf31451f4b95815625493c17ccefdfa626f471a | DevanshSoni/Projects-on-Python | /Package Based Bank Application/Auth.py | 1,549 | 3.59375 | 4 | import os
import json
import time
def sign_up():
os.system('cls')
user_name=input("Enter User_Name")
password=input("Enter Password")
balance=int(input("Enter Initial Amount"))
acc_no=None
data=os.listdir('Bank')
if data==[]:
acc_no='1000' # Assign 1000 i... |
da2ab8b944c469917752835185d397070600dc7c | shen-huang/selfteaching-python-camp | /19100202/nathanye/d4_exercise_control_flow.py | 412 | 3.859375 | 4 | # -*- coding: UTF-8 -*-
# Filename : 9*9 table
# author by : Nathanye
# 九九乘法表
for i in range(1,10): # i 代表行数
for j in range(1,i+1): # j 代表列数
product=i*j
print("%d*%d=%2d\t" % (i,j,i*j),end="")
print ()
r=1 # r 代表行数
while r<10:
c=1 # c 代表列数
while c<=r:
print("%d*%d=%d\t" % (r... |
d0557013f36be6f548917895a0cdb5b30820b33f | BRIANHG89/Python-Exercises- | /condicionalcompuesta/notasalumno.py | 564 | 4 | 4 | """
Confeccionar un programa que pida por teclado tres notas de un alumno, calcule el promedio e imprima alguno de estos mensajes:
Si el promedio es >=7 mostrar "Promocionado".
Si el promedio es >=4 y <7 mostrar "Regular".
Si el promedio es <4 mostrar "Reprobado".
"""
nota1=int(input("Ingrese primera nota:"))
nota2=i... |
715842ad8a37259ad9170257a66bf2d9dbda16d5 | TorchAblaze/spooky_manor | /spooky_manor2.py | 6,804 | 3.65625 | 4 | from room import Room
import locations
def show_help():
print("""
HOW TO PLAY:
Enter a verb (such as: 'take/get', 'drop', 'talk', 'kill', 'light', 'wear', 'use',
'enter/exit', 'go (direction)', 'north', 'south', 'east', 'west', 'up/down',
'shake', 'open', 'examine', 'eat', 'drink', 'give', 'read', 'play', 'look')
... |
c231ecd1858dc2968eec28b71e9d1aa557f7dd7b | gjq91459/mycourse | /15 Inheritance/01_inheritance.py | 948 | 3.96875 | 4 | ############################################################
#
# Inheritance
#
############################################################
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def WhereAmI(self):
print "Point(%i) is at %i,%i" % (id(self), self.... |
9b08560ae55ee50e918e156d0040148204b7b7ed | nlpet/codewars | /Fundamentals/weird_string_case.py | 776 | 4.21875 | 4 | """
Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and
returns the same string with all even indexed characters in each word upper cased,
and all odd indexed characters in each word lower cased. The indexing just explained is
zero based, so the zero-ith index is even, therefore that character s... |
46ff97c15baeaf88e3c399f9e404438a389d578e | kdveleva/SoftUni | /Python_Fundamentals/Dictionaries_Exercise/10. SoftUni Exam Results.py | 951 | 3.546875 | 4 | from collections import defaultdict
results = defaultdict(int)
submissions = defaultdict(list)
while True:
commands = input()
if commands == "exam finished":
break
if "banned" in commands:
command = commands.split('-')
results.pop(command[0])
continue
command = commands... |
867c8f171a6d4f3e44e9dc4a40edbd244015affa | 414190799/Yelp_Fake_reviews | /neuralnetwork.py | 1,374 | 4 | 4 | # coding: utf-8
# !/usr/bin/python3
"""
Authors: Jiajun Bao, Meng Li, Jane Liu
Classes:
NN: Accepts the preprocessed data and trains a Multilayer Perceptron (MLP) classifier. Reports the accuracy of the MLP model.
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifi... |
4ded34b5d6c59a3c4a66981d583217ce9cdef85b | CSC-510-Team-31/CSC_510-Team-31_HW2345 | /src/sym.py | 697 | 3.5 | 4 | import math
from print import o
class Sym:
def __init__(self, c, s):
self.n = 0
self.at = c or 0
self.name = s or ""
self._has = {}
def __repr__(self):
return o({"at": self.at, "n": self.n, "name": self.name})
def add(self, v, nums = None, rand = None):
if v == "?":
return
... |
992ca855937b774bae369131e60ffa7411c32a4a | bristolplodder/perudo | /throws.py | 662 | 3.671875 | 4 | import random
#def int():
# x = random.randrange(1,6)
# print(x)
#int()
#x, y, z = random.randrange(1,6), random.randrange(1,7), random.randrange(1,3)
#print(x, y, z)
def list():
##
player = [1,2,3]
dice = [4,3,2]
for cc in player:
print("player "+str(cc))
#for bb in dice:
... |
a8c778c77066981d067e931b1e2d750107c6a8c1 | jinurajan/Datastructures | /array/longest_common_suffix.py | 855 | 3.953125 | 4 | # -*- coding: utf-8 -*-
def longest_common_suffix(string1, string2):
if not string1 or not string2:
# if either of one becomes null string return ""
return ""
st1, str1 = string1[-1], string1[:-1]
st2, str2 = string2[-1], string2[:-1]
if st1 == st2:
# if the first element of e... |
6fec3ad707eee73c36b8d4c40c52fae0e6dde9a0 | zhaochuanshen/leetcode | /Binary_Tree_Postorder_Traversal.py | 868 | 4 | 4 | '''
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.... |
ffd824831f7f99524d63178bea1b858a19dcc5af | naye0ng/Algorithm | /OnlineCodingTest/Midas/test03.py | 1,398 | 3.734375 | 4 |
import copy
# 가득 차있는 값 고르기
def findFull(board) :
count = 0
for b in board :
if sum(b) == len(b) :
count +=1
return count
def solution(block, board):
answer = 0
if block == 0 :
dy = [0,0,0]
dx = [0,-1,-2]
elif block == 1 :
dy = [0,-1,-2]
... |
74f851af2f32364e808334251921617ff8216dc6 | tronghieu60s/python-dsa | /05_Queue/01_Static_Array_Queue/Queue.py | 755 | 3.78125 | 4 | class Queue:
def __init__(self, maxSize):
self.head = self.tail = -1
self.arr = [None] * maxSize
def full(self):
return self.tail == len(self.arr) - 1
def empty(self):
return self.head == -1
def enqueue(self, value):
if(self.full()):
raise Excepti... |
d817a928197870c7c373ca17fad170a3232667d9 | yshanstar/Leetcode_Shan_Python | /SwapNodesinPairs.py | 620 | 3.71875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class SwapNodesinPairs:
def swapPairs(self, head):
if head is None:
return None
if head.next is None:
return head
helper = ListNode(0)
helper.next = head
prev ... |
a0fdd573551c3ab2b282d3b552730d5761f68f1e | chrisfischer/DontBuyMe | /predictionAPI.py | 4,945 | 3.734375 | 4 | import csv
import random
import math
import operator
import sys
import argparse
import json
# Capital One Hackathon 1/11/2018
# hard coded cost prediction based on last 3 months of stock growth information
def findCostMarketInvestment(cost, timeReference, determinantFundData, balance, interest, payment):
data =... |
be7f9045cae1ae52b5f4274b1cbbd8ba82bbf95a | Katherinaxxx/leetcode | /208. Implement Trie (Prefix Tree).py | 1,821 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/11/18 下午1:57
@Author : Catherinexxx
@Site :
@File : 208. Implement Trie (Prefix Tree).py
@Software: PyCharm
"""
# class Trie(object):
# def __init__(self):
# self.root = {}
# self.end_of_word = "#"
# def insert(self, word):
# node = self.root
#... |
ca6b9cfd33339565f09bcb59ddb71e1c24c42f47 | crystalatk/python-algorithms | /Week 1/alg_2_Sum_Multiples.py | 348 | 3.984375 | 4 | # 2. Sum of All Multiples of 3 or 5 below 1000
# # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# # Find the sum of all the multiples of 3 or 5 below 1000.
r = 0
for n in range(1,1001):
a = 3
b = 5
if n % a == 0 or n % b =... |
509b4250fe248c93ece92feb246bbe8bb7f882b2 | Anishadahal/Assignmen2_tIW | /DataTypes/q25.py | 212 | 4.25 | 4 | # Write a Python program to check whether all dictionaries in a list are empty or
# not.
my_list = [{}, {}, {}]
my_list1 = [{1, 2}, {}, {}]
print(all(not d for d in my_list))
print(all(not d for d in my_list1))
|
6df51c80f494fd4e81a6d1c4917575714b2e3a88 | apdaza/bookprogramming | /ejercicios/python/ejercicio085.py | 731 | 3.640625 | 4 | __size = 5
def llenado_usuario(m):
for i in range(__size):
n=[]
for j in range(__size):
num = int(input("ingrese el valor para la posicion (" + str(i) + "," + str(j) + ") : "))
n.append(num)
m.append(n)
def mostrar_matriz(m):
for i in m:
for j in i:
... |
940c0d41173004008ecd8513e86441f87dbfdb07 | ProspePrim/PythonGB | /Lesson 6/task_6_4.py | 3,012 | 3.78125 | 4 | #Реализуйте базовый класс Car.
# У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
# А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).
# Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceC... |
afe67941a477a69f43968c8637852734c7c43579 | harveylabis/GTx_CS1301 | /codes/CHAPTER_4/Chapter_4.5_Dictionaries/Lessson_2/AddingandRemovingfromaDictionary-1.py | 331 | 3.578125 | 4 | #Creates myDictionary with sprockets=5, widgets=11, cogs=3, and gizmos=15
myDictionary = {"sprockets" : 5, "widgets" : 11,
"cogs" : 3, "gizmos": 15}
print(myDictionary)
#Creates the new key "gadgets" with value 1
myDictionary["gadgets"] = 1
print(myDictionary)
del myDictionary["gadgets"]
print(myDic... |
480f07625738f0ad4c82494b5fcaa50783b41a06 | tbjoern/adventofcode2017 | /02/part2.py | 387 | 3.515625 | 4 |
lines = []
with open("input.txt") as file:
lines = file.readlines()
sum = 0
for line in lines:
numbers = list(map(lambda x: int(x), line.split()))
for number1 in numbers:
for number2 in numbers:
if number1 != number2:
if number1 > number2 and number1 % numb... |
7e46d5728b96ba9db4672f9d543c382baa92d82b | supriyo-pal/Python-Practice | /List/print all positive and negetive numbers in a list.py | 340 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 10:41:08 2020
@author: Supriyo
"""
list=[34,5,-1,-5,-9,23,56,76,9,-64]
list_pos=[]
list_neg=[]
for i in list:
if i>=0:
list_pos.append(i)
else:
list_neg.append(i)
print("Positive Numbers ",list_pos)
print("Negetive numbers ",list_... |
894b08ed1dc3bc464f62e55e1ccfe81f3ff76eb0 | nrmorciglio/digitalcrafts | /week1/day3/3intCalc.py | 1,907 | 4.375 | 4 | greeting = input('Welcome to this calculator program. What is your name?\n')
print(f'Hello ' + greeting + ' ,lets begin!')
print('This calculator is designed to compute up to three numbers. You will be asked if your equation requires a third number. Please follow the prompts to complete your calculation. PLEASE KEEP ... |
0a5cb5be1d8f22a0c0a4174eb6e03954f8d6a894 | smishra06/dynamicpage | /consecutive.py | 376 | 3.578125 | 4 | string="1AABBBCCCC1AA"
#string="A"
count=1
length=""
if len(string)>1:
for i in range(1,len(string)):
if string[i-1]==string[i]:
count+=1
else :
length += string[i-1]+" occurs "+str(count)+", "
count=1
length += (string[i]+" occurs "+str(count))
else:
i=0
le... |
6f5b78d13ec7b8b9c72d92b96d923bc9dbbfe893 | mazouri/EasyPython | /small_project/web/beautiful_soup/doc/09兄弟节点.py | 2,454 | 3.515625 | 4 | from bs4 import BeautifulSoup
sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
# print(sibling_soup.prettify())
# <html>
# <body>
# <a>
# <b>
# text1
# </b>
# <c>
# text2
# </c>
# </a>
# </body>
# </html>
# .next_sibling 和 .previous_sibling
# 在文档树中,使用 .next_sibling 和 .prev... |
b732b61c40007b986cc74d8031dcb45c552faba4 | marianasoeiro/PythonIntro | /notebooks/exercicio6/exercicio6_3.py | 752 | 4.09375 | 4 |
#Autor: Mariana Soeiro
#About: Exercicio 6 - Lista 4 (Python)
# - 6. Convert temperatures from Celsius to Fahrenheit [x]
def toCelsius() :
print("my converter from Celsius to Fahrenheit ")
# 1.8c + 32 = F
c = float(input("Choose a temperatura in Celsius degrees to convert in Fahrenheit degrees "))
f... |
c88c5f70605a11452f33d53b4329e6e1f7c9288b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2397/60595/247461.py | 134 | 3.765625 | 4 | num=int(input())
for i in range(0,num*num*4):
a=input()
if(num==3):
print(17)
elif(num==7):
print(15)
else:
print(num) |
e48facdab72ab269869a7586fbed3c7bd85310f6 | HelixAngler/Repos | /Python/simplcalculator.py | 1,206 | 3.609375 | 4 | def addi(g1, g2):
return g1+g2
def subt(g1, g2):
return g1-g2
def mult(g1, g2):
return g1*g2
def divi(gi, g2):
return g1/g2
def powe(g1, g2):
return g1**g2
x=[0]
while True:
n=input("1st Number (ans for previous answer)")
p=int(input("2nd Number "))
z=int(input("select calculation"))
... |
56155f457dd097e80b15ec6a6f4ac211d5733028 | angelinn/HackBulgaria | /week0/fibonacci_lists.py | 373 | 3.875 | 4 | def fibonacci_lists(listA, listB, n):
first = listA
second = listB
if n == 1:
return first
if n == 2:
return second
for i in range(2, n):
result = first + second
first = second
second = result
return result
def main():
print(fibonacci_lists([1, 2]... |
52b66daac98f4b790ddd9070905f007f19d4ad61 | kharicha/hkarthikbabu | /python_problem_solved_100/code_chef.py | 4,244 | 3.578125 | 4 | # '''
# Input
# # An input contains 2 integers A and B.
# #
# # Output
# # Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits
# # as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not
# # allowed. If there are multip... |
32531dea6cb7715d6fd5ad0562e850fd02390a07 | pvenkatesh786/Python | /Programs/dictcount.py | 150 | 3.703125 | 4 | #!/bin/python
dct = {}
str = raw_input("Enter the string :")
for elem in str:
if elem not in dct:
dct[elem] = 1
else:
dct[elem] += 1
print dct
|
b82226026b94403a0a6881a91dc8fbb95a335ca7 | Triple-Z/Python-Crash-Course | /C8/8.4.py | 631 | 3.703125 | 4 | # 8-9
def show_magicians(magicians):
"""
Show magicians function.
:return: null
"""
for magician in magicians:
print(magician)
magicians = ['test1', 'test2', 'test3', 'test4', 'test5']
show_magicians(magicians)
# 8-10
def make_great(magicians):
for i in range(0, 5):
magicians[... |
0e5274ac6da1bcae9d552c1a17c0b1c1741f5d65 | MandragoraQA/Python | /Urok14-2.py | 851 | 4.21875 | 4 | #Игра крестики-нолики. Поля 3х3, реализуется через двухмерный массив (вложенные списки)
#* - пустое поле
#Х - крестик
#0 - нолик
pole = []#поле
for a in range (3):
row = [EMPTY for a in range(3)]
pole.append(row)
koordinati = []#координаты, которые будут меняться
komanda = input("Перед вами поле 3х3. ... |
2983285e9a02e803370c3702e31f563dad47bc12 | alexinf/AlgoritmosAvanzados | /python/python/kmp.py | 611 | 3.765625 | 4 | def partial(pattern):
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
return ret
def search(T, P):
partialVar, ret, j = partial(P), [], 0
f... |
aada279be33c74c347bf36ede0ff5be80669bd66 | ShrutiBalla9/ShrutiBalla7 | /datatypes.py | 757 | 4.125 | 4 | A=['8','java','python','9','10',11,12,13,14,15]
print("List A :",A[:])
print("List A : 2 to 5",A[2:6])
print("List A in reverse:",A[::-1])
A.append('12')
print("List A after appending :",A[:])
A.insert(3,'oop')
print("List A after inserting :",A[:])
A.pop(1)
print("List A after poping :",A[:])
A... |
3d3527c7e0fbb2ee7255fe3f2565803759af20ad | rosmoke/DCU-Projects | /week12/caesar-cypher.py | 554 | 3.671875 | 4 | import sys
v = sys.argv[1]
t = raw_input()
def encrypt(alpha):
alpha = "abcdefghijklmnopqrstuvwxyz"
word = ""
i = 0
while i < len(t):
j = 0
while j < len(alpha):
if t[i] == alpha[j]:
if j > len(alpha)-4:
word = word + alpha[j-23]
else:
word = word + alpha[j+int(v)]
elif t[i] == alpha[j]... |
ba42788e18b755324b0b3fc72106f8664a6e2891 | mattany/gomoku | /DynamicSpace.py | 3,848 | 3.8125 | 4 | import gym
from gym.spaces import Discrete
import numpy as np
import math
# You could also inherit from Discrete or Box here and just override the shape(), sample() and contains() methods
class GomokuObservationSpace(Discrete):
"""
x where x in available actions {0,1,3,5,...,n-1}
Example usage:
self.a... |
96798540b7e0d8d4280e21da8d797ab5aaa6e0e6 | FrancisPepito/practice-programming-problems | /maclaurin-series.py | 233 | 4.0625 | 4 | import math
x=float(input("Enter value for x: "))
k=int(input("Enter value for k: "))
arctan=0.0
sign=1
ctr=1
for i in range(k):
arctan=arctan+(sign*(x ** ctr)/ctr)
ctr = ctr + 2
sign = sign * -1
print(arctan)
print(math.atan(x))
|
feda51686359569e15146fe71f68c802676289c9 | a12b4c3/advent_of_code1 | /day4/d4p1-2.py | 1,578 | 3.734375 | 4 | import re
guard_sleep_minutes = {}
# outputs the laziest guard and how many minutes they are asleep, and
# what minute they were asleep the most.
def main():
laziest_guard = calculate_guard_sleep_minutes()
# reads file line by line
def calculate_guard_sleep_minutes():
with open("sorted_input.txt", "r") as p... |
86f81150a82de79857a5ae3cc4c4e19ee406f72f | Yidna/elisa-fanclub | /libs/tokenizer.py | 2,039 | 3.609375 | 4 | from functionality.exceptions import IllegalInputException
from libs.literals import LITERALS
from libs.func_table import FUNC_TABLE
class Tokenizer:
tokens = []
cur = None
def __init__(self, file_path):
# Constructor
self.cur = 0
with open(file_path, 'r') as f:
self.f... |
5ae06378645cd8f368b0d7a3c46c969f906e4cf6 | Nmazil-Dev/PythonCrashCoursePractice | /More Exercises/10-11.py | 743 | 4.09375 | 4 | # Favorite number program
import json
#looks for the stored favorite number by looking at fav.json
def stored():
filename = 'fav.json'
try:
with open(filename) as f_obj:
fav = json.load(f_obj)
except FileNotFoundError:
return None
else:
return fav
... |
d4d02cc965a3d29cb8a5a25644c7cf68965e9e38 | somanmia/URI-Online-Judge-All-Problems-Solution-in-Python | /URI_1002.py | 70 | 3.765625 | 4 | pi= 3.14159
r=float(input())
result=pi*r*r
print("A=%.4f"%result)
|
9b317912bd960e29a6c2d2967f51000a22046838 | vaishnavi-ui/event-database-management | /Remove_Member.py | 6,069 | 3.5 | 4 | from tkinter import *
import sqlite3
connection = sqlite3.connect("Event_Management.db")
cursor = connection.cursor()
def getId(val):
global Id
rem=val
Id=val[0]
def Del():
global e2,t,rowCount
rem1=("DELETE FROM COMMITTEE_MEMBERS WHERE M_ID=?")
cursor.execute(rem1,[(e2.get())... |
995cd37b7a8c732eb2ee8838efd05832c6da1043 | pierremayo/tutorials | /intro.py | 160 | 3.8125 | 4 | age = input("What is your age?")
s1 = "You are {0} years old."
s2 = "In 5 years you will be {0} years old."
print(s1.format(age))
print(s2.format(int(age) + 5)) |
9eab4e148a47e13aac3df96583a80fdf6d80614b | pod1019/python_learning | /练习题/错误与调试.py | 189 | 3.765625 | 4 | #打印1到10的平方值
# for i in range(10):
# print(i ** 2,end=',')
#测试断点
a = 1.1
b = 2.2
if round(a+b,1) == 3.3:
x = 5
y = 3
# z = x / y
# print(z)
|
ff46ee54846e6653575491398ef9b1ca198ba733 | pyslin/mypython | /my-func.py | 929 | 3.9375 | 4 | print(abs(-10))
print(abs)
#abs(10)函数的调用 ,abs是函数
x = abs(10)
#要获得函数调用结果,可以把结果赋值给变量
print(x)
f = abs
#函数本身也可以赋值给变量,变量指向函数,函数名就是指向函数的变量
print(f(-5))
def add(x,y,f):
return f(x)+f(y)
print(add(5,-6,abs))
def f(x):
return x*x
r = map(f,[1,2,3,4,5])
#map会返回一个惰性iterator,用list()函数把序列计算出来并返回list
print(list(r))
r2 = ... |
3f4a00a03125e424453e48cd1ec82ef91e422207 | Stone1231/py-sample | /tests/oop_test.py | 422 | 3.875 | 4 | import unittest
class Dog():
"""Represent a dog."""
def __init__(self, name, heigh, weight):
"""Initialize dog object."""
self.name = name
self.heigh = heigh
self.weight = weight
class OOPTestCase(unittest.TestCase):
def setUp(self):
self.dog = Dog('ccc',11,... |
b3cb41c91541098f0c4198736e036385395838a3 | C2L2C/userLogins | /userLogins.py | 699 | 3.65625 | 4 | import hashlib,sqlite3
con = sqlite3.connect('file:./db/ppab6.db?mode=rw', uri=True)
cur = con.cursor()
username = input("Please enter your username: ")
password = input("Please enter your password: ")
def is_valid_credentials(username,password):
isUsernameValid= cur.execute("SELECT EXISTS(SELECT 1 FROM users WH... |
e0bcee7a38caa630bbeb0fe6059cd585578caf68 | alexander-zw/mini-projects | /mnist.py | 2,362 | 3.8125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data", one_hot=True)
num_inputs = 784
num_classes = 10
num_layers = 4
# input layer, 3 hidden layers, output layer
nums_in_layer = [num_inputs, 10, 10, 10, num_classes]
batch_size = 100
# strin... |
b17563cf1ad0902bda26065475884c0d0575f086 | iparedes/bugs2 | /hop.py | 2,098 | 3.578125 | 4 | import sys, random, pygame
from ocempgui.widgets import Button, Renderer, Constants
# Used to see some action happending in the GUI.
amount = 0
def _count_clicks (b):
global amount
amount += 1
b.text = "Clicked %d times" % amount
# Initialize pygame window
pygame.init ()
screen = pygame.display.set_mode (... |
651ed5c361107016f8d8395c5eb139c2233acb2b | AvinashBonthu/Python-lab-work | /lab 1/lab1.2_19.py | 100 | 3.71875 | 4 | print 'Odd numbers between 0 and 100 are'
for i in range(1,101):
if i%2!=0:
print i
|
19b65806990f1e43964e591f448683c4e59bfdb4 | EdisonZhu33/Algorithm | /题型分类/双指针遍历AND滑动窗口/004-最接近的三数之和.py | 1,294 | 3.703125 | 4 | """
@file : 004-最接近的三数之和.py
@author: xiaolu
@time : 2020-05-11
"""
'''
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,
使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
'''
from typing import List
class Solution:
def threeSumCl... |
497abc78b47abb1ae87a3aeb42473fde50f31054 | charan2108/pythonprojectsNew | /pythoncrashcourse/lists/changinglists/changelist.py | 101 | 3.515625 | 4 | #Modifyinglist
bikes = ['Honda', "CBR", 'KTM', 'Ninja']
print(bikes)
bikes[0] = 'Ducati'
print(bikes) |
0b54933b8a30ceccd9d9481372476241265d8ea7 | LiuFang816/SALSTM_py_data | /python/Zeta36_Asynchronous-Methods-for-Deep-Reinforcement-Learning/Asynchronous-Methods-for-Deep-Reinforcement-Learning-master/Wrapped-Game-Code/dummy_game.py | 1,324 | 3.546875 | 4 | #!/usr/bin/python
import cv2
import numpy as np
'''
Dummy game to test the effectiveness of the DQN.
The game starts out with a white screen, and will change
to black if given input 1. A black screen turns white on
input 2. Flipping the screen color gives reward 1,
but the wrong input for a given screen will give
-1 ... |
6f7a8e0754f471a3d84529381c318dc129489edb | LeonDsouza/HackerRank | /pangrams.py | 129 | 3.734375 | 4 | if set(input().lower().replace(' ',''))==set('abcdefghijklmnopqrstuvwxyz'):
print ("pangram")
else:
print("not pangram")
|
a3e7c4d23536d27f2c95eacb12bc0deba53501b2 | dileepachuthan/Coursera-python-3.2-we | /we.py | 368 | 3.96875 | 4 | score = input("Enter Score:")
f = float(score)
try:
if(f>0.0 and f<1.0):
if(f >= 0.9):
print('A')
elif(f >= 0.8):
print('B')
elif(f >= 0.7):
print('C')
elif(f >= 0.6):
print('D')
else:
print('F')
except:
print("E... |
3cdce236932573c4148b7985e3574fe23898e3ec | vifezue/PythonWork | /IT - 412/Week_1/week_1_functions_assignment/functions/enterAddress.py | 1,064 | 4.34375 | 4 | from checkForNull import checkfor_null
from checkForValue import check_for_value
def enter_address():
"""Takes user entry and saves the address
Returns:
string -- Returns the Address or an empty string
"""
try:
invalid_addressCharacters = ["!", "\"","'", "@", "$", "%", "^", "&", "*... |
78e8b6a4f23aa8a78190fcbab45f3cd725863301 | NBALAJI95/MapReduce_Project | /Extra requirements/Source Code/map_extra.py | 1,957 | 3.546875 | 4 | #! /usr/bin/env python
import sys
for line in sys.stdin:
line = line.strip()
words = line.split()
for word in words:
n = int(word[0:2])
if n >= 0 and n < 1:
print 'Time_between_12_AM_AND_1_AM\t%s' % (1)
if n >= 1 and n < 2:
print 'Time_between_1_AM_AND_2_AM\t%s' % (1)
if n >= 2 and n < 3: ... |
9d028705eacf3af310f02bd3afe08eb574101b18 | G00364778/46887_algorithms | /assignment/contains_duplicates.py | 795 | 3.703125 | 4 | import time
def contains_duplicates(elements):
for i in range (0, len(elements)):
for j in range(0, len(elements)):
steps=(i+1)*(j+1)
if i == j: # avoid self comparison
continue
if elements[i] == elements[j]:
#return True, steps
... |
79ecbe86454e3ca6820662568c30f8a859727b8e | nikonura/theory_of_algorithms_2015_itmo_spo | /trees.py | 4,084 | 3.90625 | 4 | '''
деревья
T=<N,E>
N=nodes(узлы)
E=edges(ребра)
у дерева всегда есть корень, причём только один.
ели у дерева(корня) есть только 2 потомка, то оно называется бинарным.
дерево называется пустым, если нет ни листов, ни ребер, или состоять из
корня и нуля из более поддеревьев.
'''
def binary_tree(value):
... |
9e1605304dca72bb6dc3f35a2f4cb15ee8653704 | WarakornToey/All_Exercises_Python_3 | /Exercise5_2_Warakorn_L.py | 123 | 3.859375 | 4 | v = int(input("Car Speed (km/hr) : "))
t = int(input("Time Speed (s/hr) : "))
result = v/t
print("Result : ",result,"km/h") |
51066b8d294ee8e090c3f9466f410bdd438925c3 | FireinDark/leetcode_practice | /14_longest_common_prefix.py | 1,219 | 3.78125 | 4 | class Solution:
# 暴力解决
def longestCommonPrefix(self, strs):
if not strs:
return ""
i = 0
start = ""
min_index = None
for item in strs:
if min_index is None:
min_index = len(item)
else:
min_index = min_ind... |
15d1b7a42f2ec0896a7362040bdf97db8d102e7a | Drlilianblot/tpop | /TPOP Python 3.x Practicals/exercise_booklet/coinwar.py | 1,833 | 4.125 | 4 | import random
# these Constants are defined to facilitate code reading
COIN_HEAD = 'HEAD' # represent the head of a coin
COIN_TAIL = 'TAIL' # represent the tail of a coin
def flipCoin():
'''
flip a coin randomly and return one of the two faces of a
coin (e.g. COIN_HEAD, or COIN_TAIL).
'''
flip ... |
9e24a6b9a768acd71e55520c2a1ce6a89ad924bb | riddhinm5/myNumpy | /vector.py | 4,237 | 3.5625 | 4 | import math
class Vector():
CANNOT_NORMALIZE_ZERO_VECTOR = 'Cannot normalize a zero vector'
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
... |
2ce635527f3c26471448ef2fec19fbe05e0df76c | mikem2314/PythonExercises | /Mutations.py | 285 | 3.859375 | 4 | #Written to solve https://www.hackerrank.com/challenges/python-mutations/problem
s = input("Please enter a string: ")
t = input("Please enter an index and char to split on, separated by a space: ")
index = int(t[0])
char = t[2]
l = list(s)
l[index] = char
s = ''.join(l)
print (s) |
3fa859c1b3799fa403a8bf78a66d066a28bdf3e2 | soumyaracherla/python-programs | /call by ref.py | 267 | 3.609375 | 4 | def updatelist(mylist):
print("current data", mylist)
mylist[1]= 11
print("updated data", mylist)
list1= [1,2,3,4,5]
updatelist(list1)
def update(value):
num=20
print("num is", num)
return value
result=update(10)
print("num is ", result)
|
a99e996d8f1fa95e0b6bed7b1afc96dd2ed01896 | HafizulHaque/Python-Practice- | /membership.py | 464 | 3.9375 | 4 | vowels = "aeiou"
while(True):
vowelCnt = 0
consCount = 0
other = 0
str = input("Enter a string (-1 to exit) :")
try:
if int(str) == -1:
print("Thank you !")
break
except ValueError as error:
pass
for char in str:
if char.isalpha():
if char.lower() in vowels:
vowelCnt += 1
... |
401f8584675b314874c2b54a415a7f653925a780 | 18tbartecki/ITP-115 | /ITP115_Project_Bartecki_Tommy/MenuItem.py | 1,094 | 4.03125 | 4 | # This file defines the MenuItem class
# A MenuItem represents a single item that a diner can order from the restaurant’s menu
class MenuItem:
def __init__(self, name, itemType, price, description):
self.name = name
self.itemType = itemType
self.price = price
self.description = de... |
5601ad229d6ad66178d3e86959750b65c4028b1e | kabirbansod/EMmodelling | /a6.py | 11,545 | 3.609375 | 4 | # Unitless 1D FDTD solution to wave equation.
# Author- Kabir Bansod
# Date: 10/09/14
import numpy as np # Loading required libraries.
import matplotlib.pyplot as plt
import time
import matplotlib.animation as animation
class FdTd:
def __init__(self):
self.time_tot = 500 # Time for which the ... |
cf59bd73ce18bb69146cce53401615931f800ead | utgupta27/Utext | /test.py | 351 | 3.921875 | 4 | def check(num):
if num%2!=0:
print('Weird')
else:
if num>=2 or num<=5 :
print('Not Weird')
elif num>=6 or num<=20:
print('Weird')
elif num>20:
print('Not Weird')
else:
pass
if __name__ == '__main__':
n = int... |
b14baac35f52e7b222387e5f877727859d04be5c | liusska/Python-Basic-Sept-2020-SoftUni | /FirstSteps/lab/9.YardGreening.py | 217 | 3.5625 | 4 | yard = float(input())
price_yard = float(yard * 7.61)
discount = float(price_yard * 0.18)
price = float(price_yard - discount)
print(f"The final price is: {price} lv.")
print(f"The discount is: {discount} lv.") |
966cc62351bc90450c1769d3d6fa0f33c366de3c | mborbola/adventofcode | /2018/11/1.py | 1,164 | 3.890625 | 4 | def read_input():
with open('input', 'r') as f:
grid_serial_number = int(f.readline())
return grid_serial_number
def hundred(power):
return int(str(power)[-3])
# First I created this to generate the cell's power based on x,y and serial number
def calc_power(x, y, grid_serial_number):
rack_... |
bb45aad9636411b3da7087c888a4923c25ef6ac8 | transferome/Simulations | /fst/avgfst.py | 2,785 | 3.53125 | 4 | """ Finds the average fst value for each simulated region """
import fst.listfst as lister
import numpy as np
def fstopen(fstfile):
with open(fstfile) as f:
fstlist = [float(line.rstrip('\n').split(',')[1]) for line in f]
return fstlist
# function finds the average Fst within a between or within .... |
9c0b92bf205ad514856f0bd44af2555e6c2c4e90 | tekjar/flying-car | /fcnd.exercises/3d/astar.py | 4,781 | 4.125 | 4 | import numpy as np
from enum import Enum
from queue import PriorityQueue
# breadth-first search is to keep track of visited cells and all your partial plans
# and always expand the shortest partial plan first
# now we add the notion of cost function. which is the total cost of all the actions in a partial plan
# thi... |
e52553a913da8472c30b6fea6b177c0bb8d7a906 | MiguelOrellanaR/PROGRAMAS_PROYECTOS | /Factorial.py | 2,117 | 4.0625 | 4 |
def pedir_numero_menú():
correcto = False
num = 0
while (not correcto):
try:
num = int(input("\n>Ingrese una opción del menú:"))
print()
correcto = True
except ValueError:
print("Error, Ingrese un número que corresponda a una opción del menú\n... |
92b8816d81c3edb5f94a0a1deacb42d00bc70032 | MrAttoAttoAtto/CircuitSimulatorC2 | /components/Diode.py | 5,601 | 3.71875 | 4 | import math
from typing import List, Tuple
from components.Component import Component
from general.Circuit import Circuit
from general.Environment import Environment
class Diode:
"""
A basic diode using the Schottky Diode Equation
"""
def __init__(self, breakdownVoltage: float = 40, saturationCurren... |
ee4497f47d5b3d3f120cdd589db4c394464faebe | vmred/codewars | /katas/6kyu/Mix Fruit Juice/solution.py | 1,147 | 4.0625 | 4 | # Story
# Jumbo Juice makes a fresh juice out of fruits of your choice.
# Jumbo Juice charges $5 for regular fruits and $7 for special ones.
# Regular fruits are Banana, Orange, Apple, Lemon and Grapes.
# Special ones are Avocado, Strawberry and Mango.
# Others fruits that are not listed are also available upon request... |
56a7e682f1d8634b1df7a3f914e25bf32ec31e56 | preneetho/ML | /Capstone Project/house-prediction/src/processing.py | 13,519 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 17:18:57 2020
@author: preneeth
"""
import pandas as pd
import numpy as np
import pickle
#dataframe to hold input data from a excel. This is for testing the moldel with data from excel (1 row)
df = pd.DataFrame()
#this df holds the processed i... |
0c92a853c41fe7ca55c8de03a7fe42c7217c93ab | 314H/Data-Structures-and-Algorithms-with-Python | /Dictionaries/Maps/Longest subset zero sum.py | 1,144 | 3.671875 | 4 | """
Longest subset zero sum
Given an array consisting of positive and negative integers, find the
length of the longest subarray whose sum is zero.
NOTE :
You have to return the length of longest subarray .
#### Input Format :
Line 1 : Contains an integer N i.e. size of array
Line 2 : Contains N elemen... |
533ae9683cadaa42071508458f5cba79b58c5d1d | ajylee/cryptopals-challenges | /pkcs1.py | 1,225 | 3.671875 | 4 |
def pad(data_block, second_byte, block_size):
"""
This is the rigorous PKCS#1 described in Bleichenbacher 98.
"""
padding_string_len = block_size - len(data_block) - 3
return chr(0) + second_byte + padding_string_len * chr(0xff) + chr(0) + data_block
def check_and_remove_padding(plaintext_signa... |
c2a22bc62026ce277253c51f2dbdcd60a8274a3f | loganyu/leetcode | /problems/1925_count_square_sum_triples.py | 762 | 3.953125 | 4 | '''
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Explanation: ... |
e85fa0c74ec3f0ce036426975f8440f7383d68e3 | bastiandg/adventofcode | /2016/day09.py | 1,586 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
def recursiveUncompression(length, multiplier, substring):
index = 0
decompressedLength = 0
subCompression = False
additionalCharacters = 0
while index < len(substring):
if substring[index] == "(":
for j in range(3, 10):
if (index + j) < len(substring) and substring[ind... |
57bcf1d1d7a123424fec4cf54180e3b9a2e897f0 | thinthinhtet22/Python-Class | /variable.py | 801 | 3.578125 | 4 |
>>> 2 + 2
4
* / % + - (operator)
adddition = 75 + 25
substraction = 204 - 204
multiplication = 100 * 0.5
division = 90 / 9
power of 2 = 3 ** 2
the remainder of the division = 10 % 3
int - integer - 1, 2, 3, ---> 308930 etc
float - - 1.0, 5.9, 6.0, 63.23, etc
string - - 'Hello', "World", "A", "B",
a =1
... |
ca2dfb54ab832ef74ebb3a59b40ab2fbde518cf2 | vinayakgajjewar/bioinformatics | /hw2/2_1.py | 5,121 | 3.65625 | 4 | ## no tree/graph/tries libraries allowed
## code adapted from https://nbviewer.jupyter.org/gist/BenLangmead/6665861
class SuffixTree(object):
class Node(object):
def __init__(self, lab):
self.lab = lab # label on path leading to this node
self.out = {} # outgoing edge... |
d3417a0e6c6f6e5545849ac1387a37cb6c120a3d | human-doodle/Airline-Management-Application | /Flight.py | 620 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 18:56:26 2020
@author: Shivani
"""
class Flight:
def __init__(self, num, f, t, d, q):
self.__num= num
self.__to=t
self.__from=f
self.__date=d
self.__quota=q
def display(self):
print("\n")
print("Fligh... |
de94430dbb18b7816e16cfffde7f265ac720c3f2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4472/codes/1594_2426.py | 208 | 3.5625 | 4 | tempo = float(input("Tempo de viagem: "))
velocidade = float(input("Velocidade media: "))
distancia = velocidade * tempo
quantidade = distancia / 12
print (round(distancia, 1))
print (round(quantidade, 1))
|
8826dbbabfec1f7a8b041b0a022d36cbea40132f | hcketjow/Trips-with-python3 | /zaawansowe_TYPY/krotki-slownik.py | 525 | 3.84375 | 4 |
krotka = 1,2,3,4 # krotka nie posiada nawiasów i nie można zmienić wartości krotki
# --------------------------------------SŁOWNIK-----------------------------------------
imie = str(input("Podaj imie i nazwisko: "))
number = str(input("Podaj number pokoju: "))
pokoje = {
49:"Wojciech Chodasiewicz",
69:"Zuz... |
8eba6e56a0c8db1ee168366737df8083114f423d | Varobinson/python101 | /celsius-or-fahrenheit.py | 408 | 4.5625 | 5 | #Prompt the user for a number in degrees Celsius,
#and convert the value to degrees in Fahrenheit and
#display it to the user.
#prompt user
try:
degrees_celsius = int(input('What is the degrees celcius? '))
except ValueError:
print('Enter Valid Temp! ')
#convert celsius to fahrenheit
degrees_fahrenheit = (de... |
af500bbb7ea9ea46690003c32a87da436ca3bf53 | jacob31/python_files | /time_clock.py | 2,305 | 4.21875 | 4 | #!/usr/bin/python
import time
class NotIntegerError(ValueError): pass
class MakeScheduler():
def set_work_hours(self, work_hours=1):
''' sets the number of hours you plan on working
defaults to 8 hours.
'''
self.work_hours = work_hours
if int(work_hours) != work_hour... |
4d93c77d64256530155ae0b293915f440d662aaa | jobu95/euler | /src/pr006.py | 579 | 3.890625 | 4 | # compute the sum of squares of the first n natural numbers
def sqsum(n):
if n < 1:
return 0
def iter(cur, acc):
if cur == 0:
return acc
else:
return iter(cur - 1, acc + cur**2)
return iter(n, 0)
# compute the square of the sum of the first n natural numbers
... |
5cb0ed9991399a5b63294be53f305e6aa21b037f | qiuyunzhao/python_basis | /g_if语句/g0_if语句.py | 1,915 | 4.0625 | 4 | # 代码块
# 代码块中保存着一组代码,同一个代码块中的代码,要么都执行要么都不执行,代码块就是一种为代码分组的机制
# 代码块语句就不能紧随在:后边,而是要写在下一行
# 代码块以缩进开始,直到代码恢复到之前的缩进级别时结束
#
# 缩进有两种方式,一种是使用tab键,一种是使用空格(四个) Python的官方文档中推荐我们使用空格来缩进
# Python代码中使用的缩进方式必须统一 否则 "translate_tabs_to_spaces": true,
# 单行
num = 11
if num > 20: print('num比10大!')
print('不受if控制')
# 多行代码块
if nu... |
12f59801d2533eb8e9736003f5ab721a438ce02d | Tapan-24/python | /longest_word_string.py | 220 | 3.984375 | 4 | str = input("Insert Different String: ")
first = str.split()
len_str = len(first)
longest = 0
for i in range(len_str-1):
if len(first[longest])< len(first[i]):
longest = i
print(first[longest])
|
50a13f82d5c1bb6d1e13286bef3525446a5c2cc7 | Raymond0620/Interview | /算法笔试/腾讯3/1.py | 599 | 3.515625 | 4 | '''
@Descripttion: 柠檬的选择
@Author: daxiong
@Date: 2019-09-20 20:38:01
@LastEditors: daxiong
@LastEditTime: 2019-09-20 20:53:07
'''
s = input().strip().split()
n, m = int(s[0]), int(s[1])
lemonA = [int(x) for x in input().strip().split()]
lemonB = [int(x) for x in input().strip().split()]
lemonA.sort()
lemonB.sort()
a,... |
169e31885d91ae9d9f1a5ad28d500a0b4c225548 | slobodaPolina/ML_Lab2 | /_gradient_descent.py | 5,286 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from metrics import NRMSE
from parameters import gradient_descent as parameters
import prepare_data
# случайным образом делим наши данные на тернировочные и часть для кросс-валидации. k - какую (1/k) часть отделить
def cross_validati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.