blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4688b9c4de6153e6acef2992b4b5ae469c2d2d00 | notha99y/Understanding-MLP-using-XOR | /data_utils.py | 2,426 | 3.625 | 4 | '''
Helper function to aid the understanding of XOR problem
'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.optimizers import Adam
def generate_XOR_distribution(max_x)... |
c57f8e48465136f0ac49ceeb24dcb534ccf79541 | gracielle-ch/atividades | /input.py | 188 | 4 | 4 |
name = input('Enter your name:')
print(name)
print('What is your name?')
name = input()
print(name)
x = input('Enter a number: ')
print(type(x))
x = 5
print('The number is ' + str(x)) |
e22b25afb07f2faf6035199fceffe2007e72af1f | ahilgenkamp/Random_Projects | /fizbuzz test.py | 624 | 3.84375 | 4 | # fizbuzz test
def fizzbuzz(start, end):
fizzbuzz = []
for i in range(start,end):
if i % 3 == 0 and i % 5 == 0:
fizzbuzz.append('fizzbuzz')
elif i % 3 == 0:
fizzbuzz.append('fizz')
elif i % 5 == 0:
fizzbuzz.append('buzz')
else:
fizzbuzz.append(str(i))
return fizzbuzz
print(fizzbu... |
815051664a5bced3120136d2c491428b5256c495 | chxj1992/leetcode-exercise | /121_best_time_to_buy_and_sell_stock/_1.py | 683 | 3.640625 | 4 | import unittest
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
low, high, max_profit = 0, 0, 0
for i, v in enumerate(prices[1:]):
if v < prices[low]:
low = i + 1
high = i + 1
if v > prices[high]:
... |
f80e524b2acf078511f403b547bf3c0b54d6a961 | dmdsiz/coding-tests | /series_5/4. divide and conquer.py | 615 | 3.59375 | 4 | def longestPolydivisiblePrefix(a):
count = 0
for i in range(len(str(a))):
if int(str(a)[:i+1]) % (i+1) != 0:
count +=1
return int(str(a)[:i])
if count == 0:
return int(str(a)[:len(str(a))+1])
def isPolydivisible(a):
answer = longestPolydivisiblePrefix(a)
if a... |
5a51f0a7fdc9805c186a6a6e19b2e1ec9e4df5d6 | koustav2001/Codeforces | /Codeforces_py/Elephant.py | 72 | 3.734375 | 4 | x=int(input())
if(x%5==0):
print(x//5)
else:
print(x//5+1)
|
d05819fb9cd65a20b5887e0e3360c42375e00498 | Qiumy/leetcode | /Python/72. Edit Distance.py | 1,244 | 3.765625 | 4 | # Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
#
# You have the following 3 operations permitted on a word:
#
# a) Insert a character
# b) Delete a character
# c) Replace a character
class Solution(object):
def... |
db217af27b019df90be094c7e42b2325617b089f | jmekblad13/python-challenge | /PyBank/main.py | 2,329 | 3.859375 | 4 | import os
import csv
#fileset number can change to work with multiple or different files
fileset = ["2"]
months = 0
revenue = float(0.00)
previous = float(0)
change = float(0)
totalchange = float(0)
greatest_increase = float(0)
greatest_increase_month = ""
greatest_decrease = float(0)
greatest_decrease_month = ""
fo... |
ef6334dcf37ad1d67bc7f606d81094f4ce7755d9 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/1060.py | 3,430 | 3.703125 | 4 | import os
import sys
"""
The basic code for reading a file, should return a string
"""
def parse_input(input_file):
f = open(input_file, "r")
final_string = ""
test_cases = int(f.readline())
for case in range(test_cases):
grid = []
for i in range(4):
grid.append(list(f.readl... |
bfe351e831cc628f188965273b794b45aca0b891 | Social777/Exercicios | /Exercicio_8.py | 210 | 3.890625 | 4 | # Leia uma temperatura em graus Kelvin e apresente-a convertida em graus Celsius.
kel = float(input('\nQual a temperatura em graus Kelvin? '))
cel = kel - 273.15
print(f'\nA temperatura em Celsius é: {cel}') |
dc6e2b27c32ce95aabf637fb702d5737d50b110d | Nepherhotep/karatsuba_mult | /week3_quicksort.py | 2,896 | 3.859375 | 4 | from tools import load_input_array
class Counter:
def __init__(self):
self.counter = 0
def add(self, m):
self.counter += m
def first_element_pivot(a, from_index, to_index):
return from_index, a[from_index]
def final_element_pivot(a, from_index, to_index):
return to_index - 1, a[to... |
5010ae0c08aa46d7f0d87879e00a950ef09e35e0 | caique-santana/CursoEmVideo-Curso_Python3 | /PythonExercicios/ex108 - Formatando Moedas em Python.py | 753 | 4.03125 | 4 | """Adapte o código do desafio 107, criando uma função adicional chamada moeda() que consiga mostrar os valores como
um valor monetário formatado."""
# Caique Santana
from ex108 import moeda
valor = float(input('Digite o preço: R$'))
print(f'A metade de {moeda.moeda(valor)} é {moeda.moeda(moeda.metade(valor))}')
print(... |
26425ba8f5dc948fe6eb77774261faca30d8ccc9 | stokertobysteam/YR13PROJ | /2D.py | 325 | 4.25 | 4 | """
2D
"""
x = int(input("What is the length of your shape?: "))
y = int(input("What is the width of your shape?: "))
angle = int(input("What is the angle of your shape? :"))
if x == y and angle == (90):
print("Your shape is a square")
elif x != y or angle == (90):
print("Your shape is a rectangle")
... |
1290eb88147181113796e256dfe64a802dd0ace5 | nathanwisla/PythonScriptCollection | /School Projects/lab 4 (Functions)/lab 4.py | 1,545 | 4.15625 | 4 | #October 6, 2016
#Nathan Wisla
#AUCSC111
#Lab 4: Computing a Worker's Gross Pay
#compute an employee's pay
#by multiplying the hours worked and the rate of pay.
##if the employee has worked more than 40 hours,
##then they should be paid at 1.5 times the for the hours spent over 40.
###if the employee worked... |
a00159bd9e1a741a4d7b637b36a3b8a74e66b30b | fara0000/computational-math-numerical-integration | /methods/TrapezoidalMethod.py | 458 | 3.640625 | 4 | from calculate import calculate_value
from methods.Method import Method
class TrapezoidalMethod(Method):
name = "Метод трапеций"
@staticmethod
def integrate(f, a, b, partitions) -> float:
step = (b - a) / partitions
result = (calculate_value(f, a) + calculate_value(f, b)) / 2
x = ... |
d52a5bc2a1334cb09893196032b710a1315b8055 | CrazyStoneJy/PythonStudy | /oop/oop.py | 295 | 3.640625 | 4 | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
class MyObj:
name = ''
def __init__(self,name):
self.name = name
obj = MyObj('jiayan')
print(type(obj))
print(hasattr(obj,'x'))
setattr(obj,'x',200)
print(hasattr(obj,'name'))
print(obj.x)
obj.address = 'beijing'
print(obj.address) |
46320dfeac27d390a0d0f8de86401e0089535978 | Atinder01/Streamlit-Sudoku-Solver-Python | /sudoku_solver.py | 1,981 | 3.84375 | 4 | import imageio
def read_from_file(file_object):
img = imageio.imread(file_object, pilmode="RGB")
return img
def solve(board):
"""
A method to solve the sudoku puzzle using the other functions defined.
We use a simple recursion and backtracking method.
Arguments:
board - a list of nine ... |
d0ec5914c354582e4ca053ac1c125f80d92d6659 | jpvincent/WPT-server | /mobile/pcap2har/tcpseq.py | 2,392 | 3.671875 | 4 | '''
Defines functions for comparing and processing TCP sequence numbers, taking
into account their limited number space.
'''
def twos_comp(x):
return (~x)+1
numberspace = 2**32 # seq numbers are up to but not including this
halfspace = numberspace / 2
def wrap(x):
'''
emulates the cast to int used in the... |
491aa74935e7fcfe595c59163a8cc86bd725b8ce | Ali-Fani/Theory | /4/checkFact.py | 189 | 4.1875 | 4 | def is_factorial(n):
i = f = 1
while f < n:
i += 1
f *= i
print(f, i)
return f == n
if is_factorial(int(input("Enter a number : "))):
print("Yes")
|
678e25d78f70972fbf72722680a9d2614be5135e | MrRichard/codewars-kata | /categorize_new_member.py | 671 | 3.703125 | 4 | #!/bin/env python
# https://www.codewars.com/kata/5502c9e7b3216ec63c0001aa/train/python
def open_or_senior(data):
# First Draft
# results=[]
# for ind in data:
# if ind[0] >= 55 and ind[1] > 7:
# results.append("Senior")
# else:
# results.append("Open")
# return... |
f2184c39455e5bdaef085550aaeb2ec7af292135 | PLUTOLEARNS/computerprogramsreal | /practiceprograms 26082020.py | 590 | 3.78125 | 4 | """bonus = 0
sale = int(input("Enter Monthly Sales :"))
if sale >50000:
bonus = sale * 10 /100
print("Bonus = " + str(bonus))
t = bonus + sale
print ("Monthly Salary with bonus = " , t)"""
n = int(input ("Enter any number : "))
for i in range(1,31):
print(n," X " , i , " = " , n*i)
"""program to pri... |
fb8e599882b47f1245c39498ce748011e8f50e76 | sonjak7/games | /GessGame.py | 17,364 | 3.9375 | 4 | #Author: Sanjay Ramanathan
#Date: 6/3/2020
#Description: A program to play the board game Gess
class GessGame():
"""
This class creates a new gess game
Attributes:
turn(char): Represents whose turn it is, starts off as black's turn
game_state(string): Says whether game is unfinished, white... |
902c25db7c1105628f604e7ab0cf2cf9439d20ea | mattwelson/Archive | /2011/COMP150/Lab9/stringtools.py | 827 | 3.890625 | 4 | def reverse(s):
"""
>>> reverse("happy")
'yppah'
>>> reverse("Python")
'nohtyP'
>>> reverse("")
''
>>> reverse("P")
'P'
"""
s = s[::-1]
return s
def mirror(s):
"""
>>> mirror("good")
'gooddoog'
>>> mirror("yes")
'yessey'
>>> mirror("Python")
... |
f6075804b378e30e54533686c83b624b8f84ca92 | itsmohitj/Leetcode-Solutions | /isIsomorphic.py | 827 | 4.03125 | 4 | """
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character ... |
0d37eed68987a6c660ea9549ffe179b94244fa7a | dicao425/algorithmExercise | /LintCode/subsets2.py | 507 | 3.84375 | 4 | #!/usr/bin/python
import sys
class Solution:
"""
@param: nums: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, nums):
# write your code here
result = [[]]
nums.sort()
for i in nums:
result += [n + [i] for n in r... |
7bbe7f85af82a15ee4cea66c901b46e5683bda9b | ItsMeMegaMind/HackerRank | /Algorithm/Implementation/Strange Counter/Strange Counter.py | 253 | 3.609375 | 4 | #!/bin/python3
import math
t = int(input())
cycle = int(math.log2((t-1)//3+1))
time = 3*(2**cycle-1)+1
value = 3*2**cycle
print((value-t)+time)
"""
a = int(input())
t=a
dif = 3
n=0
while(t>dif):
n+=dif
t-=dif
dif*=2
print(dif-(a-n)+1)
""" |
4489608f40535b49e776b73a8e4afcfc81eebc74 | ikailash19/guvi | /beginpgm42.py | 168 | 3.546875 | 4 | x,y=input().split()
s1=0
s2=0
for i in range(len(x)):
s1+=ord(x[i])
for i in range(len(y)):
s2+=ord(y[i])
if(s1>s2):
print(x)
elif(s2>s1):
print(y)
else:
print(x)
|
7467f1fe0dedc18701cc25e425d0ce8726ee20b3 | Vimala390/Vimala_py | /sample_numpy_test1.py | 2,993 | 4.09375 | 4 | # Numpy is most useful feature is n-dimensional array object
import numpy as np
import time
a = np.array([1,2,3])
print(a)
print(type(a))
#print(ndim(a))
print(a.itemsize)
print(a.size)
a1 = np.arange(1000)
print(a1.size)
l1 = np.arange(1000)
l2 = np.arange(1000)
print('numpy .....')
start = time.time()
result = l1 +... |
9298d143a5c23eaba081c2441b3c7573fb4b7b93 | Boris-Rusinov/BASICS_MODULE | /Conditional Statements/Lab06-Area_Of_Figures.py | 414 | 4.125 | 4 | import math
figure_type = input()
if(figure_type == "square"):
a = float(input())
area = a * a
elif(figure_type == "triangle"):
a = float(input())
height = float(input())
area = a * height / 2
elif(figure_type == "rectangle"):
a = float(input())
b = float(input())
area = a * b
elif(fig... |
38db28ed3acf08d9d50b4c3197cb33f9d157e097 | tonytrill/crossfitgamesleaderboard | /crossfitgamesleaderboard/url.py | 4,724 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import csv
from datetime import date
import requests
"""
'https://games.crossfit.com/competitions/api/v1/competitions/open/2019/leaderboards?division=1&' \
'region=0&scaled=0&sort=0&occupation=0&page=1'
"""
def getJSON(url):
response = requests.get(url)
... |
bbe3a9ce809327f0b0072c5d93584cab92b25ac1 | linusg/adventofcode | /2020/10.py | 1,726 | 3.625 | 4 | import sys
from collections import defaultdict
from typing import DefaultDict, List, Sequence
def get_rating_differences(adapter_ratings: Sequence[int]) -> DefaultDict[int, int]:
adapter_ratings_sorted = sorted(adapter_ratings)
rating_differences: DefaultDict[int, int] = defaultdict(int)
for i, rating in ... |
d3bd82c4d781738adfc043ede05136a833cc7d78 | Tank1991/datongtest | /jiekouTest/Test03-session/t5_jso_pyth.py | 551 | 3.78125 | 4 | # coding:utf-8
import json
#json 格式的字符串
a = '[{"a" : true, "b" : null }]'
#转成list
print(json.loads(a))
# b是一个类似于dict类型的json数据,本质是str
b = '{"e": [1, 2, 3], "g": {"a": 111, "b": true}, "a": null, "b": true, "f": [null, true, "11"], "d": "hello", "c": 12}'
print(json.loads(b))
c = {"a":True ,"b":None}
print(str(c))
pri... |
087c51212d8bbdaadd4ce1054ef7c4e6efa10cb1 | NickF40/Algorithms | /sorting/quicksort.py | 1,569 | 3.921875 | 4 | """
Inspired by:
Introduction to Algorithms(1990)
By:
Thomas H. Cormen
Charles E. Leiserson
Ronald L. Rivest
Clifford Stein
"""
import time
class Quicksort:
def __init__(self, array):
self.array = array
def __call__(self, p, r):
q = self.partition(p, r)
if r > p:
self... |
eaf90453ab1226a9c829d6a2b94a3fd265f06519 | kubic71/mff | /2020-zs/datovky/hw/03-splay_experiment/splay_operation.py | 5,116 | 4.4375 | 4 | #!/usr/bin/env python3
class Node:
"""Node in a binary tree `Tree`"""
def __init__(self, key, left=None, right=None, parent=None):
self.key = key
self.parent = parent
self.left = left
self.right = right
if left is not None: left.parent = self
if right is not Non... |
84530f692df7948b12f628a63a643ead4211a547 | spybdai/gof23 | /patterns/observer.py | 3,675 | 3.65625 | 4 | #! -*- coding: utf-8 -*-
"""
observer pattern and strategy patter
"""
from abc import ABCMeta
class Observer(object):
__class__ = ABCMeta
class Subject(object):
__class__ = ABCMeta
def register_observer(self, observer):
raise NotImplementedError
def remove_observer(self, observer):
... |
added42704f20f49d11643170ba0428e03c3fd48 | almamuncsit/LeetCode | /30-Day-LeetCoding-Challenge/week-2/4-Diameter-of-Binary-Tree.py | 592 | 3.765625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.answer = 1
def diameterOfBinaryTree(self, root):
self.depth(root)
return self.answer - 1
... |
1b37d10442909d07aeefc2910677abe8e1bc6748 | xiong-zihao/u-tic-tac-toe | /Board.py | 7,891 | 3.609375 | 4 | import numpy as np
import random as rand
class Board:
"""
Representation of a Ultimate Tic Tac Toe board game
"""
board_mask = 0b111111111
def __init__(self, other=None):
"""
Initializes a Ultimate Tic Tac Toe board game
:param other:
"""
if type(other) is ... |
2d600145846cc9c20621f7ae090c6432ef005c31 | Greenwicher/Competitive-Programming | /CodeForces/Python2/467A.py | 184 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 8 01:27:49 2015
@author: liuweizhi
"""
## version 1
print sum(1 for _ in range(input()) if -eval(raw_input().replace(' ', '-')) >= 2)
|
02a757be5d59e8ce15e4b73d41d79da38d3628eb | nazmosh/data_structures | /DoublyLinkedList.py | 1,367 | 3.671875 | 4 | class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, node):
if self.head:
p = self.head
while p.next:
p = p.next
p.next = node
node.prev = p
node.next = None
else:
... |
578b5390d221376774ddb749fd819814d7512c38 | ihuger/droplets | /data_structure-algorithm/search/codeforce_449b_v2.py | 2,314 | 3.75 | 4 | #!/usr/bin/env python
#coding utf-8
from Queue import PriorityQueue
class Graph:
def __init__(self):
[n,m,k] = map(int,raw_input().split())
self.neighbs = {}
self.edges = {}
#ui to vi weight xi
for i in range(m):
[u,v,x] = map(int,raw_input().split())
... |
2cc1452cf5f686e8c0e4742b8da7f23003b35f15 | haroldjcastillo/NaturalLanguageToolkit | /stop_words.py | 369 | 3.90625 | 4 | from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
example_test = "This is an example showing off stop word filtration."
stop_words = set(stopwords.words("english"))
words = word_tokenize(example_test)
filtered_sentence = []
for w in words:
if w not in stop_words:
filtered_sentence.... |
4c1b6b79d85382e0f3a5c459a04640373de69426 | MStevenTowns/Graphics-Programming | /23 Green Screen.py | 1,970 | 3.53125 | 4 | import pygame
import pygame.camera
import sys
import numpy
#START PYGAME
pygame.init()
#START THE CAMERA MODULE OF PYGAME
pygame.camera.init()
#GET A LIST OF ALL WEBCAMS
cameras = pygame.camera.list_cameras()
#CONNECT TO A WEBCAM IF YOU CAN
try:
cam = pygame.camera.Camera(cameras[0],(640,480))
except:
sys.e... |
8381529d4ac6ff0cf2d1006ada8cfbf625fc604c | zlindacz/udacity-full-stack | /project_1_movie_trailers/media.py | 1,035 | 3.5625 | 4 | ########################################################################
# Project 1: Movie Trailer Website
# Date Completed: 12/6/2016
# Submitted by: Linda Zhang
########################################################################
############################## Media File ##############################
# This mo... |
f420ac172d0ca54dc89b78b4bcf6c47f1a323e99 | Kontowicz/Daily-coding-problem | /day_060.py | 515 | 3.5625 | 4 | # Given a multiset of integers, return whether it
# can be partitioned into two subsets whose sums are the same.
def help(set, start, stop, sum, total):
if start >= stop:
return False
if sum == total:
return True
return help(set, start + 1, stop, sum + set[start], total - set[start]) or he... |
11aaf675c94ed0d938d986147e50aa370f5b00c3 | aruzhanirgalieva/python | /TSIS_2/Lecture5_tsis/13.py | 167 | 3.640625 | 4 | f = open("text1.txt", "r")
text = f.readlines()
f.close()
with open("text2.txt", "w") as f:
for i in text:
f.write(i)
f = open("text2.txt")
print(f.read()) |
2311fbf38bc43af6c3a9a83fa964d3399e0bc141 | Sfera-IT/adventofcode2020 | /the_maxtor/day2/puzzle4.py | 527 | 3.609375 | 4 | #!/usr/bin/python3
valid = 0
with open("input_day2.txt") as inputFile:
for row in inputFile:
policy, password = row.split(":")
position1 = int(policy.split("-")[0])
position2 = int(policy.split("-")[1].split(" ")[0])
letter = policy.split("-")[1].split(" ")[1]
if (password.s... |
60e61226cede40a2e509c453d06238ba8f663b96 | WeiyiDeng/hpsc_LinuxVM | /lecture4/ww.py | 187 | 3.59375 | 4 | """
test script to show that python breaks out of the function after excuting 'return'
"""
def www(x):
if x<3:
return("lsmaller")
elif x<10:
print("larger")
x = x +100
return(x)
|
7e0ca3cee5f22b0529715107ebbfdd27ac7a028c | startsUp/Algorithms-Practice | /data-structures/trie/trie.py | 1,860 | 4.03125 | 4 | class TrieNode:
def __init__(self, v, isEnd):
self.val = v
self.next = [None for i in range(26)]
self.isEnd = isEnd
def getNext(self, c):
k = ord(c) - 97 # index
return self.next[k]
def setNext(self, c, node):
k = ord(c) - 97
self.next[k] = node
""... |
99a3cd7f70a19dcf6fd9f08c9349ee16ef978f43 | JonahFidel/COSC101 | /Documents/CompSci101/HW3/Rocket.py | 1,166 | 4.1875 | 4 | scale = raw_input("Please enter a scale: ")
print
print
print
for tin in range(int(scale) * 2 - 1):
print (((int(scale)) * 2 - 1) - int(tin)) * " " + (tin + 1) * "/" + "**" + (tin + 1) * "\\"
tin = tin + 1
for tin in range(int(scale)):
print "|" + (int(scale) - tin - 1) * "." + (tin + 1) * "/\\" + ((int(... |
9952f82b45b60ef9e4e623e6e39276812340c030 | Rude-Crow/python | /Untitled-3.py | 526 | 4 | 4 | YourName = input("Whats your name: ");
YourAge = input("Whats your age: ");
YourTown = input("Whats town are you from: ");
IsRegistered = input("Are you registered to vote (enter True or False): ");
YourOc = input("What your occupation: ");
str(YourName);
int(YourAge);
str(YourTown);
str(IsRegistered);
str(Y... |
6d08757e055dbf2f168ae492fa62879ac27b7807 | guillaumethomas/reference | /python_algo/quicksort.py | 692 | 3.84375 | 4 | '''
quicksort Guillaume THOMAS
from MIT Pseudo code
'''
from random import randint
def quicksort(lst):
def quicksort_h(lst, p, r):
if p < r:
q = partition_h(lst, p, r)
quicksort_h(lst, p, q - 1)
quicksort_h(lst, q + 1, r)
def partition_h(lst, p, r):
piv = ... |
2bc18aadf7b4eb1a3a788778ea3b6415b6234889 | nickzhq/leetcode-algorithm | /Product of Array Except Self.py | 810 | 3.5 | 4 | __author__ = 'Nick'
def productExceptSelf( nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
if n < 2:
return nums
res = list(nums)
# transform nums such that nums[i] = num[1] x nums[2] x ... x nums[i - 1]
nums[0] = 1
for i in range(1, n):
nu... |
d0a496d32baf0c198434aaa51c5abe4cd76910a1 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/plldar009/question3.py | 247 | 4.09375 | 4 | import math
d = math.sqrt(2)
a=2
b=2
while d<2:
x=a/d
b=x*b
d=math.sqrt(2+d)
print("Approximation of pi:",(round (b,3)) )
r=eval(input("Enter the radius:\n"))
ans= (b*(r)**2)
print("Area:", round(ans,3))
|
4336a697a9b9dfacf7df2a6544f40d9ecfea7dbe | JackAbel/testPython | /PythonDebugDemo/ReserveString.py | 818 | 3.5625 | 4 | # /usr/bin/env python
# -*- coding: utf-8 -*-
# idea pydev, py2.7
# w by B.X.Jin
# time: 2017.10.18
string = 'abcdef'
# 1简单的步长为-1,常用的字符串反转方法
# 2交换前后字幕的位置
# 3使用递归的方式,每次少一个字符
# 4双端队列,使用extendleft()函数
# 5使用for循环
def reserve1(st):
return st[::-1]
def reserve2(st):
t = list(st)
l = len(t)
for i, j in zi... |
d041d612846c08354aa17d827c4a29d45ce7b700 | gautam4941/Python_Basics_Code | /Loops/For/Prog2.py | 110 | 3.578125 | 4 | for i in range(1, 4):
for j in range( 1, 6 ):
print(f"{i} -> {j}", end=', ' )
print() |
1c51f63f6d32f118b83a29a46c33b4963e50cb30 | anniexen/Field-Robotics-Experiment-and-Research | /Functions/PositionTransformation.py | 6,964 | 3.78125 | 4 | #Required Libraries
from math import sqrt, cos, sin, tan, pi
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.transform import Rotation as Rot
def transl2(x_tran,y_tran):
"""Creates a homogeneous 2D translation matrix
Parameters
----------
x_tran : float
... |
ac1506c328eb094674b30f4feedf41f185b1a0d9 | jscatala/Hackerrank | /Python/SET/add.py | 355 | 4 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
n = int(input())
countries = set()
for i in range(0, n):
country = input()
if country not in countries:
countries.add(country)
... |
a8c9ac9ac0d43ecb5f3f11bc73b150d3326a794c | rupeshkumar098/rk001 | /Python/1st day programs/LIST_&Dictionary.py | 391 | 3.890625 | 4 | List1=[1,2,3,4,5,6,7,8,9,34,1,45,23]
List2even=[]
List3odd=[]
for x in List1 :
if (x%2==0) :
List2even.append(x)
else:
List3odd.append(x)
print("Even Numbers in List" ,List2even)
print("odd Numbers in List" ,List3odd)
evenSum=sum(List2even)
oddSum=sum(List3odd)
Dict={"Even Sum is " : evenSu... |
f4d94099e40080024bdf7ca7267972e09ef05d26 | MichaelElkan/Chicken-Translator | /Chicken_Translator.py | 3,732 | 3.71875 | 4 | #Michael Elkan
#3/27/16
from tkinter import *
class Window(Frame):
def __init__(self, master =None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Chicken Translator")
self.pack(fill ... |
1b5e665a0958920ba4244a5a9ea4be3b15e3c8f9 | rajsooraj30/Automation-practice | /Unit_test_framework/SetupAndTeardown.py | 1,651 | 3.828125 | 4 | #there are three types of setup and teardown which we can use
# 1st is setup and tear down method - these executes for each function i.e setup will execute before each
# function in a class and tear down method will execute after each function in a class
# 2nd is setup and tear down class - setup class will execute one... |
9365ca488a443fa4a4d5040e6df918c3a20cd2cd | Furuka-Sep/PythonTraining | /day0129/ex1_3.py | 200 | 4 | 4 | """
h=int(input('身長(cm):')) / 100
w=float(input('体重(kg):'))
bmi=w/h/h
print('BMI:{}'.format(bmi))
"""
h,w=int(input('身長(cm):'))/100,float(input('体重(kg):'))
print(f'BMI:{w/h**2 :.1f}')
|
e769219583d3448c77e629d116d9c6522697c486 | willqiao/python | /algorithm/fibonacci.py | 316 | 4 | 4 | # Uses python3
def calc_fib(n):
if (n <= 1):
return n
if n == 2:
return 1
last1 = 1
last2 = 1
#1, 1, 2, 3
sum = 0
for _ in range(2, n):
sum = last1+last2
last2 = last1
last1 = sum
return sum
n = int(input())
print(calc_fib(n))
|
9fcc37e203c8fc6dba68bcdb37a182b157c4fb67 | Sankarshan-Mudkavi/Project-Euler | /1-10/Problem-3.py | 626 | 3.671875 | 4 | """ The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143? """
from math import sqrt
def largest_prime_div(check_num):
primes = set([])
cur_prime = 2
prime_div = []
while cur_prime < check_num:
isPrime = True
for prime in primes:
... |
acefbe89d6130d73303055c79f55f063edf912da | mpeaton37/dit | /dit/utils/bindargs.py | 7,996 | 3.640625 | 4 | """
Provides usable args and kwargs from inspect.getcallargs.
For Python 3.3 and above, this module is unnecessary and can be achieved using
features from PEP 362:
http://www.python.org/dev/peps/pep-0362/
For example, to override a parameter of some function:
>>> import inspect
>>> def func(a, b=1, c=2,... |
9f0381575075a085457121509978b0d23854ac3a | samarthchadda/pypi | /Python udemy/tkinterBindingFunictions.py | 229 | 4.125 | 4 | from tkinter import *
root=Tk()
def printName():
print("Hello my name is Samarth")
button1=Button(root,text="Print my name",command=printName) #root is written to put button in main window
button1.pack()
root.mainloop() |
0a788904e90190967d0bf0e6b8ee5fe326bc3ee0 | Dioscur/Python | /bufer/person.py | 1,600 | 4.0625 | 4 | import datetime
from datetime import date
class Person(object):
SEX = ['M', 'F'] # class variable
def __init__(self, name, date_of_birth, person_sex):
"""
Attributes:
date_of_birth has format YYYY-mm-dd, '1986-04-10'
"""
self.name = name
if person_sex ... |
96ceed434fd1f7bfe4b06650e47fa74fa70cb858 | nrwade0/projects | /Sudoku/sudoku.py | 3,470 | 4.03125 | 4 | """
Sudoku puzzle solver
"""
"""
Finds the next cell to be evaluates (has a 0)
returns the coordinates as (row, col)
"""
def FindNextCell(grid):
for row in range(9):
for col in range(9):
if(grid[row][col] == 0):
return row, col
"""
Check possibilities of a cell by
- Row
... |
b0d714b8305e06d911bee1df242edab17dcdb959 | deepak1214/CompetitiveCode | /LeetCode_problems/Container With Most Water/Solution.py | 1,450 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 2020
@author: Shrey1608
"""
# Approach : 1) Brute force : In this case, we will simply consider the area for every possible pair of the lines and find out the maximum area out of those. (Time complexity= O(n^2) || space complexity = O(1))
# 2) Two pointer ... |
b02eed5bc811035f4f82e3978a7203d8a7b59870 | thomasmauerhofer/search-engine | /src/engine/datastore/models/paper_structure.py | 320 | 3.734375 | 4 | # encoding: utf-8
from abc import ABCMeta, abstractmethod
class PaperStructure(metaclass=ABCMeta):
@abstractmethod
def __str__(self):
"""Print the Data of the Object"""
return
@abstractmethod
def to_dict(self):
"""Creates an Dictionary with the objects Data"""
return
|
3bf873eddb33e41f440c05f805e91f37bebe24d2 | sunda-y/PythonDataStructure | /week06/Assignment6.5.py | 724 | 4.09375 | 4 | """
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.
Convert the extracted value to a floating point number and print it out.
"""
#output:
#0.8475
str = "X-DSPAM-Confidence: 0.8475d fds a"
left = -1
right = -1
for letter in str:
if ((not let... |
c3739ef8844a37bad0c47aa2f233142c8350e0f5 | divalentino/HackerRankProjects | /temperature-predictions/temperature.py | 2,661 | 3.734375 | 4 | #!/usr/bin/env python
# Check out here: https://machinelearningmastery.com/handle-missing-data-python/
# for imputation in Python + scikit
import pandas as pd
from pandas import read_csv
from sklearn.preprocessing import Imputer
import numpy as np
from scipy import interpolate
# Make a hash table for months to treat... |
6d97d3528ebad96692ae16caf0c2ca7d846cbfcf | sumedh105/Python-Programs | /GeeksForGeeks/DataTypes/Sets/removeElementsFromASet.py | 251 | 3.5625 | 4 | # Create a set
setOne = set([16, 3, 1987, "Sumedh", "W.", "Jambekar"])
print(setOne)
# Removing an element using discard() method
setOne.discard("Sumedh")
print(setOne)
# Removing an element using discard() method
setOne.discard(1987)
print(setOne)
|
f4655a513c8d62b4d11833eae6282d243f0eab5e | nikopa96/iti0210-ai | /EX03/nq_position.py | 2,082 | 3.734375 | 4 | from random import randint
class NQPosition:
def __init__(self, N):
# choose some internal representation of the NxN board
# put queens on it
self.N = N
self.board = []
for i in range(0, N):
j = randint(1, N)
self.board.append(j)
print(sel... |
38b70a7024fc6dff8662782e7896f354086ff60d | sarahmaeve/lpthw | /ex42.py | 1,889 | 4.4375 | 4 | ### Animal is an object (look at the extra credit session)
class Animal(object):
pass
## Dog is a class of animal
class Dog(Animal):
def __init__(self, name):
## Dog has a name
self.name = name
## Cat is a class of animal
class Cat(Animal):
def __init__(self, name):
## Cat has a ... |
b1708152914884b82926563ecde189795037fd83 | yardenTal1/Hang-Man-Game | /hangman.py | 7,813 | 3.78125 | 4 | import hangman_helper
def same_length(words, pattern):
"""
A auxiliary function for 'filter_words_lis', that receive word list and pattern and check if the in same length.
the function returns a filter list of those words
"""
new_list = list()
for i in words:
if len(pattern) ... |
7f6aa82315fb35a64d654a2eb861454e3af7c299 | oerpli/Snake | /src/Direction.py | 1,396 | 3.65625 | 4 | from enum import Enum
class Direction(Enum):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
@staticmethod
def ValidNewDirection(old_dir, new_dir):
if old_dir == Direction.LEFT and new_dir == Direction.RIGHT:
return False
if old_dir == Direction.UP and new_dir == Direction.DOWN:
return False
if new_dir == Direc... |
9d2b4e14fc802dd78a6c6d16e14143c6f5f08a90 | kannanisaboss0/C-135 | /ModifiedStarDataGraphPlotter.py.py | 4,325 | 3.515625 | 4 | #-----------------------------------ModifiedStarDataGraphPlotter.py-----------------------------------#
'''
Importing Modules:
-plotly.express (px)
-sys
-statistics (st)
-csv
-pandas (pd)
-time (tm)
'''
import plotly.express as px
import sys
import statistics as st
import csv
import pandas as pd
import time as tm
gl... |
0a9de78a6eb00936955a78d02895c3925e76583f | sidtrip/hello_world | /CS106A/week2/ass2helpsess/multiplyNumbers.py | 317 | 4.1875 | 4 |
def main():
#read two integers
num1 = float(input("Enter first number "))
num2 = float(input("Enter second number "))
#convet to float
#multiply them
multiple = num1 * num2
#print result
print("The multiplication is: " + str(multiple) + ".")
if __name__ == '__main__':
main()
|
d393ca251449471dbd5a74a2d4ad0dbc411f80a6 | raju0698/Python-codes---1 | /Fibonacci.py | 192 | 4.25 | 4 | #Code that generates Fibonacci Series
n = int(input("Enter the value of n:"))
a = 0
b = 1
i = 0
for i in range(0, n):
print(a, end=' ')
a, b = b, a + b
i += 1
|
c2e4510d41952dee026d42a82ab33361d73256e3 | eugenemonnier/data-structures-and-algorithms | /code_challenges/array_reverse/array_reverse.py | 141 | 3.734375 | 4 | def __reverseArray__(arr):
reverseArr = []
for x in range(0, len(arr)):
reverseArr.append(arr[len(arr) - x - 1])
return reverseArr
|
b5e9d9ffa01ae8021e190d70b2e7708cd5342b21 | aimdarx/data-structures-and-algorithms | /solutions/Stacks & Queues/valid_parenthesis.py | 1,383 | 4.03125 | 4 | """
Valid Parentheses / Balanced Brackets
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
https:/... |
304c61c3347e457ab4b0b83d6414459072aa0eae | Hari2019041/Fun-Scripts | /Simulations/rock_paper_scissors.py | 915 | 3.8125 | 4 | from random import randint
class Player:
def __init__(self):
self.throw = randint(1, 3)
def play_game():
player1 = Player()
player2 = Player()
throw1 = player1.throw
throw2 = player2.throw
if throw1 == throw2:
return 0
if throw1 == 1:
return 1 if throw2 == 2 els... |
1871c3550b2fdeec3aa97f6fb216eef584767666 | superoo7/Machine-Learning | /ML/Part2/Simple_Linear_Regression/simple_linear_regression.py | 1,717 | 3.796875 | 4 | # Use preprocessed template
# Data Preprocessing Template
# Import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, 0].values # Independant variable
Y = dataset.iloc[:, -1].values # Dependant variable
... |
dd0ab6a1d5facd365e944001a9d53563b9400e5b | httpssamantha/Hangman | /hangman_app.py | 3,190 | 3.984375 | 4 | """
hangman_app.py is an app for playing hangman in the terminal
it is also used as a module in the hangman_webapp flask app
"""
def get_word_so_far():
word_so_far = '-' * len(word)
return word_so_far
def generate_random_word():
import csv
import random
cool = []
f = open('words 3.csv')
... |
c34ba89406fd4298113dbf1918f95cf800ab217a | stevegraves/CodeWars | /prime_gap.py | 717 | 3.75 | 4 | import math
# Boolean primality check with 6k +/- 1 pattern
def is_prime(n):
if n <= 6:
return n == 2 or n == 3 or n == 5
if n % 2 == 0 or n % 3 == 0:
return False
limit = int(math.sqrt(n))
t = 5
while t <= limit:
if n % t == 0 or n % (t + 2) == 0:
return False
... |
abe9d4d99edb5da8bac510428e28e0b4be0c0d24 | llwsykll/leetCode | /balancedBinaryTree/blbnrtr.py | 662 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root == None or root.left == root.right == None:return True
if self.subI... |
3faf585808683c79a6d6cc36eafaf534a4606bec | WangWei90/adventofcode2017 | /04/solution.py | 700 | 3.578125 | 4 | input = open('data.txt', 'r').read()
# First part
counter = 0
for line in input.split("\n"):
check = True
spl = line.split(" ")
for word in spl:
if(spl.count(word)>1):
check = False
break
if check:
counter = counter+1
print("First part: "+str(counter))
# Secon... |
dd0a4b95e857048c8f0f5b5da3661e4df1c66d0f | lmthanh2011/luongminhthanh-fundamental-c4e17 | /fundamental/session4/nhap.py | 669 | 3.9375 | 4 | #
#
# while True:
# username = input ("username?")
# password = input ("password?")
#
# if username != "c4e":
# print ("no such user")
# elif password != "codethechange":
# print ("wrong password")
# else:
# print ("Welcome")
# break
n=0
while n<3:
username = in... |
f0f9833e83e1837e1b14fce4da5b90e36e645812 | lequan26111991/CIS8005-Data-Programming-for-Analytics | /CIS8005_Assignment2/Chapter12_Excercise3.py | 2,428 | 3.90625 | 4 | ''' Chapter 12 Excercise 3 '''
class Account:
def __init__(self,iden = 0, balance = 100.00, rate = 0.00):
self.__id = iden
self.__balance = balance
self.__rate = rate
#Accessor for ID
def getId(self):
return self.__id
#Accessor for Bal... |
0e5e1075fdaa03a13f7d727b27a486065917b0dd | ander758/HackerRank | /python/Basic-Data-Types/python-lists.py | 779 | 4.03125 | 4 | """
https://www.hackerrank.com/challenges/python-lists/problem
github.com/ander758/HackerRank
"""
arr = []
inputs = ['12', 'insert 0 5', 'insert 1 10', 'insert 0 6',
'print', 'remove 6', 'append 9', 'append 1',
'sort', 'print', 'pop', 'reverse', 'print']
for _input in inputs[1:]:
_input = _i... |
f4fe07b4232ce6a6c3f0a256235e9abd3661a0cf | ncfgrill/Project_Euler | /p012.py | 1,360 | 3.640625 | 4 | ################################################################################
# P12: Highly divisible triangular number #
################################################################################
# ... |
36bc2c94ac571efb5e0ba8a754b0d4ab8d775f33 | jimmy1087/codeKatas | /dp/fibbonaci/recursion_dp.py | 165 | 3.59375 | 4 | def fib(n, memo = {}):
if n == 0 or n == 1:
return 1
if memo.get(n) is None:
memo[n] = fib(n-2) + fib(n-1)
return memo[n]
print(fib(7))
|
ecb57b9f4e1c7a37eecea936cd6d2f14c60ab8b7 | sandorac/codingpractice | /codingpractice.py | 10,505 | 3.828125 | 4 | #!/usr/bin/env python3
# ONLINE PRACTICE PROBLEMS
#Check for pair in an array with a given sum:
def checkpair(l, sum):
for i in range(len(l) - 1):
if l[i] + l[i+1] == sum:
return True
return False
# print(checkpair([1,2,3,4,5,6], 9))
# print(checkpair([1,2,3,4,5,6], 30))
#Find whether an array is a subset ... |
e676b3e1c5fce7d362cd2550e41bc356eb6395c6 | JCardenasRdz/SandBox | /Python/1-Curve_Fitting_and_Functions.py | 1,068 | 3.765625 | 4 | # Learn several ways of performing curve fitting
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Method 01
def foo(x, a, b, c): # One input per variable
return a * np.exp(-b * x) + c
xdata = np.linspace(0, 4, 50);
ydata = foo(xdata, 2.5, 1.3, 0.5) + n... |
e8e90f25f64e88da9ae21c1a23a754cb6dde4cf8 | stevenjwoods/Advent-of-Code-2018 | /Day 1 - Chronal Calibration/chronal_calibration.py | 1,107 | 3.875 | 4 | # Steven Woods
# Advent of Code 2018
# Day 1: Chronal Calibration
# To run: python3 chronal_calibration.py <path/to/frequency_shift_file>
import sys
inFile = sys.argv[1]
with open(inFile, "r") as f:
frequency_shifts = [int(change.rstrip()) for change in f] # List of frequency changes
current_frequency, first_round... |
e287c839859be0ef6372c5447e5a608383d1eea5 | yuzisun/ooplbb | /exercises/Integer.py | 1,047 | 4.03125 | 4 | #!/usr/bin/env python3
# ------------------
# IntegerSolution.py
# ------------------
from unittest import main, TestCase
""" ----------------------------------------------------------------------
Define integer such that it's an iterable over the digits of the integer
from least to most significant digit.
"""
clas... |
0c2db8f83f31debd6852ca414ca470f602877c28 | kuroroblog/atcoder227 | /B.py | 1,831 | 3.5625 | 4 | # 標準入力を受け付ける。
N = int(input())
S = list(map(int, input().split()))
# 実際の建築面積になりうる値を演算する関数。
def calc_area(a, b):
return 4 * a * b + 3 * a + 3 * b
# 予想した面積が確実に誤りであるとわかる人数
error_cnt = 0
for i in range(N):
# 各人が予想した建築面積が正しいかどうか、検査する。
# a, bは正の整数。正の整数の初期化を行う。
a = 1
b = 1
# 各人が予想した建築面積が正しいか判定するためのフ... |
0cc232ead3d2a1b80001307777db578eaa2c66e6 | gabs136/project-euler-solutions | /problem3.py | 708 | 3.59375 | 4 | numdiv=[]
primediv=[]
largest = 0
greatest=0
def is_prime(num):
dlist=[]
for j in range(1,num):
if num%j==0:
dlist.append(j)
if len(dlist) == 1:
result = True
else:
result = False
... |
b5ccd729d465e0098e270070aed0fc47854b01ab | samantabueno/python | /CursoEmVideo/CursoEmVideo_ex115_prof/lib/interface/__init__.py | 563 | 3.8125 | 4 | def title(txt):
print('-'*40)
print(f'{txt}'.center(40))
print('-'*40)
def readInt(msg):
while True:
try:
number = int(input(msg))
except KeyboardInterrupt:
print('ERROR. The user did not enter a number.')
break
except:
print('ERR... |
6e7336c8f35b3a93cee16e6cdd24aa8ad04256c1 | sergushenkov/euler | /022_names_scores.py | 1,397 | 4.03125 | 4 | """
Using names.txt (right click and 'Save Link/Target As...'),
a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order.
Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name score.
For exa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.