blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
291d09272a542e9b24fab373d154466f9d1b0c30 | shreeji0312/learning-python | /python-Bootcamp/assignment4/assignment4notes/functionEx2.py | 1,611 | 4.84375 | 5 | # WPCC
# functionEx2.py
# When we call some Python standard functions, it gives us back
# a value that we can assign to a variable and use later in our programs.
# For example:
import random
randomNumber = random.randint(0, 10)
# This function will return the value it generates so we can assign its
# value to `rand... |
151bbbd0b691acd494d84f4f5c5968a4699b3ed1 | mahimrocky/NumerialMathMetics | /runge_kutta_fourth_order.py | 515 | 3.734375 | 4 | import math
import parser
formula = str(input("Enter the equation:\n"))
code = parser.expr(formula).compile()
def f(x,y):
return eval(code)
print("Enter the value of x0:\n")
x0=float(input())
print("Enter the value of yo:\n")
y0=float(input())
print("Enter the value of h:\n")
h=float(input())
k1=round(float(h*... |
66244ffaa12f9a0e056c3da3477ef771f9f7523a | luwinher/Python_Practice | /Day1_15/main.py | 352 | 3.828125 | 4 | import module1 as m
if __name__ == "__main__":
num = int(input("Please input a number: "))
if m.is_palindrome(num) and m.is_prime(num):
print("%d is a palindrome and prime number."% num)
a = int(input("Please input 2 number: "))
b = int(input())
print("%d and %d gcd is %d, lcm is %d." % (a,... |
bc64977973a02300fc179ad7e9d1a38e90aeb1f4 | leandroS08/SME0602_Projeto1 | /newton.py | 527 | 4 | 4 | # Calculo Numerico (SME0602) - Projeto Pratico 1 - Metodo de Newton
# Alunos: Leandro Silva, Marianna Karenina, Marilene Garcia
import math
import numpy as np
def newton( f, x0, e ):
x = []
x.append(x0)
x_now = x0 - f(x0)/f_der(f,x0)
x_previous = x0
while abs(x_now - x_previous) > e:
... |
2d9a58c322d52353857e3032e6a99c1f28fb49bb | buming65/LeetCode | /剑指offer/leetcode/editor/cn/[面试题58 - II]左旋转字符串.py | 742 | 3.703125 | 4 | # 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数
# 将返回左旋转两位得到的结果"cdefgab"。
#
#
#
# 示例 1:
#
# 输入: s = "abcdefg", k = 2
# 输出: "cdefgab"
#
#
# 示例 2:
#
# 输入: s = "lrloseumgh", k = 6
# 输出: "umghlrlose"
#
#
#
#
# 限制:
#
#
# 1 <= k < s.length <= 10000
#
# Related ... |
e1771aa360ab52c754c04b0b267830bb2fae580f | kovasa/academy | /Lesson I/ex07.py | 387 | 3.546875 | 4 | def merge_dicts(dict1, dict2):
new_dict = {}
new_dict.update(dict1)
new_dict.update(dict2)
return new_dict
def test1_7():
print(merge_dicts({1: 'one', 2: 'two', 3: 'three'},
{4: 'four', 5: 'five'}))
print(merge_dicts({1: 'one', 2: 'two', 3: 'three'},
... |
33af18bf1f21c3fc2769c772031d2f612dae8298 | mehulchopradev/muhammad-python | /com/abc/college/college_user.py | 808 | 3.78125 | 4 | # generalize code in this parent class
# super class
# parent class
# CollegeUser -> object : Single Inheritance
class CollegeUser(object): # every class in python implicitly inherits from the object class
def __init__(self, name, gender):
# self - (5006 Student object)
# self - (5004 Professor obj... |
894083cec80f728ca38a463aa5ce48967c69529e | Aasthaengg/IBMdataset | /Python_codes/p03252/s313883542.py | 231 | 3.5 | 4 | s = input().rstrip()
t = input().rstrip()
m = dict()
for a, b in zip(s, t):
if a in m and b != m[a]:
print('No')
exit()
m[a] = b
if len(m) == len(set(m.values())):
print('Yes')
else:
print('No')
|
d737f0c70363695a1b64a24d7da8224134115f4c | TongLing916/alien_invasion | /settings.py | 1,653 | 3.515625 | 4 | class Settings():
""" a class to store all settings"""
def __init__(self):
"""initialize settings for the game"""
# settings for screen
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# settings for ship
self.ship_speed_... |
db34643b2992f0108a07b2d66f52c2072d317ad1 | Stonewang123/AlienInvasion | /bullet.py | 747 | 3.53125 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, screen, ai_settings, ship):
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.get_bullet_width(), ai_settings.get_bullet_height())
self.r... |
27ec6d51c19cacc5d401fbb61997e40ba90382ca | yordan-marinov/fundamentals_python | /text_processing/replace_repeating_chars.py | 346 | 4 | 4 | string = input()
print(
"".join(
[
symbol
for index, symbol in enumerate(string)
if index == 0 or symbol != string[index - 1]
]
)
)
# result = ""
# for index, letter in enumerate(string):
# if index == 0 or letter != string[index - 1]:
# result +=... |
aef46e63006f735b0f9557f41c00e7e2a0117328 | Hamng/hamnguyen-sources | /python/set_intersection.py | 1,918 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 21:03:24 2019
@author: Ham
HackerRanch Challenge: Set .intersection() Operation
Task
The students of District College have subscriptions to English and French newspapers.
Some students have subscribed only to English,
some have subscribed to only French
a... |
6a1094763daefbe916a5b85faa0b40dc12594b18 | AnujBalu/Matplotlib_Notes | /Ls_7_legend.py | 634 | 4.0625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,5,10)
y = x**3
fig,axes = plt.subplots(figsize=(12,3),dpi=100)
axes.plot(x,y,'b',label='x&y') # 'label=' function will be plotted in graph using legend() method
axes.legend() # this legend method will locate the label automatically in... |
1f38ebbfacbe2e03f75ebb3aa98df7b1187bf727 | Mayankjh/Python_tkinter_initials | /canvas.py | 268 | 3.625 | 4 | #canvas
from tkinter import*
root = Tk()
canvas = Canvas(root,width=300,height=300)
canvas.pack()
def createrect(x1,y1,x2,y2):
canvas.create_rectangle(x1,y1,x2,y2,fill="#453423")
createrect(5,50,200,70)
createrect(5,5,40,200)
root.mainloop()
|
269f54e5e5c121b6cca18cdacfbe023dfa49fec7 | samwilliamsjebaraj/networkautomation | /PythonCode/lambda_functions.py | 511 | 4.21875 | 4 | """
File:lambda_functions.py
Shows the map(),filter(),reduce() function operations using lambda
"""
my_list=range(1,101)
#using map() on lambda
print map((lambda x:x%2==0),my_list)
print map((lambda x:x%2!=0),my_list)
#using filter() on lambda
print filter((lambda x:x%2==0),my_list)
print filter((lambda x:x%2!=0),my_l... |
a0bdcdf7f81947125b1db6c259fc5ecc8622079c | ahmednofal/DSP_Project | /steganography.py | 4,683 | 3.671875 | 4 | # This files contains the implementation of the Steganography effect using Phase coding
# The source for the theory of the implementation will be in the external sources file.
# What TO DO :
# According to the source:
# 1- Get audio file( supposed to be created using the audio morphing techniques)
# 2- Convert audio f... |
84645b7abedb4075451bf6bbfaf536bb6e41c84b | peelstnac/Employee-Management-System | /parsing.py | 10,335 | 3.625 | 4 | """
File containing relevant REPL/AST classes and methods.
"""
from typing import List, Any, Optional
import graph
def remove_whitespace(s: str) -> str:
"""
Remove whitespace from a string.
>>> s = ' this is a string with whitespace '
>>> remove_whitespace(s) == 'thisisastringwithwhitespace'
True... |
bd051c385037c91db25f3560462a10f190f64096 | harrytsz/JianZhiOffer | /SourceCode/面试题51:数组中重复的数字3.py | 736 | 3.90625 | 4 | #数组中重复的数字 Edition3
# in []
def duplicate(numbers, length, duplication):
if numbers == None or length <= 0:
return False
for item in numbers:
if item < 0 or item > length - 1:
return False
container = []
for i in range(length):
if numbers[i] in containe... |
a33460b7c4d575a7bc09d59bda1c9a75111ed3ae | TheBillusBillus/snek | /taking inputs.py | 631 | 4.375 | 4 | #how to take different types of inputs
#strings
#intigers
#and floats
print("*******************************")
print("welcome to my example program")
print("*******************************")
#used input function to take input
name = input("what is your name? ")
print ("welcome",name)
age = input("how old are you? ")#al... |
a145fd47a8b0dab28b442d2b60f6b058791c64b9 | KistVictor/exercicios | /exercicios de python/Mundo Python/011.py | 229 | 3.796875 | 4 | altura = float(input('Qual a altura da parede? '))
largura = float(input('Qual a largura da parede? '))
area = altura*largura
litros = area/2
print('A área da parede é {}\nPrecisa-se de {} litros de tinta'.format(area, litros)) |
1a731280980c7ca76e12e0629aec4e7b30717ebb | Wanghongkua/Leetcode-Python | /Archive/283_Move_Zeroes.py | 1,697 | 3.609375 | 4 | from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
using array rotation in reversed method
"""
# def reverse(nums):
# start = 0
# end = len(nums) - 1
# while end > start:
# nums[end], n... |
f772614e8bc44d07ac8c2d4de38fb16302275776 | skypea/pgmpy | /pgmpy/utils/state_name.py | 7,418 | 3.828125 | 4 | """
The file contains decorators to manage the user defined
variable state names. It maps the internal representaion
of the varibale states to the user defined state names and
vice versa.
"""
class StateNameInit():
"""
The class behaves as a decorator for __init__ methods.
It adds a dictionary as an attri... |
9b15b9a71a2f7eb1e40993d24aeaa1ebe3617564 | the-deep/DEEPL | /helpers/data_structures.py | 3,185 | 3.8125 | 4 | """
Collection of data structures
"""
class TrieNode:
def __init__(self, val):
self.value = val
self.children = {}
class Trie:
def __init__(self):
self.root = TrieNode(None)
self.items_count = 0
def insert(self, iterable, value=None, parent=None):
if len(iterable... |
7b63a4114ee68205d25f79700ae4107544137c11 | SethDeVries/My-Project-Euler | /Python/Problem007.py | 296 | 3.90625 | 4 | # Maximum value of the prime
n = int(input("What number should I go up to? "))
# The prime
p = 2
# The number of the prime
x = 0
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
x +=1
print ("#", x, "->",100 p),
print ("Done")
|
61b67a543f0341e8f079f1e570901425d078fd5c | JoaoVarela1/Jo-oV | /Aula.py | 482 | 3.65625 | 4 |
País=["Brasil","Holanda","Espanha","França"]
print(País)
del País[1]
print(País)
País.append("Argentina")
print(País)
País.remove("Brasil")
print(País)
País.sort()
print(País)
País=["Brasil","Holanda","Espanha","França"]
País2=sorted(País)
print(País)
print(País2)
País=["Brasil","Holanda","... |
d6a8ebafc2c9f212147ac84bec4bc9da0c9f76fd | Cruzader20/ProjectEuler | /problem10.py | 683 | 3.671875 | 4 | """
rasul silva
Project Euler
problem 10
"""
def is_prime(num):
if num == 0 or num == 1: return False
if num % 2 == 0: return False
for value in range(2,int(num**.5) + 1):
if num % value == 0:
return False
return True
def generate_prime_list(range_top):
primes = [... |
421b8376457f9d86e3315f6d4fa6337cd3dbe41c | arya-pv/pythonjuly2021 | /flow_of_controls/conditional_statements/if_else.py | 218 | 4.1875 | 4 | #..if..else..
# a=int(input("enter the number"))
# if a>0:
# print("hi")
# else:
# print("hello")
a=int(input("enter the number"))
if a>0:
print("number is positive")
else:
print("number is negative") |
a4a27faec0a3389a1c8d974dcff05de86ad07d9e | JonNData/Python-Skills | /fundamentals/sumdiff.py | 910 | 3.546875 | 4 | import random
"""
find all a, b, c, d in q such that
f(a) + f(b) = f(c) - f(d)
"""
#q = set(range(1, 10))
q = set(range(1, 200))
# q = (1, 3, 4, 7, 12)
def f(x):
return x * 4 + 6
# Your code here
matches = []
# nest for loops for every combination of a and b,
# them pick c and d to match?
... |
07ea7521b9a3e4569bed9a8d58f0caa0d45469f1 | Dynamitelaw/UDC7pAPxtknuBxa8 | /StockSelectionInterface.py | 2,084 | 4.34375 | 4 | '''
Dynamitelaw
Standard interface for selecting stocks to buy and sell.
All selectors MUST be compatible with the methods included in this class.
'''
from abc import ABC,abstractmethod
class stockSelector(ABC):
def __init__ (self, genericParams=[]):
'''
selecetorName must be a ... |
ba8cfaca435b6ea8d9243f3709d6cbee741c5843 | 562350782/simple | /ex/ex1_improve.py | 2,000 | 3.578125 | 4 | import IterativeSolution
import Initialization
import numpy as np
"长度为1m,横截面积为0.01m2的圆柱型金属棒,一端横截面露出,其余部分被厚的绝热橡胶层包裹。金属棒表面均匀缠绕着热电阻丝,热电阻丝的发热总功率为20W"
"将横截面露出的一端放入100℃沸腾的水池中,已知该金属材料的导热系数平均为 5w/mk,放置很长时间后求解金属棒的温度分布"
"------------------------------------------Initialization-----------------------------------------------------... |
f95aed5af52e68d1c22fa3bd6a6be75f5ce90fca | jjbskir/AirPollutants | /src/Validation.py | 4,012 | 3.53125 | 4 | from PyQt4 import QtGui
'''
Used for validating user inputs.
'''
class Validation:
# string containing the error.
errors = []
'''
Called when ever a error is made. Adds the error message to a list.
@param msg: Error message. string
@return: False, indicating a error occured. boolean
... |
e3a5c2ccbc3ca341d447be4f9b3024abdb4bc2d4 | shivBshah/programming_practice | /Data Structures/SimplifyPath/solution.py | 423 | 3.75 | 4 | #use of stack
def simplifyPath(path):
directories = []
string_array = path.split("/")
for s in string_array:
if s != "" and s!= ".":
if s == "..":
if len(directories) != 0:
directories.pop()
else:
directories.append(s)
return "/" + ... |
397bec61e5f6651b8d597ce7926b2488dc0ab0a0 | Burbon13/Python | /Tidor/aha.py | 570 | 3.625 | 4 | dimensiune=int(input("Dati numar:"))
def backRec(x, dim):
el = -1
x.append(el)
while (len(x) <= dim):
x[-1] = el
if consistent(x, dim):
#if solution(x, dim):
if(len(x) == dim):
print(x)
backRec(x, dim)
el = 1
def consistent(x,dim):... |
d6741cfdeebeee96bc7d03117382e5076b58a125 | VitaliiStorozh/Python_marathon_git | /4_sprint/Tasks/s4.3.py | 1,277 | 3.90625 | 4 | # Create a class Employee that will take a full name as argument, as well as a set of none, one or more keywords.
#
# Each instance should have a name and a lastname attributes plus one more attribute for each of the keywords, if any.
#
# Examples:
# john = Employee("John Doe")
# mary = Employee("Mary Major", salary=12... |
7537a805dac383dbe95f87e84cd3688cefd1a66e | ArthurChaigneau/dqn | /GroupOfBirds.py | 1,597 | 3.953125 | 4 | from random import choice
from Bird import Bird
class GroupOfBirds:
"""
Créer une ligne d'oiseau (obstacles)
Le principe c'est que aléatoirement on va choisir un trou sur la hauteur de l'écran, on remplit la ligne verticale
d'oiseau sauf au niveau du trou
"""
LENGTH_HOLE = 180
HEIGHT_BIRD... |
c1642f83650cf678037c8c50354174b85c5025cc | chudsonwr/python-examples | /4/example4.py | 893 | 4.40625 | 4 | # Ask the user which value they want to work out, distance covered or speed requireed.
choice = input('To work out (D)istance enter \'d\'\nTo work out (S)peed enter \'s\'\n')
# declare the variables but give them a null value, so that they can be operated on
speed = None
distance = None
# Get the input for either d... |
7a4da3886f56b2b151ffb84c25e5aba51fe99835 | uhcho2020/uhcho2020 | /[2021-10] 3rd/1676.py | 193 | 3.640625 | 4 | from math import factorial
N = int(input())
fac_n = factorial(N)
fac_n = str(fac_n)
count = 0
for i in reversed(fac_n):
if i == '0':
count += 1
else:
break
print(count) |
7025d619e8c67eabce9e44137eac20d54296c016 | Herasymov/GoIT_solutions | /lesson9.2/third.py | 639 | 3.984375 | 4 | # class Node of binary tree
class Node:
def __init__(self, val, l=None, r=None):
self.val = val
self.left = l
self.right = r
def insertToNode(root, val):
if not root: return Node(val)
elif root.val <= val:
root.right = insertToNode(root.right, val)
else:
root.le... |
2ae1b6abb86bd7f9d2739411abea16c37b3d8be0 | chenshl/py_study_demo | /Study_kaifaban/py_mofacanshu.py | 704 | 3.8125 | 4 | #!/usr/bin/python
# coding:utf-8
# @author : csl
# @date : 2018/04/22 22:24
# 魔法参数*args和**kwargs的用法
# *args可以捕获到所有的位置参数(非keyword参数);**kwargs可以捕获到所有的keywords参数
def args(f_arg, *args):
print("first normal arg:", f_arg)
for arg in args:
print("another arg through *args:", arg)
alist = [1, 'python1', 'h... |
1a8d108c1885a35f5c29e2ceeb6cd4ca993806dc | rogue0137/practice | /leetcode_python/easy/SOLVED-subtract-the-product-and-sum-of-digits-of-an-integer.py | 783 | 3.765625 | 4 | # 1281. Subtract the Product and Sum of Digits of an Integer
# https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution:
def subtractProductAndSum(self, n: int) -> int:
n_as_list = [int(x) for x in str(n)]
prod_of_digits = 1
for i in range(len(n_as_... |
85c7ab782e9a7fd2022f00760f51f972fa9e2c1a | MohdMazher23/PythonAssingment | /Day5/Max_list.py | 413 | 4.3125 | 4 |
def max_list(list_value):
"""It is a funtion to find the highest value present in list"""
value=max(list_value)
print("THE MAXIMUM NO PRESENT IN LIST IS:" ,value)
#creation a list and assinging values to id
list_value=[90,40,50,60,77,98,43]
#calling list funtion
print(list_value)
max_list(list_val... |
54fc2596708ebd8eea0d095942dd237cdf8e2538 | amit8810/Python-programs | /python program 01/mygrade_marks.py | 457 | 4.125 | 4 | marks=int(input("enter the marks"))
if(marks>=90 and marks<=100):
print(" grade is excellent")
elif(marks>=80 and marks<=90):
print("grade is A")
elif(marks>=70 and marks<=80):
print("grade is B")
elif(marks>=60 and marks<=70):
print("grade is C")
elif(marks>=50 and marks... |
867b63a1084ecd32ac1d89e7b43d39913f579b4d | GGGGGarfield/Python_Study | /Python基础教程/Python训练营资料/Python基础训练营代码/01_basic/12-if_statement.py | 2,039 | 3.515625 | 4 | # coding: utf-8
# True/False
# a = True
# b = False
# print type(a)
# print type(b)
# if False:
# print 'success'
# else:
# print 'fail'
# print 'finished'
# a = 1
# b = 2
# if a == b:
# print 'equal'
# else:
# print 'not equal'
# username = raw_input(u'请输入用户名:'.encode('gbk'))
# if username == 'zhiliao':
# ... |
d99085fb2cf4a4b7afbf736a2adea972f55fb7a5 | Coderode/Python | /OOPS/init method.py | 560 | 4.03125 | 4 | #The __init__method
#it is similar to constructors in c++
#it is run as soon as an object of a class is instantiated
#useful to do any initialization you want to do with your object
class Person:
#init method or constructor
def __init__(self,name='None'): #using bydefault name as none if not given during calling the... |
ea52e733e178170c254812aefe3acd81d33f4f25 | AswiniSankar/OB-Python-Training | /Assignments/Day-2/p8.py | 198 | 4.3125 | 4 | # program to print the number of occurence of sub string in the given string
mainstring = input("enter the main string")
substring = input("enter the sub string")
print(mainstring.count(substring))
|
5f7e810f56fb142f6d1ad68799dc8d4ef294785c | haripriya2703/KNN_Using_SmallWorldGraphs | /KNN_Classifier.py | 1,155 | 3.71875 | 4 | from KNN_Search import knn_search
def knn_classifier(knn_graph, distance_metric, d, m, k):
"""
:param knn_graph: existing graph
:param distance_metric: metric using which the nearest neighbors should be determined
:param d: new data point
:param m: number of searches to be performed
:param k: ... |
9e323728bba4374af6847d857bd3ce9a01f5f703 | lillapulay/python-foundations | /return.py | 621 | 4.34375 | 4 | # Takes an integer and prints out its square
# x = int(input("x: "))
# print(x * x)
# Defining a function
# Takes an input called n
# In Python, we need to define the function prior to calling it, otherwise we get an error
# It reads from top to bottom
# def square(n):
# return n * n
# Using this function we can sim... |
87d53a3994f920ecb42f3a24b00b38fc7d1755c0 | sumanth0892/Basic-Data-structures | /graphs.py | 4,173 | 3.953125 | 4 | import sys,heapq
class Vertex:
def __init__(self,n):
#Each vertex will have a few characteristics
self.name = n
self.color = 'Black'
self.previous = None #Set previous vertex to be none for now
self.neighbours = {}
self.distance = sys.maxsize
def addNeighbour(self,v,weight):
#Use this to add an edge t... |
154b92734fbf9f37cb90712f7f9d023296862654 | MachineDragon/ReplaceVowelsWithG | /ReplaceVowelsWithg.py | 271 | 3.921875 | 4 | # function replaces vowels with the letter "g"
def translate(phrase):
new_word = ""
for i in phrase:
if i in "AEIOUaeiou":
new_word += "g"
else:
new_word += i
return new_word
print(translate(input("enter a word: ")))
|
e7fd8aac55abd77ea96f67aaa59b689b9c7f4570 | theovoss/BoggleSolver | /bogglesolver/load_english_dictionary.py | 3,734 | 4.1875 | 4 | #!/usr/bin/env python
"""Stores the dictionary in a linked list."""
from bogglesolver.twl06 import WORD_LIST
from bogglesolver.twl06 import TEST_WORD_LIST
class _dictnode:
"""
An element of the dictionary.
Each element represents one letter in a word.
Each element contains an array of potential n... |
b8126cc93c76ed9206f18e443f6ee9f6d488fb3a | gustavogattino/Curso-em-Video-Python | /Mundo 2 - Basico/Aula12/aula12_desafio03.py | 272 | 4.0625 | 4 | """Aula 12 - Desafio 03."""
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
if n1 > n2:
print('{} é maior que {}!'.format(n1, n2))
elif n2 > n1:
print('{} é maior que {}!'.format(n2, n1))
else:
print('Os valores são iguais.')
|
dd8164197b3e8f93784d0daa4f0050da614cd49c | tthtlc/turtle-graphics-explorer | /src/ellipse.py | 427 | 3.640625 | 4 |
import math
import turtle
wn = turtle.Screen()
wn.bgcolor('lightblue')
PI=3.14
fred = turtle.Turtle()
fred.speed(99999)
fred.penup()
steps=2*PI/360
R1=100
R2=50
i=0
angle=0
alpha=2*PI/8
beta=2*PI/8
while i < 360:
y1 = R1*math.sin(angle+alpha)####+R1*math.sin(angle+beta)
x1 = R2*math.cos(angle)####+R2*math.co... |
a5cae9c3d4ae4d7d5f1aa4daa1ef837a64387fcc | emanoelmlsilva/Lista-IP | /exercicio03/exercicio15.py | 377 | 3.578125 | 4 | valor_reais = int(input('Valor em reais: '))
c = 100
l = 50
x = 10
v = 5
i = 1
resC = valor_reais/c
valor_reais = valor_reais%c
resL = valor_reais/l
valor_reais = valor_reais%l
resX = valor_reais/x
valor_reais = valor_reais%x
resV = valor_reais/v
resI = valor_reais%v
print('A quantidade de notas de 100 é %d, 50 é %d, 1... |
f0d96cbd6c2b0a090a9089c9794db74c885d4f89 | gustavowl/Algorithms-Cormen | /Chapter07/quick_sort_recursive.py | 1,990 | 4.3125 | 4 | #The user will type a list separated by the character "space". The list will be stored in lst
lst = [int(num) for num in input("Type the list. Elements are separated by space\n").split()]
#prints the original list
#print("The original list is: {}".format(lst))
#starts quick sort
#print("\nQUICK SORT BEGIN\n")
#the ef... |
1eec2a5f0dd4cf98a1fa827813deaed9ee7af79f | abhinav-bapat/PythonPrac | /for_loop_example1.py | 221 | 4.03125 | 4 | # Write a program to add all the numbers of a list and print the result
list1 =[10, 20, 30, 40, 50]
sum = 0
for x in list1:
sum = sum + x
print(sum)
|
f9d131e93d0e1b0af2cd424d67c55aa5169c1959 | manchenkoff/geekbrains-python-homework | /lesson04/task07.py | 804 | 4.125 | 4 | """
Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор.
Функция должна вызываться следующим образом: for el in fact(n).
Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 ... |
09054d28a59ecf6b845607b54c808909c884c6b7 | Praharshinibujji/pythonprogrammer | /130.py | 141 | 3.921875 | 4 | num=int(raw_input())
reverse=0
while(num>0):
remainder=num%10
reverse=reverse*10+remainder
num=num//10
print reverse
|
e2577867074094d2550050e9d1a6612751eeace7 | inaph/30DaysOfPython-inaph | /Day_03/Excercise03.py | 1,624 | 4.03125 | 4 | #age = 29
#height = 5.65
#cmplx = 1+5j
#print(type(age))
#print(type(height))
#print(type(cmplx))
#base = int(input("Enter base: "))
#height = int(input("Enter height: "))
#area = print ("The area of triangle " , 0.5 * base * height)
#side_a = int(input(" Enter side a: "))
#side_b = int(input(" Enter side b: "))
#si... |
ccf52c76638ac9197b48e3e61487fca7c11058ea | robertopc/urioj | /beginner/1001.py | 155 | 3.5 | 4 | #!/usr/bin/python3
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1001
A = int(input())
B = int(input())
X = A + B
print("X = {}".format(X))
|
74bbdd40c28ec27140de7fd44fdfb250d9e7957d | JasonSun/Misc | /Codeforces/61A.py | 334 | 3.609375 | 4 | r = ''
# zip() built-in function
# Using * operator to unzip
for a, b in zip(raw_input(), raw_input()):
if a != b:
r += '1'
else:
r += '0'
print r
'''
s1 = raw_input()
s2 = raw_input()
s3 = ''
for i in xrange(len(s1)):
if s1[i] != s2[i]:
s3 = s3 + '1'
else:
s3 = s3 + '0'... |
78cb7717811704b6f9e4c2c755dce601ac5de4b2 | Markers/algorithm-problem-solving | /BLOCKGAME/cjm9236_BLOCKGAME.py | 3,580 | 3.5625 | 4 | # BLOCKGAME problem
# Author: JeongminCha (cjm9236@me.com)
cache = None
strategy = []
L_block = [
[[0,0],[1,0],[1,1]],
[[0,0],[0,1],[1,1]],
[[0,0],[0,1],[-1,1]],
[[0,0],[1,0],[0,1]]
]
I_block = [
[[0,0],[1,0]],
[[0,0],[0,1]]
]
def initial_setting():
global strategy
for row in range(5)... |
b65be1e6a9e4d24d460dcc9853019132bdb1f488 | adamhammes/advent-of-code | /aoc_2021/lib.py | 2,181 | 3.703125 | 4 | import itertools
import math
import typing
from typing import Iterable
T = typing.TypeVar("T")
def get_input(day: int) -> str:
with open(f"inputs/day{day:02}.txt") as f:
return f.read()
def product(nums: Iterable[int]) -> int:
p = 1
for n in nums:
p *= n
return p
def window(seq:... |
afa43e5492fab06a11935abedb24281ca8d0fedc | clementnduonyi/snbank | /back_site.py | 4,120 | 3.8125 | 4 | import json
import os
import random
header= '-----Welcome to SNBANK Platform-----'
print(header.upper())
def login_algorithm():
signed_in = False
while True:
try:
login_action = input(str('Enter "login" to sign in/"close" to close the APP ')).lower()
except ValueError:
... |
380348ed13c79da7bb488e361e79698486131b3f | yegeli/month1 | /day14/skill_system.py | 2,600 | 3.828125 | 4 | """
技能系统
封装:创建了DamageEffect、DizzinessEffect、LowerDeffenseEffect、SkillDeployer
继承:创建了SkillImpactEffect
隔离了SkillDeployer与具体技能影响的变化
多态:SkillDeployer调用SkillImpactEffect的impact方法
DamageEffect、DizzinessEffect、LowerDeffenseEffect重写SkillImpactEffect的impact方法
... |
916ed052ed46238336cbd95773f9f02950200edc | Mayur-Debu/Datastructures | /Linked List/Basic/Exercise_3.py | 1,850 | 4.1875 | 4 | """
Create a method to delete any element from the linked list.
"""
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insertAtEnd(self, data):
if self.head is None:
... |
8810ab4c76e7c1f6a5053ec14b4935679869c91c | AlfonMnz/Python-1DAW-Programacion | /Ejercicios/Ejercicio 33.py | 508 | 3.984375 | 4 | '''Ejercicio 33. Escribe una función en la que le paso 2 puntos y te da la suma vectorial'''
def punto(p1, p2):
puntototal = p1[0] + p2[0], p1[1] + p2[1]
return puntototal
x1 = int(input('introduce la coordenada x del primer punto:\n'))
y1 = int(input('introduce la coordenada y del primer punto:\n'))
x2 = i... |
8ce37eadb03625a88363fbfe5d65dd08914af577 | rafacab1/1daw-python-prog | /Primer Trimestre/04 Funciones/Ejercicios 20 a 28 (p. 148)/9_rota_izquierda_array_int.py | 720 | 3.875 | 4 | # -*- coding: utf-8 -*-
from funciones.funciones2028 import *
# Comprobación de 9_rota_izquierda_array_int
print("Rota n posiciones a la izquierda los números de un array.")
print("\nPrimero vamos a crear un array con enteros aleatorios...")
n = int(input("Introduce la longitud del array: "))
minimo = int(input("Int... |
fdacb09e75b7b22ddf02d35ca1d9b84a6f49d167 | roysegal11/Python | /Objct_exs/Bus.py | 905 | 3.5625 | 4 | class Bus():
def __init__(self, size):
self.size = size
self.num_of_passengers = 0
self.seats = ['free' for i in range(self.size)]
def getOn(self, name):
for i in range(self.size):
if self.seats[i] == 'free':
self.seats[i] = name
self.... |
e6674bb5edadfbf78bb42f4e631f7d5d300a2806 | meera-ramesh19/codewars | /homework/power-of-three.py | 390 | 4.25 | 4 | # This is my solution for AlgoDaily problem Power of Three
# Located at https://algodaily.com/challenges/power-of-three
def power_of_three(num):
# fill in
while(num>1):
if(num%3==0):
num=num//3;
return True;
else:
break;
return False;
value=power_of_three(49)... |
51d447028f6aff329b4cbe758ec9c5923842f4a7 | rafaelperazzo/programacao-web | /moodledata/vpl_data/27/usersdata/109/8514/submittedfiles/divisores.py | 303 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
n=input('Digite o valor de n:')
a=input('Digite o valor de a:')
b=input('Digite o valor de b:')
cont=0
x=1
while True:
if (x%a)==0 or (x%b)==0:
print x
cont=cont+1
when cont==n:
break
x=x+1 |
8d5a61ddc62e0137254d7fe11f3307c38be85883 | Tobias-rv/skole | /Python/Lab2/Oppgave4.py | 234 | 3.8125 | 4 | import math
x = input("Skriv inn et tall:\n")
y = input("Skriv inn enda et tall:\n")
z = x + y
y = y + x
z = float(z)
y = float(y)
w = z * y
w = math.sqrt(w)
w = round(w, 2)
print("Kvadrat roten av", y, "*", z, "=", w)
|
397fbcb970ee86e10326d3c9c0db1e57e6a611dd | shivaconceptsolution/PYTHON-12-01-Batch-Palasia | /pytraining/LoopExampleWithIfElse.py | 189 | 4.03125 | 4 | num = int(input("enter mobile number"))
for i in range(1,11):
a=num%10
num=num//10
if a%2!=0:
print("square is ",a*a)
print("cube is ",a*a*a)
|
5b4d656434311a73a5e34553c9e9588f4c8c88aa | JoshFowlkes/Sorting | /src/recursive_sorting/recursive_sorting.py | 2,571 | 4.0625 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [None] * elements
a = 0
b = 0
for i in range(0, elements):
if a >= len(arrA):
merged_arr[i] = arrB[b]
b += 1
elif b ... |
83d2e85f1ccb46fb500e7848df0955e86d195cf4 | djiang3/Battleship_Game | /Battleship.py | 5,569 | 3.8125 | 4 | #
#Darrel Jiang
#Professor Clair
#CSCI 150 MTWF(9:00-9:50am)
#
#The main Battleship class. Initializes the game.
#
#
from Board import *
from Player import *
from GraphicsManager import *
class Battleship():
def __init__(self):
"""Creates a game of Battleship with either a human vs. human, human vs. computer, or... |
4506eca9b3b0caf2fb82f305e4e2049e85115ecb | smsxgz/euler_project | /problems/problems@201~700/problem_356/Largest_roots_of_cubic_polynomials.py | 754 | 3.53125 | 4 | mod = 10**8
K = 987654321
def matrix_mul(A, B):
C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
for j in range(3):
for k in range(3):
C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod
return C
def matrix_pow(A, k):
R = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
wh... |
3de6e3fa81cc12b31bc0bc51897a8202bc703a90 | LeoVilelaRibeiro/opfpython | /opf.py | 2,786 | 4.15625 | 4 | # DEFINICOES DE CLASSES
class Noh:
"""
Esta classe define o Nó de um grafo
É instanciado com um identificador (String) e a classe pertencente
"""
def __init__(self, no_id, classe):
self.no_id = no_id
self.classe = classe
self.dono = None
self.distancia = 0
s... |
cd52262c9fe8c8690741b41dff4c1eac9fd5e2ac | jeongyongwon/Algo_Coding | /swexpert/모음이보이지않는사람.py | 312 | 3.625 | 4 | import sys
sys.stdin = open( '모음이보이지않는사람.txt' , 'r')
T = int(input())
for t in range(T):
text_ = input()
vowels = ['a','e','i','o','u']
result = ''
for i in range(len(text_)):
if text_[i] not in vowels :
result += text_[i]
print(f'#{t+1} {result}')
|
1dfdcd03126a40b85e831ddd2df529eb91df1fd2 | Gilbert-Gb-Li/Artificial-Intelligence | /f4_func_model/dataset_process/data_split.py | 972 | 3.5625 | 4 | from __future__ import print_function
from sklearn.model_selection import train_test_split
"""=============
数据集切分
================"""
def dataset_split(X, y):
"""
2. 可以调用sklearn里的数据切分函数:
参数:
train_data:被划分的样本特征集
train_target:被划分的样本标签
test_size:如果是浮点数,在0-1之间,表示样本占比;如果... |
431ffdbf919d3e1ed63eb2a61ab926e5dbfe8855 | shoark7/second-accountbook | /apis/help_method.py | 1,399 | 3.59375 | 4 | """
This file defines some helper methods for the project.
It's simple.
"""
from datetime import datetime, date
import os
TODAY = datetime.today()
YEAR = TODAY.year
MONTH = TODAY.month
DAY = TODAY.day
ALL_MONTH_NAMES = [
'January', 'February', 'March',
'April', 'May', 'June',
'July', 'August', 'September... |
ae89cb878ed144d0038a33ad92d4fc0002002e72 | SHE-43/Scraper-First- | /OurFirstScraper.py | 709 | 3.625 | 4 | from urllib.request import urlopen
import requests
r = requests.get("https://xkcd.com/353/")
h = ""
for x in r.iter_lines():
if ".png" in str(x) and "http" in str(x):
h = str(x.decode("utf-8")) # change from bytes to string
link_to_image = h[h.find("http"):] # We've found the link to the ... |
1b54b8acd624d3f48d8bc0dd0e1eea922395dd11 | RAZAKNUR/PYTHON | /queueExercise.py | 603 | 3.71875 | 4 | from collections import deque
class Queue:
def __init__(self):
self.buffer = deque()
def enqueue(self, val):
self.buffer.appendleft(val)
def dequeue(self):
return self.buffer.pop()
def is_empty(self):
return len(self.buffer)==0
def size(self):
return len(self... |
a851104976bf82af835a819c9c3d67fe2fe82c6e | shubhamprkash/Python_Learning | /Day3.2.2_BMI_calv2.0.py | 701 | 4.21875 | 4 |
weight = input("Enter your weight in kgs : ");
height = input("Enter your hight in meters : ");
# My Code
bmi=float(weight)/(float(height)**2);
covBmi=round(bmi,2);
if covBmi < 18.5:
print(f"Your BMI is {covBmi}, You are Underweight!");
elif covBmi >35:
print(f"Your BMI is {covBmi}, You are clinically o... |
ef3a8b2a619f47c71891037e3f80bbbfc7c1708d | refine-P/NLP100Knock | /Mecab/question38.py | 370 | 3.53125 | 4 | #coding:utf-8
import matplotlib.pyplot as plt
if __name__ == "__main__":
freq = []
for line in open("word_freq.txt", "r", encoding='utf-8'):
key, value = line.split(' ')
value = int(value)
freq.append(value)
plt.hist(freq, bins=range(0, 21)) #20回より多く出現する単語は殆ど無いので排除
plt.xlabel("freq")
plt.ylabel("word")
p... |
7cbfee938932f8c114ef68b1a57cd8554eae2d80 | RobotGyal/Generating-Fractals-with-Recursion | /recursion/recursion.pyde | 293 | 3.828125 | 4 | # FRACTAL TREE
# KOSH CURVE
# CANTOR SET
# MANDELBROT SET
def setup():
print("The recursive factorial is: ", factorial(4))
def draw():
pass
def factorial(n):
""" Calls itself to provide recursion """
if n == 1:
return 1
else:
return n * (factorial(n-1))
|
b3e54b137c4da0b4cedbf5cc98f8c813117605aa | banana-galaxy/challenges | /challenge5(ranges)/Stilton.py | 1,115 | 4.03125 | 4 | def erange(*args):
result = []
if len(args) == 1:
stop, start, step = args[0]-1, 0, 1
while start <= stop:
result.append(start)
start += step
elif len(args) == 3:
start, stop, step = args[0], args[1], args[2]
if step == 0:
raise Exception("Step argument needs to be bigger than... |
961e8986559e8a869f905edf4a30fbfe70ca2adf | NathanZorndorf/cheat-sheets | /Python/Dictionary Cheat Sheet.py | 654 | 4.21875 | 4 | #-------------------- DICTIONARIES ---------------------#
#---- Make a dict using keys from a list
d.fromkeys()
# Example :
liquor_dict = {}
liquor_dict.fromkeys(liquor_categories, None)
#---- Get value from key if key in dict
d.get()
#---- Check if a dict has a key
d.has_key()
#---- Returns list of key,value pai... |
1e95f6e6b7b3dcd8ef5a2b1530d994466dd577ea | Petrichorll/learn | /learn/2021/0202/single_cycle_link_list.py | 2,623 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# 单向循环链表
from single_link_list import Node
class SingleLinkList(object): # 单向循环链表
def __init__(self, node=None):
self.__head = node
def is_empty(self): # 链表是否为空
return self.__head is None
def length(self): # 链表的长度
ret = 0
cur = self.__head
... |
28c50d97f9ecd89211f494a20d12eba57a859d92 | PatrickKelly95/Python-Assignment-1 | /database/models.py | 1,765 | 3.671875 | 4 | # Program Name: models
# Purpose: Creates individual tables in database for each statistic
from database.database import db
# Create table based on age statistics
class Age(db.Model):
id = db.Column(db.Integer, primary_key=True)
average_age = db.Column(db.Integer, unique=False)
min_age = db.Column(db.Int... |
b7ca9ed84d64fba692e3ad704aad410f267a33c4 | GraceDurham/hackbright_challenges | /sum_list.py | 243 | 4 | 4 |
def sum_list(lst):
"""Returns the number from summing all the numbers in a list"""
sums = 0
for num in lst:
sums = sums + num
print num,
print sums
return sums
print sum_list([5, 3, 6, 2, 1]) |
7c0bd089b25b06a8ef4e4180e38cea9b58824f9a | AthosFB/Exercicios-Python | /ExercícioDoCurso/067.py | 302 | 3.796875 | 4 | while True:
print()
tabuada = float(input("Qual número da tabuada deseja ver: (Qualquer número negativo para parar) "))
print()
cont = 1
if tabuada < 0:
break
while cont != 11:
print(f"{cont} * {tabuada} = {cont * tabuada:.2f}")
cont += 1
print("Fim")
|
daa8fecbbf492b4e0eafd084572d65d681df1160 | kumastry/atcoder | /arc/014/014a.py | 66 | 3.640625 | 4 | n = int(input())
if(n%2):
print('Red')
else:
print('Blue') |
3fc2ef8a0fba3cfd52c4e87a53d36254ab436d55 | sudhanshu-jha/python | /python3/Python-algorithm/Bits/nextNumber/getNext.py | 894 | 3.515625 | 4 | # Given a positive number, print the next smallest and the next
# largest number that have the same number of 1 bits in their
# binary representation.
def getNext(n):
c = n
# let p denote the position of first non-trailing 0 ie a zero which is followed by 1s
c0 = 0 # number of zeros to right of position ... |
7e6bf30720732ecc92d0b62301b5f262d58d434c | IdiotCirno/MFTI | /Test1/F.py | 605 | 3.703125 | 4 | a = int(input())
b = int(input())
while b != 0:
if a < b:
a, b = b, a
a, b = b, a%b
print(a)
'''
Необходимо найти НОД двух чисел, используя алгоритм Евклида.
Формат входных данных
На вход подаются два натуральных числа, по числу в новой строке.
Формат выходных данных
Одно число - НОД ... |
5d564e1a33f76ffdba4fb1f128b08557a2cb42f1 | yyHaker/PythonStudy | /algorithms/常见面试编程题(剑指offer&leetcode)/动态规划dp/5. 不同路径.py | 715 | 3.546875 | 4 | #!/usr/bin/python
# coding:utf-8
"""
@author: yyhaker
@contact: 572176750@qq.com
@file: 5. 不同路径.py
@time: 2019/8/19 14:52
"""
"""
leetcode62:不同路径
思路:动态规划
"""
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# 思路:动态规划,... |
d4b187f1c9049d1639989587d216bc756b33d577 | dty999/pythonLearnCode | /挑战python/052因子平方和.py | 915 | 3.53125 | 4 | """6 的因子有 1, 2, 3 和 6, 它们的平方和是 1 + 4 + 9 + 36 = 50. 如果 f(N) 代表正整数 N 所有因子的平方和, 那么 f(6) = 50.
现在令 F 代表 f 的求和函数, 亦即 F(N) = f(1) + f(2) + .. + f(N), 显然 F 一开始的 6 个值是: 1, 6, 16, 37, 63 和 113.
那么对于任意给定的整数 N (1 <= N <= 10^8), 输出 F(N) 的值."""
N = 20
l = []
def f(n):
res = []
for i in range(1,int(n/2 +1)+1):
if n... |
e659751cb0fac10d81a80e9fd26f349603c63e0b | joanamucogllava/PythonPrograms | /max_num.py | 300 | 3.984375 | 4 | #This prigram will find the largest number from the given ones.
#Author: Joana Mucogllava
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(20, 50, 40))
|
fda5701524c17f7e4c2b7370df1ab6db485618d5 | roshan-malviya/Strings | /reverse.py | 148 | 3.75 | 4 | # slicing
def reverse(stri):
return arr[::-1]
def reverse0(stri):
b=''
for i in stri:
b=i+b
return b
c=input()
print (reverse0(c))
|
93f4f937c61e2899cb3eba6ba55448630054cc22 | maguedon/codingup | /2017/bug_chemin.py | 2,152 | 3.859375 | 4 | import math
def getCoord(chemin):
direction = "N"
x = 0
y = 0
for char in chemin:
if char == "A":
if direction == "N":
y += 100
if direction == "S":
y -= 100
if direction == "E":
x += 100
if direction == "O":
x -= 100
elif char == "D":
if direction == "N":
direction = "E"
... |
c099538833c3c4113b33299b4f9096a0c1c12778 | f-fathurrahman/ffr-MetodeNumerik | /AkarPersamaan/python3/ridder.py | 1,823 | 3.5 | 4 | from math import sqrt
def ridder(f, x1, x2, TOL=1.0e-9, verbose=False, NiterMax=100):
if verbose:
print("")
print("Searching root with Ridder's method:")
print("Interval = (%18.10f,%18.10f)" % (x1,x2))
print("TOL = %e" % TOL)
print("")
assert TOL >= 0.0
f1 = f(x1)... |
645a2330360db40d5cd7a001acbd002346b5447f | DavidJaimesDesign/MIT-IntroCS | /1-lecture/ps1c.py | 1,175 | 3.90625 | 4 | annual_salary = input("Your yearly salary: ")
total_cost = 1000000.0
portion_down_payment = total_cost/4.0
epsilon = 100
high = 1.0
low = 0
num_steps = 0
guess = (high + low)/2
def amountSaved(guess, salary):
annual_salary = salary
portion_saved = guess
semi_annual_rate = 0.07
months_to_save = 36
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.