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
75ba5024c26aa67dbb6ab93ab3ecbc2fdf5abba3
superY-25/algorithm-learning
/src/algorithm/202006/findLadders.py
1,221
3.6875
4
""" 单词接龙 II 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回一个空列表。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 示例 1: 输入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","l...
4e23c28250eb391cab3d57011f138adc09130312
superY-25/algorithm-learning
/src/algorithm/201912/multiply.py
1,462
3.859375
4
""" 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。 """ def multiply(num1: str, num2: str): """ 暴力破解 :param num1: :param num2: :return: """ if num1 == 0 or num2 == 0: return '0' ret = '0' k = 0 for i in reversed(num1): pre = 0 cur = '' ...
827171da0a7dcd363d2faead2bfbdd85649fb6b5
superY-25/algorithm-learning
/src/algorithm/bubbleSort.py
558
3.71875
4
""" 冒泡排序算法思想:遍历数组大的元素往后调换位置 算法的时间复杂度:最坏是O(n^2),最好是O(n),平均O(n^2) """ def bubbleSort(num): size = len(num) - 1 for i in range(size): flag = 0 for j in range(size - i): if num[j] > num[j + 1]: temp = num[j] num[j] = num[j + 1] num[j + ...
0b65b29c814cde2a98aa81cffda7f12d9d562a18
superY-25/algorithm-learning
/src/algorithm/inorderTraversal.py
1,358
3.90625
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 inorderTraversal(self, root: TreeNode): """ 使用递归的方式来遍历 :param root: :return: """ if root == No...
aaf640a3831c58eb30dec72d908b99075993f4b7
sumanth19k/Python
/tkinter/entry.py
308
3.8125
4
from tkinter import * root = Tk() e = Entry(root, width=50, border=4) e.pack() def myClick(): myLabel = Label(root, text="hello "+e.get()+" have a good day!!") myLabel.pack() myButton = Button(root, text="click me!", command = myClick, bg="blue", fg="#ffffff", ) myButton.pack() root.mainloop()
b2b84943cccde2365011e5bbb0cd6134d0d98347
cmobrien123/Python-for-Everybody-Courses-1-through-4
/Ch9Notes.py
3,304
4.28125
4
# ES = dict() # # # ES['one']= 'uno' # ES={'one': 'uno', 'two': 'dos', 'three':'tres'} # print(ES) # # # try: # print(ES['four']) # except: # print('not here') # # # print(len(ES)) # # # ## this is how you test if something is in a dictionary # x = list(ES.values()) # print('four' in x) ## something very powerf...
542892acdc3ff81d2928d4c7345fd5cd0af95e88
cmobrien123/Python-for-Everybody-Courses-1-through-4
/Ch10Notes.py
3,103
4.09375
4
####TUPLELS ARE IMMPUTABLE#### # t ='a', 'b', 'c' # print(t) # print(type(t)) ## the () are recomended but not needed ## similar to lists and dictionaries, you can make an empyty one # t = tuple() # print(t) # t = tuple('kitty cat') # print(t) ## please don't make tuple a variable name ## indexing also works # t...
83265b7915746a67e8240e49d3819e8e6d840526
cmobrien123/Python-for-Everybody-Courses-1-through-4
/Ch7Asmt7.2.py
1,146
4.34375
4
# Exercise 7.2: Write a program to prompt for a file name, and then read # through the file and look for lines of the form: # X-DSPAM-Confidence:0.8475 # When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart # the line to extract the floating-point number on the line. count these lines # and then...
a972758b274de936d1913171477fc0feb4b81707
magezil/board_game_puzzles
/sudoku/sudoku.py
3,520
3.984375
4
from random import randint, shuffle class SudokuBoard(object): def __init__(self, board=None): if not board: self.board = self.generate_random_board() else: self.board = board def __str__(self): """Return board as a string """ lines = [''.join(['...
da03c24520e81b1e24716eb1c145a0572210925e
eschulte/ctfp-book-club
/exercises/barrymoo/chapter08/bifunctor.py
765
4.03125
4
import abc class Bifunctor(abc.ABC): @abc.abstractmethod def bimap(self): pass @abc.abstractmethod def first(self): pass @abc.abstractmethod def second(self): pass class PairBifunctor(Bifunctor): def bimap(self, f, g, pair): x, y = pair return (f(x...
07ef80af5844b27f292e6a9d18c7658046935ea5
marysia/set
/board.py
4,474
3.53125
4
import numpy as np from attribute import CARD_ATTRIBUTES, NUMBER_OF_PLAYABLE_CARDS, NUMBER_OF_OPTIONS_PER_PROPERTY from card import Card from set import Set class Board: def __init__(self, rows=3, columns=3): ''' Board class Manages the cards on the board, the unplayed cards, and can retrieve pro...
168c2ae8adc5e308376f6efc6038ab2b519f6c7c
carolninganga/project5CS5001
/test.py
6,872
3.53125
4
# Caroline Ninganga # CS 5001 # Project 4 # Man on a ship import graphicsPlus as gr import time import random import sys # def move( shapes, dx, dy ): """ Draw all of the objects in shapes by dx in the x-direction and dy in the y-direction """ # for each item in shapes for item in shapes: it...
709ccdd4ec3a29f9adca939763015cfa37ee521b
Denysios/Geekbrains
/python/base/dz_lesson1/lesson1_task2.py
1,338
4.1875
4
# Задание 2 # Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды # и выведите в формате чч:мм:сс. Используйте форматирование строк. # Простой способ, но с некоторыми недочетами # time_sec = int(input('Введите время в секундах: ')) # minutes = time_sec // 60 # hours = minutes // 60 # sec = ...
934be154a4abaef6d8f283ebdec35e7686fa347d
Tusharsharma86/descriptive_statistics_project
/q04_spearman_correlation/build.py
987
3.609375
4
# %load q04_spearman_correlation/build.py # Default Import import pandas as pd import numpy as np dataframe_1 = pd.read_csv('data/house_prices_multivariate.csv') dataframe_2 = pd.read_csv('data/house_prices_copy.csv') # Your code here def spearman_correlation(): #Convert Series in DF sale_price_1 = dataframe_...
e4d51d483742d30bd1287e0ecf04023b3f0d7598
r3dcrosse/pong
/Paddle.py
1,566
4
4
""" Paddle is a moving paddle in a graphics window (David Wayman 2012) """ #from time import sleep #from random import randrange, random from graphics import * #from Ball import * class Paddle: def __init__(self, win): self.pad = Rectangle(Point(950,310), Point(970,190)) self.pad.setFill("tan") self....
3a67ee608570a3df336d8f8d645ec7681d84076b
tintinker/media-analysis
/old stuff/scripts/combine.py
1,510
3.671875
4
''' Combines all of the .txt file in directory and subdirectories into one .txt file for group analysis ''' import sys import os import io import re from sys import argv, exit def combine(path, delete_pdf = False): ''' Recusively grabs text from all .txt files in path and its subdirectories @param path: ...
81b9fef53e6c075161e402adfce40fcded97d5a3
yourmean/Programmers_Algorithm_HBYM
/Hyebin/Lv1_소수찾기.py
237
3.65625
4
def solution(n): answer = 0 numbers = set(range(2,n+1)) for i in range(2,n+1): if i in numbers: # print(numbers) numbers -= set(range(2*i,n+1,i)) answer = len(numbers) return answer
85cce965331c3f644cf770fdbf5ef1cf9d787449
yourmean/Programmers_Algorithm_HBYM
/Yumin/Lv1_이상한문자만들기.py
588
3.515625
4
def solution(s): answer = [] s= s.split(' ') for word in s: tmp='' for j in range(len(word)): tmp+= word[j].upper() if j%2==0 else word[j].lower() answer.append(tmp) return ' '.join(answer) # failed solution (ㅠㅠ) # def solution(s): # answer = [] # s = ' '.jo...
8146afe83415141d0cb9c4669e957a7d0e81da9a
yourmean/Programmers_Algorithm_HBYM
/Hyebin/Lv2_캐시.py
749
3.515625
4
def solution(cacheSize, cities): answer = 0 cache = [] cities = [s.lower() for s in cities] if cacheSize != 0: for s in cities: if not s in cache: if len(cache) < cacheSize: cache.append(s) answer +=5 else: ...
2039175e79c95ad16e7e30deb5a5ab1df7a67ee2
moodymood536/python_lessons_level1
/lesson01/home_work/hw01_easy.py
3,767
4.03125
4
__author__ = 'Мартыно Никита Сергеевич' # Задача-1: Дано произвольное целое число (число заранее неизвестно). # Вывести поочередно цифры исходного числа (порядок вывода цифр неважен). # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании решите задачу с применением цикла ...
cdf2b0cd4c4c69512fd010bed4e2e2a732090aa0
moodymood536/python_lessons_level1
/lesson03/hw03_easy.py
3,137
3.921875
4
# Задание-1: # Напишите функцию, округляющую полученное произвольное десятичное число # до кол-ва знаков (кол-во знаков передается вторым аргументом). # Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0). # Для решения задачи не используйте встроенные функции и функции из модуля math. def ...
c277c14e847aca6c8b4c035ebb2bbd5e0e92b38b
pranay101/MIT-OpenCourseWare-Python-Assignments
/ps1/main-pset-1C.py
3,026
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 6 15:44:20 2021 @author: Rajesh """ def savings (current_savings , portion_down_payment , \ annual_salary , semi_annual_raise , guessed_savings_rate): for number_of_months in range(0 , 36): if number_of_months % 6 == 0 and number_of_months...
897799334d4972f98af22f0e87aaecd0ef382fdf
loozhang/shiyanlou-001
/calculator2.py
950
3.953125
4
#!/usr/bin/env python3 import sys def calculate_tax(before_tax): if before_tax<=0: tax=0 elif before_tax<=1500: tax=before_tax*0.03 elif before_tax<=4500: tax=before_tax*0.1-105 elif before_tax<=9000: tax=before_tax*0.2-555 elif before_tax<=35000: tax=before_t...
fe63f1264d41508b7873c7575826231ad71b69db
Sherwen2333/CSE101
/Hw/hw3/homework3_driver.py
6,653
3.6875
4
from homework3 import * import sys student_file = 'homework3.py' lines = open(student_file).readlines() lines = [line.strip() for line in lines] code_clean = True for i in range(len(lines)): if 'input' in lines[i] and not lines[i].startswith('#'): print('Line {} of {} contains an input() state...
d0a8a00b9834f82ef386fb2d2bc1a93bbd5c092a
arkadym74/pthexperience
/helloworld.py
1,664
4.3125
4
#Prints the Words "Hello World" '''This is a multiline comment''' print("Hello World") userAge, userName = 30, 'Peter' x = 5 y = 10 y = x print("x = ", x) print("y = ", y) brand = 'Apple' exchangeRate = 1.235235245 message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1...
d6db42ea0653b10335c371b177ee0e3d8974d0a6
data-8/summer
/su17/labs/lab02/tests/q3.py
2,168
3.5625
4
test = { 'name': 'Exercise 3', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> # It looks like you didn't make a table. murder_rates_1960 >>> # should be a table, produced by calling where. Your code >>> # should look something like this: ...
4af66f31e555e7fd67d00869653e8c7048c1f472
mgomesq/neural_network_flappybird
/FlappyBird/brain.py
1,735
4.46875
4
# -*- coding: utf-8 -*- ''' Brain ===== Provides a Brain class, that simulates a bird's brain. This class should be callable, returning True or False depending on whether or not the bird should flap its wings. How to use ---------- Brain is passed as an argument to Bird, which is defin...
4e111bd85f086be6d0c4c5b3ce42ca3cf8f72537
RyanClement/Timers
/scripts/Timer.py
1,368
3.71875
4
# -*- coding: utf-8 -*- """ Created: May 2020 @author: Ryan Clement (RRCC) """ ##### Imports ##### from time import perf_counter as sTime ##### Classes ##### class TimerError(Exception): """ * Custom exception used to report errors in instantiations of Timer class. * Timer is derived fr...
bba081265a85bbf2988ee18245ba83140fe8bb4a
Tlepley11/Home
/listlessthan10.py
225
4.1875
4
#A program that prints all integers in a list less than a value input by the user a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = input("Please enter a number: ") b = [] for i in a: if i < x: print(i); b.append(i) print(b)
a21492abe75615ac8a7b49182ca6abe0aff3c16a
rehanadi30/15-Puzzle-Solver
/src/StrAlgo3-13518061-RehanAdiSatrya.py
7,516
3.5
4
# Nama/NIM : Rehan Adi Satrya/13518061 # Keterangan : Tugas Kecil 3 Strategi Algoritma import time from copy import deepcopy class Puzzle: #Default constructor def __init__(self, data=[]): self.data = data #Getter----------------------------------------------------------------------------------- ...
fb89971ea0ea84e95f796dfe377dd81b71f4d7fa
Pradeep-Deepu/Deepu
/2.7.py
165
3.90625
4
import string alphabet = set(string.ascii_lowercase) c=str(input("Enter your string")) print(alphabet) print(set(c.lower())) print(set(c.lower()) >= alphabet)
235c059ffe38a64ab3819606f9ff95d846ad2d23
Pradeep-Deepu/Deepu
/1.9.py
163
3.9375
4
x=[] n=int(input("enter size fo the list:")) for i in range(0,n): elements=int(input()) x.append(elements) for num in x: y= "*"*num print(y)
b5d856b215510cc0fbfc3b62af75f8ed146b43ef
hesstry/directed_undirected_graphs
/d_graph.py
18,110
3.890625
4
# Course: CS261 - Data Structures # Author: # Assignment: # Description: import heapq from collections import deque class DirectedGraph: """ Class to implement directed weighted graph - duplicate edges not allowed - loops not allowed - only positive edge weights - vertex names are integers ...
2e3b96a6d369a57299e3b79c2255d613f988c80a
beyoung0110/p_code
/python/learn/inheritance.py
210
3.59375
4
#!/usr/bin/env python3 class Animal(object): def run(self): print('Animal is running...') class Cat(Animal): def eat(self): print('Cat is running...') a1 = Animal() a1.run() c1 = Cat() c1.run() c1.eat()
389300bdf1bea02d65f222f0f7c2560b9dc2b446
manvitha-1212/Graphing-Python-Course
/1/without air resistence/1_2.py
260
3.640625
4
#range as a function of angle import numpy as np import matplotlib.pylab as plt import math as m u=38 ang=np.arange(0,90,1) _range=[] for angle in ang: _range.append(((u*u)*(m.sin(2*(m.radians(angle)))))) plt.plot(ang,_range) plt.show()
10a23fe650aeff2fa878d7d99496fb2b75fe4fac
sophiepopow/ASD-AGH
/Sorting/HeapOperations.py
407
3.6875
4
def insert(heap, el): arr = heap[0] arr.append(el) i = heap[1]-1 heap[1] += 1 while i > 0 and arr[i] > arr[i//2-1]: arr[i], arr[i//2-1] = arr[i//2-1], arr[i] i = i//2-1 def get_max/min(heap): # heap = (arr, size) arr = heap[0] res = arr[0] arr[0] = arr[n-1] heap[1] -= 1 heapify(heap[0],0, heap[1]) ...
ebdaf4bce1fc8de095f78b60fdcc5eaa0f4b6ac2
sophiepopow/ASD-AGH
/Trees/Exercises/13_4_Geny.py
1,310
3.625
4
from enum import Enum class Name(Enum): A = 1 C = 2 G = 3 T = 4 class TreeNode: def __init__(self,parent, count = 0): self.count = 0 self.kid1 = None self.kid2 = None self.kid3 = None self.kid4 = None class Tree: def __init__(self): ...
b652e232cb08379678bcdd9173d596a4afef4a05
jamie0725/LeetCode-Solutions
/566ReshapetheMatrix.py
1,737
4.25
4
""" n MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshap...
1ae54688b4a317f95562bd4c1240f8b0885697c2
jamie0725/LeetCode-Solutions
/455AssignCookies.py
1,015
3.84375
4
""" Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j...
9098bfdbd7db6283725e567cd3dda2d034e79410
wida00/Intento-fallido
/main.py
438
3.984375
4
a=int(input("Introduce el primer número: ")) c=int(input("Introduce el segundo número: ")) producto=a*c print("el producto de", a ,"y", c ,"es", producto) doble_a=2*a print("el doble de", a , "es", doble_a) b=int(input("Introduce el cuarto número: ")) cuadrado_b=b**2 print("El cuadrado de", b , "es" ,cuadrado_b) import...
ef253ff70b6cb09f15463116f303dc2a44a7fda4
GuiThink/opc_projet5
/processing/substitute.py
5,004
3.5625
4
#! /usr/bin/env python3 # coding: utf-8 from data_base.database_connect import UseDatabase class Substitute(object): """ Class to find and work with substitutes """ def __init__(self, category_choice, pdct_input, pdct_index, pdct_id, pdct_nutrition_grade): self.category_choice = category_choi...
9f40c8f9ca0d745652d30c06d62002a47bcc3917
StarStories1999/Python
/graph_adjacency-matrix.py
1,266
3.703125
4
# implementation of an undirected graph using Adjacency Matrix, with weighted or unweighted links class Node: def __init__(self, n): self.name = n class Graph: nodes = {} links = [] link_indices = {} def add_node(self, node): if isinstance(node, Node) and node.name not in self.nodes: self.nodes[node.name...
d7e7a91880ec5e7c7064b716f34560bec2fd7711
hyperaeon/pythonBibile
/chapter12/tkinterDialog.py
1,222
3.5
4
# -*- coding:utf-8 -*- __author__ = 'hzliyong' import tkinter import tkinter.messagebox class MyDialog: def __init__(self, root): self.top = tkinter.Toplevel(root) label = tkinter.Label(self.top, text = 'Please Input') label.pack() self.entry = tkinter.Entry(self.top) self...
9eee5808b4fc9343f809ed8229ef941f9b40b0c8
hyperaeon/pythonBibile
/chapter4/Boook.py
845
3.515625
4
__author__ = 'hzliyong' class Boook: __author = '' __name = '' __page = 0 price = 0 __press = '' def __check(self, item): if item == '': return 0 else : return 1 def show(self): if self.__check(self.__author): print(self.__autho...
672d46ebd0ede91275e8a58baedf8f8276e1b6e7
uppala-praveen-au7/monthly_tests
/coding-challenges/week02/Day3/W2D3CC3.py
128
3.9375
4
# Print multiplication table of 14 print("Multiplication table of 14:") for i in range(1,21): print('14*'+str(i)+'=',14*i)
a455bed036e8a3c8c2455faa022406d6bd003371
loveu3000s/learnPython
/exp2/exp2.py
8,503
3.859375
4
# string_list=["test1", "test2", "test3"] # for i in map(lambda string: string+"_good",string_list): # print(i) # from functools import reduce # """ the function just to ignore the float point to turn to a integer number: """ # def strToInteger(s): # def fn(x, y): # return x * 10 + y...
a73b65dbdc68d79765666fdd3fdc51873a239d01
loveu3000s/learnPython
/algorithm/sort_algorithm/merge_sort.py
4,711
3.515625
4
''' Description: Version: 2.0 Author: xuchaoxin Date: 2021-03-06 11:25:50 LastEditors: xuchaoxin LastEditTime: 2021-03-23 22:31:14 ''' """ 归并排序有些类似于二叉树的遍历算法,分为左支递归调用和右支递归调用 利用递归思想并调用合并算法(递归算法和合并算法是调用和被调用的关系)(而合并算法本身不是用递归方式实现的)""" def MergeSort(list): """这个运行过程是:当将最初地大问题规模降低到1时,各级深度地递归调用开始回归(出栈) 将这...
c7a90663c74b54bed3cff014ad5ddb514319f0e5
loveu3000s/learnPython
/python_study_Demos/reduce.py
663
3.59375
4
''' Description: Version: 2.0 Author: xuchaoxin Date: 2021-02-01 16:40:42 LastEditors: xuchaoxin LastEditTime: 2021-02-01 17:30:25 ''' from functools import reduce def turnToInteger(x,y): """[summary:turn the integer numbers to a big integer in sequence ] Args: x ([int ]): [integer elemen...
ab127e8e1b4f0a5648e6f3c57b1224886a97fa7b
lidiaxp/Learning-Python
/TSP/cvKNN.py
2,779
3.671875
4
#!/usr/bin/env python3 import numpy as np import math as m import matplotlib.pyplot as plt import time tempo = time.time() #coordenadas dos locais em que o veículo deverá passar # x = [8,0,3,2,1,9,7,4,10,2,5,4,8,8,2,5,5,7,8,8] # y = [1,7,7,2,3,5,10,4,6,8,8,3,6,7,9,10,6,2,2,3] x = [0.75, 3, 7, 4, 6, 7] y = [0.5, 1, 0...
349248dcab3e0417d8acb5921bf0682a5d8dc872
uncmp/BSU
/numerical-linear-algebra/1. Gaussian eliminiation with pivoting, Thomas algorithm/1.py
4,652
3.53125
4
import copy import time import tabulate as tb import numpy as np def generate_matrix(n): """Генерация случайной матрицы""" return np.round(np.random.randint(-10, 10, (10,10)) + np.random.rand(n, n), 2) def generate_vector(n): """Генерация случайного вектора""" return np.round(np.ran...
45ab9770e7f0266098a83645de1586b6c925cdca
twahakateete/StockControlProject
/stockcontrol.py
6,907
4.3125
4
## Advanced Programming, coursework 1: Object Orientation ## The stock control system classes are unfinished. ## Work through the 14 steps of the coursework to ## implement and extend the methods and classes. ## GROUP MEMBERS ## NAME: KATEETE TWAHA STUDENT'S NO.: 1800737883 REG. NO: 2018/HD05/1958U ## NAME...
4ea640d1c8278b199395ef078e3928e721ea0c83
nse1994/l5kit
/l5kit/l5kit/geometry/transform.py
6,866
3.75
4
from typing import Optional, Sequence, Tuple, Union, cast import numpy as np import pymap3d as pm import transforms3d def rotation33_as_yaw(rotation: np.ndarray) -> float: """Compute the yaw component of given 3x3 rotation matrix. Args: rotation (np.ndarray): 3x3 rotation matrix (np.float64 dtype re...
4013596bb6758af3cc69405c0e8244b75fccbb8d
AXiKe/python
/week1/Untitled5.py
1,218
3.765625
4
# coding: utf-8 # 打印一个边长为n的正方形 # In[22]: a = int(input(">>>")) for j in range(a): for i in range(a): print("*",end=" ") print("") # 求100以内所有奇数的和 # In[28]: sum = 0 for i in range(100): if i%2: sum += i else: print(sum) # 计算次数更多 # In[27]: sum = 0 for i in range(1,100,2): ...
fcfe8a4ce28abcaef9ac4cb3ffb4b95d4edb07e7
StefanWahl/Reinforcement-Learning-for-Bomberman
/agent_code/coin_agent/feature_selection.py
623
3.5
4
import numpy as np def coins_simple(game_state: dict) -> np.array: loc = game_state["self"][3] state = np.zeros((2, 2)) #Step 1: Add the absolute position of the agent to feature vector state[0] = np.array(loc) min_dist = 100 #Step 2: Get the relative coordinates of the closest coin...
f2a79c300ff21613550d15462f85276a1ded15bf
TeamNoh/Code
/urllib/urlparse1.py
292
3.515625
4
from urllib.request import urlopen from urllib.parse import urlencode api = "https://api.ipify.org/" # url = api + "?" + "format=json" values = {"format": "json"} url = api + "?" + urlencode(values) print("요청 URL ", url) response = urlopen(url).read().decode("utf-8") print(response)
981ef2d69f0c17fb48e6420f204919196ee12d8a
TeamNoh/Code
/db/sqlite1.py
316
3.546875
4
import sqlite3 from datetime import date, datetime print("sqlite3.version {}".format(sqlite3.version)) print("sqlite3.sqlite_version {}".format(sqlite3.sqlite_version)) now = datetime.now() print("now : {}".format(now)) nowDateTime = now.strftime("%Y-%m-%d %H:%M:%S") print("nowDateTime : {}".format(nowDateTime))
d1b38431167993f31e4905155348132457db9774
dayaj/FileDeDup
/helloWorld.py
2,275
3.921875
4
import os #required module for file-processing operations such as renaming or deleting files, directory related operations import shutil import os.path def main(): print ("Hello World") a = """two three""" print a list=['abc',123,"ghi",46.0,34+5j] print(list[0]); ...
9a4eaa9cc84f16eaa31a2114b86dee40eb37a6e6
tathagatasengupta2000/Mini-Python-Projects
/Calculator.py
3,155
4.21875
4
from tkinter import * root=Tk() root.title("Simple Calculator") def Click(number): current=Enty.get() Enty.delete(0,END) Enty.insert(0,str(current)+str(number)) def Clear(): Enty.delete(0,END) def Add(): FistNumber=Enty.get() global f_num global Sign Sign="Addition" ...
d4f8da0f54c59c7ed77b7fda8bcfc8dbf5684079
savobully/wallee
/intro.py
1,077
4.09375
4
class Inizio: while True: concordanze=["Si", "Certo", "Ovvio", "Ovviamente", "Ok", "Per forza", "Assolutamente" , "Eh certo", "Certamente", "certamente", "si", "certo","ovvio" ,"ovviamente", "ok", "per forza", "assolutamente", "eh certo"] discordanza=["No", "Mai", "Certo che no", "Ovvio che no", "A...
fd5fac3c917ee50b2d2cc98bb9025d994db2f742
Bachatero/AKOB
/pyscripts/loops1.py
631
3.984375
4
#smallest_so_far = 0 int_list=[3,33,43,2,222,32,-10,55,168] #for numero in [3,33,43,2,222,32,55,168]: for indx, value in enumerate(int_list): print indx, value if indx == 0: smallest_so_far = value elif value < smallest_so_far: smallest_so_far=value print "smallest number:", smallest_so_far ### OR s...
de4454b3ad9bcd4c8ac8cab739c1e371a6eedb50
Bachatero/AKOB
/pyscripts/reverse.py
222
3.875
4
def reverse(text): rtext = "" strln = len(text) #print strln for i in range(1,len(text) + 1): rtext = rtext + text[strln - i] #print rtext return rtext #print rtext print reverse("basmeg")
c8a464e1449400765a68a20aed0fd8d8e4fb3089
Bachatero/AKOB
/pyscripts/binary.py
1,655
4
4
print int("1",2) print int("10",2) print int("111",2) print int("0b100",2) print int(bin(5),2) # Print out the decimal equivalent of the binary 11001001. print int("11001001",2) #bitwise operations: shift_right = 0b1100 # binary 12 shift_left = 0b1 # binary 1 # Your code here! shift_right = shift_right >> 2 shi...
e7f37605eddbbec4db0cfd98c70ca75b2fad1dfa
irina-chizh/trainig
/сортировка_пузырьком.py
452
3.9375
4
pr = [52, 123, 5, 77, 1, 13,54,12] print(pr) # cортировка пузырьком: def bubble_sort(a_list): for pass_num in range(len(a_list) - 2, 0, -1): if (pass_num % 2) == 1: for i in range(pass_num): #if (pass_num % 2) == 1: if a_list[i] > a_list[i +2]: ...
5e806bb8ad3ffe5977250ec31759928b77624528
lwplvx/cowrie
/cowrie/files/do_slice.py
799
3.765625
4
# -*- coding: utf-8 -*- def trim(s): sindex = 0 word = s[sindex:sindex+1] while word == ' ': sindex = sindex + 1 word = s[sindex:sindex + 1] ecount = -1 word = s[ecount:] if word == ' ': while word == ' ': ecount = ecount-1 word = s[ecount:] ...
a84fdedc0b141c0b5dc79acfb3685fa7a7f04b99
jorgemauricio/INIFAP_Course
/Exams/Respuestas/ejercicio_15_r.py
495
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio - Crear un programa el cual permita al usuario imprimir una serie de "*" de acuerdo al número que se ingresar Ej 1. funcion(10) * ** *** **** ***** ****** ******* ...
acb77dd39d213b0b7d128864094a2a2e585c1561
jorgemauricio/INIFAP_Course
/ejercicios/ej_23_mapping.py
699
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio """ # librerias import numpy as np import pandas as pd from pandas import Series, DataFrame # vamos a crear un dataframe con las ciudades con mayor elevación de USA dframe = DataFrame({'city':['Alma','Brian ...
20ba7ae0f6cfeafc0865b75654580ea82031b1da
jorgemauricio/INIFAP_Course
/Exams/Respuestas/ejercicio_11_r.py
690
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio - Escribe un programa que calcule el valor neto de una cuenta de banco basado en las transacciones que se ingresan en la consola de comandos. Ej: D 200 D 250 P 300 D 100 P 200 Donde: D = Deposito P...
a9f1b9b93badc8325d211501be4fc66b12eda2db
jorgemauricio/INIFAP_Course
/ejercicios/ej_9_dataframes.py
1,791
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio """ # librerias import numpy as np from pandas import Series, DataFrame import pandas as pd # DataFrames # vamos a obtener un poco de informacion, que tal de la NFL? import webbrowser website = 'http://en.w...
6d0ec4ce4028698dc87c2a4f0fb9516661bebe67
jorgemauricio/INIFAP_Course
/Exams/Respuestas/ejercicio_10_r.py
549
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio - Escribe un programa que toma una frase ingresada por el usuario y contabilice el numero de letras y números que contiene la frase. Ej Hola mundo! 1234 Números = 4 Letras = 9 """ s = input("Ingresa un...
dd6d379abbf82292e28e380933406bdd525b0332
Munanna/Rosalind-solutions
/FIBO.py
223
3.9375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 6 23:47:26 2017 @author: OMNISLO """ n=6 def Fib(n): if n==0: return 0 if n==1: return 1 else: return Fib(n-1)+Fib(n-2) print (Fib(n))
64e0f66bc0c33348d81982f73ade89e995e68af1
CMalaitai/Pizza-Ordering-System
/details.py
1,558
3.828125
4
import tkinter as tk import intro def go_back(): root.destroy() intro def window_one(): # Pick up details root = tk.Tk() root.title("Details for Pickup") name_label = tk.Label(root, text = "Name") name_label.grid(row = 0, column = 0) name_entry = tk.Entry(root) na...
293fe7ead7c870e3f25bde546f2b34337eb32378
optionalg/cracking_the_coding_interview_python-1
/ch4_trees_and_graphs/4.2_minimal_tree.py
1,190
4.125
4
# [4.2] Minimal Tree: Given a sorted(increasing order) # array with unique integer elements, write an algorithm # to create a binary search tree with minimal height # Space complexity: # Time complexity: import unittest def create_bst(array): if not array: return None elif len(array) == 1: r...
68605481e963d7cb78d700c63f7936318d46da11
optionalg/cracking_the_coding_interview_python-1
/ch3_stacks_and_queues/3.4_queue_via_stacks.py
962
4.09375
4
# [3.4] Queue via Stacks: Implement a MyQueue class # which implements a queue using two stacks. import unittest class MyQueue(object): def __init__(self): self.s1 = [] self.s2 = [] def push(self, value): self.s1.append(value) def pop(self): if not self.s1 and not s...
b0d9de4d3f59d074ea1ffc412a99e8610ddccab6
optionalg/cracking_the_coding_interview_python-1
/ch5_bit_manipulation/5.7_pairwise_swap.py
1,734
4.15625
4
# [5.7] Pairwise Swap: Write a program to swap odd and even bits # in an integer with as few instructions as possible (e.g., bit # 0 and bit 1 are swapped, bit 2 and bit 3 and swapped, and so on) import unittest def pairwise_swap(num): even_mask = create_even_mask(num) odd_mask = create_odd_mask(num) ...
3dc3b3e5045027bcccafc7907b667a0d2c8ec606
optionalg/cracking_the_coding_interview_python-1
/ch1_arrays_and_strings/1.1_is_unique.py
798
4.1875
4
# Time complexity: O(n) because needs to check each character # Space complexity: O(c) where c is each character import unittest def is_unique(s): # create a hashmap to keep track of char count char_count = {} for char in s: # if character is not in hashmap add it if not char in char_c...
4e24b60180d46b42eb2406238f595bd89a9711c1
optionalg/cracking_the_coding_interview_python-1
/ch1_arrays_and_strings/1.8_zero_matrix.py
3,152
4.15625
4
#Time Complexity: O(MN) #Space Complexity: O(M+N) import unittest def set_zeros2(matrix): #Time Complexity: O(MN) #Space Complexity: O(1) if not matrix: raise Exception("Matrix is empty") rows = len(matrix) cols = len(matrix[0]) first_row_zero = False first_col_zero = False ...
738c5f3cfa7d3c58b05c5738822e0d807dbf1f7b
optionalg/cracking_the_coding_interview_python-1
/ch8_recursion_and_dynamic_programming/8.1_triple_step.py
1,634
4.15625
4
# [8.1] Triple Step: A child is running up a staircase with n # steps and can hop either 1 step, 2 steps, or 3 steps at a # time. Implement a method to count how many possible ways # the child can run up the stairs. import unittest def fib(n): if n < 1: raise ValueError('Must be positive Integer') el...
1a1c6efe30ffc267bea760e4ed7bd5df105d30a8
Pearltsai/lesson5HW
/lesson5HW_1.py
153
3.71875
4
r=0 s=[] x=int(input('學生數量')) for i in range(x): y=int(input('學生成績')) r=r+y s.append(y) print('平均是',r/x)
c639e5f97c3e687d28e52b5485c83dd1e1e238ba
eswecha/machine-learning-python
/cuurentbills/lacky.py
263
3.71875
4
n=input("enter no.of units") if(n<25): s=n*3.25 print("total amount=",s) if(26<n<50): s=n*5.25 print("total amount=",s) if(51<n<100): s=n*8.25 print("total amount=",s) if(n<101): s=n*12.25 print("total amount=",s)
e14c14ae89edfd38551622878b191318c3d5f995
AlvaroPaniaguaT/RIM-Exercises
/NLTK-exercises/8-9-Lemmatizer.py
2,157
3.8125
4
import nltk from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords tokenizer = RegexpTokenizer(r'\w+') lemmatizer = WordNetLemmatizer() def get_wordnet_pos(word): """Map POS tag to first character lemmatize() accepts""" ...
11cca641900d9b4fa623b7bdc00c3e581c899b9e
AlvaroPaniaguaT/RIM-Exercises
/NLTK-exercises/1-RemoveCommas.py
297
3.65625
4
from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(r'\w+') def main(): # Remove commas from input text file file = input('Path to the file to use -> ') with open(file, 'r', encoding="utf-8") as f: f = f.read() print(tokenizer.tokenize(f)) main()
b445940ae8709998ff288f0905b82605505d12bb
LuisAlfaro998/201603100-Cortos980
/corto1/corto1.py
867
3.546875
4
#--------------------------CORTO 1-------------------------------------------- #LUIS ALBERTO ALFARO HEREDIA-------------------------------------------------- #201603100-------------------------------------------------------------------- def collat(n): #se crea una funcion para solo llamarla despues ...
8bb1a9dc796f4c86264baa233fbcf0530e50911f
VigneshSahoo/Second-Milestone-Project
/Variables.py
1,185
3.734375
4
import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = { 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, ...
b0f1b9a2085273978bbedfa8df79e22ac882da5b
SamuraiT/sicp-memo-ans
/chap1/py_implementation/primality.py
1,113
4.09375
4
#! /usr/bin/env python # coding: utf-8 """ Copyright 2014 Tatsuro Yasukawa. Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ import sys sys.setrecursionlimit(10000) def main(): pass def is_prime(n): """ >>> is_prime(10) False >>> is_prime(17) True >>> is_...
e878ee5190bad3809e9b05431068cce15d511596
kelvindecosta/ctf-levels
/games/2019-10-02-codathon/levels/02-way-down-you-go/solution.py
652
4.09375
4
def flag(i): # Returns a string (flag) given an integer (i) return "CTF{" + str(i) + "_r3cur510n5_p3rm1773d}" def factorial(n): # Returns the factorial of a number if n == 0: return 1 return n * factor...
ecc13cf152d3044d17f532590a43e4ccfa7af0e8
jutish/master-python
/21-tkinter/13-proyecto.py
3,711
3.5625
4
""" Crear un programa que tenga: - Ventana - Tamaño Fijo - No Redimensionable - Un Menu - Diferentes Pantallas - Formulario de añadir producto - Guardar datos temporalmente en una variable - Mostrar datos listados en la pantalla - Opcion Salir """ from tkinter import * from tkinter import ttk #Definir Ventana ventana ...
86ff44ba86aa11b8ce4e3ae20b2fe624e14f17c7
jutish/master-python
/11-ejercicios/ejercicio4.py
619
3.640625
4
""" Crear un script que tenga 4 variables una Lista, String, un Entero, una Bool. Y que imprima un mensaje segun el tipo de dato. Primero hacerlo normal y luego con funciones. """ var1 = [] var2 = "Pepe" var3 = 15 var4 = True def check(variable,formato=0): if formato == 1: print(f"La variable es del tipo: {type(va...
24a35e007a840bcae5b25b34fcee7d74abbd5790
jutish/master-python
/10-sets-diccionarios/dicts.py
598
4.03125
4
""" Tenemos un tipo de dato clave:valor. La clave puede ser alfanumerico """ # persona = { # "nombre":"Esteban", # "apellido": "Marcelloni", # "web":"www.emarcelloni.com" # } # print(persona) # print(type(dict)) # print(persona["apellido"]) #Como acceder a los datos. #Lista con diccionarios contactos = [ { ...
ff7e1c2a4dc59cb1786841b7fff931fc5db1e00f
jutish/master-python
/07-ejercicios/ejercicio4.py
360
4.15625
4
""" Pedir dos numeros al usuario y hacer todas las operaciones de una calculadora. Suma, resta, multiplicacion y division. """ nro1 = int(input("Ingrese Nro1: ")) nro2 = int(input("Ingrese Nro2: ")) print(f"{nro1} + {nro2} = {nro1+nro2}") print(f"{nro1} - {nro2} = {nro1-nro2}") print(f"{nro1} * {nro2} = {nro1*nro2}")...
a9d002810cc75cc79d531413be8bf5fbcbf70546
jutish/master-python
/07-ejercicios/ejercicio5.py
223
3.953125
4
""" Hacer un programa que muestre todos los nros. entre dos nros. que el usuario diga """ nro1 = int(input("Ingrese limite inferior: ")) nro2 = int(input("Ingrese limite superior: ")) for i in range(nro1,nro2+1): print(i)
465baa489b2b4fd87631c15b57305e02ec40c303
a95818rw/OCR
/bubbletest/bubbleGui.py
535
3.5
4
def clear(): entryTxt.set("") def Go(): print("null") import tkinter as tk gui = tk.Tk() gui.title("Sheng") frame1 = tk.Frame(gui) label = tk.Label(frame1, text = "Picture Address:") entryTxt = tk.StringVar() entry = tk.Entry(frame1, textvariable = entryTxt) label.grid(row = 0, column = 0) entry.grid(row = ...
c3fe1c6b5ae519f893efd74ff2e4a89b629a30cf
dbotwinick/python-botwinick-math
/botwinick_math/geo/wind.py
3,928
4.4375
4
# author: Drew Botwinick, Botwinick Innovations # license: 3-clause BSD from math import (atan2 as _py_atan2, floor as _py_floor) from .cartesian import PI, TWO_PI, normalize_angle WIND_ROSE_CONVENTION_OFFSET = PI * 1.5 def convert_angle_math_wind(angle_radians): """ Function to convert a single angle betw...
b33ad3439951c4cc1b5996ad0beceb22f1b475b1
zuka1129/python-ml-exercise
/python-ml-exercise/lesson_7/py_decorator/venv/demo/func_args.py
678
3.515625
4
#本模块测试参数传递问题 def my_func(a, b, c=1, d=2, *args, **kwargs): print(a,b) print(c,d) print(args) print(kwargs) #my_func(1,2,3,4,7,8, e=5, f=6) ### 参数列表*以后的所有参数必须写名字如:name = value的形式传入 # 命名关键字参数是必须参数,如果不需要他是必须参数,那么可以给一个默认值 def my_func1(a, b, *, c, d): print(a,b) print(c,d) #my_func1(1, 2, c=3, d=...
4755f34857aa5f6ce984fc1a3c21d69fe06eee72
PhilosophyzJY/EE219-2017W
/project5/part1.py
1,646
3.5625
4
import json import xlsxwriter from math import floor def main(): # Change this line for the hashtag # AverageTweetsPerHour('tweets_#superbowl.txt','For #superbowl, the stats are:') def AverageTweetsPerHour(filename,title): length = 0 followers = 0.0 retweets = 0.0 byHour = [] for line in open(filename, 'r...
1665c3ffd3e9b900d92514246a31876f70f2d5ef
7avenged/women_review
/womencopy2.py
3,996
3.59375
4
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB, BernoulliNB import numpy as np import re import string import pandas as pd import numpy as np import matplotlib.pyplot as plt #im...
fdee0f3aaae1372696e95ba72cb3ca090df592fb
pieland-byte/Introduction-to-Programming
/week_4/ex_3.py
1,341
4.3125
4
#This program creates a dictionary from a text file of cars and prints the #oldest and newest car from the original file #create a list from the text file def car_list(): car_list = [] #Empty list with open ("cars_exercise_3.txt" , "r") as car_data: #Open text...
2e0d8cbe84dc1a8a57e90e9c34e015d1c4eebfe5
pieland-byte/Introduction-to-Programming
/week_1/ex_5.py
298
4.3125
4
# This is a program to convert temperature in fahrenheit to celcius/centigrade fahrenheit = input("Enter the temperature in fahrenheit: ") fahrenheit = int(fahrenheit) celsius = ((5/9) * (fahrenheit - 32)) print(fahrenheit, "Degrees Fahrenheit is",round(celsius,2), "degrees Celsius")
c546d7555f99c6bb2b2fa6d0266e6615256aecb2
pieland-byte/Introduction-to-Programming
/week_3/ex_2.py
1,309
4.625
5
#This program calculates the volume of given shapes specified by #the user using recursion import math # creating a menu with options for user input def main_menu(): menu_choice = input("Please type 1 for sphere, 2 for cylinder and 3 for cone: ") if menu_choice == "1": result = sphere(int(inp...
119d31f2c4846ba1416da750b0e87a38d77509f3
pieland-byte/Introduction-to-Programming
/week_4/ex_2.py
1,159
4.15625
4
#This program asks the user to name a sandwich ingredient and shows #corresponding sandwiches from the menu sandwiches = [] #Empty list with open ("menu.txt","r") as menu: #Read menu.txt for line in menu: #For each line sandwiches.append(line....
401075a7b543a9eb6a6d81c820a371aa3a24a66f
pieland-byte/Introduction-to-Programming
/week_4/ex_1.py
546
4.1875
4
#This program asks the user to name a sandwich and shows corresponding #sandwiches from the menu sandwiches = [] with open ("menu.txt","r") as menu: for line in menu: sandwiches.append(line.rstrip("\n")) def sandwich_choice(): choice = input("Enter which sarnie you would like: ") for...