blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
be760a2488631c90a135637a524a857ee1bfc7d3 | Divyansh-coder/python_challenge_1 | /area_of_circle.py | 244 | 4.5625 | 5 | #import math to use pi value
import math
#take radius as (real number)input from user
radius = float(input("Enter the radius of the circle: "))
#print area of circle
print("The area of the circle with radius",radius,"is :",math.pi*radius**2)
|
500b16ce9297be218960951f2495366cbda6bff8 | ririro93/algorithm_probs | /Baekjoon/_old_solves/warmup/problem1330/6_problem1330_moon.py | 816 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## 문제
# 두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
# ## 입력
# 첫째 줄에 A와 B가 주어진다. A와 B는 공백 한 칸으로 구분되어져 있다.
# ## 출력
# 첫째 줄에 다음 세 가지 중 하나를 출력한다.
#
# A가 B보다 큰 경우에는 '>'를 출력한다. <br>
# A가 B보다 작은 경우에는 '<'를 출력한다. <br>
# A와 B가 같은 경우에는 '=='를 출력한다. <br>
# ## 예제입력, 예제출력
# 10 5 <br>
# \>
# ... |
cfcb0d29879aa1fd3f716f64d4c07dbb968eddc1 | ririro93/algorithm_probs | /Baekjoon/3rd_week/1927.py | 1,068 | 3.5 | 4 | # from sys import stdin
# stdin = open('input.txt', 'r')
# input = stdin.readline
'''
# 1. deque 사용 -> 시간초과 뜬다(당연히 sorted 때문에ㅎㅎ..)
from collections import deque
## inputs
N = int(input())
cmds = []
for _ in range(N):
cmds.append(int(input()))
## init
deq = deque()
mx = 0
mn = 2 ** 31
## exe
for cmd in cmds:
... |
c7d23817f0517c55bdb6dbd91d90def635592710 | ririro93/algorithm_probs | /Baekjoon/3rd_week/11729_1.py | 256 | 3.9375 | 4 | def move(N, start, to):
print(N, start, to)
def hanoi(N, start, to, via):
if N == 1:
move(1, start, to)
else:
hanoi(N-1, start, via, to)
move(N, start, to)
hanoi(N-1, via, to, start)
hanoi(3, 'A', 'C', 'B') |
8f4ec2029acdb0f94c5081f92c8875475fc2334c | ririro93/algorithm_probs | /Baekjoon/_old_solves/3rd_week/10-10026-color_blind/moon.py | 2,310 | 3.515625 | 4 | from collections import deque
# get inputs
N = int(input(''))
pic = [[*input('')] for _ in range(N)]
# initialization
checked = [[-1]*N for _ in range(N)]
qu = deque()
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
counterRG = 0
counterB = 0
counter = 0
# first: find (R, G), B
for i in range(N):
for j in range(... |
2d813881bb52c18de7f0e16ebb30d00efdcc8873 | ririro93/algorithm_probs | /leetcode/daily_problems/21_Merge_Two_Sorted_Lists.py | 1,113 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# if either has no nodes
if not l1:
return l2
if... |
e6590a1cd81568356bded31cdb40c490418cc351 | ririro93/algorithm_probs | /Baekjoon/_old_solves/1st_week/10951multiplelineaddition_X/hong.py | 672 | 3.609375 | 4 | '''
풀이1
input()은 입력의 끝에서 EOFError을 발생시킨다.
try:
while True:
print(sum(map(int, input().split(' '))))
except EOFError:
pass
풀이2
import sys
for line in sys.stdin:
print(sum(map(int, line.strip().split(' '))))
풀이3
import sys
for line in sys.stdin.readlines():
prin... |
d37bee0f62c49ac7c8c5f723de26f214eef43e7f | zynaxsoft/leetcode-solutions | /2-add-two-numbers_2.py | 1,315 | 3.703125 | 4 | """ https://leetcode.com/problems/add-two-numbers/"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import itertools
def list_generator(node):
yield node
cur_node = node
while cur_node.next:
cur_node = cur_node... |
7a287ab16b4fa019dc5190951f5f6268ae9d6d0b | Mannuel25/Mini-Store-Project | /items_in_file.py | 657 | 4.34375 | 4 | def no_of_items_in_file():
"""
Displays the total number of
items in the file
:return: None
"""
filename = 'myStore.txt'
# open original file to read its contents
open_file = open(filename,'r')
description = open_file.readline()
# make a variable to count the number of items
... |
4d361aaabaa6c9fc8d55a2731f6eb46b039274ef | Paupau18me/Introduction-to-Programming-using-Python-Final-Project | /InterfaceCalcu.py | 3,277 | 3.609375 | 4 |
import tkinter as tk
root = tk.Tk()
txt = tk.StringVar()
txt.set('')
num = tk.StringVar()
cnt = tk.IntVar()
para_div = tk.DoubleVar()
sw = tk.IntVar()
sw.set(0)
print(sw.get())
#1 -> suma
#2 -> resta
#3 -> prod
#4 -> div
def suma():
cnt.set(0)
cnt.set(int(txt.get()))
txt.set('')
sw.set(1)
def resta():... |
6a317714f3107eab6a95cc52182a00dd7f48b18f | CasaDeMill/Fractal2 | /NEWTON.py | 5,806 | 3.71875 | 4 | from scipy import *
from pylab import *
from sympy import *
from numpy import *
"""
Takes two functions containing variables x, y and computes Newton's method.
"""
# allows variables x and y to be inputs
x, y = symbols('x, y', real=True)
class fractal2D:
def __init__(self, f1, f2, f1dx, f1dy, f2dx, f2dy, tol=1.... |
2b01c4404047dabc01cfe471fc55fccba6a49ccf | Severson-Group/eMach | /mach_cad/model_obj/dimensions/dim_base.py | 1,892 | 3.5 | 4 | from abc import abstractmethod, ABC
class DimBase(float, ABC):
@abstractmethod
def _conversion_factor(self):
pass
def __new__(cls, value):
return float.__new__(cls, value)
def __add__(self, other):
add = self._to_dimensionless() + other._to_dimensionless()
return typ... |
1896bde5a75b855c34c9b802cc0ae2a03f559281 | 8bitbeard/flask_finances_api | /src/services/accounts_service.py | 1,668 | 3.578125 | 4 | """
Accounts Service File
"""
import numbers
from src.database import db
from src.models.accounts import Account
from src.models.users import User
from src.exceptions.accounts_exception import AccountNotFound, AccountInvalidName
from src.exceptions.users_exception import UserNotFound
from src.exceptions.balance_exc... |
a9c73e0698b136c184011b01c59262825d340cca | shruthi45/pythonbasics | /ss4.py | 103 | 3.53125 | 4 | value="sherlock"
mylist=['holmes',['hhh',value,46,74],25,2,[723,5,2],6,84,8]
print(mylist.index(2))
|
c907453b7542d7b27cf86d98d2aa185156ce5df4 | KubanLink/Python | /Problem1.py | 745 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 18:05:40 2020
@author: corbinyoung
"""
#User Input; 2(Strings),2(Numbers),(Number+String)
def supertime():
x=input()
noW1=x.strip()
y=input()
noW2=y.strip()
#Bool Input1
A=noW1.isalpha() #IS X==LETRR
#Bool Inpu... |
62f63d88f1ef95dfc07c3afe4f45ec78a3be0ed8 | theKyleL/HR_solutions | /army_game.py | 1,020 | 3.71875 | 4 | """
Hackerrank problem: Army Game
Solution by: Kyle Latino
Problem:
Luke is daydreaming in math class. He has a sheet of graph paper with n rows and m columns,
and he imagines that there is an army base in each cell for a total of n*m bases. He wants
to drop supplies at strategic points on the sheet, marking each dr... |
b9001558aed71f92e7c82c5bdd6834540e52aedc | theKyleL/HR_solutions | /connectingTowns.py | 499 | 3.84375 | 4 | # Hackerrank problem Conecting Towns
# calculate number of possible routes
def findNumRoutes():
numTowns = int(input())
routes = list(map(int, input().split())) # store values as a list of integers
totalRoutes = routes[0]
# find an efficient method for calculating the product of all integers
for... |
bda3e461aed89921d98ac27ec0d940f6e2ff0454 | paskahlisanjas/temporal-database | /allen/allen.py | 1,738 | 3.640625 | 4 | from datetime import datetime
class ValidInterval:
def __init__(self, start, finish):
if isinstance(start, str):
self.start = datetime.strptime(start, '%Y-%m-%d')
else:
self.start = start
if isinstance(finish, str):
self.finish = datetime.strptime(finish... |
0ab5635d7803525281ea3f07f2060dd8450a48fe | chapman-cs510-2016f/cw-08-needcoffee | /juliaPlane.py | 6,382 | 3.78125 | 4 | #!/usr/bin/env python3
import cplane_np as cpnp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numba as nb
class JuliaPlane(cpnp.ComplexPlaneNP):
"""
This module allows the user to create a plane of
complex numbers, which can then be transformed
under the function julia... |
77e208fe723706ee8aa30562d4c17559837b14c6 | mike1334/Team-Tree-House- | /Project 1 - Number_Guessing_Game/Number_guessing_game.py | 1,512 | 3.90625 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
"""
import sys
from random import randint
def play_again():
while True:
try:
play = input("Would you like to play again (y/n)?? ")
if play.lower() == 'y':
start_game()
... |
2e93d1859265eb0f7f53a7a34c2458c8201acc20 | xiaofeixiawang/cs101 | /lesson5/problem-set2.py | 1,744 | 4.1875 | 4 | 1.
# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
if letter=='z':
return 'a'
return chr(ord(letter)+1)
print shift('a')
#>>> b
print shift('n')
#>>> o
print shift('z')
#... |
2ac38a05bb991b77b4bc6335b852c7c36a34e2e7 | sherpahu/AlgorithmEveryday | /leetcode/Day4/No14_devide.py | 855 | 3.734375 | 4 | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
def commonLongestPrefix(left,right):
length=min(len(left),len(right))
for i in range(length):
if left[i]!=right[i]:
return left[:i]
return left[:length]
... |
7604deac877de7e1f8173d556b21f70931c9a168 | myiwt/drug-reviews-text-classification | /DrugReviewTextClassification.py | 13,453 | 3.5 | 4 | """
This is an implementation of text classification on online drug reviews to
predict the drug effectiveness. This is the main script to execute the text classification.
Two classifiers are built:
1. Random Forest algorithm using a Bag of Words model
2. Support Vector Machine algorithm using Word Embeddings
Mo... |
1eef8c7df2086b4f7ba5d07beb6cd80504405d24 | andreea200423/Instructiunea-WHILE | /3.py | 163 | 3.984375 | 4 | x=0
s=0
while not((x%2!=0) and (x%3==0)):
x=eval(input("Introduceti un nr: "))
if x%2==0:
s+=x
print("Suma tuturor nr pare introduse este",s) |
de2bf7a8bdd7bda24e38a5910f7c18be428eb859 | AshleySetter/optoanalysis | /optoanalysis/optoanalysis/Saleae/Saleae.py | 4,291 | 3.5 | 4 | import struct
import numpy as _np
def get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize]
def read_data_from_bin_file(fileName):
"""
Loads the binary data stored in the a binary file and extra... |
f2ab32f4136eb09cfe9bb280469ab2cacf3077ff | drquant/Python_Finance | /Interpolation/interpolation_point_example.py | 686 | 3.734375 | 4 | '''
Created on April 30, 2014
@author: Steven E. Sommer
@summary: Python script to define X and Y values and to interpolate a Y value
for a given value of X. Employs scipy.interpolate.
'''
# Imports
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
# Define X and Y values
x = ... |
24c8f9576fc4e95349dbc3d41285e23ef3506c21 | RaisuFire/ExProject | /leetCode/easy/SqrtX.py | 632 | 3.8125 | 4 | from math import sqrt
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# y = x/2
# up = x
# low = 0
# count = 0
# while abs(y * y - x) > 0.01:
# count += 1
# print(count)
# if y... |
6f5a6dba06446576a172f0dd9f37a8add9a80b40 | RaisuFire/ExProject | /leetCode/easy/LengthofLastWord.py | 511 | 3.734375 | 4 | class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
# if s == '':
# return 0
c = s.split(' ')
b = []
for i in c:
if i != '':
b.append(i)
if len(b) > 0:
retu... |
e424eb0df975b287825768065921bdac8473c72d | RaisuFire/ExProject | /leetCode/Medium/Rotate Image.py | 758 | 4.125 | 4 | from copy import deepcopy
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
c = deepcopy(matrix)
for i in range(len(matrix)):
matrix[i] = [c[j][i]... |
5618a26744bd19a305ff07574d0eed631b2d1860 | RaisuFire/ExProject | /leetCode/easy/Delete Node in a Linked List.py | 737 | 3.953125 | 4 | # # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# class Solution:
# def deleteNode(self, node):
# """
# :type node: ListNode
# :rtype: void Do not return anything, modify node in-place instead.
# ... |
63dbf1e99801cc7befabee69d4aa9dffd677edda | RaisuFire/ExProject | /leetCode/easy/FindModeinBinarySearchTree.py | 1,034 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def proc(data):
data*2
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
... |
3d02d6eaa7ad344f7bde9655a0b926a9fc9eb7c5 | RaisuFire/ExProject | /leetCode/Medium/Populating Next Right Pointers in Each Node.py | 1,841 | 4.03125 | 4 | # Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x, left=None, right=None, next=None):
self.val = x
self.left = left
self.right = right
self.next = next
from collections import deque
class Solution:
# @param root, a tree link node
# @re... |
b90e6cac35a43984edfbd2e916f5d571e991a8c7 | RaisuFire/ExProject | /leetCode/easy/PlusOne.py | 873 | 3.546875 | 4 | class Solution(object):
def plusOne(self, digits):
for i in range(len(digits), -1, -1):
if digits is None:
return
elif digits[i] == 9:
digits[i-1] += 1
digits[i] = 0
else:
digits[i] += 1
# i = -1
... |
337d878e94a47b8ffd4c582ffb8e84260159e848 | RaisuFire/ExProject | /leetCode/easy/N-ary Tree Postorder Traversal.py | 929 | 3.875 | 4 |
# Definition for a Node.
from queue import Queue
class Node(object):
def __init__(self, val):
self.val = val
self.children = []
def add_child(self, node):
self.children.append(Node(node))
class Solution(object):
def postorder(self, root):
"""
:type root: Node
... |
aeca2a9b20564854381cba2a7478f5cfbb266201 | sumitdba10/learnpython3thehardway | /ex11.py | 1,108 | 4.25 | 4 | print("How old are you?", end=' ')
age = input()
print("How tall are you in inches?",end=' ')
height = input()
print("How much do you weigh in lbs?",end=' ')
weight = input()
# end=' ' at the end of each print line. This tells print to not end the line with a newline character and go to the next line.
print(f"So, you'... |
f1169d8cfd40df1dcf07287ffaab636bb51f28db | sumitdba10/learnpython3thehardway | /ex20.py | 1,856 | 4.5625 | 5 | # from sys package, we are importing argument variables module
from sys import argv
import os
# asigning two variables to argv module
script,input_file = argv
# defining a function to read all content of a file
def print_all(f):
print(f.read())
# defining a function to reset pointer to 0 position
def rewind(f):
... |
6ff3500c81ed429be175c5610a853c2e0f98a728 | sumitdba10/learnpython3thehardway | /ex23.py | 1,738 | 4.5625 | 5 | # importing sys package
import sys
#assigning three variables to argv (argument variable) module
# script : this whole program as .py
# encoding : variable to define encoding e.g. unicode - utf8/utf16/utf32 or ASCII etcself.
#error : to store errors
script,encoding, errors = sys.argv
# defining a function with 3 argu... |
b96118a63d10a22c895281e025abea0e7fe8d2fc | sumitdba10/learnpython3thehardway | /ex19.py | 1,543 | 4 | 4 | def cheese_and_cracker(cheese_count,boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_cracker(10,2... |
c640eccb766d3be16d513516ca9b3bb7499df39e | Sophorth/mypython_exercise | /ex11.py | 569 | 4.4375 | 4 | print " "
print " ------Start Exercise 11, Asking Question ------"
print " "
print "What is your name: ",
name = raw_input()
print "How tall are you: ",
height = raw_input()
print "How old are you: ",
age = raw_input()
print "You name is %s and your are %s inches tall and you are %s" % (name, height, age)
# We can do... |
3255af00ef39bc54055ad6865f55ba3e0b187387 | jerredrogero/CodingPracticeProblems | /LeetCode/409.py | 782 | 3.96875 | 4 | """
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
"""
class Solution:
def longestPalindrome(self, s: str) -> int:
char_... |
a6024ab26d95a3acc79479abacd3f6a7df0aab56 | xiaonilee/Intro_to_Computer_Science_CS101 | /10122019Lesson18.py | 6,658 | 3.96875 | 4 | # Better Hash Functions
# Define a function, hash_string,
# that takes as inputs a keyword
# (string) and a number of buckets,
# and returns a number representing
# the bucket for that keyword.
def hash_string(keyword,buckets):
hash = 0
for char in keyword:
hash += ord(char)
return hash % buckets
... |
9fb33802cd8348fc3fa37be0c0bc61e81bfb683c | nojronatron/PythonPlayarea | /PycharmProjects/Chapter4Explorations/Heros_Inventory.py | 1,366 | 4.25 | 4 | __author__ = 'Blue'
# Hero's Inventory
# Demonstrates tuple creation
# Create an empty Tuple
inventory = ()
# Treat the tuple as a condition
if not inventory:
print("You are empty-handed.")
# create a tuple with some items
inventory = ("sword",
"armor",
"shield",
"healing p... |
97dda3a9cbdf8572e0832a36db91223aa236c4e1 | nojronatron/PythonPlayarea | /PycharmProjects/Chapter 6 Exercises/Default_Params_in_Functions.py | 649 | 3.828125 | 4 | # -- data code --
v1 = None # first argument
v2 = None # second argument
lstData = None # result of processing
# --processing code--
# Define the function
def addValues(value1=None, value2=None, value3=None):
lstResults = None #Holds results list
if (value3 == None):
decAnswer = value1 + v... |
ded65d3035bd4b45455013ed0b951c6d53711d5d | nojronatron/PythonPlayarea | /PycharmProjects/Chapter 6 Exercises/Return_Data_by_Reference.py | 587 | 3.96875 | 4 | # -- data code --
v1 = 10 # first argument
v2 = 5 # second argument
decAnswer = [None] # result of processing in a list
# --processing code--
# Define the function
def AddValues(value1, value2, answer): # answer receives the address this time!
answer[0] = value1 + value2 # answer is a list object... |
aca33cc8e9e6394ba986c45caf8d3eb96f8e367c | nojronatron/PythonPlayarea | /PycharmProjects/Chapter 4 Exercizes/Word_Jumble_Game.py | 1,319 | 4.25 | 4 | # -------------------------------------------------#
# Title: Chapter 4: Word Jumble Game
# Author: Jon Rumsey
# Date: 3-May-2015
# Desc: Computer picks a random word from a list and jumbles it
# User is asked to guess the word.
# 1. Create sequence of words
# 2. Pick one word randomly from the seque... |
0fa82d4d97eb32ad3d11757fb4b25d8716f27b96 | nojronatron/PythonPlayarea | /PycharmProjects/Various Lessons/Chpt2 fiddling2.py | 599 | 3.921875 | 4 | #intFirstNumber = 5
#print( type(intFirstNumber) )
#intFirstNumber = 5.8
#print( type(intFirstNumber) )
#intFirstNumber = "5"
#print( type(intFirstNumber) )
#intFirstNumber = True
#print( type(intFirstNumber) )
#print("Enter your name:");
#strData = input();
#print("Saving name as: " + strData);
#print("Saving name... |
2fcea960bf337d1dba62002735d7dad1e61acfc7 | nojronatron/PythonPlayarea | /PycharmProjects/Chapter 5 Explorations/Chapter Practice Code.py | 893 | 3.890625 | 4 | __author__ = 'Blue'
nested = ["first", ("second", "third"), ["fourth", "fifth", "sixth"]]
print("Nested has only", len(nested), "elements.")
print(nested)
print("\n")
scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)]
print("Scores has", len(scores), "elements.")
print(scores)
print("\nHere are the scores, b... |
4086f73e53be88127cf0f0d158cdc15c77d8a304 | wang8063/Python | /ex2a.py | 533 | 3.828125 | 4 | # calculate the number of bars that a person need
import math
def main():
w=input("please gimee your weight: ")
w=float(w)
h=input("and ur height: ")
h=float(h)
a=input("age, please: ")
a=float(a)
sex=input("your gender:(M) or (F) ")
if sex== "M":
bmr= 66+ (6.3* w)+ (1... |
6b4567414124808c5d8c8723aa877a97bb31e20c | wang8063/Python | /ex3b.py | 574 | 3.796875 | 4 | import math
##perfect(n) what is the n means. How to use argument
def perfect(n):
s=0
for i in range (1,n,1):
if n % i==0:
s=s+i
if s==n:
return True
else:
return False
def main():
x=input("enter lower bound: ")
y=input("enter upper bound: ")
... |
faa983659c8e613aa92aaebdbb08bbaec82bbf8c | Kiriketsuki/Project-Euler-Solutions | /Euler 2.py | 1,054 | 3.953125 | 4 | global dict_of_fib
dict_of_fib = {}
def fib_rec(n):
if n == 1 :
return 0
elif n == 2:
return 1
elif n in dict_of_fib:
return dict_of_fib[n]
else:
dict_of_fib[n] = (fib_rec(n-1) + fib_rec(n-2))
return fib_rec(n-1) + fib_rec(n-2)
def fib_ite(n):
a,b = 0,1
for i in range(0,n):
a,b = ... |
d3ac2f12f77fb46a9507304c8f16467660c4a411 | luisniebla/queue | /kSumPairs.py | 897 | 3.609375 | 4 | # You are given an integer array nums and an integer k.
# In one operation, you can pick two numbers from the array
# whose sum equals k and remove them from the array.
# Return the maximum number of operations you can perform on the array.
def kSum(nums, k):
# Idea: Sort the array
# Start from the beginning... |
b8253734ebee29a6ff617fe23d8343b5379f76dd | luisniebla/queue | /python/is_multiple.py | 4,000 | 4.3125 | 4 | # Write a short function that takes 2 integer values
# It returns True if n is multiple of m
# That is, n=mi for some i and False otherwise
def is_multiple(n, m):
return n % m == 0
assert is_multiple(4,2) == True
assert is_multiple(2,4) == False
assert is_multiple(6,9) == False
assert is_multiple(96,3) == True
#... |
787c737dd72e68e7d1ede086ad62df07e7c76f96 | junbock/pre-education | /quiz/pre_python_03.py | 918 | 3.953125 | 4 | """3.Enter key를 눌러 주사위를 던지게 한 후, 주사위의 눈이 높은 사람이 승리하는
간단한 주사위 게임을 만드세요
예시
<입력>
첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력
두번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력
<출력>
첫 번째(두 번째) 참가자의 승리입니다. or 비겼습니다.
"""
import random
print('첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요: ')
input()
x = random.choice(range(1,7))
prin... |
f02c0745d7f30cda845ff2734992677b637f02d0 | junbock/pre-education | /quiz/pre_python_02.py | 674 | 4.0625 | 4 | """"2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오
예시
<입력>
첫 번째 수를 입력하세요 : 10
두 번째 수를 입력하세요 : 15
어떤 연산을 하실 건가요? : *
<출력>
150
"""
x = int(input('첫 번째 수를 입력하세요 : '))
y = int(input('두 번째 수를 입력하세요 : '))
op = input('어떤 연산을 하실 건가요? : ')
answer = 0
if op == '+':
answer = x+y
elif op == '-':
answer = x-y
eli... |
56321bc2ea255b211551506b56bc2e255cdcd34d | rahuldevyadav/Portfolio-PYTHON | /gui/program2.py | 436 | 4.375 | 4 | #In this program we will create frame
#size of widget
#and putting button on it
from tkinter import *
root= Tk()
frame = Frame(root, width=300,height =200)
# ONCE WE DEFINE BUTTON WIDTH AND HEIGHT IS DEFAULT
button = Button(frame,text='Button1')
button.pack()
frame.pack()
#
# frame2 = Frame(root,width=300,height =20... |
6867945ef633f2d6f81561fa57dd25baea01bbeb | fabio-deep/deep-learning-courses | /course2/week1/initialization/initialization.py | 12,229 | 4.125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import sklearn
import sklearn.datasets
from init_utils import *
matplotlib.use('TkAgg')
#plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
#plt.rcParams['image.interpolation'] = 'nearest'
#plt.rcParams['image.cmap'] = 'gray'
# ... |
a93796faa13a6805f0f5c76b815f2ae4545d4ba6 | Lazyb0y/learning-python | /scripts/iterations.py | 456 | 4.0625 | 4 | nums = [1, 2, 3, 4, 5]
# For Loop
for num in nums:
print(num)
# Break
for num in nums:
if num == 3:
print('Found')
break
print(num)
# Continue
for num in nums:
if num == 3:
print('Found')
continue
print(num)
# Range
for i in range(1, 11):
print(i)
# While Loo... |
1f2a7e54fb988a433f71d9a6e8a032071aa1678c | rdubwiley09/halite_2 | /Non-ML/vector_field_v2/reinforcement_bot/bot.py | 8,747 | 3.640625 | 4 | """
Instead of trying to construct a vector, we use Gaussians to create gradients that push our ships towards good stuff and away from bad stuff.
This bot uses five gaussians:
1) Dock unowned planet (Gu)
2) Dock friendly planet (Gf)
3) Enemy planet (Ge)
4) Enemy Ship (Ges)
5) Friendly ship (Gfs)
W... |
210dea65424605ce897e6e284bb68dc1cae76e05 | 31b4/alt_isk_math_solver | /gyakorl.py | 107 | 3.609375 | 4 | a = int(input("a ="))
b = int(input("b ="))
osszead = a+b
osztas = a/b
print(osszead)
print (osztas)
|
bb338515b47a588ca509d8caf7466033dd099843 | freshmangoes/cmpm146-pa2 | /mcts_modified.py | 7,124 | 3.5 | 4 | # Kyle Cilia
# Joseph Rossi
# CMPM146 P2
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
num_nodes = 100
explore_faction = 0.3
def traverse_nodes(node, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from wh... |
24f8aa16d82595fac073250643a5b12e488f15d4 | Erivks/aprendendo-python | /Exercicios/EstruturaSequencial/CircleArea.py | 97 | 4.09375 | 4 | radius = int(input('Type the radius: '))
area = 3.14159 * radius ** 2
print('Circle area:', area) |
fb730db397474d437aea8fb7ff24f6d6b33fb940 | Erivks/aprendendo-python | /Exercicios/EstruturaSequencial/Sum.py | 135 | 3.59375 | 4 | numbers = input('Type two numbers: ').split()
nOne, nTwo = list(map(int, numbers))
sumResult = nOne + nTwo
print('Result:', sumResult)
|
4c4eda77068ff3b077039b6cdad46f29b679cb94 | Erivks/aprendendo-python | /POO/POOIII/Objetos e Dicionários.py | 1,430 | 4.375 | 4 | #COMPARAÇÃO ENTRE OBJETOS E DICIONÁRIOS E
# MÉTODO ESPECIAL PARA DICIONÁRIOS
'''DICIONÁRIO'''
#Criando dict
pessoa = {'Nome': 'Lucas', 'Emprego': 'Advogado', 'Idade': 20, 'Cor de cabelo': 'Pedro'}
#Mudando um valor dentro do dict
pessoa['Nome'] = 'Erick'
#Acessando valor
print(pessoa['Emprego'])
#Criando novas chaves... |
3919afb86d34336697bc608ef479171de902c198 | Erivks/aprendendo-python | /Coursera/jogo_nim.py | 3,636 | 4.0625 | 4 | #menu de escolha de modo de jogo
def menu():
parar = False
while parar != True:
print("Bem-vindo ao jogo do NIM! Escolha:")
print("")
print("1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
resposta = int(input())
#verifica a resposta do ... |
f45c48c8967497c1e4d6a9fb7f445de51145508f | Erivks/aprendendo-python | /Coursera/maior_elemento.py | 342 | 3.71875 | 4 | def maior_elemento(lista):
for index in range(len(lista)):
if index == len(lista):
if lista[index] > lista[index - 1]:
maior = lista[index]
break
if lista[index] > lista[index + 1]:
maior = lista[index]
return maior
lista = [7, 5, 3]
print(m... |
e00bc24ca2b49a7e26f7429a7e51292b37c20f9c | Erivks/aprendendo-python | /Coursera/decrescente.py | 471 | 4 | 4 | #definições
decrescente = True
anterior = int(input("O primeiro número da sequência: "))
valor = 1
#condição de parada e repetição
while valor != 0 and decrescente:
valor = int(input("O próximo número da sequência: "))
if valor > anterior:
decrescente = False #para a repetição
anterior = valor
#re... |
b4e453849848ec859b07535d5174ae3c81b0d7c2 | francisk/accessible | /entropy.py | 576 | 3.734375 | 4 | import math
def weight(locDistribute):
infoList=[]
locList = locDistribute.split(',')
locTotal = 0;
for loc in locList:
locTotal+= int(loc)
for loc in locList:
infoList.append(round(int(loc)/locTotal,3))
return infoList
def entropy(infoList):
entropy = 0
for info in inf... |
1a75f4a4e721c7f19991a46f54aaa5f45072073d | dawidpacia/pytest_wsh | /src/calculator.py | 340 | 3.703125 | 4 | class Calculator:
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
def mul(self, x, y):
return x * y
def div(self, x, y):
if y == 0:
return False
return x / y
if __name__ == "__main__":
calculator = Calculator()
print(ca... |
26555a7584a538112d532b232dc340ccfb6956f7 | dawidpacia/pytest_wsh | /python_basics/basic_data_type.py | 378 | 3.640625 | 4 | a_string = "1" # string
a_float = 1.0 # float
a_int = 1 # int
a_boolean = True # boolean
a_list = [1, "string"] # list
a_dict = {
"1": 1,
"apple": "fruit"
} # dictionary
a_tuple = (1, 2) # tuple
new_value = str(a_int) # projecting types
# print(a_dict["apple"])
# print(a_list[2])
# if a_boolean:
# ... |
c493a1732fea3f31701d7e36c52fee2d3b4ba47d | martapanc/dailyProgramming | /src/main/java/codewars/python/tribonacci.py | 661 | 3.953125 | 4 | def tribonacci_rec(signature, n):
if n == 1:
return signature[0]
if n == 2:
return signature[1]
if n == 3:
return signature[2]
return tribonacci_rec(signature, n-1) + tribonacci_rec(signature, n-2) + tribonacci_rec(signature, n-3)
def tribonacci(signature, n):
result = [... |
8a80887a2d41386d9f9097abc97c08298076757d | learnPythonGit/pythonGitRepo | /Assignments/20200413_Control_Flow/secondLargeNumSaurav.py | 998 | 4.40625 | 4 | # ....................................
# Python Assignment :
# Date : 15/04/2020 :
# Developer : Saurav Kumar :
# Topic : Find Second Largest Num :
# Git Branch: D15042020saurav :
# ...................................
# Compare two number and fi... |
cd1f6862b5cae32aa0b6b28c6c084ef3d69afa5c | learnPythonGit/pythonGitRepo | /Assignments/20200413_Control_Flow/ControlFlowAssignments_Kiran.py | 2,828 | 4.40625 | 4 | # :................................................................................:
# : Python Assignment. :
# :................................................................................:
# : Date : 15/04/2020 ... |
3c8b872f3d603d9bf1778a2b515c4bbd56962c78 | MikeVelazcoMtz/MongoDbCourse | /getting_started.py | 444 | 3.515625 | 4 | from pymongo import MongoClient
#Enviroment Variables
host = "localhost"
port = 27017 # Default MongoDB Port
# Set Up the Connection
connection = MongoClient(host, port)
db = connection.test # MySQL USE command Like ( Selecting the DB)
names = db.names # Selecting (or creating) the 'names' collection
select_on... |
823112e8776e6f73d90188af290a6b4e137b81d0 | spratt/SphereAngles | /angles.py | 3,634 | 3.609375 | 4 | #!/usr/bin/env python3.3
MIN_MRD = -180.0
MAX_MRD = 180.0
MIN_PAR = -90
MAX_PAR = 90
ERR_MRD = -1
ERR_PAR = -2
################################################################################
# Arguments
import argparse, sys, math
parser = argparse.ArgumentParser(
description='Given two meridians and two paral... |
507b17e47276d78e5fbd16e6ed393995c2d10fa5 | Ripple-zjw/Algorithm | /Heap/PriorityQueue.py | 2,867 | 3.890625 | 4 | # 优先队列
# 大顶堆
from Heap.HeapSort import HeapSort
from Heap.HeapSort_small import HeapSortSmall
class PriorityQueue:
def __init__(self):
self.heap = []
self.heap_size = 0
def insert(self, v):
'''
:param v: 需要插入的元素
:return: None
'''
self.heap_size += 1
... |
83baa227c6798aa47e29ed25fdd9cd69925fdeaf | Ripple-zjw/Algorithm | /DivideAndConquerAlgorithm/OrderStatistics.py | 1,379 | 3.5625 | 4 | # 顺序统计量
# 第k小(大)元素
from random import randint
class OrderStatistics:
def calculate(self, arr, k):
return self.order_statistics(0, len(arr) - 1, arr, k)
def order_statistics(self, l, r, arr, i):
if l == r:
return arr[l]
pivot = self.partition(l, r, arr)
k = pivot - ... |
cf401f5c3b5126f7a3fd3feb5c9eb9a548ae9e24 | reinahuang/geekbangpython | /exercise/5 条件和循环/exercise5.py | 1,421 | 4.09375 | 4 | # 练习一 条件语句的使用
# 使用if语句判断字符串的长度是否等于10,根据判断结果进行不同的输出
first_string = input("Please input a string: ")
if len(first_string) == 10:
print(first_string + " The length equal 10")
else:
print("The length of" + first_string + "is: " + len(first_string))
提示用户输入一个1-40之间的数字,使用if语句根据输入数字的大小进行判断,如果输入的数字在 1-10,11-20,21-30,31... |
2b091a7f26fb26dab8568ff4e8d9bc650e9d8cd0 | jailukanna/100daysofcodechallenge | /table_copy.py | 507 | 3.796875 | 4 | import sqlite3
connection = sqlite3.connect('addressbook.db')
c = connection.cursor()
c.execute(""" CREATE TABLE IF NOT EXISTS New_details
(name TEXT,address TEXT, phone_number INT, location TEXT, zipcode INT)
""")
# Copy data from one table to another
c.execute("""INSERT INTO New_details(name,address,phone_number,l... |
a23bbc9f3c4c4a88862bcf92a361c1fc0a9ce2e9 | jailukanna/100daysofcodechallenge | /day5_practice_collections_movie_dataset.py | 1,609 | 3.828125 | 4 | import csv
from collections import defaultdict, namedtuple, Counter
MOVIE_DATA = 'movie_metadata.csv'
MIN_MOVIES = 4
Movie = namedtuple('Movie', 'title year score')
def get_movies_by_director(data='movie_metadata.csv'):
'''Extracts all movies from csv and stores them in a dictionary
where keys are directors... |
413c365ca048e9c128f019e51c033a23306a866a | jailukanna/100daysofcodechallenge | /day15_guessnumber.py | 2,050 | 3.984375 | 4 | from random import randint
MAX_GUESSES = 5
START,END = 1, 20
def get_random_number():
return randint(START, END)
class Game:
def __init__(self):
self._guesses = set()
self._answer = get_random_number()
self._win = False
def guess(self):
''' Takes ... |
a789cd82b509e86df6e37557ee95ec0f2ab69312 | jailukanna/100daysofcodechallenge | /explore_apis/day62_game_data_api.py | 579 | 3.65625 | 4 | import requests
import json
from pprint import pprint
# read a json file in to python data object
with open('mount-data.json') as f:
data = json.load(f)
# parse through the nested dict and get the names of the mounts
for item in data['mounts']['collected']:
print(item['name'])
# get the list of dictionaries ... |
a8ed6b422b23d30edfce74caf0339c0a22afd89b | tland-p/Kinematics | /test_program/debug_demo.py | 172 | 3.59375 | 4 | def sigma(n):
z = 0
for i in range(1, n+1):
z = z + i
return z
def main():
n = int(input('n = '))
result = sigma(n)
print(result)
main() |
636a447d89387773056d4e81c6a7519cea3675dd | TCIrose/watchlist | /app/models/movie.py | 1,124 | 4.125 | 4 | class Movie:
'''
Movie class to define Movie Objects
'''
def __init__(self, id, title, overview, poster, vote_average, vote_count):
'''
Args:
1. Title - The name of the movie
2. Overview - A short description on the movie
3. image- The poster image for the movie
... |
07bd1dd1e1c9b800c5e793fca1ce4043462a742e | tomotaka/ProjectEuler | /problem020/p020.py | 177 | 3.5 | 4 | # -*- coding: utf-8 -*-
import math
def main():
ans = 0
for c in str(math.factorial(100)):
ans += int(c)
print ans
if __name__ == '__main__':
main()
|
c0a03baabfe23eb8fd2d7777fb0c4dd80f7b42ee | bryanbuiles/Algorithms | /python_algoritms/hackerAlgoritms/sorting/Comparator_class.py | 1,249 | 3.75 | 4 | """
Title: Sorting: Comparator
link: https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
ordenando por el algoritmo de int compare(T o1, T o2)
Se comparan dos argumentos por orden return -1 if a <... |
1403dc85d596fad8e38f5291a58f9776b5f87755 | bryanbuiles/Algorithms | /python_algoritms/cake_interview/Array_and_string_manipulation/reverse_words.py | 2,438 | 3.5625 | 4 | """ Reversar el orden de las palabras completas """
def reverse_words(message):
reverse(message, len(message), -1, 0)
spaces = message.count(" ")
temp2 = -1
contador = 0
temp1 = index1 = message.index(" ")
for times in range(spaces + 1):
contador_pala = temp1
reverse(message, c... |
ea20ae83520940c39da363af0d0ded32fff1a756 | bryanbuiles/Algorithms | /python_algoritms/hackerAlgoritms/hash_tables/Ransom_Note.py | 1,163 | 3.984375 | 4 | #!/bin/python3
"""
Hash Tables: Ransom Note
https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps
Si es posible formar el mensaje con las palabras de la revista
"""
def checkMagazine(magazine, ... |
9d8590c09573db47c7d29d7d795c6da9ff281f8f | rindlerr1/practicalstats | /PracticalStats.py | 8,322 | 4.125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Basic Statistical Calculations
All functions can work with a list, an array, or the column of a dataframe
"""
"""
Hey Lisa
potatoes1
"""
def MeanAD(x):
import numpy as np
x = np.array(x)
mad = np.mean(abs(x - np.mean(x)))
return mad
... |
0d65e21dc0115939f1c5a5aa1fb2456cd0cc408c | OpenWeek/inginious-task-LINGE | /2018_aout_01_football/src/CorrQ.py | 660 | 3.53125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
def arret(but):
hb,lb,lg=0,0,0
output=[0,0,0]
for h in range(len(but)): #until H
for l in range(len(but[0])): #until L
if but[h][l]=='B':
hb,lb=h,l
elif but[h][l]=='G':
hg,lg=0,l
# //G... |
594c09f41cb0461e7874ded94b318f3c71d1ea78 | OpenWeek/inginious-task-LINGE | /TP3Ex1Supp/src/CorrQ.py | 221 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
def premier(n):
if n == 0: return(False)
if n == 1: return(True)
for i in range(2, n):
if n % i == 0:
return(False)
return(True)
|
75b955288fd2178b9d56196b653670531b6489a5 | OpenWeek/inginious-task-LINGE | /TP6Ex3/src/CorrQ.py | 635 | 3.578125 | 4 | def examen(notes):
maxi = notes[0]
mini = notes[0]
moy = 0
nombre = [0 for i in range(10)]
for i in range(len(notes)):
moy+=notes[i]
nombre[notes[i]//10]+=1
if notes[i]>maxi:
maxi=notes[i]
if notes[i]<mini:
mini=notes[i]
print("La note maxi... |
b39a86ec359d862986dda457bbb75c5924de00cf | OpenWeek/inginious-task-LINGE | /TP4Ex2Supp/src/CorrQ.py | 627 | 4 | 4 | def inverse (a, b):
if len(a) != len(b):
print("taille differente !!")
else:
x=0
for i in range(len(a)):
x = a[i]
a[i] = b[i]
b[i] = x
print("A = ")
for i in range(len(a)):
print(a[i], end=" ")
print()
pri... |
3503495e8a03f17ad4ddd7ece57550851f48a5e8 | OpenWeek/inginious-task-LINGE | /TP1Ex2/src/CorrQ.py | 244 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def moyenne(a,b):
return (a+b)/2
def main():
a = int(input("Entrez le premier nombre :"))
b = int(input("Entrez le deuxième nombre :"))
print("La moyenne est :" + str(moyenne(a,b)))
|
4b11b5f80610aa514338426c0b0262b20c81aa3c | Cretis/Triangle567 | /TestTriangle.py | 2,667 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html h... |
4e181509d24af8124bceb5b533cc838853f32c56 | cscal/practice | /fizzbuzz.py | 528 | 3.9375 | 4 | #! /usr/bin/python
# This is the python version of the classic fizzbuzz problem
# This was the first version, correct although it does repeat
#for i in range(1, 101):
# if i%15 == 0:
# print('FizzBuzz')
# elif i%3 == 0:
# print('Fizz')
# elif i%5 == 0:
# print('Buzz')
# else:
# ... |
986e921989658a41e090ebcd43045e28007a99a5 | SurajChess/robotics | /6dof_IK.py | 5,828 | 3.546875 | 4 | """
inverse kinematics for 6dof and simualation of helix function as end points
Written by Akshay Khemnar while doing Internship at Robiotar Labs pvt ltd
"""
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math
import matplotlib.pyplot as plt
# input the thetha4,thetha5,theth... |
a7eabc386f60ea48bf5554bd9e7676fc9ab89283 | ghostSystem/ML_Assignments | /HW1/112008011_Astitv_Nagpal/code.py | 5,049 | 4 | 4 | import random
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as sta
def question2(N,M):
'''
Main function call where we get value for:
X, Exp of X, Var of X
Returns Expectation, Variance, Co-Variance for List X.
'''
X = []
ProbX = []
X = calculateFunction... |
ca6a7c434e39c622cddd868ca796263fd3ff9c4e | belykia/polito | /main.py | 123 | 3.609375 | 4 | print "hello Topix!"
for i in range(0,10):
print i
for i in range(0,10):
print i
my_dict = {}
my_dict['topix'] = 10
|
bb7df7dbd0bbfef800e25757eea3ea0470f4344d | marcelohuber/sa2programacao | /exercicio 3 sa2 recuperação 130821.py | 1,121 | 3.703125 | 4 |
n1 = int(input("digite valor 1: "))
n2 = int(input("digite valor 2: "))
n3 = int(input("digite valor 3: "))
n4 = int(input("digite valor 4: "))
n5 = int(input("digite valor 5: "))
n6 = int(input("digite valor 6: "))
n7 = int(input("digite valor 7: "))
n8 = int(input("digite valor 8: "))
n9 = int(input("digite valor 9... |
673b242e950d43a7485e117c86d02b71fa644d71 | hoiho77/Algorithm | /Green/Greedy/6. 무지의 먹방 라이브.py | 516 | 3.515625 | 4 | # 원형 : %3 해서 2(=len(food_times)-1)가 될 때 인덱스 0으로 돌아감
food_times = [3,1,2]
idx = 0
k = 5
while k != 0:
print(food_times)
print('idx',idx)
print('k',k)
if food_times == [0]*len(food_times):
print(-1)
break # return -1
# 값이 0이면 다음 리스트로
if food_times[idx%3] == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.