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
bb6347693916aef5311fb7cbcdc475fa866cf6c8
pramodsbaviskar7/PDF2WORD
/pdf to word.py
3,278
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: from tkinter import * from tkinter import filedialog from tkinter.filedialog import askopenfilename,asksaveasfile from PyPDF2 import PdfFileReader #opening the file with .pdf extension only def openFile(): file = askopenfilename(defaultextension=".pd...
88b5c461b7fc519a726a1961994eb28984e7be50
ivanchen52/leraning
/python/checkint.py
209
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 24 14:26:10 2017 @author: ivanchen """ try: guess_row = int(input("Guess Row:")) except ValueError: print("That's not an int!")
1a78c13413ea3afdfc85f9d38600c34572b2dad8
ivanchen52/leraning
/ST101/mode.py
433
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 1 11:36:09 2017 @author: ivanchen """ #Complete the mode function to make it return the mode of a list of numbers data1=[1,2,5,10,-20,5,5] def mode(data): modecnt = 0 for i in range(len(data)): icount = data.count(data[i]) ...
71efcddc5c0c45076e53e41f5338cabff052e651
dmilstein/Asphodel
/app/asphodel/render/map.py
2,235
3.671875
4
""" Render a map of the planets in a game """ import cStringIO import math from random import randint as rint, gauss import shutil # From PIL import Image,ImageDraw planet_pixels = 20 map_size = 800 def render_png(planets): """ Given a list of planets, create a PNG for the map, and return an open file-li...
a6e2087b0faa17c338e51dbb54f3fab71895a3e4
Dudblockman/proj6
/proj6_code/simple_net.py
1,766
3.75
4
import torch import torch.nn as nn import torch.nn.functional as F class SimpleNet(nn.Module): def __init__(self): ''' Init function to define the layers and loss function Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means ''' super().__init...
82406e2adff693908081d2cf3a689d2846b8bac6
svetoslavastoyanova/Python_Fundamentals_Mid_and_Final_Exams
/Exam_Preparation/002.roblem_Two.py
1,730
3.625
4
line = input() collection = {} while line != "Results": tokens = line.split(":") command = tokens[0] if command == "Add": person_name = tokens[1] health = int(tokens[2]) energy = int(tokens[3]) if person_name not in collection: collection[person_name] = {"h": heal...
3d9295bc87f51dcf9fcbdc52bedbeb504d3fe396
svetoslavastoyanova/Python_Fundamentals_Mid_and_Final_Exams
/Fundamentals_Mid_Exam_Prep/15.Seize_The_fire.py
963
3.890625
4
type_of_fire = input().split("#") amount_of_water = int(input()) effort = 0 total_fire = 0 list_of_numbers = [] print(f"Cells:") for types in type_of_fire: command = types.split(" = ") type = command[0] number = int(command[1]) if amount_of_water < number: continue if type == "High" and 8...
b6d1a548a63f29b4bc7e420d816d982092fe2ce5
svetoslavastoyanova/Python_Fundamentals_Mid_and_Final_Exams
/Fundamentals_Mid_Exam_Prep/14.The_Hunting_Games.py
830
3.703125
4
days = int(input()) count_of_players = int(input()) group_energy = float(input()) water_per_day = float(input()) food_per_day = float(input()) total_food = food_per_day*count_of_players*days total_water = water_per_day*count_of_players*days for day in range(1, days + 1): energy_loss = float(input()) group_ener...
42044147ea2817968fb76a963184415a4069d173
svetoslavastoyanova/Python_Fundamentals_Mid_and_Final_Exams
/Fundamentals_Mid_Exam_Prep/23.Counter_Strike.py
508
4
4
energy = int(input()) line = input() battle_counter = 0 while True: distance = int(line) if distance > energy: print(f"Not enough energy! Game ends with {battle_counter} won battles and {energy} energy") break else: energy -= distance battle_counter += 1 if battle_cou...
0ab7e88fb959f3f54cfb68c19170f047bc9aa36f
svetoslavastoyanova/Python_Fundamentals_Mid_and_Final_Exams
/Fundamentals_Mid_Exam_Prep/04.Pirates.py
344
3.8125
4
command = input().split("||") while command != "End": town = command[0] population = int(command[1]) gold = int(command[2]) if command == "Sail": command = input().split("=>") events = command[0] towns = command[1] people = command[2] treasure = command[3] ...
3d5747fe6e84cd90c5717510f036360bdb69aab6
EFanZh/google-foobar
/src/challenge_4_1_running_with_bunnies/solution.py
1,520
3.71875
4
import itertools def all_pairs_shortest_path(matrix): """ https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm. """ nodes = len(matrix) cache = [num for row in matrix for num in row] temp_cache = [0] * (nodes * nodes) for k in range(nodes): for i in range(nodes): ...
6ff69db594b311ab8aeb7dc40c06fd7b3f51189d
7566565794/must_do_array
/wave_array.py
726
4.03125
4
#Method 1: O(n^2) : sort and swap adjacent elements class Solution: #Complete this function #Function to sort the array into a wave-like array. def convertToWave(self,A,N): A.sort() temp=0 for i in range(0,len(A)-1,2): temp=A[i] A[i]=A[i+1] A[i+1]=...
af1e8b082c586a32e0d745c0c5e8482903d6a51f
Narasimhareddy26/smart-glesses
/infos_api/time_engine.py
977
3.78125
4
from datetime import date from datetime import time from datetime import datetime class TimeEngine(): def __init__(self): self.today = datetime.now() def date(self): days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] months = ["January", "February...
4e1d9648b201c038aab692726c331da81c44b1e0
ScottOglesby/number-theory
/sums.py
3,302
3.8125
4
import argparse """Variation of the subset sum problem: given a set B ("blocks"), of integers > 1, each with prime factors <= P: * can an integer n be expressed as the sum of m or fewer numbers from B? * what is the lowest number n that cannot be expressed that way? """ # largest prime factor that a numbe...
9e3536996dfb52e5d0ec6a0e4b46d7121c3f3de6
KathySkyer/AlgorithmQIUZHAO
/Week_06/[344]反转字符串.py
1,166
3.75
4
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 # # 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 # # 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 # # # # 示例 1: # # 输入:["h","e","l","l","o"] # 输出:["o","l","l","e","h"] # # # 示例 2: # # 输入:["H","a","n","n","a","h"] # 输出:["h","a","n","n","a","H"] # Related ...
a87eb4f0d5e070b7ffb4df062088f99424ffd8f1
KathySkyer/AlgorithmQIUZHAO
/Week_03/[102]二叉树的层序遍历.py
1,349
3.671875
4
# 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 # # # # 示例: # 二叉树:[3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # # # 返回其层次遍历结果: # # [ # [3], # [9,20], # [15,7] # ] # # Related Topics 树 广度优先搜索 # 👍 576 👎 0 # leetcode submit region begin(Prohibit modificatio...
a502a5919e592bfaf5580f83ff294cb866ca1742
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
/Chapter 10/Exercise10-3.py
293
4.125
4
def middle(t): """It takes a list and return a new list with all but the first and last elements.""" t1 = t[:] del t1[0] del t1[len(t1)-1] return t1 if __name__=='__main__': t = [True,'Hello world',431,None,12] print('Original: ' + str(t)) print('Modified : ' + str(middle(t)))
7760610b35f45b8ae1b9493a8e210aaa5a19f867
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
/Chapter 6/palindrome.py
1,160
4.1875
4
#Exercise 6-3 from "Think python 2e" def first(word): """It returns the first character of a string""" return word[0] def last(word): """It returns the last character of a string""" return word[-1] def midle(word): """It returns the string between the last and the first character of a stirng""" ...
7b22dbbe8673675d1ecfca185877c903899b4745
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
/Chapter 10/Exercise10-5.py
363
4.125
4
def is_sorted(t): """It take a list and returns True if it's sorted in ascending order and False otherwise.""" t1 = t[:] t1.sort() if t == t1: return True else: return False if __name__=='__main__': t = [42,1,32,0,-2341,2] t1 = [1,3,5,10,100] print(str(t)+'\nSorted: '+str(is_sorted(t))) prin...
e3c29eb97cb71fe245be15eff2a1dfb64a9eb972
lovepreet19/python-project
/main.py
383
3.921875
4
print ('enter 1 for students_to_teacher') print ('enter 2 for battleship') print ('enter 3 for exam_stats') ch = input("enter choice") if ch=="1": import students_to_teacher students_to_teacher.students_main() elif ch=="2": import battleship battleship.battleship() elif ch=="3": import exam_stats ...
46b9e87c2c97450e20bdf258c9d24c47a8a8c909
codeperson1/coderbytes
/array_addition.py
897
3.703125
4
def ArrayAddition(arr): # tmparr = arr.copy() tmparr = [] for i in range(0, len(arr)): tmparr.append(arr[i]) tmparr.sort(reverse=True) most = tmparr[0] for i in range(0, len(tmparr)-1): total = tmparr[i] j = i + 1 while(j < len(tmparr)): ...
b338d392a17331a6e5cf9f33a3e9f788b932eea3
AlexsandroMO/html_cc_js
/PROJETO_DB_HCJ/db.py
455
3.53125
4
import sqlite3 def criar_tabela(): conn = sqlite3.connect('DB_PROJECT.db') c = conn.cursor() table_createdb = f""" CREATE TABLE IF NOT EXISTS myTable ( ID INTEGER PRIMARY KEY, NOME VARCHAR(50) NOT NULL, FORNECEDOR VARCHAR(50) NOT NULL, QT INTEGER, CAT VARCHAR(50) NOT NU...
3d66def5497be5d449fd933374273710ff3fa21f
EricLeeN1/daily-exercise
/demo43-python/base/数据类型/break.py
185
3.84375
4
n = 1; while n <= 100: if n > 10:# 当 n = 11 时,条件满足。执行break语句 break #break语句会结束当前循环 print(n) n = n + 1 pass print('end')
ef48eb5bcb72b2279f4ccc0adcc227c496ac5dad
njs236/DesignPatternsAssignment
/class.py
2,622
3.828125
4
import cmdmodule class Console(cmdmodule.Cmd): def __init__(self, view): """ :return: None """ cmdmodule.Cmd.__init__(self) self.myView = view self.prompt = "=>> " self.intro = "Welcome to console!" # defaults to None def do_exit(self, line): "...
1f818dae0774333a105a9d4171b95bfb63a0cef3
jinyoung-lim/comp211-f17
/programming2/Python/MazeGraph.py
12,494
4.1875
4
""" File: MazeGraph.py Author: Susan Fox Date: August 2014 Contains a program to read in mazes from a file. It assumes that the file has no blank lines. Each line in the file represents a row of the maze. Each line must be the same length: the number of columns in the maze. Each character represents a grid square. Pos...
bee222ad1f74fac03e8d41900568bd4110a92c33
Mercytunz/ecx
/unique.py
541
3.96875
4
""" Create a function unique that takes a list(L) which contains numbers as a para- meter and returns a sorted new list with unique elements of the first list. """ def unique(*numbers): seen = [] for number in numbers: if number not in seen: seen.append(number) return f"Unique List: {s...
02aaa57762b4b9c90e3a1f6406b0c5e81b4f6c51
terminalcloud/udacity-integration-demo
/fixtures/persistence.py
598
3.765625
4
# Write a function, persistence, that takes in a positive parameter num and returns its # multiplicative persistence, which is the number of times you must multiply the digits # in num until you reach a single digit. import operator def persistence(n): cur = n i = 0 while cur > 9: i = i + 1 ...
a0e5fad31cb9ecd3e1508936c3d88833a3acc9e5
aalderdyce1986/Python-Projects
/Python Projects/OnlineRestaurantMenu.py
1,319
3.8125
4
def submit(): food = [] for index in lBox.curselection(): food.insert(index,lBox.get(index)) print("You have ordered: ") for index in food: print(index) #print(lBox.get(lBox.curselection())) def add(): lBox.insert(lBox.size(), entry.get()) lBox.config(height=lBo...
08ef849355133819f6e1f634d163e4a34a0d38a8
Ronin11/School
/Algorithms/5/formatter.py
275
4
4
import os, re #returns a list of characters from the specified file. def format(filename): read = open(filename, 'r') data = "" for line in read: data += re.sub("(\d+)|(ORIGIN)|\s|\n", "", line).upper() chars = [] for line in data: chars.extend(line) return chars
f94c2ea556f56fcc72e43babe069081d13c13ede
matteomurat/Programming_with_python_2021
/Part3-ExternalSources/a_functions.py
1,353
4.03125
4
# encoding: utf-8 ################################################## # This script shows an example of a script using functions as a way to simplify programming. # This is a common structure # ################################################## # ################################################## # Author: Diego Pajari...
6e6282e5b82061e84a7ad60998815d58020305ab
josephc2195/SortPY
/MergeSort.py
709
3.921875
4
def merge_sort(lst): if len(lst) <= 1: return lst midpoint = len(lst) //2 left, right = merge_sort(lst[:midpoint]), merge_sort(lst[midpoint:]) return merge(left, right) def merge(left, right): result = [] left_point = right_point = 0 while left_point < len(left) and right_point < le...
80963c058f74542790f08c0f638738aaecbfc129
vijayanjua/pythondemo
/arraytest.py
1,003
3.890625
4
'''import array as arr vals=arr.array() ''' from array import * vals = array('i',[5,8,6,3,9,4,1,2]) #print(vals.buffer_info()) '''for i in range(len(vals)): print(vals[i]) for e in vals: print(e) chars=array('u',['a','e','i','o','u']) print(chars) for e in chars: print(e) newArr=array...
658f18737f1c7c9c5c257c219e9d85014eac0e9a
vijayanjua/pythondemo
/fibonaciseries.py
323
3.796875
4
def fib(n): a=0 b=1 if n==1: print(a) else: print(a) print(b) for i in range(2,n): c=a+b a=b b=c if c>100: break print(c) fib(int(input('Enter the no of fibonaci number you want:'...
f2be4f6ad825037cf57fcd4b25bb50fc415f0a1e
myjr1/2021
/2ndSep2021.py
1,415
3.6875
4
print("welcome") import time time.sleep(1) print (".") time.sleep(0.5) print ("..") time.sleep(0.5) print ("...") time.sleep(0.5) print ("..") time.sleep(0.5) print (".") time.sleep(0.5) print ("..") time.sleep(0.5) print ("...") time.sleep(0.5) print ("..") time.sleep(0.5) print (".") time.sleep(1)...
c27f578f0af828a678cc226742cc1cf02e2976e8
peterchanw/Test
/MyCode12.py
886
3.796875
4
# Super class class A: def feature1(self): print('Feature 1 working') def feature2(self): print('Feature 2 working') # Sub-class - Child class of A class B(A): def feature3(self): print('Feature 3 working') def feature4(self): print('Feature 4 working') # Class A <- C...
d9a24c3d204073219186393f4e4a5bb4c5185c8b
suntrian/smartme
/command.py
885
3.5
4
# encoding: utf-8 from threading import Thread class Command(Thread): """ 接受命令,返回结果 命令类型有1)查询2)更改 """ prompt = 'cmd:' def __init__(self, manager): Thread.__init__(self) self.manager = manager def run(self): self.go() def go(self): while True:...
ef257947de68c0a305af208801565a5040e476d8
mjmeli/romspam
/romspam/romimage.py
2,038
3.515625
4
import os import random import shutil """ getimage Get a random image from a directory. """ def getimage(directory): if not os.path.isdir(directory): raise Exception("romimage.getimage was supplied an invalid directory.") choices = [f for f in os.listdir(directory) if f.lower().endswith(".png")...
1db706030f7e0832bc2c103b1526bac9fb597877
NickElixir/graphProject
/final2/main.py
1,157
3.53125
4
import math, random, tkinter, time, drawing, physics, gr, rotate def main1(): print("Main Start") g = gr.Graph() g.readVertexFile('vertices.txt') g.readEdgeFile('only_with_pairs.txt') print(len(g.V)) drawing.setID(g) # вставь граф physics.setConstans(g) while True: ...
926f9d28e8ba0e7f39d486d885e1b1301317bdac
KoenvHeertum/SchoolRepos
/Structured Programming/Mastermind/Mastermind.py
8,670
3.671875
4
import random from termcolor import colored """"termcolor gebaseerd op https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python""" """Zwart is goede plek, wit is niet op goede plek""" colorkey = [] # Dit is de code die geraden moet worden kleurenList = ["r", "g", "b", "y", "w", "p"] #...
3fbb87124e710e29509d8cb800bf97d0c32a353e
elllena/DB-labs
/lab1/FlightCenter.py
1,948
3.578125
4
from FlightF import Flight class Airplanes(object): def __init__(self): self.airplanes = [] def add(self, airplane): self.airplanes.append(airplane) def __str__(self): return '\n'.join(str(airplane) for airplane in self.airplanes) def existsId(self, aid): result = Fal...
f4a7bc6284642ab75a6461bb71864acd6e2778a5
wjdwls0630/Khlug-Python
/반복/반복(5).py
2,536
3.78125
4
#보초값(sentinel)사용하기 예제 #필요한 변수 초기화 score=0 sum=0 n=0 print("종료하려면 0미만 100 초과의 값을 입력하세요.") #score가 0이상 100이하이면 반복합니다. #성적을 계속 입력받아 합계를 구하고 학생 수를 센다. #score가 0이상 100이하의 범위를 벗어나면 계산하지 않고 반복을 끝낸다. while 0<=score<=100 : score=int(input("성적을 입력하세요 : ")) if 0<=score<=100 : sum = sum + score n = n + 1 #s...
bbacd39ed0a3d18d34c4da40555217564bc8e3b3
wjdwls0630/Khlug-Python
/함수/함수(3).py
689
3.734375
4
# 함수가 정의됩니다. def sub(mylist): # 리스트가 함수로 전달됩니다. mylist = [1, 2, 3, 4] # 새로운 리스트가 매개변수로 할당됩니다. print("함수 내부에서의 mylist :", mylist) return # 여기서 sub() 함수를 호출합니다. mylist = [10, 20, 30, 40] sub(mylist) print("함수 외부에서의 mylist :", mylist) from math import pi constant=pi def space_length(user_radius) : space=constan...
7c57ba4afbcbbbf3fc248004deb04c77a2121675
kolarius27/roman_number
/rom_num.py
6,790
4.15625
4
# function that converts numbers to Roman numerals # attributes: 'num' = input numeric value, 'rom' = result (Roman numeral) def converter_num_to_rom(num, rom): # new variable: 'new_num' = residue of input value new_num = 0 # if 'num' equals 0, goes to else and prints out the result if num > 0: ...
85d2bc3fafe9db796d78085d69219682694f3eb5
ephraimeg/learn-numpy
/np_indexing.py
700
3.9375
4
import numpy as np # Given array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) a = np.arange(10, 101, 10) index = np.array([0, 0, 2, 4, 4, 1, 5, 3]) print(a[2]) # 30 print(a[index]) # [10, 10, 30, 50, 50, 20, 60, 40] print(a[2:5]) # [30, 40, 50] print(a[::2]) # from start to end steps by 2 # [10, 30, 50, 70, 90] a ...
a7822633c678a4d9122c046d70090db5746f661f
Rotvig/cs231n
/Deep Learning/Exercise 1/cs231n/classifiers/neural_net.py
6,513
4.3125
4
import numpy as np import matplotlib.pyplot as plt def init_two_layer_model(input_size, hidden_size, output_size): """ Initialize the weights and biases for a two-layer fully connected neural network. The net has an input dimension of D, a hidden layer dimension of H, and performs classification over C classes...
b70cca5b74a4766033b0863154ba8e4034e6f7d7
Chris-LewisI/OOP-Python
/week-4/assignments/assignment-4.py
969
4.0625
4
# author: Chris Ibraheem # OOP Assignment 4: Take the average of the values from the user until they input 0 # When the user enters 0 to end the numbers entered by the user, # that last 0 is NOT to be included in the average calculation. print(f"Enter Ctrl + C to cancel the program OR\nEnter `0` to stop the program a...
1475f834d657d0a4bd22927def4b5ec47f8f9b24
Chris-LewisI/OOP-Python
/week-7/set_assignment.py
1,043
4.375
4
# Author: Chris Ibraheem # The following code below will use the random module to create a list of values from 1 to 10. # Using the code below to create a random list of values, do the following: # Count the number of times each number (1-10) appears in the list that was created. Print out a formatted string that lists...
8ce325259a74dff8fb76ded6fbbaca275aa86624
Chris-LewisI/OOP-Python
/week-1-&-2/exercise-1.py
267
4.1875
4
# author: Chris Ibraheem # takes first name as input after prompt first_name = input("First Name: ") # takes last name as input after prompt last_name = input("Last Name: ") # prints a greeting using the string input from the user print(f"Hello {first_name} {last_name}!")
51feae1799695820696b6be33e4f65a89d3ff229
NickjClark1/PythonClass
/Chapter 5/Chapter5notes.py
284
3.5625
4
def printname(firstname, lastname): print(firstname, lastname, "Is an asshole.") #Function Calls printname("John", "Smith") printname("Karen", "Smith") printname("Chad", "Smith") def addTwoNumbers(number1, number2): print(number1 + number2) addTwoNumbers(1, 2)
e05c34f51f48f43c670bd50ca204a3bf75d0c9e7
NickjClark1/PythonClass
/exam 1/Ch4 exercises/Lab4.py
911
4.09375
4
#Output program purpose print ("This program calculates the total cost of a series of items based on the Canadian payment method.") #Output how to stop entering values print("Enter -1 to stop entering item prices\n") # Set variables equal to zero counter = 0 total = 0 # input the price of an item price ...
c2ca0fda6cce4e0a8461479fba4b2488dc930471
NickjClark1/PythonClass
/Chapter 5/rebuiltfromscratch.py
682
4.125
4
# Output program's purpose print("Decimal to Base 2-16 converter\n") def main(): print("Decimal to Base 2-16 converter\n") number = int(input("Enter a number to convert: ")) for base in range(1, 17): print (convertDecimalTo(number, base)) #end main function def convertDecim...
c423ceed74343ea0f2dd4c522beeb3d05c523e51
NickjClark1/PythonClass
/Chapter 10/coin.py
1,129
3.71875
4
from random import choice class Coin: def _init_(): self._denomination = "Penny" self._worth = 0.01 self._sideUp = "Heads" self._sideDown = "Tails" def setDenomination(self, denomination): self._denomination = denomination if denomination.lower() ...
0e98d6c70a7088ef020fc2f141410a309ee6fcb2
NickjClark1/PythonClass
/Chapter 9/Chapter9LabFinal.py
1,697
3.953125
4
def main(): print("Text File Analyzer") filepath = input("File Path: ") try: # Open file path for reading fileObject = open(filepath, "r") # Read all lines from file fileContents = fileObject.read().lower() except FileNotFoundError: raise FileNotF...
db6d55d959a711c8d4305e9d12b5e49b0422d012
data-intensive-computing-4020/Lab3
/Code/remove_punctuation.py
647
3.625
4
import re import string import sys def remove_punc(file): temp_store = open('Matrix_no_punctuation.txt','wb') with file: for line in file: values = re.findall(r"[\w']+",line) if len(values) == 2 or len(values) == 1: continue temp_store.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\r\n'...
24872acdd8477406df6b61c8d9eff320a2992786
PrachetaBA/measuring-internet-mobility
/bgp_path_selection.py
12,526
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 12 15:13:12 2019 @author: prach """ import networkx as nx from collections import deque import random import pickle #demo_Graph-2 def build_small_graph(text_file_name): try: f = open(text_file_name,"r") for line in f: line = line.rstrip('...
23482f463393a6ba44e5a6cde8844405f1044d0e
Zahin-10/PYPJWS2020
/agents/common.py
8,115
3.65625
4
from enum import Enum from typing import Optional from typing import Callable, Tuple import numpy as np BoardPiece = np.int8 # The data type (dtype) of the board NO_PLAYER = BoardPiece(0) # board[i, j] == NO_PLAYER where the position is empty PLAYER1 = BoardPiece(1) # board[i, j] == PLAYER1 where player 1 has a pie...
231971d8a95d0e49e28ff9e4264f87c10c2bd733
oh1001/Python-class-5
/dasgal6.py
501
3.8125
4
# list, tupe, set, dict # list - element davhardah bolon uurchluh bolomjtoi mun embleh bolomjtoi # ugugdliin butets (collection,struct) turul yum mylist = [1,3,9, "a", "bb"] e = mylist[4] print(type(mylist)) mylist = [1,3,9,0,-9] count = len(mylist) # listiin elementiin urtiig ol print(count) #append = ardaa...
d37f663156e2d76a8acb58085c3452dba6ddeb6d
katarina/learnPython
/Exercises/Ex18/ex18.py
562
4.03125
4
#Exercise 18: Names, Variables, Code, Functions #def = define #this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) #ok, that *args is actually pretty pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (...
c5d0c24b987cf7d7bc95b2412a767b97e79a70ad
blazeorite/mitx
/untitled2.py
188
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 31 20:23:12 2018 @author: Sujith """ mysum=1 for x in range(1,7): mysum = mysum*x print(mysum) x = 2 2/x
0150b6513fe7cf6ad45d9e76642da3362ac21d55
AI-Rabbit/Python-problems
/p26.py
267
3.703125
4
# p26.py Grade = input() if Grade == 'A': print('90 100') elif Grade == 'B': print('80 89') elif Grade == 'C': print('70 79') elif Grade == 'D': print('60 69') elif Grade == 'E': print('50 59') elif Grade == 'F': print('0 49')
9afafdd3fa2840605def0cc7dbfb774a0054df10
time-consume/Python-Crash-Course
/Chapter 8/ex6.py
211
3.703125
4
def city_country(city,country): pair={'ci':city,'co':country} return pair result=city_country(city=['shanghai','beijing'],country=['china','China']) for i in result.values(): print(result['ci']+result['co'])
6d6fda08e7304be557e15f4625fa51fb4d220852
time-consume/Python-Crash-Course
/Chapter 7/sandwich.py
408
3.53125
4
print("Deli is out of pastrami") sandwich_orders=['tuna','cheese','egg','pastrami','pastrami','pastrami',] while 'pastrami'in sandwich_orders: sandwich_orders.remove('pastrami') finished_sandwiches=[] while set(sandwich_orders): progress=sandwich_orders.pop() print("your "+progress+" is being processed") finished_s...
102369f1e7e6ef7366271419ad880b870b937c15
time-consume/Python-Crash-Course
/Chapter 10/10-8.py
260
3.5625
4
def show_content(filename): try: with open(filename) as content: content=content.readlines() except FileNotFoundError: msg="sorry, the content can bot be found" print(msg) else: for line in content: print(line) show_content('learn.txt')
7191f817915c1b921fabed25b7ced57141a4df20
reshinto/reshinto.github.io
/docs/interviewPrep/designPatterns/Behavioral_patterns/State/python/Context.py
829
3.5625
4
class Context: """ The Context defines the interface of interest to clients. It also maintains a reference to an instance of a State subclass, which represents the current state of the Context. """ _state = None """ A reference to the current state of the Context. """ def __ini...
01e7d8a5b5578c3c9dba1ca1952edeb2b51a1f54
reshinto/reshinto.github.io
/docs/interviewPrep/designPatterns/Behavioral_patterns/Template/python/run.py
870
4.09375
4
""" Template Method Design Pattern Intent: Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure. """ from ConcreteClass1 import ConcreteClass1 from ConcreteClass2 import ConcreteClass2 def client_code(abstract_class): "...
13bb7ec8e906589a8df7cec7e62824d0e51adeea
reshinto/reshinto.github.io
/docs/interviewPrep/designPatterns/Behavioral_patterns/Iterator/python/AlphabeticalOrderIterator.py
776
3.53125
4
class AlphabeticalOrderIterator: def __init__(self, collection, reverse=False): self.collection = collection self.reverse = reverse self.position = 0 if reverse: self.position = collection.get_count() - 1 def rewind(self): self.position = self.collection.get_...
3b7455349fb18555c91dbca11ee87052952dc14d
pavik/Software-Testing
/1 - What is testing/fixed_size_queue.py
3,993
4.03125
4
# CORRECT SPECIFICATION: # # the Queue class provides a fixed-size FIFO queue of integers # # the constructor takes a single parameter: an integer > 0 that # is the maximum number of elements the queue can hold. # # empty() returns True if and only if the queue currently # holds no elements, and False otherwise. # # fu...
8d1e7460b5251fc13179b80436459b0f00a46f0e
jgargiulo/cours_python
/exercices/fibo.py
161
3.953125
4
first, last = 0 ,1 iteration = int(input("Choisir le nombre d'itération")) for i in range(1,iteration): last, first = first + last, last print (first)
2bc7a666dc6cf7ff6eabcbddd5e55423ed019ae8
Jjmcclain89/codenames
/Word.py
330
3.546875
4
class Word: def __init__(self, word): self.word = word self.team = 'neutral' self.guessed = False def __str__(self): #return '(' + self.word + ', ' + self.team + ')' return self.word def guess(self): self.guessed = True print(self.word + ' is ' + se...
18ed40375cd180795abac819605f9e9f3fae9302
gcleroux/pytorch-learning
/some_random_stuff/gradients_numpy.py
4,852
3.9375
4
#%% # Implementation of the linear regression completely from scratch import numpy as np from numpy.core.fromnumeric import shape from torch.autograd import backward # Implementation of a linear regression # f = w * x -> 2 * x X = np.array([1,2,3,4], dtype=np.float32) Y = np.array([2,4,6,8], dtype=np.float32) w = 0...
50e4dd712f9c08f29d72fe782a8cee29e05fcaa0
sarangbishal/Competitive-Coding-Solutions
/Hackerrank Project Euler/Project Euler #20 Factorial digit sum.py
231
3.6875
4
# Author: Bishal Sarang for i in range(int(raw_input().strip())): fact , sum = 1, 0 for j in range(1,int(raw_input().strip()) + 1): fact = fact * j for char in str(fact): sum += int(char) print sum
0a7603cd17344d5ac28c059209056bb6c98d7fa0
ibrahimhalilbayat/numpy-tutorials
/2_array_creation.py
1,321
4.21875
4
print(""" İbrahim Halil Bayat Department of Electronics and Communication Engineering İstanbul Technical University İstanbul, Turkey """) import numpy as np # First way a = np.array([1, 2, 3]) print("With array command: \n", a) # Second way b = np.array([[1, 2], [3, 4]], dtype=complex) print("...
c1a075e56aa3976845d5a7a68fec247bc2627a90
phulsechinmay/Advent_Of_Code
/Spiral_Memory_Day_3/spiral.py
835
3.859375
4
''' This is my solution script for Advent of Code Day 3, Spiral Memory. It heavily relies on just a mathematical formula, not doing any kind of matrix operations or iteration ''' from math import * dataPoint = input("Please enter the number to find the steps for: ") dataPoint = int(dataPoint) armLength = floor(sqrt(...
52a068c126325f5c1e4d02b1ff626058a20632b7
CoralMalachi/neural_network_numpy_only
/main.py
11,457
3.53125
4
import numpy as np def tanh_deriv_function(x): return (1 - np.power(x,2)) def sigmoid(matrix): return 1/(1 + np.exp(-matrix)) def sigmoid_derivative(x): return (1.0-x)*x ############################################################### #Function Name: softmax #Function input: matrix z #Function output:...
c886b51d647392360ef332269d2c844764ed90ab
anish-bardhan/ia
/main_alg.py
1,349
3.609375
4
input = input("what is the order type?") if input = "hoodie": input = hoodie elif input = "tshirt" input = tshirt items = { hoodie : 6, tshirt : 3} supplies = {hoodie : "list of supplies for hoodie", tshirt : "list of supplies for tshirt"} month_t = [[[6],[6],[6],[6],[6],[6],[6]], [[6],[6],[6],[6...
fd092c1d1450d72976d56fc49864f8f9198145d8
AStrizh/MORSE_Project
/Main.py
2,728
3.625
4
import datetime import ReadTrades import ReadStats from pathlib import Path def main(): selection = -1 while selection is not "0": print("---------------------------------------------------") print("1 - Get trading price at a date/time.") print("2 - Get statistics on trades for a date/...
ecd554d959b94b98a157a6b98f580f1b5001cb0d
howisonlab/wrangling-docker
/python_scripts/6_lists_and_dicts/solarsystem.py
1,433
3.59375
4
import pprint solarsystem = { "1" : "O", "2" : "K", "3" : "B", "Mars" : { "1" : "T", "2" : "M", "Venus" : { "1" : "R", "2" : "K", ...
2294a19efd69e7dffd40b3622665e8060fc719b5
brucekk4/pyefun
/pyefun/encoding/compress/zip.py
2,489
3.703125
4
import os import sys import zipfile # # def rename(pwd: str, filename=''): # """压缩包内部文件有中文名, 解压后出现乱码,进行恢复""" # # path = f'{pwd}/{filename}' # if os.path.isdir(path): # for i in os.scandir(path): # rename(path, i.name) # newname = filename.encode('cp437').decode('gbk') # os.renam...
99c7d14653eec46562b841cd74488bf673ba588b
Yvonne-Young/HSpice-like-EDA-design
/src/UI.py
5,480
3.75
4
#This file is the UI definition of MySpice with tkinter from Tkinter import * import os import tkFileDialog from parse_netlist import * from simulation import * from plotting import * #choose a file to open and show it in the text area def open_file(text): default = "C:/Python27/netlist_test" global...
c30b623f07c957c70f97f4508693ee6abeead21d
jpecoraro342/Project-Euler
/Problem 2.py
546
3.65625
4
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. #By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, #find the sum of the even-valued terms....
825d8220572aa8175d107f4db66b5f1e9acae848
gqmv/problemas-stream
/loteria.py
566
3.953125
4
# Fonte https://www.thehuxley.com/problem/2253?locale=pt_BR # TODO: Ordenar saidas de forma alfabetica, seguindo especificacoes do problema tamanho_a, tamanho_b = input().split() tamanho_a = int(tamanho_a) tamanho_b = int(tamanho_b) selecionados_a, selecionados_b = input().split() selecionados_a = int(selecionados_a) ...
3d9422c5224502865826f694a0d9c38737f6589f
gqmv/problemas-stream
/romanos.py
553
3.796875
4
# Fonte: https://www.thehuxley.com/problem/348 numero_romano = list(input()) numero_romano.reverse() romano_para_arabico = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} numero_arabico = [romano_para_arabico[numero_romano[0]]] numero_final = numero_arabico[0] for i in range(1,len(numero_romano))...
c58781c8afd0e079647f4f3a4d1212a1bdd43306
Drogheda/Deeplearning
/TensorFlowDemo/MNIST/mnist_softmax.py
2,468
3.546875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) #x并不是一个固定值而是一个占位符,只有在TensorFlow运行时才会被设定真实值。 #x是一个[任意维,784]的矩阵 x = tf.placeholder(tf.float32, [None, 784]) # Initialize variables(初始化变量) #tf.Variable()用来创建变量 #W是一个[784, 1...
561ad2945cff6779ccc05d26472ceefcf2d404e6
thierrydecker/ipi-pyt010
/fonctions.py
329
3.65625
4
def additionner_deux_nombres(premier_nombre, second_nombre): """ Additionne deux nombres inputs: Deux nombres outputs: Un nombre """ total = premier_nombre + second_nombre return total a, b = "1", 10 print("la somme de {} et {} est {}".format(a, b, additionner_deux_nombres...
4a4d86961a5dda782289aabfc6fba2279803a673
thierrydecker/ipi-pyt010
/ranges.py
783
3.984375
4
import random # # Exercices sur les ranges # # # Afficher le compte à rebours d'un entier à un autre # # Correction # debut, fin = 20, 0 for i in range(debut, fin - 1, -1): print("De {} à {} --> {}".format(debut, fin, i)) # # Créer une liste d'entiers et la trier en ordre décroissant # debut, fin = 10, 20 ma...
f096618f8fcc4561054f8ed7666c3d2a01d10193
Tori-pop/integration
/games.py
3,080
4.1875
4
''' This file holds all the mini games to be implemented in main.py author = Victoria Poplawski ''' # Coin Flip function import random import ass import Main import sprites def coinflip(): ''' credit to: http://purcellconsult.com/simulate-coin-flipping-in-python/ :return: random heads or tails '...
a4f604c73bbb41d64c3e7e1fcd86a8a0cd8ce387
moranguo/python3playground
/python_interview/code/q60.py
584
3.65625
4
# 给定一个任意长度数组,实现一个函数 # 让所有奇数都在偶数前面,而且奇数升序排列,偶数降序排序,如字符串'1982376455',变成'1355798642' def func1(l): # 如果传入的参数是字符串,转化为整数数组 if isinstance(l,str): l = list(l) l = [int(i) for i in l] l.sort(reverse=True) for i in range(len(l)): if l[i] % 2>0: l.insert(0,l.pop(i)) print...
127bcb2454b5ef113220135083eb2ea18a000b90
moranguo/python3playground
/data_structure_algorithm/sort/insertion_sort.py
692
4.09375
4
def insertion_sort(my_list): n = len(my_list) if n <= 1: return for i in range(1, n): value = my_list[i] j = i - 1 # 查找插入的位置 while j >= 0 and my_list[j] > value: my_list[j + 1] = my_list[j] # 数据移动 j -= 1 my_list[j + 1] = value # 插入数据...
d1f5eff795dce24bdef418004f5e3b149b4be0b7
SrikarMurali/Python-Scripts
/Python Scripts/Python Scripts/Python data structures and algorithims/Chapter 3/QueueList.py
1,452
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 12 15:41:38 2017 @author: Nathan """ from UnorderedList import Node class Queue: def __init__(self): self.front = None self.back = None self.numlinks = 0 def enqueue(self, data): newNode = Node(data) if self....
973b2b13e77e2a719baa29e0e0e03d44c4902782
SrikarMurali/Python-Scripts
/Python Scripts/Python Scripts/Python data structures and algorithims/Chapter 3/QueueADT.py
389
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 12 16:56:12 2017 @author: Nathan """ class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def size(self): return len(self.items) def enqueue(self, item): self.items.appe...
02a9c6f3b0bde1b8fccef9fd6bb24f25d4581cfb
SrikarMurali/Python-Scripts
/Python Scripts/Python Scripts/Python data structures and algorithims/Chapter 4/recursivepractice.py
8,152
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 13 17:24:30 2017 @author: Nathan """ import random import math from Stack import Stack from turtle import * def dpMakeChange(coinValueList, change, minCoins, coinsUsed): for cents in range(change + 1): coinCount = cents newCoin = 1 for j in [...
5bc69b58f1239003a493e8882c8ab81959ea1448
ahammadshawki8/Head-Tail
/old.py
4,788
4.03125
4
# Head_tail game import time import random score_list=[0,1,2,3,4,5,6] bat_ball=["batting","balling"] def start(): print("Hey, I am computer8.08. But you can call me comp.") print("I am not interested in this class. So I want to play head-tail.") answer=input("Do you want to play with me?(yes/no): ") i...
517d839fbbe4ad585393953f97487e2e34faedf1
gouyanzhan/daily-learnling
/class_08/class_03.py
1,627
4.15625
4
#继承 class RobotOne: def __init__(self,year,name): self.year = year self.name = name def walking_on_ground(self): print(self.name + "只能在平地上行走") def robot_info(self): print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name)) #继承 class RobotTwo(RobotOne): def walking_on_g...
9d50930d5c280fa962bd5c55165e400e9bc6469f
gouyanzhan/daily-learnling
/class_03/home_work.py
4,027
3.796875
4
#一家商场在降价促销,如果购买金额50-100元(包含50和100)之间,会给10%折扣 #如果购买金额大于100元,会给20%折扣 #编写一个程序,询问购买价格,再显示出折扣(%10或20%)和最终价格 # a = int(input("请输入购买金额")) # if a>=50 and a<=100: # print( a * 0.9) # elif a > 100: # print( a * 0.8) # else: # print(a) #生成随机整数,从1-9取出来 #然后输入一个数字,来猜,如果大于,则打印bigger #小了则打印less #如果相等,则打印equal # import ra...
1734adda50062e2c077ba859fe6da9d2ea20b918
gouyanzhan/daily-learnling
/class_09/class_01.py
492
3.796875
4
#超继承 class MathMrthod: def __init__(self,a,b): self.a = a self.b = b def add(self): print("我是父类的加法" , self.a + self.b) def sub(self): return self.a - self.b class MathMrthod_1(MathMrthod): def divide(self): #拓展 return self.a/self.b def add(self): #重...
d22cb89c21cbb2981781350e58ce654845c685cd
gouyanzhan/daily-learnling
/class_01/basic.py
623
4.0625
4
#标识符:我们自己写代码的时候,取的名字 #项目名 project name #包名 package name #模块名 .py python文件名 #标识符规范:1.由字母数字下划线组成 但是不能以数字开头 # 2.见名知意 # 3.不同字母 数字之间,用下划线隔开 提升你的可读性 # 4.不能用关键字 int if while #注释 ctrl+/ #多行注释: 成对的三个单/双引号 ''' ''' #变量名 x=1,y = x + 1 求y的值 x = 2 #赋值运算 print(x) #当你要使用某个变量时,确定它已经被定义和赋值 #print(你要输出的内容) 输出函数 输出内容到控制台
daee6a0d099136157ae484a0ab5375b37153a899
x3CJX/blog
/multi-agent-framework/multi-agent-framework-example.py
2,886
3.859375
4
import random class Env: def __init__(self): """ Initialize the environment """ def play(self, agents, options): """ Play a single game with a number of agents. When an agent has to decide on an action, the environment calls the agent.action(observati...
a7ac24ad028f21cd5c286e9eb3715ae06ba6caf6
jefferycao1/competitive_programming
/coding_problem_answers/chapter2/5.py
1,231
3.796875
4
# -*- coding: utf-8 -*- import unittest def sumlists(list1, list2): carry = 0 resulthead, resultnode = None, None while list1 or list2 or carry: nextnum = carry if list1: nextnum += list1.data list1 = list1.next if list2: nextn...
399441f6d41a65c3bb2239cace794202de7b55eb
jefferycao1/competitive_programming
/coding_problem_answers/chapter 4/2.py
990
3.875
4
# -*- coding: utf-8 -*- import unittest def minheight(array): if (len(array) == 0): return None middle = int(len(array) / 2) left = minheight(array[:middle]) right = minheight(array[(middle + 1):]) return BST(array[middle], left, right) class BST(): def __init__...
db085a21605a9863902e0a2892616f148e270a24
sbyount/hard_ways
/ex17.py
811
3.546875
4
from sys import argv from os.path import exists # uppack from argv script, from_file, to_file = argv print "\nCopying from %s to %s." % (from_file, to_file) # open the input file to pointer in_file = open(from_file) # read the file into var in_data = in_file.read() # measure the file length in decimal print "The in...