blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
c620e5d12e747fc9a2cafae10ed10c29556fcdff
AbhinavOldAccount/MathInterpreterInPython
/Lexer.py
2,541
3.65625
4
# Lexer.py # Programmed By Abhinav.. # The Program That Splits The Expression Into Tokens # .. from Tokens import Token, TokenType Digits = "0123456789" class Lexer: def __init__(Self, Text): Self.Text = iter(Text) Self.Advance() def Advance(Self): try: ...
62b3d9b5de64209b13310158e1ff698314065dc0
JuliaVoronenko/Python_1_lessons
/lesson_02/home_work/hw02_normal.py
4,216
4.21875
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь. Вывести результат # Пример: Дано: [2, -5,...
6939ab32416d84c316791722517d6719e92ff679
JasonMuscles/Net_01
/wjs_06_download_client.py
957
3.640625
4
import socket def main(): # 1.创建套接字 tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2.获取服务器的IP、PORT dest_ip = input("请输入下载服务器的IP:") dest_port = int(input("请输入下载服务器的PROT:")) # 3.链接服务器 tcp_socket.connect((dest_ip, dest_port)) # 4.获取下载的文件名称 download_file_name = inp...
60a1ac5857e25ea80b93363fa7ab98210d8128f9
ArianeDucellier/Programmation
/Amazon/recommend.py
1,836
3.921875
4
#Buy It Again #Given a CSV file in the following format: #CustomerID, ProductID, Date of Purchase, Quantity #1, 295872, 2020-01-02, 2 #1, 295872, 2020-02-03, 1 #1, 235984, 2019-01-06, 3 #2, 325982, 2018-05-05, 1 #... # ... i.e. the CSV file contains multiple # `(customer ID, product ID, purchase date, quantity)` # ...
e8ff0c204015040873dcba862d6129089ba16a5f
mdujava/PB016
/1.1_13.py
1,205
3.75
4
class Osoba(): """trieda osoba""" def __init__(self, meno): self.meno = meno self.otec = None self.mama = None def nastavOtca(self, otec): self.otec = otec def nastavMamu(self, mama): self.mama = mama def ziskajRodicov(self): rodicia = [] rodicia.append(self.otec) rodicia.append(self.mama) r...
536db9d2b4fe5d39ca9e0e062a960f1d19207ad0
mdujava/PB016
/1.3.1_18.py
546
3.84375
4
import sys def fib_rec(i): if i < 3: return 1 return fib_rec(i - 1) + fib_rec(i - 2) def fib_iter(i): array = [1, 1] for j in range(2, i): array.append(array[j-1] + array[j-2]) return array[i-1] # pole indexujeme od nuly def main(): # pre veľké čísla # sys.setrecursionlimit(10000) print("Príklad na výpo...
cc95b92b07bcdc8267676dda50e56831e2505644
N9199/Tareas
/Algebra Abstracta/Tarea V Algebra Abstracta/gcd.py
392
3.71875
4
def gcd(a,b): if a == 0 and b == 0: return 0 if min(a,b)==0: return max(a,b) if a>b: print("\\[",a,":",b,"=",a//b,"\\]") print("Resto:$",a%b,"$") return gcd(b,a%b) else: print("\\[",b,":",a,"=",b//a,"\\]") print("Resto:$",b%a,"$") retu...
a1acd77a9c1adbe44056a532909bc9378681122a
OnoKishio/Applied-Computational-Thinking-with-Python
/Chapter15/ch15_storyTime.py
781
4.1875
4
print('Help me write a story by answering some questions. ') name = input('What name would you like to be known by? ') location = input('What is your favorite city, real or imaginary? ') time = input('Is this happening in the morning or afternoon? ') color = input('What is your favorite color? ') town_spot = input('Are...
06a380932170c792cb2344c553c0ee01489451bd
OnoKishio/Applied-Computational-Thinking-with-Python
/Chapter10/ch10_functions2.py
186
3.859375
4
def myNumbers(minNum, maxNum): myList = [] for num in range(minNum, maxNum + 1): myList.append(num) print(myList) myNumbers(4, 9) myNumbers(1, 3) myNumbers(9, 17)
d6d652ccebc7793c98b26c9b66e58c75ae9317d8
ron20-meet/y2s19-mainstream-python-review
/part1.py
291
3.515625
4
# Part 1 of the Python Review lab. def hello_world(): print("hello_world") def greet_by_name(): name = input("NAME PLS") print ("hello " + name) def encode(number): return (3953531 * number) def decode(y): return(int(y) - 3953531) pass hello_world() greet_by_name() encode(676)
ff491a42ef7f5d9785d2e74f1852e70e26f4d4ce
diemacre/Online-Social-Network-Analysis
/a4-project/collect.py
4,517
3.609375
4
""" Collect data. """ import sys import time from TwitterAPI import TwitterAPI import pickle consumer_key = 'KxKS7dbjBA4ig3PveHJMZKO3y' consumer_secret = 'JJe9f5jvDCcYcv9fVpcHGQHc4WVQUXXNUG5D4I32Ucodwm7WZ8' access_token = '303155366-OipyjHaPAbbIzG04ReDLCZjwfxxDqjxdY3qGX3I8' access_token_secret = '1e4HljCtZD0Piq6g1W...
fb6e40198a90315f178625254ae60a66d9afa97a
emacenulty/py-121-code
/code-snippets/count_most_common_letter_in_text_solution.py
2,029
4.0625
4
import string from operator import itemgetter #use a dictionary to count the most common letter in the text text=""" Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as:...
1ef5f61d191324288973c68201f4a1807c9ab7db
emacenulty/py-121-code
/code-snippets/ci_data_science__lesson_01_without_answers.py
6,145
4.09375
4
scores = [91,88,83,84,92,95,88,91,88,86] # Algorithm for Median # check the length of list # sort the list # if length of list is odd # calculate median of odd list # if length of list is even # calculate median of even list len(scores) # print(scores) scores.sort() print(scores...
99580d3bdb4d4b76c75c6fd1593ec0b9df38e771
emacenulty/py-121-code
/code-snippets/python_exercise_set__with_answers.py
6,165
4.1875
4
########################################################################## # Exercise 1: Accept a list of 5 float numbers as an input from the user # ########################################################################## #################### # EXPECTED OUTPUT # #################### ''' Enter the list size : 5 En...
fe07080465b1ba2807e3349183eb2045a5cfe688
akashbaran/PyTest
/fileIO/11.py
179
3.984375
4
"""1. Write a Python program to get the file size of a plain file. """ import os def file_size(filename): size = os.stat(filename) return size print(file_size("red.txt"))
aa9f37f884c0b5db1a0e7479b72119c9c86e4a8f
akashbaran/PyTest
/github/q13.py
523
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed May 30 13:04:23 2018 @author: eakabar Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 """ s = input("e...
3cca295b200f107f100923509c3a31077be52995
akashbaran/PyTest
/github/q6.py
635
4.25
4
"""Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma ...
fcd79c9dec21381fe182094407238d40d55db6e4
akashbaran/PyTest
/github/q5.py
425
4
4
"""Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. """ class testStr: def __init__(self): self.s = "" def getStr(self): self.s = raw_in...
b0b2d09c383a9d1354caf54eedc9d0df4a0e9d6a
akashbaran/PyTest
/github/q21.py
1,077
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed May 30 15:34:34 2018 @author: eakabar A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after t...
c6e7af5146e9bcacd925ea9579dd15a8f571bfed
akashbaran/PyTest
/github/re_username1.py
405
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu May 31 12:25:27 2018 @author: eakabar Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. """ import re ema...
7b00ec2635f61211bfa986f31a86eb65c5ad05c7
akashbaran/PyTest
/regex/2.py
262
4
4
"""Write a Python program that matches a string that has an a followed by zero or more b's""" import re str = raw_input("enter the string ") prog = re.compile(r'a[0b*]') res = prog.search(str) if res: print("found",res.group()) else: print("nt found")
55f0dfff9d3c23dc82cd099380dcfe68788f6ebe
pattu777/CompetitiveCoding
/SPOJ/sizecon.py
85
3.546875
4
t=int(raw_input()) s=0 while t: ip=int(raw_input()) if ip>0: s+=ip t-=1 print s
636b5c22658d278d27aa8965022c2ddd5fe24c68
pattu777/CompetitiveCoding
/CodeForces/horseshoe_228A.py
206
3.59375
4
if __name__ == '__main__': num = [int(x) for x in raw_input().split(" ")] count = 0 num.sort() for i in xrange(0, 3): if num[i] == num[i+1]: count += 1 print count
9aee675f320ff34f3434f53c6142a96e9ad32dc6
maxymilianz/CS-at-University-of-Wroclaw
/Python - advanced course/Solutions/2/3.py
1,622
3.765625
4
import timeit class ResException(BaseException): def __init__(self, n): self.n = n def factorial_rec(n): return 1 if n == 0 else n * factorial_rec(n - 1) def factorial_e(n): def factorial(n, acc): if n > 1: factorial(n - 1, acc * n) else: raise ResException...
9593466bc12fb8d87a65c2e0ed30975ddc58a270
NeonLeexiang/codewar
/6kyu/multiples_of_3or5.py
419
3.96875
4
def solution(number): rt = 0 for i in range(number): if i%3 == 0 or i%5 == 0: rt += i return rt """ def solution(number): return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0) """ """ def solution(number): a3 = (number-1)/3 a5 = (number-1)/5 a15 = (numb...
295907728ee6ba7f4e26d32e29d26b2464bd4ed6
NeonLeexiang/codewar
/5kyu/Memorized Fibonacci.py
733
4.03125
4
# method 1 def fibonacci1(n): def fibo_liter(n, x, y): if n == 0: return x else: return fibo_liter(n-1, y, x+y) return fibo_liter(n, 0, 1) # method 2 def fibonacci2(n): numlist = [0, 1] for i in range(n - 2): numlist.append(numlist[-2] + numlist[-1]) ...
8cdfdb9bd50dd410be0597ab06102f06d2968c3a
NeonLeexiang/codewar
/5kyu/Where my anagrams at?.py
597
3.90625
4
def anagrams(word, words): #your code here wordsort = [''.join(sorted(word))] w2 = [sorted(item) for item in words] w2 = [''.join(item) for item in w2] rword = [] count = 0 for item in w2: if item == wordsort[0]: rword.append(words[count]) count += 1 e...
1354b90ac40bb428dfd7666955ff8aa2c4a06193
NeonLeexiang/codewar
/6kyu/which_are_in.py
526
3.6875
4
def in_array(array1, array2): return_list = [] for c1 in array1: for c2 in array2: (s1, s2) = (c1, c2) if (len(c1) < len(c2)) else (c2, c1) if s1 in s2: # and s1 != "46" and s2 != "ode" return_list.append(s1) return sorted(set(return_list)) """ return...
4d05ab8118b35353fb839e0579f6f0fa1043b143
NeonLeexiang/codewar
/7kyu/round2nearest0or5.py
173
3.640625
4
def round_to_five(numbers): return [5*int(x/5 + 0.5) for x in numbers] """ def round_to_five(numbers): return [5 * round(n / 5) for n in numbers] """
fd0a2ae9f812fffeb5714ca1e6c090260276f4a6
NeonLeexiang/codewar
/6kyu/Playing with digits.py
367
3.5
4
def dig_pow(n, p): # your code nlist = [int(i) for i in str(n)] for i in range(len(nlist)): nlist[i] **= p p += 1 sumnl = sum(nlist) if sumnl % n == 0: return sumnl / n else: return -1 """ def dig_pow(n, p): s = 0 for i,c in enumerate(str(n)): s += pow(...
c3a9cf80965eb1766a1c54719cacc153972f3e67
NeonLeexiang/codewar
/6kyu/not_prime_number.py
3,522
3.703125
4
from math import sqrt def is_prime(n): if n < 2: return False for x in range(2, int(sqrt(n)) + 1): if n % x == 0: return False return True def judge_number(n): for c in str(n): if c not in "2357": return False return True def not_primes(a, b): ...
6e139b999ca38394f726e903271f83224cc2241b
NeonLeexiang/codewar
/5kyu/number_of_trailing_zero_of_N!.py
517
3.8125
4
# math.factorial(n) == n! import math def zeros(n): n_trailing = str(math.factorial(n)) for i in range(1, len(n_trailing)): if n_trailing[-i] != 0: return i # while version:2.7 # while version:3.4 should pay attention to / and // """ def zeros(n): count=0 while n: count+=...
a8f813efdbfd47da8cd66b471023ac17ae801f94
Bluegroundhog18/grephy
/grephy.py
2,085
3.5
4
import re import io #regexIn = open('test.txt', 'r') #lineScan = file.readlines() #alphTrack = int(6) #alphabet = [] #for i in range(lineScan): # if i in alphabet # # else # alphabet.append(regexIn.readline()) #print(alphabet) #for char in alphabet: # print(char, end="") #def readFile(file): # try: # w...
2e79189d7e88fbd3bab38f6a9ecd6facc199f96c
NguyenHoaiPhuong/BasicPython
/tutorials/tut05/loops.py
1,652
4.0625
4
# -*- coding: utf-8 -*- def WhileLoop(): print("while loop") var = 0 while var < 9: print(var) var += 1 print("\n") def InfiniteWhileLoop(): print("infinite loop") var = 1 while var == 1: num = input("Enter an integer number: ") try: ...
0ecf0e4f6f979a5632219d8c05398728b96b0c45
spglancy/Makeschool-Coding-Challenges
/assignment4.py
1,059
3.984375
4
# Rotate a given linked list counter-clockwise by k nodes, where k is a given integer. # What clarifying questions would you ask? # What do you mean by counterclockwise # What reasonable assumptions could you state? # Ill assume that I have the head and the tail of the LL and that the nodes are connected via .next #...
84573ae7f5183f3d4de8657bbde5f8b88e73d229
medev21/cbprogrammingchallenges
/numberAdditionPython/numberAddition.py
678
4
4
def NumberAddition(str): nums = '' #empty nums variable for i in range(0, len(str)): #check if i char is a number, between 48 and 57 represents chars 0 to 9 if(ord(str[i]) >= 48) and (ord(str[i]) <= 57): nums = nums + str[i] #add the i char else: nums = nums ...
137ed85ba6f1bb5820f6cc0b6a8f9b7207f49dd4
armine94/myWorks
/python/countOfThreeMultiples.py
640
4.09375
4
def countOfThreeMultiples(n): #multiples count count = 0 for i in range(102, n + 1, 3): #separating number start = i // 100 mid = (i // 10) % 10 end = i % 10 #check if repeated number if(start != mid and start != end and mid != end): count = ...
9f4e9bf2c5afa814dad92bd3646d255b91d490b2
armine94/myWorks
/python/equalNumber.py
277
3.828125
4
def boolFunction(num): #if number greater or less 1000/2000 of 100 return True else False return (abs(1000 - num) == 100 or abs(2000 - num) == 100) def main(): num = int(input("Enter number: ")) print(boolFunction(num)) if __name__ == "__main__": main()
5a5d773411d81d69d0b391fad666d4da3ecb6b0d
bastrob/DataScience_from_Scratch
/python/statistics.py
1,939
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 21:56:32 2020 @author: Bast """ from typing import List from collections import Counter from algebra import sum_of_squares import math from algebra import dot def mean(xs: List[float]) -> float: return sum(xs) / len(xs) def _median_odd(xs: List[float]) -> floa...
210fa6b7144f48b460ec4fe1245c64eb79ff6fa6
tyroneruss/RLGAnalysis
/CountModule.py
871
3.53125
4
import os import sys def CountRecords(filevalue1,filevalue2): with open(filevalue1, "r") as infile1: data1 = infile1.read() # Read the contents of the file into memory. file1_list = data1.splitlines() with open(filevalue2, "r") as infile2: data2 = infile2.read() # Read the contents of the file into memory...
8532681a74c900c004f042fc144eeb7a69e939ae
seetwobyte/Terraform
/kids_python/list.py
111
3.890625
4
# list Daysoftheweek = ["Monday", "Tuesday", "Wednesday"] print(Daysoftheweek[1]) print(Daysoftheweek[-1])
68ba729f65ebb354b334e17b89683d6e1e9c6326
hoffie/ripple
/ripple/entry.py
3,947
3.59375
4
import re import math from datetime import datetime KEYWORD_ENTRY_RUNNING = 'running' DATE_FORMAT = "%Y-%m-%d %H:%M:%S" DATE_SPEC_RE = "((?:\d{4})-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}|running)" ENTRY_MATCHER_RE = DATE_SPEC_RE + '\s+' + DATE_SPEC_RE + '(?::?$|:\s+(.*))' ENTRY_MATCHER = re.compile(ENTRY_MATCHER_RE) split_wo...
ffaeafa42a45813f8d596164edef9bb8b7283cd3
barrosotadeu/Calculadora-OOP
/calculo.py
619
3.625
4
from calculadoraoop import Calculadora from sys import exit from math import sqrt, pow calculadora = Calculadora() print('*********Calculadora*********\n\n\n\n') while True: escolha = int(input('''Qual operação você deseja fazer: 1: Soma ...
80b3c58e0d0aaa58619977b46a3b087ab069d42c
MarcusPlieninger/codility
/ch6_Triangle.py
570
3.578125
4
''' because A is sorted, the following obtains: A[i] <= A[i+1] <= A[i+2] A[i] <= A[i+2] therefore: A[i] < A[i+1] + A[i+2] A[i+1] < A[i] + A[i+2] Triangular is defined by: 0 <= A[i] < A[i+1] < A[i+2] < N (satisfied by above) A[i] + A[i+1] > A[i+2] this criterion must be checked A[i+1] + A[i+2] > A[i] (satisfied by abo...
1558f4c6d3316be6921fe5ea74b6b0bad476bba4
MarcusPlieninger/codility
/ch6_Distinct_test.py
1,487
3.921875
4
''' Write a function def solution(A) that, given an array A consisting of N integers, returns the number of distinct values in array A. Assume that: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]. For example, given array A consisting ...
02016936b76ed95aa603a47735726745ae8de573
wlchagas/workspace
/enjoei_bi_case/exercise_02/sum_avg.py
1,074
3.921875
4
#!/usr/bin/env python3 """sum_avg.py: Retornar soma e média de cinco números""" __author__ = "Wellington Chagas" __copyright__ = "Open-source" __license__ = "Free" __version__ = "1.0" __maintainer__ = "Wellington Chagas" __email__ = "wlchagas@gmail.com" __status__ = "Done" from statistics import mean numbers...
74e1d194b033d70e82f31bc2d8bb88d92543cdbd
rupikarasaili/GuiProject
/tkinter/seven.py
238
3.859375
4
from tkinter import * root = Tk() def myClick(): myLable = Lable(root, text = "Button is CLicked!!") myLable.pack() myButton = Button(root, text = "click" , command = myClick, fg = "red", bg = "grey") myButton.pack() mainloop()
0039e343aa1308443becd1d18a35988a1df8d42e
makimaliev/BIL622
/HW1/rk3.py
829
3.671875
4
from math import sqrt from matplotlib import pyplot as plt def rk4(f, x0, y0, x1, n): vx = [0] * (n + 1) vy = [0] * (n + 1) h = (x1 - x0) / float(n) vx[0] = x = x0 vy[0] = y = y0 for i in range(1, n + 1): k1 = h * f(x, y) k2 = h * f(x + 0.5 * h, y + 0.5 * k1) k3 = h * f...
89c612f5467e292eb53fb43c3a3c902ecb998559
makimaliev/BIL622
/HW4/bvp.py
5,361
3.640625
4
#!/usr/bin/env python """A variety of methods to solve ODE boundary value problems. AUTHOR: Jonathan Senning <jonathan.senning@gordon.edu> Gordon College Based Octave functions written in the spring of 1999 Python version: October-November 2008 """ import numpy #-------------------------------------...
f91153b1e733eda10e2d41e238f13931e5aa90fe
picklesueat/free-college
/conner/labs/lab03/lab03.py
3,006
4.46875
4
HW_SOURCE_FILE = __file__ def summation(n, term): """Return the sum of numbers 1 through n (including n) wíth term applied to each number. Implement using recursion! >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3 225 >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 +...
d745008be9f1aa78f450aca4bd3b0c7b6476a972
P1sec/openapi-python-client
/end_to_end_tests/golden-record/my_test_api_client/models/an_enum.py
177
3.515625
4
from enum import Enum class AnEnum(str, Enum): FIRST_VALUE = "FIRST_VALUE" SECOND_VALUE = "SECOND_VALUE" def __str__(self) -> str: return str(self.value)
7f4ee1a6f8712582e90a4c3ffb1577150d02b3cf
Spencerx/dashscrape
/bin/scrape-github
1,101
3.515625
4
#!/usr/bin/env python """ Usage: scrape-github [count] < repos.txt This program expects to read a newline-delimited list of GitHub repositories on STDIN. It will fetch the recent events feed for all of them and will interleave the output, printing at most 'count' entries. By default, 'count' is 30. """ from __future...
04ef0a5ad63b2181071cec55522bc840d897a428
wiwi12138/lg4
/game/game_2.py
1,264
3.671875
4
# -*— coding:utf-8 —*— # @time :2020/10/2610:20 # @Auttor :wiwi # @File :game_2.py """ 一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力, hp的初始值为1000,power的初始值为200。 定义一个fight方法: my_final_hp = my_hp - enemy_power enemy_final_hp = enemy_hp - my_power 两个hp进行对比,血量剩余多的人获胜 """ def fight(): # 给四个变量初始值,并定义规则,只要不是我的血量大于对手,则算我输,反之...
941074af565321169866cc6008c8f2387043f91c
rathalos64/hgb-algo5
/03_kmeans_gmm/kmeans/lib/cluster.py
1,892
3.796875
4
#!/usr/bin/env python import math from functools import reduce class Clusters: def __init__(self): self.clusters = {} def __iter__(self): return iter(self.clusters.values()) def append_cluster(self, cluster): self.clusters[cluster.id] = cluster def append_to_nearest_cluster(self, observation, dist, D): ...
11c22845f253c53f3e4d3fd438ff68e92a7f8866
rathalos64/hgb-algo5
/03_kmeans_gmm/kmeans/lib/distance.py
484
3.734375
4
#!/usr/bin/env python import math class Distance: @staticmethod def get_distance_method(key): mappings = { "euclidian": Distance.euclidian_distance } if key not in mappings.keys(): return Distance.euclidian_distance return mappings[key] @staticmet...
5ccf28d51be597cb3ab2713e4c91cc9b3b22afa0
MANC3636/TensorFlow2_intro
/tf2_optimizer.py
468
3.84375
4
import tensorflow as tf """not clear on what optimizer does""" a=tf.Variable(0.0) def myloss(x): loss =a*x return loss tf.print("my loss is ", myloss(5)) loss=lambda:abs(myloss(5)-[25])#why is 25 in brackets? optimizer=tf.optimizers.Adam(1)#one is the learning rate optimizer.minimize(loss, [a])#here, a is a...
735f13d7a9e88438e2b00afb330f7397eb8ca741
tugrazbac/sorting_algorithm
/towers_of_hanoi.py
467
3.71875
4
a = [2,3,1,5,4] b = [] c = [] ndisks = len(a) print("-----------test---------") print( a.count(3)) #print an der listenstelle 3 print(a.pop(0)) #first item print(a.pop()) #last item print("--------testende--------") print(ndisks) def hanoi(ndisks, a, b, c): if(ndisks == 1): print("move disk", a, " to ", ...
04a70b7f8f70a6d3d52571aa3f095edba2499fa3
lamhuy/audioUtils
/utils/update_time_change.py
1,337
3.515625
4
def update_time_change(time_elapsed, track_time): elapsed = time_elapsed.split(":") if len(elapsed) == 2: elapsed_h = 0 elapsed_m = int(elapsed[0]) elapsed_s = int(elapsed[1]) if len(elapsed) == 3: elapsed_h = int(elapsed[0]) elapsed_m = int(elapsed[1]) elapse...
b761d29007cc6ccf91f4c838e7fb2f4ebc972e8f
JimNastic316/TestRepository
/DictAndSet/challenge_simple_deep_copy.py
1,020
4.375
4
# write a function that takes a dictionary as an argument # and returns a deep copy of the dictionary without using # the 'copy' module from contents import recipes def my_deepcopy(dictionary: dict) -> dict: """ Copy a dictionary, creating copies of the 'list' or 'dict' values :param dictionary: ...
42455a07e117cf79b631630e7fe65f6cceaf5911
micmoyles/hackerrank
/alternatingCharacters.py
880
4.15625
4
#!/usr/bin/python ''' https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings You are given a string containing characters and only. Your task is to change it into a string such that there are no matching adjacent cha...
3a53c4f41bf1a8604ea073a17762e2dcfc39c8d8
jbsec/pythonmessagebox
/Message_box.py
598
4.21875
4
#messagebox with tkinter in python from tkinter import * from tkinter import messagebox win = Tk() result1 = messagebox.askokcancel("Title1 ", "Do you really?") print(result1) # yes = true no = false result2 = messagebox.askyesno("Title2", "Do you really?") print(result2) # yes = true no = false result...
1f3a715307f9811e774dc52218691c7b87dee3a3
jvalin17/Machine-Learning-algorithms
/Self-Training Semi-Supervised Program/MLP3.py
5,006
3.8125
4
# coding: utf-8 # In[22]: import numpy as np import math import csv #name is name of test file that is Du in the homework name = 'test_ml3.csv' #t is theta values ; randomly taken t = [1,2,3,4] loop = 0 #k denotes the number of times we run self training algorithm to classify unlabled data k = 10 for loop in ra...
a993b0b69e113eefbf033a5a6c4bbebd432ad5e9
cs-fullstack-2019-fall/codeassessment2-insideoutzombie
/q3.py
1,017
4.40625
4
# ### Problem 3 # Given 2 lists of claim numbers, write the code to merge the 2 # lists provided to produce a new list by alternating values between the 2 lists. # Once the merge has been completed, print the new list of claim numbers # (DO NOT just print the array variable!) # ``` # # Start with these lists # list_of_...
f9020c1d3f2edfdbb410bbe1a5fe56010a1faf09
quinzel25/Capstone
/week1/warmup2.py
227
3.671875
4
## warmup 2 classes = input('How many classes are you taking? ') classes = int(classes) print(classes) list1 = [] for x in range(classes): stuff = input('Enter name of the class: ') list1.append(stuff) print(list1)
79ebae96957df1b1218dd38885c400a4b0eddb30
spear61/DRILL
/04/graph.py
335
3.84375
4
import turtle count=1 while (count<=6): turtle.pendown() turtle.forward(500) turtle.penup() turtle.goto(0,count*100) count+=1 turtle.home() count=1 turtle.left(90) while (count<=6): turtle.pendown() turtle.forward(500) turtle.penup() turtle.goto(count*100,0) count+=1 turtle....
705101fd2723d7b37537f1f72de560c692b198cd
wula50/tryForGit
/venv/ball.py
857
3.6875
4
# !/usr/bin/python # -*- coding: utf-8 -*- ''' 显示2个球 隐藏第一个球 小球来回动 小球满屏动 ''' import pygame, sys pygame.init() screen = pygame.display.set_mode([800, 480]) screen.fill([255, 255, 255]) my_ball = pygame.image.load("ball.png") x = 50 y = 50 x_speed = 20 y_speed = 20 # screen.blit(my_ball, [50, 50]) # pygame.display.fl...
02a31cdaa4bf34d2214d27a70b8111ed81eff0cc
wula50/tryForGit
/TestYourTank.py
836
3.78125
4
# !/usr/bin/python # -*- coding: utf-8 -*- ''' 长途旅行中,遇到一个加油站,编写一个程序确定是否要在这里加油 问题: 你的油箱有多大? 油箱有多满?(百分比) 汽车每升走多远? 包含一个5升缓冲区,以防油表不准 ''' volumeOfTank = int(raw_input("Size of tank:")) percentOfTank = float(raw_input("percent full:")) * 0.01 literPerKm = float(raw_input("km per liter:")) buffer = 5 distanceToNextStation = ...
74063105a4a48ff4a8b40ccd41d88436f1f06609
roconthebeatz/python_201907
/day_06/file/file_09.py
872
3.59375
4
# -*- coding: utf-8 -*- import csv input_file_name = "data/file_08.txt" #input_file_name = "data/scores.txt" with open(input_file_name, "r") as input_file : # 파일을 읽을 수 있는 객체를 사용하여 # CSV 모듈의 reader 객체를 생성하는 코드 reader = csv.reader(input_file) # CSV 모듈의 reader 객체는 for 문의 변수로 # ...
dfccab9f95be2b883dddb721f22ddf50bf5b2166
roconthebeatz/python_201907
/day_02/dictionary_02.py
1,141
4.1875
4
# -*- coding: utf-8 -*- # 딕셔너리 내부에 저장된 데이터 추출 방법 # - 키 값을 활용 numbers = { "ONE" : 1, "TWO" : 2, "THREE" : 3 } # [] 를 사용하여 값을 추출 print(f"ONE -> {numbers['ONE']}") print(f"TWO -> {numbers['TWO']}") print(f"THREE -> {numbers['THREE']}") # [] 를 사용하여 값을 추출하는 경우 # 존재하지 않는 키값을 사용하면 에러가 발생됩니다. print(f"FIVE -> {n...
e48d07d876002a58aa706bf5479a0e2917c1987d
roconthebeatz/python_201907
/day_04/function_05.py
1,383
3.640625
4
# -*- coding: utf-8 -*- # 파이썬의 함수/메소드는 하나가 아닌 # 다수개의 값을 반환할 수 있습니다. # 두개 이상의 값을 반환하는 함수 # - 최대값과 최소값을 반환하는 함수 def max_and_min(n1, n2) : max_value = min_value = n1 if n2 > max_value : max_value = n2 if n2 < min_value : min_value = n2 # 2개의 값을 반환하는 return 문...
cde49f33ba3d46cf761cecf681720a4d51a75662
roconthebeatz/python_201907
/day_06/file/file_04.py
844
3.5
4
# -*- coding: utf-8 -*- # 파일의 내용을 한줄이 아닌 경우의 처리 방법 # readlines 메소드와 반복문을 활용하여 # 처리할 수 있습니다. input_file_name = "data/file_02_gugudan.txt" input_file = open(input_file_name, "r") # 대용량의 데이터인 경우 일괄작업보다는 # 개별작업이 작업 부하를 줄일 수 있습니다. input_data = input_file.readlines() print(type(input_data)) print(input_data...
e968254435df2ee885e8de6479127eae39bfc2ed
roconthebeatz/python_201907
/day_04/function_02.py
1,282
3.5
4
# -*- coding: utf-8 -*- # 매개변수가 사용되는 함수의 선언 # - 매개변수 : 함수의 실행에 필요한 값을 의미함 # (기존의 변수와 동일한 개념) # - def 함수명( 매개변수명1, 매개변수명2, ... ) # 매개변수를 1개 전달받아 실행될 수 있는 # showNumber 함수의 선언 def showNumber(number) : # 함수가 호출될 때 값이 전달되는 매개변수는 # 변수와 동일한 방법으로 사용할 수 있습니다. # 매개변수는 함수가 실행(호출)될 때 생성되며 # 함수의 호출 ...
c3dc66f1f11af9ac316ed4788fc604125f51d854
roconthebeatz/python_201907
/day_08/matplotlib/matplotlib_06.py
837
3.765625
4
# -*- coding: utf-8 -*- from matplotlib import pyplot as plt from random import random x = list(range(1,11)) y = list(map(lambda data : data * random() + 3, x)) plt.title('Plot Example') plt.xlabel('1 ~ 10') plt.ylabel('random data') plt.xlim(min(x) - 1, max(x) + 1) plt.ylim(min(y) - 1, max(y) + 1) ...
2fd3c44b20263c1c5dd0a3c34e3469063571c184
roconthebeatz/python_201907
/day_02/list_08.py
1,199
3.9375
4
# -*- coding: utf-8 -*- # 리스트에 데이터를 추가하는 방법 # 1. append 메소드를 사용 # - 기본적으로 리스트의 가장 마지막 요소로 추가 numbers = [1,3,5] print(numbers) # numbers 리스트의 마지막 요소로 7 추가 numbers.append(7) print(numbers) # numbers 리스트의 8과 9 추가 # append 메소드는 매개변수로 1개를 입력받기 때문에 # 아래의 append 메소드 실행은 에러가 발생됩니다. # numbers.append(8,9) # ...
cfe42110b1bd27b861bcf017cb893f9e41873699
roconthebeatz/python_201907
/day_05/exception_02.py
774
3.859375
4
# -*- coding: utf-8 -*- # 예외처리 문법 # try : # 예외가 발생할 가능성이 있는 코드 # except : # 예외가 발생한 경우 처리 코드 # else : # 예외가 발생하지 않은 경우의 실행코드 # finally : # 예외의 발생 여부와 상관없이 실행되는 코드 # 예외가 발생될 가능성이 있는 코드 #n1 = int(input("정수 입력 : ")) #n2 = int(input("정수 입력 : ")) #r = n1 / n2 #print(f"r -> {r}") try : n1 ...
ec2279635d73dfabdce13ef10a7922ad697939a2
roconthebeatz/python_201907
/day_02/list_03.py
484
4.25
4
# -*- coding: utf-8 -*- # 리스트 내부 요소의 값 수정 # 문자열 데이터와 같은 경우 배열(리스트)의 형태로 저장되며 # 값의 수정이 허용되지 않는 데이터 타입입니다. msg = "Hello Python~!" msg[0] = 'h' # 반면, 일반적인 리스트 변수는 내부 요소의 값을 # 수정할 수 있습니다. numbers = [1,2,3,4,5] print(f"before : {numbers}") numbers[2] = 3.3 print(f"after : {numbers}") ...
09ab816af51e743bf7eca63f65327a4edc84dce8
roconthebeatz/python_201907
/day_06/exception_03.py
767
3.640625
4
# -*- coding: utf-8 -*- # 예외처리 시, except 절을 정의하게 되면 # 어떠한 예외가 발생하더라도 # 동일한 예외처리 코드를 실행합니다 # 만약, 지정한 예외만 처리하고자 하는 경우 # 예외 클래스를 정의하여 처리할 수 있습니다. # - except 예외클래스 as 예외의 메세지를 전달받을 변수 : # - 정의된 예외가 발생한 경우 처리할 코드 ... try : n1 = int(input('정수 입력 : ')) n2 = int(input('정수 입력 : ')) r = n1 / n2 exce...
4d820a5480f429613b8f09ca50cacae0d2d5d377
roconthebeatz/python_201907
/day_03/while_02.py
603
4.28125
4
# -*- coding: utf-8 -*- # 제어문의 중첩된 사용 # 제어문들은 서로 다른 제어문에 포함될 수 있음 # 1 ~ 100 까지의 정수를 출력하세요. # (홀수만 출력하세요...) step = 1 while step < 101 : if step % 2 == 1 : # 제어문 내부에 위한 또다른 제어문의 # 실행 코드는 해당 제어문의 영역에 # 포함되기 위해서 # 추가적으로 들여쓰기를 작성해야 합니다. print(f"step => {step:...
93e23d423f8a32bddc4ff1bb3cebec4d84d0125f
roconthebeatz/python_201907
/day_08/matplotlib/matplotlib_12.py
568
3.953125
4
# -*- coding: utf-8 -*- from matplotlib import pyplot as plt from random import random x = list(range(1,11)) y = list(map(lambda data : data * random() + 3, x)) plt.subplot(2,1,1) plt.title('Plot Example') plt.xlabel('1 ~ 10') plt.ylabel('random data') # color 속성은 색상 지정 # 기본값은 blue plt.bar(x, y, co...
98746802113577c3ba515ab652b9dcf0a6c9f719
roconthebeatz/python_201907
/day_04/for_14.py
938
3.8125
4
# -*- coding: utf-8 -*- # 구구단의 실행 결과를 저장하는 리스트를 생성하세요. # (홀수단에 해당되는 결과만 저장) #result = [] #for dan in range(2,10) : # # if dan % 2 == 0 : # continue # # for mul in range(1,10) : # result.append(dan * mul) # 리스트 변수의 선언에 중첩된 반복문이 사용되는 예제 # (외부/내부 반복문에 조건식을 적용하려는 경우) # 리스트변수명 ...
f8cee34470276d3eb0f8e127d6698c39990a68c2
yuto-te/my-python-library
/src/factrize_divisionize.py
730
4.21875
4
""" 素因数分解 約数列挙 """ """ e.g. 2**2 * 3**2 * 5**2 = [(2, 2), (3, 2), (5, 2)] """ def factorize(n): fct = [] # prime factor b, e = 2, 0 # base, exponent while b * b <= n: while n % b == 0: n = n // b e = e + 1 if e > 0: fct.append((b, e)) b, e = b ...
440c12a65788bbb74cf729fb513fdda244218e57
timo-juhani/check_password
/check_password.py
1,901
3.578125
4
import requests import hashlib import sys # API uses SHA1 hash function to secure password so that # clear text password is not sent to API # Check hashes that have only five first hash digits same # the password. # Function for hashing the password as expected by API def hash_password(password): ...
37de3a4d5c27f29a322045130318adb155f3bda7
GoldwinXS/roomreader
/ProjectUtils.py
3,318
3.546875
4
import cv2,os import matplotlib.pyplot as plt import face_recognition.face_recognition as fr import numpy as np # test_file = 'test4.jpg' # pixels = plt.imread(test_file) def detect_faces(image): """ simply draw a rectangle around the face in question """ faces = fr.face_locations(image) for face in f...
d043edc1821521c83c1313bce11cfb1d28421443
chenhanfang/test2
/xuexi/test1.py
13,924
3.53125
4
# alien_0={'x_position':0,'y_position':25,'speed':'medium','points':'5'} # print('original x_position:'+str(alien_0['x_position'])) # print(alien_0) # if alien_0['speed']=='slow': # x_increment=1 # elif alien_0['speed']=='medium': # x_increment=2 # else: # x_increment=3 # alien_0['x_position']=alien_0['x_...
ddaa285fefbaa4082ed3c9316ea73fc772e2c1dd
chenhanfang/test2
/class/Survey.py
781
3.609375
4
class AnonymousSurvey(): def __init__(self,question): self.question=question self.responses=[] def show_question(self): print(self.question) def store_response(self,new_response): self.responses.append(new_response) def show_results(self): print('survey results:')...
78716b631ae317be5e8dc3c0122d064ea2d8f9b0
chenhanfang/test2
/betterpython/100ti.py
4,115
3.5625
4
# for i in range(1,5):#####1,2,3,4组成的无重复的三位数字 # for j in range(1,5): # for k in range(1,5): # if (i!=j)and(i!=k)and(j!=k): # print(i,j,k) # import math######一个整数加上100或者268都是完全平方 # for i in range(100000): # x=int(math.sqrt(i+100)) # y=int(math.sqrt(i+286)) # if (x*x =...
67eda0475ddaca871d0c092032a458f994e94a0d
dvbckle/RoboGarden-Bootcamp
/Create edit and Delete files.py
1,515
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu May 2 14:48:35 2019 @author: dvbckle """ # code snips to create, edit and delete files def main(): _file = 'my_create_and_delete_file.txt' _CreateFile(_file) _WriteToFile(_file) _ReadandPrintFromFile(_file) _AppendToFile(_file) _ReadandPrintFromFile(...
78afb53bc73098bac2841a3bf864c6efac9f5523
OscarScrooge/dice-rolling-simulator
/Main.py
441
3.921875
4
from Dice import Dice def main(): dice = Dice(1,6) rolling = int(input("Do you want to roll de the dice? 1==\"YES\" 0==\"NO\" ")) if rolling == 1: while rolling ==1: #dice.roll() print("\ndice says: " + str(dice.roll())) rolling =int(input("\nDo you want try...
aeed95e12a93431e9b87176add01b289828b2613
caocmai/SPD-2.31-Testing-and-Architecture
/Homework/Refactoring-Code/rename_method.py
827
3.84375
4
# by Kami Bigdely # Rename Method # Reference: https://parade.com/1039985/marynliles/pick-up-lines/ def calc_area_under_graph(graph): # TODO: Rename this function to reflect what it's doing. """Calculate the area under the input graph.""" # bla bla bla. pass ##################### def find_max_val(nums_...
bdf4327b61ab7ae02a7f8911a65f1ca2752277fb
bvorjohan/Hangman
/ps3_hangman.py
5,240
4.15625
4
# Hangman game # v1.01 # ----------------------------------- # Simple command-line game # Exercise to learn Python basics # # # Tasks to be done: # Modify input code to accept uppercase letters (in progress) # Improve code to use str.find() function instead of custom loops # Merge isLetterGuessed and let...
efeac3a8c79fb0009b973093727db6c46cb0e61b
FrAnKyGOO/Mini-Project-Candy-Shop
/miniproject.py
5,498
3.515625
4
m = {"hard candy": {"chocolate": 5, "vanilla": 5, "coffee": 5, "strawberries": 5, "orange": 5}, "chewy candy": {"chocolate": 5, "lychee": 5, "lemon": 5, "orange": 5, "strawberries": 5}, "soft candy": {"chocolate": 20, "vanilla": 20, "strawberries": 15, "mixed fruit": 10} } def password(): usr ...
077d2a8b93aa8ba96f9073b1bf183a3eaa552254
guusjoppe/Assignment-Software-Quality
/forms.py
1,169
4.03125
4
from validation import Validator class Form: def newClientForm(self): fullname = input("What's the clients fullname?") print("What's the clients address?") street = input("What's the clients streetname?") number = input("What's the housenumber?") zipCode = input("What's the...
843645b0a924d46b345b46044429d47324833683
kddor/PythonAction
/face_to_offer/13FindKthToTail.py
1,646
4.03125
4
# -*- coding:utf-8 -*- class Node: def __init__(self, data): self.data = data self.next = None #定义链表 class LinkedList: def __init__(self): """ Linked list 的初始化 """ self.length = 0 self.head = None def is_empty(self): """ 判断该链表是否为空 ...
b312ca3b426d287ccb0c3496b78ae6dfd83cb6ba
sam-val/algorithmic-problems
/K_Closest_Points.py
1,887
3.953125
4
import math import functools def further_point(p1, p2): x1, y1 = p1 x2, y2 = p2 dis1 = abs(x1) + abs(y1) dis2 = abs(x2) + abs(y2) if dis1 > dis2: return p1 else: return p2 def find_max_points(closest_points_heap): closest_points_heap.sort(key=lambda x: x[0]*x[0] + x[1]*x[...
55137e02cfbd1d1b794b4b0740996c4bddf4ec74
JiungChoi/PythonTutorial
/list_practice.py
2,644
3.859375
4
##실습 1. greetings 리스트의 원소를 모두 출력하는 프로그램을 작성해 보세요. while문과 리스트의 개념을 활용하시면 됩니다.## greetings = ["안녕", "니하오", "곤니찌와", "올라", "싸와디캅", "헬로", "봉주르"] i = 0 while i < len(greetings): print(greetings[i]) i += 1 ##실습2. 화씨 온도를 섭씨 온도로 변환해 주는 함수 fahrenheit_to_celsius를 써 보세요. 이 함수를 파라미터로 화씨 온도 fahrenheit를 받고, 변환된 섭씨 온도를 리턴...
386234ae46da2de3ff2f9250f01530ea0484a619
JiungChoi/PythonTutorial
/cacluate_change.py
567
3.96875
4
def calculate_change(payment, cost): # 코드를 작성하세요. payment -= cost print("50000원 지폐: {}장".format(int(payment / 50000))) payment %= 50000 print("10000원 지폐: {}장".format(int(payment / 10000))) payment %= 10000 print("5000원 지폐: {}장".format(int(payment / 5000))) payment %= 5000 print...
af3dd2583562a8fa5f2a45dacb6eea900f1409f5
JiungChoi/PythonTutorial
/Boolean.py
402
4.125
4
print(2 > 1) #1 print(2 < 1) #0 print(2 >= 1) #1 print(2 <= 2) #1 print(2 == 1) #0 print(2 != 1) #1 print( 2 > 1 and "Hello" == "Hello") # 1 & 1 print(not True) #0 print(not not True) #1 #True == 1 print(f"True is {int(True)}") x = 3 print(x > 4 or not (x < 2 or x == 3)) print(type(3)) print(type(True)) print(type(...
8ebe92b8c4be59269053902d5c52d39efa533113
nurulsucisawaliah/python-project-chapter-10
/latihan 6.py
778
3.578125
4
#Input dari nama file text berisi teks asli masukkan = input('Masukkan nama file : ') #Input dari nilai keyword n n = int(input('Masukkan nilai n : ')) #membuka file buka = open(masukkan, 'r') #membaca file baca = buka.read() karakter = list(baca) isi = [] for x in karakter : a_ascii = ord(x) if (a_ascii == 3...
656308a178b4030ca71db62c9565431a1b9ef6b9
TheNoblesse05/python_projects
/Sudoku/sudoku.py
1,728
4
4
import numpy as np import sys import random n = 9 #Solves the matrix uisng backtracking def solve(arr,seq): if(0 not in arr): print(arr) print('THANK YOU FOR PLAYING!') sys.exit() for i in range(n): # to iterate over the rows test = np.setdiff1d(seq,arr[i]) #gives the numbers that are not present in the r...
7a93dfe5082ef046d45f4526081c317063641b66
rafal1996/CodeWars
/Remove exclamation marks.py
434
4.3125
4
#Write function RemoveExclamationMarks which removes all exclamation marks from a given string. def remove_exclamation_marks(s): count=s.count("!") s = s.replace('!','',count) return s print(remove_exclamation_marks("Hello World!")) print(remove_exclamation_marks("Hello World!!!")) print(remove_e...