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
050f58b3d3f1bfc6f6f65e4dee30c8899c8fdf51
wuzixiao/ARTS
/Algorithms/ProductionOfArrayExceptself.py
2,045
3.8125
4
''' Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including...
8644298a21694406242b6bb6c8251e0576fe5432
OAFA-team/OAFA-BE
/infra/utils.py
277
3.703125
4
def positive_int(integer_string, strict=False, cutoff=None): '''Cast a string to a strictly positive integer.''' ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: return min(ret, cutoff) return ret
9e17cea4e9b5ef973d52a0b79078a17348775d7d
sasiashwin/infosys
/lcm.py
194
3.90625
4
def lcm(x,y): if(x>y): lcm = x else: lcm = y while(lcm): if(lcm%x==0 and lcm%y==0): break lcm+=1 return lcm x=22 y=26 print(lcm(x,y))
07bf01648ec762b3c03c6fcc3b4dae660f3a680f
faishalirwn/visualisasi-selection-insertion-sort
/sortAlgoVis.py
4,497
4.25
4
import random import time import copy import matplotlib.pyplot as plt import matplotlib.animation as animation def swap(A, i, j): # Helper function to swap elements i and j of list A if i != j: A[i], A[j] = A[j], A[i] def insertionsort(A): # In-place insertion sort for i in range(1, len(A))...
67a538b8a02da6b2b89fbf9cd1e044f35f9a055e
ngoyal16/ProjectEuler
/Project Euler #0022- Names scores/p0022.py
352
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys def count_word(word): return sum(ord(c) - 64 for c in word) name_string = raw_input().replace('"', '') name_list = name_string.split(",") name_list.sort() res = 0 for i, val in enumerate(name_list): res += (i+1) *...
cadb39762867de0d2e12c60f050cf5a9737c6088
YukiT1990/Shortest-Path-Algorithms
/ThresholdDistance1334.py
1,321
3.546875
4
# 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: matrix = [[float('inf') for _ in range(n)] for _ in range(n)] for i in range(n): matrix[i][i] = 0 ...
f6ebaab6da904b449934b592c73ebf42fe26c7c3
QueraltSM/GreedyAlgorithms
/Kruskal/main.py
1,001
3.71875
4
def kruskal(graph): assert type(graph)==dict nodes = graph.keys() visited = set() path = [] next = None while len(visited) < len(nodes): distance = float('inf') for s in nodes: for d in nodes: if s in visited and d in visited or s == d: ...
ed5a5372415392b6ba52e013b3dffc3d129f577b
saadjamil5/Chapter5
/IF Statements.py
1,465
4.09375
4
cars =['audi','bmw','subaru','toyota'] for car in cars: if car =='bmw': print(car.upper()) else: print(car.title()) requested_topping ='mashrooms' if requested_topping != 'anchovies': print("Hold the anchovies!") answer =17 if answer !=42: print("That is not correct amswer,Please tr...
4fb4a5ce88f359f2dfa717aeda26411b97579249
Darr-en1/practice
/AlgorithmProblem/单链表翻转.py
1,210
4.09375
4
__author__ = 'Darr_en1' """ 链表反转 """ class ListNode: def __init__(self,val,next=None): self.val = val self.next = next class RecursionSolution: """ 复杂性分析 时间复杂度: O(n) 空间复杂度: O(n) """ def reverse_list(self, head: ListNode, tail=None) -> ListNode: """ :...
bdf77cc4af0c8645c504afa232dbf01a1a00c274
Darr-en1/practice
/AlgorithmProblem/反转链表 II.py
1,051
3.875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode ""...
28e550a021981c10b38ac48d720c71be6b67dff1
Darr-en1/practice
/AlgorithmProblem/两数之和.py
682
3.609375
4
""" 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 """ class Solution: def twoSum(self, nums, target): """ 时间复杂度:O(n) 空间复杂度:O(n) """ n = len(nums) d = {} for x in range(n): a = target - nums[x] if nums[x] in...
060e264d68a003aef82301151a09c27a30ecf2ca
Darr-en1/practice
/剑指offer/29_顺时针打印矩阵/code.py
1,214
3.5625
4
from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return matrix s_length, e_length, s_width, e_width, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, [] while True: for j in range(s_length, e_length...
0855958536589a5cb0ee76a1af28d39b912185e5
Darr-en1/practice
/剑指offer/36_二叉搜索树与双向链表/code.py
1,464
3.71875
4
from collections import deque class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def arr_to_tree(li): tree_list = deque() tree = Node(li[0]) if li else None i = 1 tree_list.append(tree) while i < len(li): ...
880b3b158b1f8e2b56d01ac8e6042cbd2d4b484a
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
589
4.40625
4
#!/usr/bin/python3 """ This function will print a square equal to the size given """ def print_square(size): """ This function will raise errors if an integer is not given as well as if the value is equal or less than zero. """ if not isinstance(size, int): raise TypeError("size must be an intege...
ab396ea8fa83578e55ee4e24db98b4830749cc27
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_square.py
1,879
4.21875
4
#!/usr/bin/python3 """ this is the unittest file for the Base class """ import unittest from models.square import Square class SqrTest(unittest.TestCase): """ These are the unit tests for the base class """ def test_basics2(self): s = Square(1) self.assertEqual(s.width, 1) s = Squar...
4d3a8bef55942c0f3c4142e807f539ac5cfcda46
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
247
4.28125
4
#!/usr/bin/python3 """ This function appends a string to a file! """ def append_write(filename="", text=""): """ apppends to the end of a file then returns character count """ with open(filename, 'a') as f: return f.write(text)
705c3befaee07078ffc689aaec49729f571697ef
makpe80/Boot-camp
/24 lesson. Module 6. OOP/code_examples/gui.py
3,575
3.921875
4
# import tkinter as tk # window = tk.Tk() # label = tk.Label(text = "Hello world!") # label.pack() # input() ############################ # import tkinter as tk # window = tk.Tk() # label = tk.Label(text="Hello world!", foreground="green", background="red", width = 20, height = 20) # label.pack() # input() ###########...
978bad038ca358c0515806600ccd6bc92e53dfad
makpe80/Boot-camp
/7 lesson. Модуль 4. Модули и пакеты/code_examples/sphinx/ex_1.py
291
4.125
4
def say(sound:str="My")->None: """Prints what the animal's sound it. If the argument `sound` isn't passed in, the default Animal sound is used. Parameters ---------- sound : str, optional The sound the animal makes (default is My) """ print(sound)
090b6dba7dd5e1e4e85b31176d8e8c09545911e4
hinsley/scan2
/pdf2jpg.py
883
3.765625
4
#!/usr/bin/env python3 import argparse import os import sys import tempfile from pdf2image import convert_from_bytes parser = argparse.ArgumentParser(description="Convert PDFs to JPEG images.") parser.add_argument("-o", "--output", help="Output directory. Defaults to current directory.", default=".") args = parser....
aabbd0eb6bd2452e43cd49b61ef707c706a1f119
mershavka/get
/2-gpio-led/2-6-binary-numbers.py
700
3.578125
4
import RPi.GPIO as GPIO from time import sleep leds = [21, 20, 16, 12, 7, 8, 25, 23] bits = len(leds) GPIO.setmode(GPIO.BCM) GPIO.setup(leds, GPIO.OUT) def num2led(value): mask = bin(value)[2:].zfill(bits) for i in range(0, len(mask)): GPIO.output(leds[i], GPIO.HIGH if mask[i] == '1' else GPIO.LOW) ...
22710fcf9c704a893d6c4e31fd5eda174421ca7b
ericflyfly/Algorithms-practice
/findLargetValueInRow.py
1,041
3.953125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # LeetCode#515 Problem. You need to find the largest value in each row of a binary tree. # Use BFS to go through every node in every row and find the larges...
3174a3c416027f569e9a18897d3af6c051919516
ohcarole/AMLDatabaseCode
/Examples/test.py
579
3.515625
4
import Tkinter import tkMessageBox window = Tkinter.Tk() window.wm_withdraw() MsgResp = tkMessageBox.showinfo(title="Log Download", message="Would you like to send email to Center IT?", type="yesno") window.wm_withdraw() print(MsgResp) import ctypes # An included library with Python install. # import easygui def M...
478d36cb7ba562363b23bff4696d80a54f12f7e3
adgarboc/Platzi-PythonIntermedio
/dict_comprehensions.py
329
3.875
4
from math import sqrt def run(): # dict = {} # for x in range(1,101): # if x % 3 != 0: # dict[x] = x**3 dict = {i: i**3 for i in range(1, 101) if i % 3 != 0} print(dict) dict_challenge = {i:sqrt(i) for i in range(1, 1001)} print(dict_challenge) if __name__ == '__main__': ...
e24992b8d452a95a0e5b5ea10fc109050b610332
SteelFlow/advent-of-python-2019
/01.py
479
3.625
4
import math import io def partOne(mass): return math.floor(mass / 3) - 2 def calculateFuel(mass): fuel = math.floor(mass / 3) - 2 if fuel > 0: fuelMass = calculateFuel(fuel) return (fuelMass + fuel) else: return 0 f = open("0102.txt", "r") input = f.readlines() f.close()...
0ab0a052a247fbcc29ad44ca7b05740eb65cd1f8
Taranoberoi/Practise
/List Less Than Ten.py
357
4.28125
4
# Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # write a program that prints out all the elements of the list that are less than 10. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [] # for i in a: # print("Value is ",i) # if i <= 10: # b.append(i) # els...
463f9708d9e3cec7047f3541bc8f0b570b5b44dc
Taranoberoi/Practise
/10_LIST OVERLAP COMPREHESIONS.py
690
4.25
4
# This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. # Take two lists, say for example these two:and write a program that returns a list that contains only the elements that are # common between the lists (without duplicates). Make sure y...
d413470cd6e36f814e42b53bf2c23cf75ee3c78c
Taranoberoi/Practise
/FB_Test_Vowels.py
176
3.65625
4
n = " I am soumya" v = 0 for i in n.lower(): if i == "a" or i == "e" or i == "i" or i == "o" or i == "u": v = v + 1 print("show me vowels",i) print(v)
df0d59cdffe47b341b2f5f161eea315bee47eb2a
csides/SEChallenge
/optimizeParty.py
5,666
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 5 17:35:10 2017 Decide which food and drink options to buy for the party SE Challenge @author: Chris """ import numpy as np # This function will plan which food and drinks to buy for # A party given peoples preferences and a total budget # Input...
92a0429afb21d39eb64817d068b73f229a608c09
Othielgh/Cisco-python-course
/5.1.11.7 - Palindromes.py
905
4.25
4
# Your task is to write a program which: # asks the user for some text; # checks whether the entered text is a palindrome, and prints result. # Note: # assume that an empty string isn't a palindrome; # treat upper- and lower-case letters as equal; # spaces are not taken into account during the ch...
a0a00cec203bbaaeee83a82db647317f2db296b3
Othielgh/Cisco-python-course
/5.1.11.11 - Sudoku.py
1,186
4.3125
4
# Scenario # As you probably know, Sudoku is a number-placing puzzle played on a 9x9 board. The player has to fill the board in a very specific way: # each row of the board must contain all digits from 0 to 9 (the order doesn't matter) # each column of the board must contain all digits from 0 to 9 (again, the...
b0359b386614b79b6072a39963be680644dcba53
FernanGI/teoria_codigos
/huffman_binario.py
7,678
3.53125
4
from collections.abc import Container, Iterable, Sized from abc import abstractmethod import sys #Código creado por el propio IDE class IMap(Container, Iterable, Sized): # [imap @abstractmethod def __getitem__(self, key: "K") -> "T": pass @abstractmethod def __setitem__(self, key: "K", value: "T"): pas...
16251250d0790bea5ab86ccd1b13384a1fdbd884
pesi1874/algorithm-with-python
/Code/Test/SelectionSort.py
2,039
3.59375
4
from SortingAlgorithm.utils import count_time, gen_random_list, base_log @count_time @base_log def selection_sort(nums): length = len(nums) for i in range(length-1): # print(i) _min = i for j in range(i+1, length): # print(j, least) if nums[j] < nums[_min]: ...
294badc187f81a321cf7475f263bb959a1a311ca
pesi1874/algorithm-with-python
/Code/Test/MergeSort.py
2,361
3.59375
4
from SortingAlgorithm.utils import count_time, base_log def merge_sort(nums): print(nums) length = len(nums) if length <= 1: return nums num = int(length/2) left = merge_sort(nums[:num]) right = merge_sort(nums[num:]) print('merge', left, right) return merge(left, right) def m...
88aa9dfcb04c80b32596df743a96802c2bae826a
aelimon/CTI-110-Repository
/P2T1_ SalesPrediction_LimonAlisabeth.py.py
372
3.59375
4
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> total_sales=float(input('Enter the projected sales: ')) Enter the projected sales: 10000 >>> profit=total_sales * 0.23 >>> print('The profit is $', forma...
c7ef964dd8b0539600d0a1cbacac5a161effe9c0
rluedde/sudoku
/python_implementation/sudoku.py
7,168
3.890625
4
# Big-picture ideas for this: # -An algo that solves a puzzle that you put in # -An algo that creates solvable puzzles # -aka generates a grid # -Two new classes: SudokuGenerator and SudokuSolver # -I'd get to practice with inheritance # -some graphics to make this playable by a user # -Option to cho...
faee1c46d94a7b02c9ad9f8810c327e704f68584
BiaChaudhry/ATMsystem
/codeATM.py
5,503
3.890625
4
print(" \n\t $$$$$$$ WELCOME to ATM sevice .py $$$$$$$ \t \n \t >>>GET AND CARRY WITH GREAT CARE \n\t OUR MOTTO:WE ARE HERE TO SERVE YOU") #function defined that runs the ATM system def atmSystem(pinCode,pinCode01,pinCode02,pinCode03,pinCode04,pinCode05,names,name01,name02,name03,name04,name05,acountNums,acountnum01,...
34bf9584bac420e97822bd97761c5d5bd3c048f1
zhangMr123456/DesignPatterns
/singleton_pattern.py
2,557
3.84375
4
""" 单例模式: 全局只能出现一个对象 """ import threading """ 第一种: 纯天然 Python是编译性语言,运行时会编译为 .pyc 字节码文件,所以只需要导入使用就是纯天然的单例模式了 """ class Singleton: pass singleton = Singleton() """ 第二种: 装饰器实现 定义一个装饰器,然后对类进行装饰这样就可以实现单例了 """ def Singleton(cls): _instance = {} def _singleton(*args, **kwargs): if cls not in...
35b77632e0c762c397ee4888bf5cb39a70245194
SeungUkLee/LeetCode
/Easy/1. Two Sum/Two Sum.py
425
3.609375
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # hashmap 이용 dic_nums = {} for i, num in enumerate(nums): check_num = target - num if check_num in dic_nu...
fc09677a9a2e133d354ec43a017bd1187ef5b8fa
jackrdavies1/MMGame
/game.py
8,109
3.75
4
#!/usr/bin/python3 import time from map import rooms from player import * from items import * from gameparser import * from people import * def print_inventory_items(items): """This function takes a list of inventory items and displays it nicely, in a manner similar to print_room_items(). The only di...
02b8345f83ec6c221a30a344316bc6ad2ffdfc3d
btr1975/persistentdatatools
/persistentdatatools/persistentdatatools.py
13,930
3.59375
4
#!/usr/bin/env python3 """ Updated By: Benjamin P. Trachtenberg Date Written 9/17/2015 Description: Some quick tools to make persistent data quicker """ import logging import csv as __csv import os as __os import re as __re import random as __random import string as __string import zipfile as __zipfile LOGGER = log...
5c49c1bce88597e037c6d476053bb88747d02615
debskiszymon/learning-git-task
/main.py
433
3.859375
4
shopping_list = { "piekarnia": ["chleb", "chalka"], "warzywniak": ["pomidory", "cebula", "marchew", "ziemniaki"] } count = 0 for key, value in shopping_list.items(): count += len(value) for key, values in shopping_list.items(): print(f"Idę do {key.capitalize()} i kupuję tam {[value.capitalize() for value in ...
789de50dc6abf50a2cf37a2d357b8b0abcbd2811
vinodvr81/miscellaneous
/phythonClassMethod.py
970
4.03125
4
# @classmethod vs @staticmethod vs "plain" class MyClass: def plainmethod(self): """ Instance methods need a class instance and can access the instance through `self`. """ return 'instance method called here, Okay!!!', self @classmethod def classmethod(cls): ...
799c29722fb4022bcd8467990267789655e3209f
ShivaPrasadhegde101/tic_tac_toe_gui
/tic_tac_toe_gui.py
7,407
3.875
4
from tkinter import * from tkinter import messagebox window=Tk() window.configure(background="light blue") window.title("TIC-TAC-TOE-GAME") l1=Label(window,text="Player1:-X",font=('Times New Roman','12')) l1.grid(row=0,column=0) l2=Label(window,text="Player2:-0",font=('Times New Roman','12')) l2.grid(ro...
94cdd414098db2889b19f8a5418ca0a1957ca0f0
havardnyboe/ProgModX
/2019/42/Oppgave 6.py
503
3.890625
4
import random rand_tall = random.randint(1,10) # genererer et tilfeldig tall mellom 1 og 10 br_tall = int(input("Skriv inn et tall mellom 1 og 100: ")) produkt = rand_tall*br_tall print("\nProduktet av tallene er", produkt) br_gjett = int(input("Hva tror du tallet er?: ")) print("\nDu gjettet {} og tallet var {}".fo...
e389e036c99b84dc841c8fce314a1a2bf25af929
havardnyboe/ProgModX
/2019/43 Prøve/Oppgave 4.py
328
3.703125
4
# a) print("a)") oddetall = 0 for i in range(101): if i % 2 == 1: # hvis resten blir 1 når det deles på 2 oddetall += i print(oddetall) # b) print("\nb)") partall = 0 tall = 0 while tall <= 100: if tall % 2 == 0: # hvis resten blir 0 når det deles på 2 partall += tall tall += 1 print(parta...
bb7cdb1c3423b10371a07d519035b7ddc0ec029f
havardnyboe/ProgModX
/2019/39/Oppgaver Funksjoner/Oppgave 6.py
315
4.125
4
def fibonacci(nummer): fib_liste = [0, 1] for i in range(nummer-1): nytt_nummer = fib_liste[-1]+fib_liste[-2] fib_liste.append(nytt_nummer) i = i+1 return print("Tall nummer", i+1, "er", fib_liste[-1]) tall_nummer = int(input("Hvilket tall nummer vil du se i fibonaccifølgen?: ")) fibonacci(tall_nummer)
0872a18482c26fae6af328ca7c6ab9c3b73e71a3
havardnyboe/ProgModX
/2020/2-3 Derevasjon/Oppgaver Derevasjon/Oppgave2.py
390
3.578125
4
from matplotlib import pyplot as plt import numpy as np dx = 1E-4 x_verdier = [] y_derevert = [] def f(x): return x**3 - 2*x**2 - x + 5 def deriver(f, x, dx): return (f(x+dx)-f(x))/dx for i in np.arange(0, 10, dx): x_verdier.append(i) y_derevert.append(deriver(f, i, dx)) plt.plot(x_verdier, y_de...
0a7d14870674e0891c580335e881030cf8b56ccd
havardnyboe/ProgModX
/2019/36/Oppgave 1.6-1.11/Oppgave 1.7.py
376
3.96875
4
tall1 = int(input("Skriv inn et tall - ")) tall2 = int(input("Skriv inn et annet tall - ")) tallSum = tall1 + tall2 tallDiff = tall1 - tall2 tallProd = tall1 * tall2 tallForh = tall1 / tall2 print("Summen av tallene er", tallSum) print("Differansen av tallene er", tallDiff) print("Produktet av tallene er", tallProd) ...
e281a6c2e97163336c6dd784a3e11699223d1c74
havardnyboe/ProgModX
/2019/37/Oppgave 3.1-3.6.py/Oppgave 3.7.py
508
3.5
4
#Lag et program som løser andregradslikningen 𝑎𝑥^2+𝑏𝑥+𝑐=0, ved å ta 𝑎,𝑏 𝑜𝑔 𝑐 som input. a = float(input("Skriv inn en verdi for a: ")) b = float(input("Skriv inn en verdi for b: ")) c = float(input("Skriv inn en verdi for c: ")) if (b**2) - (4*a*c) == 0: en_losning = -b/(2*a) print(en_losning) elif (b**2 ...
1c4de502a1c1bee6cd6ba895a5e27f945b13de4e
jasonchang0/PyBoard
/data_structures/LinkedList.py
3,754
3.625
4
class LinkedList(object): def __init__(self, head=None, fromArray=None): if head and fromArray: raise Exception('Bad Argument!') if fromArray is not None: self._fromArray(fromArray) return self.sentinel = 0 self.head = self.Node(val=self.sentine...
bab50a1b6b24478833fc3419f92fd4e2afd51b68
camilolaiton/Artificial_Intelligence
/Search-Algorithms/tree-searchs.py
19,282
4.15625
4
#!/usr/bin/env python """ Made by: - Camilo Laiton University of Magdalena, Colombia 2019-2 Artificial Intelligence Topic: Tree Searchs GitHub: https://github.com/kmilo9713/ Algorithms bfs and dfs taken from: https://eddmann.com/posts/depth-first-search-a...
1e67af2a8b6603f13b4e1fa270749b903b094d6a
FarihaKhalid/Python-Progrmming-CISCO
/Qno5.py
190
4.03125
4
First_Name = input("Enter your First Name: ") Last_Name = input("Enter your Last Name: ") First_Name_L = (len(First_Name)) Last_Name_L = (len(Last_Name)) print(Last_Name, " ", First_Name )
ff96ed00125f140d2f86e8b44007fd20ce14e6e2
Ashish7783073120/MyCaptainTestPython
/Task-10.py
229
3.84375
4
# Python-beginners-tasks class rectangle(): def __init__(self ,l ,w): self.length = l self.width = w def rectangle_area(self): return self.length*self.width print(rectangle(10,5).rectangle_area())
a20288b098bf3a709df7256a6c644351d90d9cda
lakshmilux/ctslice
/EDAoperations/TrainPreprocessor.py
3,662
3.546875
4
from ApplicationLogger.AppLogger import Logger import pandas as pd class TrainPreprocess: """ This class is used for train data preprocessing """ def __init__(self,file_object,log_writer): self.Training_file = "TrainingDatabase\Traindf.c...
435588d92eab30058a2630b14ca1e40881f3ed37
NamISNaN/Lab3-markov-decision-process
/src/MDP.py
5,377
3.59375
4
import numpy import sys def markov_decision_process(o, g, h, s, T, f, p, test=False): def cal_transition_function(): """ Return P where P[before_sold][after_sold] is the probablity of given before_sold products at the begining of the month, there is after_sold products left at the end if the month....
553561e487766bf703a125cfd4a7b80a586df553
mothermember/codecademy_tasks
/pandas_aggregates_AB_testing.gyp
3,035
3.65625
4
import codecademylib import pandas as pd ad_clicks = pd.read_csv('ad_clicks.csv') print(ad_clicks.head(10)) #inspects the first 10 rows of the DataFrame ## USING PANDAS TO EXPLORE AD DATA. USING AGGREGATES AND PIVOTS TO COME TO CONCLUSIONS ABOUT AD PERFORMANCE ## ##ANALYZING AD SOURCES## print(ad_clicks.groupby('ut...
05e91096052dea88d065bd0636937e501d4d6da3
priyanka332/Login_Signup
/Login_Signup.py
3,961
3.953125
4
import json import os main_dict={} list=[] dict_out={} user_info={} if os.path.exists("userdetails.json"): # path():- this method is used to check whether the specified path exists or not. pass else: create=open("userdetails.json","w+") create.close() choose=int(input("choose 1 for signing in or choose ...
00e62e0fbf1bdbbfd35372e99dd366f2d034558c
greenfox-velox/oregzoltan
/week-03/day-3/11.py
496
3.875
4
# Create a function that prints a diamond like this: # * # *** # ***** # ******* # ********* # *********** # ********* # ******* # ***** # *** # * # # It should take a number as parameter that describes how many lines the diamond has def printtriangle(lines): for i in range...
fff52176408ddc67628b6c3707bc204363824ab8
greenfox-velox/oregzoltan
/week-04/day-3/09.py
476
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square...
898e238c890f11156ed324e0beabfe505010fcaf
greenfox-velox/oregzoltan
/codewars/python/digitize.py
197
3.875
4
def digitize(n): num_str = str(n) num_list = [] for i in range(len(num_str)-1,-1,-1): num_list.append(int(num_str[i])) return num_list print(digitize(35231)) # [1,3,2,5,3]
cdbb475550043d2c10c24e936cd750b5bae0badd
greenfox-velox/oregzoltan
/codewars/python/alphabet_position.py
281
3.796875
4
def alphabet_position(text): text = text.lower() text_numbers = [] for i in text: if i.isalpha(): text_numbers.append(str(ord(i)-96)) text = ' '.join(text_numbers) return text print(alphabet_position("The sunset sets at twelve o' clock."))
ccf32bfe44003b5bec6efdb0a064462edf443c77
greenfox-velox/oregzoltan
/week-04/day-3/12.py
554
3.890625
4
# create a 300x300 canvas. # fill it with a checkerboard pattern. from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square(size): x = 2 y = 2 for i in range(1, 9): for j in range(1, 9): if (i+j) % 2 == 0: color =...
1770563787875d4a0556e98ce9f12179ebbe4903
greenfox-velox/oregzoltan
/week-03/day-2/34.py
175
3.78125
4
numbers = [4, 5, 6, 7, 8, 9, 10] # write your own sum function def sum(numbers): total = 0 for a in numbers: total += a return total print (sum(numbers))
6684dd5cfcbfbcbd32a553d09ea0c0fdc57b5cba
greenfox-velox/oregzoltan
/codewars/python/namelist.py
420
3.515625
4
def namelist(names): if names == []: return '' name_list = [] name_str = '' for i in names: name_list.append(i['name']) if len(name_list) > 1: name_str = ', '.join(name_list[0:-1]) + ' & ' + name_list[-1] else: name_str = name_list[0] return name_str print(na...
9aca5975f136ec7a9820b7a03e5d6dd5762e2739
greenfox-velox/oregzoltan
/week-05/day-3/project/todo.py
3,821
3.609375
4
import sys import csv def main(): todo = TodoApp() if len(sys.argv) > 1: todo.menu(sys.argv) else: print(todo.usage()) class TodoApp(): def __init__(self): self.name = 'todo.csv' def menu(self, arg): self.arg = arg if self.arg[1] == '-l': print(...
38bf2fa152fbe028217728b502544ce1f5732432
greenfox-velox/oregzoltan
/week-04/day-3/11.py
751
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 2 parameters: # the square size, and the fill color, # and draws a square of that size and color to the center of the canvas. # create a loop that fills the canvas with rainbow colored squares. from tkinter import * import random root = Tk() ca...
b30b662fe551e7517c0dce1f2545a81b9ef7f294
greenfox-velox/oregzoltan
/week-03/day-1/exercise31-37withfor.py
706
3.84375
4
ad = 6 # print the numbers till ad from 0 for a in range(ad+1): print (a) ae = 4 text = 'Gold' # print content of the text variable ae times for a in range(ae): print (text) af = [4, 5, 6, 7] # print all the elements of af for a in af: print (a) ag = [3, 4, 5, 6, 7] # please double all the elements of th...
759d1ccc16111836397201807e4736892fa26c05
kopp/arcade_games
/grid_based_game.py
6,125
3.8125
4
# https://arcade.academy/examples/array_backed_grid_sprites_1.html#array-backed-grid-sprites-1 """ Array Backed Grid Shown By Sprites Show how to use a two-dimensional list/array to back the display of a grid on-screen. This version syncs the grid to the sprite list in one go using resync_grid_with_sprites. If Pytho...
a93c93e35d0b7323e9c2d590b1174c64abccc00f
MaheshShivayogi/PythonRS_GitPractice
/testData/ExcelDemo.py
756
3.859375
4
import openpyxl book = openpyxl.load_workbook("C:/Users/mahesmahesh/PycharmProjects/PythonSelfFramework/testData/TestData.xlsx") sheet = book.active Dict = {} cell = sheet.cell(row=1, column=2) print(cell.value) # To write data to excel # sheet.cell(row=2, column=2).value = "Mahesh" # print(sheet.cell(row=2, column=2...
3fbadf9127a88ba040b84fd90a6505a08d366d2c
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex013.py
365
3.84375
4
''' Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. ''' #Recebendo valores: salario = float(input('Digite o salario do funcionario: R$')) #Calculando aumento: aumento = salario + (salario * 15 / 100) #Resultado: print('O salrio do funcionario passou de {} reais p...
ba4b735ad6b8404b5fd529fdf62be47e237cd33d
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex022.py
649
4.34375
4
''' Crie um programa que leia o nome completo de uma pessoa e mostre: - O nome com todas as letras maiúsculas e minúsculas. - Quantas letras ao todo (sem considerar espaços). - Quantas letras tem o primeiro nome. ''' #Recebendo informações: nome = input('Digite um nome: ') #Declarando variaveis: maiusculas = nome.u...
ed81c73b24a8f4439d810ea641b72c7fb5751c79
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex015.py
711
4
4
''' Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelo quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0.15 por km rodado. ''' #Recebendo valores: dias = int(input('Digite a quantidade de dias que você andou com o ...
9db5e4fd057483a9e45ca51726cb81bcf46accd5
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex024.py
395
3.953125
4
''' Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome "SANTO". ''' #Recebendo valor: cidade = str(input('Digite o nome da sua cidade: ')).strip().upper() #Strip = Tirar espaços #Upper = Deixar tudo maiusculo #Declarando variavel: resultado = bool(cidade[:5] == 'SANTO') #Resultado:...
532eea4a81fa3151ea92a0f3f00d9b0dc71bccb4
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex008.py
379
4.15625
4
''' Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. ''' #Recebendo valores: metros = float(input('Digite o valor em metros: ')) #Declarando variaveis centimetros = metros * 100 milimetros = metros * 1000 #Informando resultado: print('{} metros é: \n{} centímetros\n{}...
2cb5df68d2b8544e1f290483a00b5db528e5cd35
purinxxx/math_python
/fibo.py
147
3.609375
4
# -*- coding: utf-8 -*- list = [] for i in xrange(100): if i==0 or i==1: list.append(1) else: list.append(list[i-2]+list[i-1]) print list
7997d00e4552dfa8af33e027ce87268565c3970f
parthsarin/SpotifyLibraryAnalysis
/years.py
848
3.84375
4
""" Analyzes the year-release distribution of the songs in someone's Spotify library. """ import collections import matplotlib.pyplot as plt def analyze(sp, songs): """Gives a year-breakdown of the songs in someone's library. :sp: An authenticated Spotipy object. :type sp: spotipy.Spotify :songs: A list of Spoti...
bacc4e387d32dbb572495c890ae3db921553bcd8
huytranvan2010/Sliding-Windows-for-Object-Detection
/test.py
956
3.609375
4
""" Ở đây mình muốn kiểm tra khi nó trượt nó có lấy phần dìa nếu còn dư không? Đáp án là: YES Ở đây có thể tạo một list để lưu các sliding window cũng được nhưng có vẻ dùng generator tiện hơn, duyệt đến khi nào hết thì thôi """ import numpy as np image = np.zeros((7, 7)) def slide(image, stepSize): ...
698356633a8d0f8f57e7cb359327550753514953
cesardramirez/python-platzi
/29_DictionaryFunctions.py
526
3.578125
4
import sys def add_value(value): print('Add Value', value + 5) def delete_value(value): print('Delete Value', value - 5) def exit_operations(value): sys.exit() def wrong_option(value): print('Invalid option') operations = { 'a': add_value, 'd': delete_value, 'e': exit_operations, } whi...
ff37410c6cf2cb917317145247a05d1dab9f0bb2
Marusiahoma/class_v1PIN
/OddEvenSeparator.py
462
3.609375
4
class OddEvenSeparator: def __init__(self): self.odd = [] self.up = [] self.over = [] def add_number(self, n): self.odd.append(n) def even(self): for i in range(len(self.odd)): if i % 2 == 0: self.up.append(i) return self.up ...
f4144a0d90298a681466ffcdbcaef4dc8d0f9889
shigessen/pythonExcelTraining
/python_prg/sample3.py
134
3.546875
4
score = 94 if score >= 90: print("S") elif score >= 70: print('A') elif score >= 50: print("B") else: print("NG")
7f927b014331b695e53ce21e49aec13dfc6e5901
mohitsshetty986/Personal-Projects
/Connect4 PyGame/Connect4.py
7,899
3.671875
4
import numpy as np import pygame import sys import math RED=(255,0,0) BLACK=(0,0,0) YELLOW=(255, 255, 0) GREEN=(0,255,0) row_count=6 column_count=7 def creating_board(): board=np.zeros((row_count,column_count)) return board def drop_piece(board,row,selectColumn,piece): board[row][selectColumn...
810c56da49dfbadd211538777de350a81c8c5c2f
rrbyn/AdventOfCode-2020
/aoc1.py
266
3.546875
4
f = open("input.txt", "r") n = f.readlines() for line in n: for line2 in n: for line3 in n: if int(line) + int(line2) + int(line3) == 2020: print(int(line)*int(line2)*int(line3))
72229eb78ece05158848c6e78667bcc878257830
purplecoder04/blackjack
/main.py
3,357
3.65625
4
import random from replit import clear from art import logo ############### Blackjack Project ##################### #Difficulty Normal 😎: Use all Hints below to complete the project. #Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project. #Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the p...
ab83676df09659b36dc3270b78fa6a5b07e13686
FrailCarter/ProgrammingChallenges
/quicksort.py
1,349
4.03125
4
def quicksort(arr): def qsort(low , high): if low >= high: return i , j = low , high pivot = arr[random.randint(low , high)] while i <= j: while arr[i] < pivot: i += 1 while arr[j] > pivot: ...
68ab1fd3687845f17060e21af84a9fdc767e6586
haveano/codeacademy-python_v1
/02_Strings and Console Output/02_Date and Time/03_Extracting Information.py
896
4.03125
4
""" Extracting Information Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don't want the entire date and time? from datetime import datetime now = datetime.now() current_year = now.year current_month = now.month current_day = now.day You already have the first two lines. In the third line, ...
bbd021753a87846dbe8ddb6353170691adff6d9f
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/01_Conditionals and Control Flow/05_To Be and or Not to Be.py
794
3.53125
4
""" To Be and/or Not to Be Boolean operators compare statements and result in boolean values. There are three boolean operators: and, which checks if both the statements are True; or, which checks if at least one of the statements is True; not, which gives the opposite of the statement. We'll go through the operators ...
7a9084979864dc2e1bc3a23b964d8d9790370ee5
haveano/codeacademy-python_v1
/05_Lists and Dictionaries/02_A Day at the Supermarket/13_Lets Check Out.py
1,142
4.3125
4
""" Let's Check Out! Perfect! You've done a great job with lists and dictionaries in this project. You've practiced: Using for loops with lists and dictionaries Writing functions with loops, lists, and dictionaries Updating data in response to changes in the environment (for instance, decreasing the number of bananas ...
30091839818331c9cf1831ab4f57ea5889a21128
haveano/codeacademy-python_v1
/08_Loops/01_Loops/05_Infinite loops.py
632
3.890625
4
""" Infinite loops An infinite loop is a loop that never exits. This can happen for a few reasons: The loop condition cannot possibly be false (e.g. while 1 != 2) The logic of the loop prevents the loop condition from becoming false. Example: count = 10 while count > 0: count += 1 # Instead of count -= 1 Instru...
29198699ac44500c390f06fc132dc7e362debc2d
haveano/codeacademy-python_v1
/07_Lists and Functions/01_Lists and Functions/08_Passing a list to a function.py
348
4
4
""" Passing a list to a function You pass a list to a function the same way you pass any other argument to a function. Instructions Click Save & Submit Code to see that using a list as an argument in a function is essentially the same as using just a number or string! """ def list_function(x): return x n = [3, 5...
97ce0591bd0ed48a9918db96043117d016f3cc06
haveano/codeacademy-python_v1
/11_Introduction to Classes/02_Classes/08_Modifying member variables.py
1,115
4.375
4
""" Modifying member variables We can modify variables that belong to a class the same way that we initialize those member variables. This can be useful when we want to change the value a variable takes on based on something that happens inside of a class method. Instructions Inside the Car class, add a method drive_c...
d2b8e32208cd60547fb0ce5e786064a1d4a17906
haveano/codeacademy-python_v1
/12_File Input and Output/01_File Input and Output/05_Reading Between the Lines.py
847
4.4375
4
""" Reading Between the Lines What if we want to read from a file line by line, rather than pulling the entire file in at once. Thankfully, Python includes a readline() function that does exactly that. If you open a file and call .readline() on the file object, you'll get the first line of the file; subsequent calls t...
dae86bdb60b625882e4524138412fdd218a2fce9
haveano/codeacademy-python_v1
/01_Python Syntax/01_Python Syntax/05_Whitespace.py
534
3.65625
4
""" Whitespace In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it. Instructions The code on the right is badly formatted. Hit "Save & Submit Code" to see what happens. You should see an error message. We'll fix it in the next exercise! """ def spam(...
2f923054d4a23e2001daee538249e2317af1c684
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/10_Ending Up.py
928
4.0625
4
""" Ending Up Well done! However, now we have the first letter showing up both at the beginning and near the end. s = "Charlie" print s[0] # will print "C" print s[1:4] # will print "har" First we create a variable s and give it the string "Charlie" Next we access the first letter of "Charlie" using s[0]. Remember l...
e988e9f53a578404a3c6c4b81174c704f395f19c
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/04_The bin() Function.py
1,150
4.65625
5
""" The bin() Function Excellent! The biggest hurdle you have to jump over in order to understand bitwise operators is learning how to count in base 2. Hopefully the lesson should be easier for you from here on out. There are Python functions that can aid you with bitwise operations. In order to print a number in its ...
572f9b19515b5f46c03ddafedb0f93b37b13a49e
haveano/codeacademy-python_v1
/08_Loops/02_Practice Makes Perfect/03_is_int.py
1,183
4.21875
4
""" is_int An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. This means that, for this lesson, you can't just test the inp...
64ec9944bed7e1f79e268bb3085b028f4c1d73a1
haveano/codeacademy-python_v1
/05_Lists and Dictionaries/02_A Day at the Supermarket/09_Something of Value.py
870
4.09375
4
""" Something of Value For paperwork and accounting purposes, let's record the total value of your inventory. It's nice to know what we're worth! Instructions Let's determine how much money you would make if you sold all of your food. Create a variable called total and set it to zero. Loop through the prices dictiona...
6876089ff1413f4e3bc30adecefa91b75a59e006
haveano/codeacademy-python_v1
/07_Lists and Functions/01_Lists and Functions/11_List manipulation in functions.py
594
4.34375
4
""" List manipulation in functions You can also append or delete items of a list inside a function just as if you were manipulating the list outside a function. my_list = [1, 2, 3] my_list.append(4) print my_list # prints [1, 2, 3, 4] The example above is just a reminder of how to append items to a list. Instructions...
15f47141d90b1e773ff194272ae57c357f3572b4
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/09_This XOR That.py
1,487
4.15625
4
""" This XOR That? The XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both. a: 00101010 42 b: 00001111 15 ================ a ^ b: 00100101 ...
4b1a907a1f05d61a2904551c34cfc20e1a733840
haveano/codeacademy-python_v1
/08_Loops/01_Loops/13_For your lists.py
625
4.78125
5
""" For your lists Perhaps the most useful (and most common) use of for loops is to go through a list. On each iteration, the variable num will be the next value in the list. So, the first time through, it will be 7, the second time it will be 9, then 12, 54, 99, and then the loop will exit when there are no more valu...
8062706113405bd9f941524f9a15961160619c3f
haveano/codeacademy-python_v1
/04_Functions/02_Taking a Vacation/06_Hey You Never Know.py
1,034
4.0625
4
""" Hey, You Never Know! You can't expect to only spend money on the plane ride, hotel, and rental car when going on a vacation. There also needs to be room for additional costs like fancy food or souvenirs. Instructions Modify your trip_cost function definition. Add a third argument, spending_money. Modify what the t...