blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
867c00104b83ef67f468333af95906285b6f7ddf | JeremiahZhang/gopython | /python-programming-an-introduction-to-CS/src/ch05/chaos2.py | 1,114 | 4.0625 | 4 | # chaos2.py
# A program to print a nicely formatted table showing
# how the values change over time.
"""
This program illustrates a nicely formatted table.
Enter two numbers between 0~1,seperated by a comma: 0.25, 0.26
index 0.25 0.26
------------------------------
1 0.731250 0.750360
2 ... |
a58a201f8e790bd4e4b072c201fb9dd6426fcfdd | jackneer/my-leetcode | /no24_swap_nodes_in_pairs.py | 881 | 3.859375 | 4 | class ListNode():
def __init__(self, x):
self.val = x
self.next = None
def print_all(self):
s = ''
s += str(self.val)
if self.next is not None:
s += '->' + self.next.print_all()
return s
def pair_swap(list):
current = list
prev... |
70c86ec849bbba83941024118ca18ef070813ada | chanayus/The-Exchange | /Exchange rates graph/2009Exchange.py | 628 | 3.828125 | 4 | """ Exchange """
import matplotlib.pyplot as plt
def main():
""" function """
x = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",\
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]
y = [34.965, 36.175, 35.495, 35.28, 34.31, 34.06, 34.025, 34.02, 33.44, 33.455, 33.24, 33.36]#input rate exchange
avg = sum(... |
acd76131bc03a05447059a6661a776387abdc21e | SoftwareEngineering4Scientists/python_primer | /list_tup_set_str.py | 422 | 4.15625 | 4 | my_list = [1, 2.0, "three", 4]
my_tup = (1, 2.0, "three", 4)
my_set = {1, 2.0, "three", 4}
my_str = "1, 2.0, three, 4"
# Subscripting ordered datatypes
print(my_list[0]) # indexing
print(my_tup[0:2]) # slicing
print(my_str[-8:]) # negative index and slice
# Adding elements
my_list.append(5.0)
print("my_l... |
d12dbe75c1786efb7a7f7770d928438e9f8d974b | SedaSedrakyan/ASDS_python | /Homework2_python2/problem6.py | 991 | 3.515625 | 4 | '''
Open the image pic3.jpg and display it with the name pic3.
Find the edges of the image using Canny edge detector and
then try to find its contours with parameters of your choice.
Then convert the original image to grayscale and try to find
the contours on a blurred version of the grayscale of the original image... |
a46375f6ebd301ddc69db4f1946b2abee2816ce9 | RohitV123/cs043 | /lab_projects/telephone.py | 1,256 | 4.1875 | 4 | from database import Simpledb
loop=True
db = Simpledb('telephone.txt')
db.__repr__()
while loop==True:
print('Would you like to:\n1:Delete a phone number?\n2:Update a phone number?\n3:Add another phone number?\n4:Find a phone number?\n5:Quit the program\nEnter a number 1-5')
choice=input()
while choice!='1'... |
79729626a1739b8e7a2a7a35e3bfb60903155ca2 | yasheymateen/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 1,137 | 3.546875 | 4 | #!/usr/bin/python3
""" Unittest for Square Size """
import unittest
import sys
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
from io import StringIO
class TestSquareSize(unittest.TestCase):
""" Test Square Size Method """
def test_size(self):
sel... |
c4bd970e239e9f812e0c64a92ea6bb737a15c0d2 | yuanyixu/nlp_book | /ch12/timeexp/datetime_extra.py | 4,980 | 3.578125 | 4 | #! /usr/bin/env python
# coding:utf-8
'''
Created on 2020年1月9日
@author: Lichengang
'''
from datetime import datetime, date, timedelta
def _week_param(year):
'''
· 计算“星期日历表示法”的关键参数
Returns:
tuple 当年1月1日的序数, 当年第一周开始时间与1月1日相差多少
'''
first_day = date(year, 1, 1)
# 如果1月1日是星期一~星期四,它所... |
21dac5165a637b379fddef3316c89843c9e3cdbc | DinakarBijili/Data-structures-and-Algorithms | /STACK AND QUEUE/1.Stack(LIFO).py | 2,450 | 3.546875 | 4 | """
Stack Data Structure (Introduction and Program)
Difficulty Level : Easy
Last Updated : 10 Mar, 2021
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operatio... |
af8b2d6065953fd8009fd9807c8174ba742e3ea1 | CVinegoni/Course_Python_MIT6001x | /Week02_SimplePrograms/PS02_02.py | 2,048 | 4.15625 | 4 |
# # Version 01
# # define global scope variables
# annualInterestRate = 0.2 # Monthly interest rate
# balance = 3926 # Balance
# numberMonths = 12 # Number of months over which to calculate the
# # balance
# # calculate the monthly interest rate
# mon... |
7045cca39da57e004ce37c1fc87a1add483449a3 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/1-200/000060/deliberate-WA--000060.py | 1,381 | 3.671875 | 4 | class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
prefixMultiple = ["placeholder", 1]
for i in range(2, n):
prefixMultiple.append(prefixMultiple[-1] * i)
def add_reversed_numbers_to_list... |
162a318ad770111581f23b34cd5e28fa0d8590af | Gibbo81/LearningPython | /LearningPython/40Metaclass.py | 7,685 | 4 | 4 | import types
class C: pass
class Eggs:pass
class Spam(Eggs):
data = 1
def meth(self, arg):
return self.data + arg
class Meta(type): #meta are normal class that derives from type
def __new__(meta, classname, supers, classdict): #called at the and of MetaSpam class statement
... |
b5509fc70d557d36aee33948dd35301a645d3e6c | mikel-codes/python_scripts | /internet/gui.py | 536 | 3.625 | 4 | import Tkinter as T
class TG(T):
def __init__(self):
super(self)
pass
def quit(icon):
print "Hello, closing the application"
import sys; sys.exit
def hello():
print "hello world"
top = T.Tk()
widget = T.Label(top, text="Hello world")
button = T.Button(top, text="test", co... |
94dc43b542af6ace400ce2e61701b956584d3290 | shannonh90/seventeen | /seventeen1.py | 2,078 | 4.125 | 4 | #Seventeen Game
#The jar begins with seventeen marbles, and each player can remove one,
#two, or three marbles during each turn.
#human always goes first
#if human enters incorrect input(anthing other 1,2,3) or a number larger than how
#many marbles are left, display error
#prompt them to try again
#computer chooses... |
14523dca81616b7d721946e0eb1a19fe596c43ad | htl1126/leetcode | /1884.py | 356 | 3.671875 | 4 | # Ref: https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1248560/Simple-Math-Problem-with-intuition-explained-O(1)-time-O(1)-space-or-Python
class Solution:
def twoEggDrop(self, n: int) -> int:
a, b, c = 1, 1, -2 * n # solve x^2 + x -2n <= 0
x = (-b + (b * b - 4 * a * c) ** 0... |
ccdadfe763909a42b0f9a5d4b75bd61b8c717b68 | KSAJN2020/KSpython101 | /Python data structures/frozenSet.py | 321 | 3.515625 | 4 | frozen_set1 = frozenset(["e", "f", "g", "a", "b"])
print(len(frozen_set1))
for x in frozen_set1:
print(x)
frozen_set1.clear()
set1 = {'a', 'b', 'c'}
print(len(set1))
for y in set1:
print(y)
set1.clear()
print(frozen_set1.issuperset(set1))
print(set1.issubset(frozen_set1))
# sets are not traversed sequentially... |
a66a195f7c14d0dad50c91868d8b664ab5b337a9 | WildDogOdyssey/bitesofpy | /27/omdb.py | 844 | 3.78125 | 4 | import json
def get_movie_data(files: list) -> list:
"""Parse movie json files into a list of dicts"""
movies = []
for fi in files: # because the original list is bundled into files
with open(fi) as f: # I guess the need to use a 'with' statement is to be able to
jso... |
00d295b95007859671ac0d815d6f0fb64ea9f001 | tesschung/TIL | /startCamp/04_day/dictionary/02_dict_practice.py | 2,948 | 3.703125 | 4 | """
Python dictionary 연습 문제
"""
# 1. 평균을 구하시오.
score = {
'수학': 80,
'국어': 90,
'음악': 100
}
# 아래에 코드를 작성해 주세요.
print('==== Q1 ====')
sum_ = 0
for value in score.values():
sum_ += value
print(sum_/3)
# 2. 반 평균을 구하시오. -> 전체 평균
scores = {
'a': {
'수학': 80,
'국어': 90,
'음악':... |
5b04d6629c2edcc5fa73bd73049a10901574402c | 61a-su15-website/61a-su15-website.github.io | /slides/15.py | 1,327 | 3.953125 | 4 | class Pokemon:
def __init__(self, name):
self.name = name
self.level = 1
self.hp = 5 * self.level
self.damage = 2 * self.level
def talk(self):
print(self.name + '!')
def level_up(self):
self.level += 1
self.hp = 5 * self.level
self.damage = 2... |
e37b4eb523de673b3015c62f1f978b4a13b69a99 | brickgao/leetcode | /src/algorithms/python/Binary_Tree_Right_Side_View.py | 1,136 | 4 | 4 | # -*- coding: utf-8 -*-
from Queue import Queue
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bfs(self, root):
q, ret = Queue(), []
tmp, end = None, root
q.put(r... |
b4dc738c7a73b643a8bda4f78265951787dc3f7b | DrorEf/pythonCourse3.6.5 | /81/tuple.py | 1,323 | 3.765625 | 4 | #for homogeneous use
#immutable
#create
newTuple = 1,2,3,4
print(newTuple)
print(type(newTuple))
print("\n")
#use parentheses
newTuple = (1,2,3,4,5,6)
print(newTuple)
print(type(newTuple))
newEmptyTuple = ()
print(type(newEmptyTuple))
print("\n")
#create with one element
newTuple = (1)
print(newTuple)
print(type(n... |
30bc46ccf9488312d37a0c5060f3fb8b7e91fff7 | 321HG/SyPy | /ListsExample.py | 469 | 3.96875 | 4 | list = [1, 2.2, 3.33, 4.44, 'a', 'bcdefg']
for item in list:
print (item);
if item == 'bcdefg':
alist = list[len(list)-1]
for subitem in alist:
print("Printing subitem ", subitem)
print("++++++++++++++++++++++++Sceanrio 2222++++++++++++++++++++++++++")
#Scenario 2
list2 = [1, ... |
ea3d659f4de34975c21d2d0238aa3996ae11a377 | Lohith-Aswathappa/LeetCode | /two-sum/two-sum.py | 516 | 3.5625 | 4 | class Solution:
def twoSum(self, nums, target):
#create an empty hashmap
hashmap = {}
for k,v in enumerate(nums): #run through the entire array
b = target - nums[k] #check for the difference between target and every element in k
if b in hashmap:#for every value in has... |
ddd5c38c77685f9a6a0f78312bca794af1ad1b32 | Wlubster/Marek-Krzymowski- | /Zad1Lab5.py | 112 | 3.515625 | 4 | count=0
x = input()
for i in x:
if(i.isspace()):
count=count+1
print("Liczba spacji wynosi:",count)
|
18cc3673fd5e8d312c29a8e9d0cc376debbac417 | JiJibrto/examen | /exam.py | 1,851 | 3.625 | 4 | # !/usr/bin/evn python3
# -*- config: utf-8 -*-
# Составить программу для решения задачи: В списке, состоящем из целых элементов, вычислить:1) номер
# максимального элемента списка; 2) произведение элементов списка, расположенных между первым и вторым
# нулевыми элементами. Преобразовать список таким образом, чтобы в ... |
23c88765ca10dd9da305f06f518ec5251380b800 | abdulrahimiliasu/password-manager-python | /main.py | 3,558 | 3.53125 | 4 | from tkinter import *
from tkinter import messagebox
from password import Password
import pyperclip
import json
# ---------------------------- PASSWORD GENERATOR -------------------------------
def find_password():
website = ent_website.get()
if len(website) == 0:
messagebox.showerror(title="Error", ... |
51940808d3ef2fcc44d46f20cc4dfb032202d566 | sureshsarda/ds-and-a | /hackerrank/contests/project_euler/001_multiples_of_3_and_5.py | 440 | 3.859375 | 4 | #!/bin/python
import sys
# Solution inspired from: https://math.stackexchange.com/questions/9259/find-the-sum-of-all-the-multiples-of-3-or-5-below-1000
def sum_of_divisors(n, base):
numbers = (n - 1) / base
s = (numbers * (numbers + 1)) / 2
return s * base
t = int(raw_input().strip())
for a0 in xrange... |
4f759ab13497df1122f47bfa4177cf1107126ae9 | nsjethani/Python | /cycleDetection.py | 1,176 | 3.96875 | 4 | class Node:
def __init__(self,data=0,nextNode=None):
self.data = data
self.nextNode = nextNode
class linkedList:
def __init__(self,head=None):
self.head = head
self.size = 0
def hasCycle(head):
def getlen(end,step=0):
start = end
while True:
step... |
6fd6852b1aa0c2c8b4b5b54db858f42411b05bc6 | kbokka/ECE-364 | /ECE-364/Prelab08/.svn/text-base/lists.py.svn-base | 613 | 3.953125 | 4 | #! /usr/bin/env python2.6
#
#$Author$
#$Date$
#$HeadURL$
#$Revision$
import sys
sys.argv
listone=raw_input('Enter the first list of numbers: ')
listone=[int(i) for i in listone.split(' ')]
listtwo=raw_input('Enter the second list of numbers: ')
listtwo=[int(i) for i in listtwo.split(' ')]
print "First list: ",liston... |
ce335b1e12de8d6dad0e2ef961f24cb04651279f | sunnyyeti/Leetcode-solutions | /1309 Decrypt String from Alphabet to Integer Mapping.py | 1,647 | 3.703125 | 4 | # Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
# Characters ('a' to 'i') are represented by ('1' to '9') respectively.
# Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
# Return the string formed after mapping.
# It's g... |
31155a08cc17c2350d0a2e81b8ee30ab8e4b89b3 | Ananthu/think-python-solutions | /fibo.py | 125 | 3.5625 | 4 | def fibo (n) :
if n==0 :
return 0
if n==1 :
return 1
else :
return fibo(n-1)+fibo(n-2)
x=fibo(2)
print x
|
3eb941195f16765cf1709bdd6899817bd98519ac | YuYangHuangJCU/1404 | /APPupdated2/test_song.py | 578 | 3.65625 | 4 | """(Incomplete) Tests for Song class."""
from song import Song
def run_tests():
"""test empty song (defaults)"""
song = Song()
print(song)
assert song.artist == ""
assert song.title == ""
assert song.year == 0
# test initial-value song
song2 = Song("My Happiness", "Powderfinger", 1996, True)
... |
227cc43ac494b95098ec44105c74980dd136b793 | zingesCodingDojo/PythonAlgorithms | /_PythonAlgorithms/_DLL.py | 3,597 | 3.59375 | 4 | from _Nodes import OtherDLLNode as node
from _Nodes import DLLNode
"""
This is the Doubly Linked List Class.
We will be able to add, remove, edit, traverse both forwards and backwards, and check for circular movements.
"""
class DLL:
def __init__(self):
self.head = node()
def append(self, data):
... |
641ada4eb3e86990f7629a9a81cc16b94d2d926b | henrylei2000/cs | /21/labs/snow.py | 707 | 3.96875 | 4 | """
This is the condition practice program
Henry Lei
Spring 2020
"""
def snow_depth():
initial_depth = float(input("Enter today's snow depth in inches: "))
track_days = int(input("Enter number of days to track: "))
for day in range(track_days):
print("Day " + str(day + 1) + ":")
meltin... |
2114e3774a9e91d890e1c41180697d2b4e1e162c | michalo21/JezykSkryptowy | /LAB2/poker.py | 718 | 3.5625 | 4 | import itertools
import random
def deck():
color = ['pik', 'kier', 'karo', 'trefl']
value = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jupek', 'Królowa', 'Król', 'As']
deck = list(itertools.product(value, color))
return deck
def shuffle_deck(decko):
random.shuffle(decko)
... |
3ac42055b842f8721ef198bd678cf53239e3e737 | marftabucks/algorithms | /Single Linked List.py | 5,240 | 4.3125 | 4 | """
Single Linked List
Operations:
1. Insert - add a node at the beginning of linked list
2. Delete - delete a node at the beginning of linked list
3. Delete data - delete node that contains the data from the linked list
4. Search - search a node using the given data
5. Update - update a node that contains th... |
49cc6b549df6e20c8d3b201a882d1d68d5d29fd0 | naganikshith04/CRD | /code.py | 2,047 | 3.53125 | 4 | import threading
from threading import*
import time
dictionary={}
def create(key,value,timeout=0):
if key in dictionary:
print("Key already exists in database")
else:
if(key.isalpha()):
if len(dictionary)<(1024*1020*1024) and value<=(16*1024*1024):
i... |
179bcc03ad381fd6ea32feb047f533c4f5f623c8 | josevini/python | /Introdução à Programação/capitulo5/ex_5-8.py | 212 | 3.953125 | 4 | # Exercício 5.8 - Livro
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
cont = 1
res = 0
while cont <= num2:
res += num1
cont += 1
print(f'{num1} x {num2} = {res}')
|
6d7eb004ad04fbb863895aaeeee42ab6c69606df | Aasthaengg/IBMdataset | /Python_codes/p02995/s289916775.py | 283 | 3.625 | 4 | from math import gcd
def lcm(a, b):
return a * b // gcd(a, b)
a, b, c, d = map(int, input().split())
e = lcm(c, d)
num_e = b // e - (a - 1) // e
num_c = b // c - (a - 1) // c
num_d = b // d - (a - 1) // d
num_can_div = num_c + num_d - num_e
print((b - a) - num_can_div + 1)
|
d2d2f6bb7345d143f041a45a9b0d93367bc92f55 | Paul-Cl-ark/sorting-algorithms | /merge_sort.py | 731 | 3.84375 | 4 | import math
def merge(arr_1, arr_2):
merged_arr = []
i = 0
j = 0
while len(merged_arr) < len(arr_1) + len(arr_2):
if i == len(arr_1):
merged_arr.extend(arr_2[j:])
elif j == len(arr_2):
merged_arr.extend(arr_1[i:])
else:
if arr_1[i] < arr_2[j]:
merged_arr.append(arr_... |
b0098fac69b5dee088b8d9418d1908e2fe47c7e9 | ssandyy/pythonpro | /Lambda2.py | 176 | 3.8125 | 4 |
a,b=int(input("enter the value of a= ")),int(input("enter the value of b= "))
p=lambda a,b:pow((a+b),2) # or pow(a,2)+pow(b,2)+2*a*b
p(a,b)
print(p(a,b)) |
829e8e7438a8b967f96b2d1848ec3a0bb9616731 | petropurdue/ece404hw6 | /playground.py | 89 | 3.828125 | 4 | eight = [1,2,3,5,6,7,8]
print(len(eight))
for i in range(8-len(eight)%8):
print("A")
|
2fc4032959037c13a5275c0518c9cc76d7b3b686 | dineshchandvarre/pythonpractice | /selection.py | 220 | 3.828125 | 4 | def selection_sort(arr):
for i in range(len(arr)):
new=arr.index(min(arr[i:len(arr)]))
swap(arr,new,i)
print(arr)
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
selection_sort([i for i in range(100)]) |
c63a92b8b99ff1447c5f88d76e389cf35df61371 | b1ck0/python_coding_problems | /Sequences/027_sum_of_pairs_in_list.py | 480 | 4.125 | 4 | def sum_of_pairs_in_list(array, number):
# find all pairs in the list which sum up to 'number'
seek = {}
pairs = []
for i in range(len(array)):
value = array[i]
if value in seek:
pairs.append((value, number - value))
else:
seek[number - value] = 1
r... |
7236de800aa1b999ee57f0be499f00a3a420b600 | c-phillips/pathnet | /nn_trainer.py | 4,457 | 3.578125 | 4 | """Net Trainer
This module holds the class to train a neural network
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import sys
from neural_net import NeuralNetwork
class Net... |
52d57cb39d656a721ce4012064633ff3a5cfcda7 | pedrostaub23/2019_Algoritmos | /aula004.py | 4,977 | 4.1875 | 4 | """
v and v = v
v and f = f
f and v = f
f and f = f
v or v = v
v or f = v
f or v = v
f or f = f
not (v = f) e (f = v)
"""
"""
Construa um programa que recebe três valores, A, B e C. Em seguida, apresente
na tela somente o maior deles.
"""
# a = int(input("Digite o valor de A: "))
# b = int(input("Di... |
0844a074d2bf8c4497be2905780c6b85f2ec174a | Markiewi/AlgGeo | /labs/Overlay/Point.py | 306 | 3.578125 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return '(%s, %s)' % (self.x, self.y)
@staticmethod
def to_points(points):
p = []
for point in points:
p.append(Point(point[0], point[1]))
return p
|
2b4d0f3f337a08e3a483226a252a48d21a0bd775 | kienga445/c4tA | /text.py | 953 | 3.625 | 4 | # list = ' * '
# for i in range(5):
# for j in range(5):
# print((list),end = "")
# print()
playerX = 3
playerY =3
def printMap(side):
for i in range(side):
for j in range(side):
if i == playerY and j == playerX:
print(" P ", end="")
else:
... |
e04da234352106b63841758db8525eb809fb1ead | Anecdotal/Sorting | /quick.py | 419 | 3.8125 | 4 | import util
def quick_sort(array):
if len(array) <= 1:
return array
else:
pivot = array[len(array) - 1]
wall = 0
for i in range(len(array) - 1):
if array[i] < pivot:
array = util.swap(array, i, wall)
wall += 1
array = util.swap(array, len(array)-1, wall)
subarray = quick_sort(array[:wall])
s... |
e3c55f6b1d2e0a7f963b820cbace5f297b4c6396 | ShakoorTaj/hackerrank_python | /day20_sorting.py | 437 | 3.625 | 4 | #!/bin/python3
import sys
n = 3 # int(input().strip())
a = [3,1,2]#list(map(int, input().strip().split(' ')))
# Write Your Code Here
numberOfSwaps = 0
for j in range(n):
for i in range(n-1):
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
numberOfSwaps +=1
print('Array is sorted in ... |
e0d34f7f7e0016602d50ffd07b90f99d2241b6df | longzekai/Python | /src/test/day03/dataType.py | 6,575 | 4.4375 | 4 | # 多个变量赋值
# Python允许你同时为多个变量赋值。例如:
a = b = c = 1
print(a, b, c)
# 您也可以为多个对象指定多个变量。例如:
a, b, c = 1, 2, "Danny"
print(a, b, c)
# Number
# Python3 支持 int、float、bool、complex(复数)。
# 在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
# 像大多数语言一样,数值类型的赋值和计算都是很直观的。
# 内置的 type() 函数可以用来查询变量所指的对象类型。
# Python还支持复数,复数由实数部分和虚数部分构成,可... |
01cbb4206946ec9baf248b7027011e62f487d5d2 | Grantrd/P0_Final_Project_Grantr | /hero_class.py | 2,864 | 3.78125 | 4 | ######################################################################
# Author: Rodney Grant
# Username: GrantR
#
# Assignment: P0_Final
#
# Purpose: To demonstrate my knowledge of programming and make a fun Mario Clone
# ###############################################################################
import sys
from s... |
0fe1f2086cb5870e15cc9e15a00428435d1b3bce | thuurzz/Python | /curso_em_video/mundo_01/desafios/tratando_de_dados_e_fazendo_contas/ex004.py | 396 | 3.875 | 4 | algo = input('Digite algo:')
print('o tipo primitivo desse valor é:', type(algo))
print('só tem espaços?', algo.isspace())
print('é um número?', algo.isalnum())
print('é alfabético?', algo.isalpha())
print('é alfanumérico?', algo.isalnum())
print('esta em minúscula?', algo.isupper())
print('esta em minúsculo?', algo.i... |
61a0647669761f04e638a44c8bdcfa315aa6c60e | akshaali/Competitive-Programming- | /Hackerrank/DayOfTheProgrammer.py | 3,484 | 4.8125 | 5 | """
Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the day of the year) during a year in the inclusive range from to .
From to , Russia's official calendar was the Julian calendar; since they used the Gregorian calendar system. The transition from... |
5df6c4d00746c094f5f13544a9f494582bafe22a | laseka/Arena-of-Heroes | /files/game.py | 1,168 | 3.671875 | 4 | from random import randint
import datetime
import pytz
from potions import HealthPotion, SpeedPotion, AttackPotion
import random
def create_potions():
potions = {
"HEALTH": HealthPotion,
"SPEED": SpeedPotion,
"ATTACK": AttackPotion
}
return [potion() for potion in random.choices(li... |
39bd7b3007e6bd808261eb766307fb62683d8c41 | Braitiner/Exercicios-wiki.python | /estrutura_de_repeticao_exercicio37.py | 1,817 | 4.15625 | 4 | # Uma academia deseja fazer um senso entre seus clientes para descobrir o mais alto, o mais baixo, a mais gordo e o mais
# magro, para isto você deve fazer um programa que pergunte a cada um dos clientes da academia seu código, sua altura e
# seu peso. O final da digitação de dados deve ser dada quando o usuário digi... |
0c905628a43b2be8371e986397dd0524ccb4cee0 | 0lk1/python | /toss_coins.py | 804 | 4.03125 | 4 | """The program tosses two coins and when they are the same type, will quit.
"""
import random
TOSS_TYPES = ['Heads', 'Tails']
def TossCoins():
"""Uses random to emulate the toss of the coins.
"""
coin1 = random.choice(TOSS_TYPES)
coin2 = random.choice(TOSS_TYPES)
return CheckIfSame(coin1, coin2)... |
c6b21a62648daecdfe9852cb9f19dfd0f4220cd7 | junghyun4425/myleetcode | /easy/Number_Of_Segments_In_A_String.py | 935 | 3.5625 | 4 | # Problem Link: https://leetcode.com/problems/number-of-segments-in-a-string/
'''
문제 요약: 스페이스로 나뉜 단어들이 몇개인지 세는 문제. (단어간 분리는 스페이스로만 이뤄짐)
ask: s = "Hello, my name is John"
answer: 5
해석:
내장함수를 사용하면 한줄에 끝나기 떄문에, 직접 해보기로 함.
일단 주어진 문제가 굉장히 간단함.
어떤 단어가 나올때 이전값이 공백이라면 단어 하나를 추가해주는 방법으로 하면 굉장히 깔끔하게 해결이 가능.
여러가지 방법이 존재하고 몇가지 방... |
b1c23c095bde0fd04f77c7e5a1f1217d584b6b5a | mstf-svndk/Sayi-tahmin-oyunu | /sayı tahmin oyunu.py | 916 | 3.703125 | 4 | import random
import time
print("""
********************************************************************
1 ile 100 arasındaki gizli sayıyı tahmin etme oyunu
********************************************************************""")
rasgele_sayı=random.randint(1,100)
tahmin_hakkı=5
kullanıcı=input("İsminizi Girin:... |
01d552d20954fa1965ee64a4e8f92eac1fc4a43c | sh92/Algorithms-Study | /python/word_split.py | 417 | 3.546875 | 4 |
def word_split(phrase,list_of_words, output= None):
if output is None:
output = []
for word in list_of_words:
if phrase.startswith(word):
output.append(word)
return word_split(phrase[len(word):],list_of_words,output)
return output
print word_split('themanran',['... |
92d717ef4612719a15611b40027a9e1e76a00485 | thirumald/Data-Structure-and-Algorithms | /ds/circularQueue.py | 2,985 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## Baiqiang XIA implementation of data structures
## circular queue (ring buffer)
## key point: from front to rear (inclusive) the number of elements should not exceed a constant (qsize)
## references:
## https://www.pythoncentral.io/circular-queue/
## https://www.geeksfo... |
137c094a217d90d71004a9027165ba572535648d | abaldeg/EjerciciosPython | /tp 5 ej 6.py | 554 | 3.71875 | 4 | #Devolver True si el número entero recibido como primer parámetro es múltiplo
#del segundo, o False en caso contrario.
#Ejemplo: esmultiplo(40,8) devuelve True
#y es multiplo(50,3) devuelve False.
def fVerificarMultiplo(a,b):
if a % b == 0:
Multiplo = True
else:
Multiplo = Fa... |
1b9e356252d40c2f92e19e4b1236501d19e1fa23 | ynikulyak/tictactoe | /tictactoe.py | 6,915 | 4.625 | 5 | # -----------------------------------------------------------------------------
# Name: tictac
# Purpose: Implement a game of Tic Tac Toe
#
#
# Date: 11/30/2018
# -----------------------------------------------------------------------------
'''
Tic-tac-toe game for two players: user and computer.
The pla... |
25c182f1bcfa730282f1be06fd185438ddce18e0 | vineeta786/geeksForGeeks_python | /DP/sum_even_fib.py | 624 | 3.71875 | 4 | def fibdp(n):
if n == 1:
t=[0,1]
return t
elif n == 2:
t = [0,1,1]
return t
else:
t = [0 for i in range(n+1)]
t[1]=1
t[2]=1
for i in range(3,n+1):
t[i]=t[i-1]+t[i-2]
if t[i]>n:
return t
return t
d... |
cd2087f2153121fa7afdbed785efb29907891912 | vthorat1986/python-programs | /list.py | 739 | 3.921875 | 4 | #!/usr/bin/python
list1 = [ 'vaibhav' , 1 , 5.567 , 'thorat' , 'A' ]
list2 = [ 'wait' , 0.21 ]
print (list1)
print (list1[4])
print (list1[1:4])
print (list1[1:])
print (list2 * 3)
print (list1 + list2)
#modify list values
print ('Before modification : ', list1)
list1[2] = 'vijay'
print ('After modifi... |
2f90ca6d254b880556d898090dcd1243196dea7c | Eduardo-Quirino/python | /aula12/loop_for12.py | 215 | 3.9375 | 4 | #Loop FOR
carros = ["HRV", "Golf", "Argo", "Focus"]
for x in carros:# <FOR> percorre a lista e o <IN> informa qual lista percorrer
print(x)
if(x == "Golf"):
print("VW")
input()#aguarda teclar ENTER |
156c93d0dceb149458044c11b1e769834465233f | manan76/Smallest_Substring | /Smallest_Substring.py | 352 | 3.5 | 4 |
def SmallestSub(str):
result = [str[i: j] for i in range(len(str))
for j in range(i + 1, len(str) + 1)]
max=0
for i in range(len(result)):
se=len(set(result[i]))
le=len(result[i])
if(se==le):
if(max<se):
max=se
return max
st... |
00d44e30cfbae3ee3b0029437b58bfd73fa2ba82 | erenyceylan/python-exercises | /prime_factor.py | 600 | 3.90625 | 4 | def raw_to_power(somelist):
powers = []
sentence = ""
j = 0
for i in sorted(set(somelist)):
powers.append(somelist.count(i))
while j < len(powers):
sentence += "%d^%d "%(sorted(list(set(somelist)))[j],powers[j])
j += 1
return sentence
def prime_factor(num):
some = []
i = 2
while i in range(2,num+1):
... |
93cd1cfdf0185d5d287eac46bddfe83ed9fa90f8 | Nagendracse1/Competitive-Programming | /graph/Nagendra/dfs.py | 1,385 | 3.8125 | 4 | #User function Template for python3
'''
g : adjacency list of graph
N : number of vertices
return a list containing the DFS traversal of the given graph
'''
from collections import defaultdict
import sys
import io
import atexit
def vis(g, v, visited, res):
visited[v] = 1
res.append(v)
#print(res)
... |
e481697878302d44f1629305827a94850926c702 | Confucius-hui/LeetCode | /字节跳动/数组与排序/接雨水.py | 1,022 | 3.734375 | 4 | class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
#找到最大的扳子
n = len(height)
if n<1:
return 0
max_index = 0
max_value = 0
result = 0
for i in range(n):
if height[i]... |
ff8c1f8e840a9b8986df8281c353ac5a9f7d5944 | DavisDataScience/DataInterviewPrep | /DataStructures/Chapter6_Multithreading/profiling_runtime.py | 977 | 3.75 | 4 | # finding performance bottlenecks and optimizing code
# prefer tuples to lists with read-only data
# use generators rather than large lists or tuples to iteration
# Ex:
# instead of:
mylist = [x for x in range(14)]
# use a generator, replacing [] with ()
mygenerator = list(x for x in range(14))
import timei... |
261b4815e7ff4d0cabd9e79d9e4e7b1b96313d3e | anthonybotello/Coding_Dojo | /Python/python/fundamentals/bankaccount.py | 1,046 | 3.8125 | 4 | class BankAccount:
def __init__(self,int_rate=0.01,balance=0):
self.interest_rate = int_rate
self.balance = balance
def deposit(self,amount):
self.balance += amount
return self
def withdraw(self,amount):
if self.balance - amount < 0:
print... |
339f982cf4711a246b30c01bec5c1a4892be5f0b | MAPLE-Robot-Subgoaling/IPT | /data/HW4/hw4_262.py | 576 | 4.28125 | 4 | def main():
startingHeight = abs(int(input("What is the current height of the hailstone?")))
currentHeight = startingHeight
print("Hailstone is currently at height", currentHeight)
while currentHeight != 1:
if currentHeight % 2 == 0:
currentHeight = currentHeight / 2
prin... |
797f4f52a0734929b2f730e2c1a726034421f8b0 | RedMike/pYendor | /lib/map.py | 11,747 | 3.625 | 4 |
import random
import ConfigParser
import os
# Generator creates a map, then gen_map returns it.
#
# Map contains a basic 2D array of tuples of the form (blocks, blocks_light), for easy referencing.
#
# Tile is (blocks, blocks_light).
#
# Globals _WALL and _FLOOR to ease modification.
_WALL = (1,1)
_F... |
4656a7b6093c8f4e950855435013b099c8c93544 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2620/60761/233719.py | 135 | 3.5625 | 4 | t=int(input(""))
while(t>0):
n=int(input(""))
sum=0
while(n>0):
sum=sum+n**5
n=n-1
print(sum)
t=t-1 |
3f0b451bfff89c38a396136ddcc14165de09f355 | noveroa/DataBaseAWS | /f_RESTful.py | 11,854 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Scripts to insert/delete json file into database'''
import sys,os
import sqlite3 as sql
import pandas as pd
import f_deletionbyPaperID as delP
import f_SqlScripts as sqlCMDS
DEFAULTDB = '/var/www/html/flaskapp/Abstracts_aug14.db'
DEFAULTJSONDIRECTORY = '/var/www/html/flaska... |
499a963b1740d34d46dfc7069fba483bef565de9 | Arda-Bati/Card-Game | /starter_code/Suits.py | 2,667 | 3.5625 | 4 | from Base_Card import *
class Warrior_Card(Card):
""" This class represents all cards belonging to Warriors of Marina.
Inherits from the Card class """
# Class Attributes
suit = "WM"
chant = "Marina before all!"
traitor_offset = 5
suit_comp = [warrior_ordinary, warrior_specials, warrior_le... |
f6a9fbf8e4e33264d5b3cbd74a8c18ca1086317e | halltristanj/hackerrank-solutions | /practice/algorithms/implementation/apple_and_orange.py | 748 | 4.1875 | 4 | from itertools import zip_longest
# Complete the countApplesAndOranges function below.
def count_apples_and_oranges(s, t, a, b, apples, oranges):
"""
s: Starting of house
t: Ending of house
a: Where apple tree is located
b: Where Orange tree is located
apples: n apples
oranges: n oranges
... |
7fa273923e478ef9f7150482c2dbbb0d46cd6e1e | caoyuan0816/BiDirectionalSearch | /cube/cube.py | 8,142 | 4.15625 | 4 | """
ASU CSE571 Artificial Intelligence Team Project.
--------------------------------------------------------------------------------
Cube.py
--------------------------------------------------------------------------------
Implementation of class Cube, which used to describe a cube in the real world.
"""
class Cube:
... |
d137088a5a014bfa4d97f12e2f80bde2f4fc9f79 | EricaSwift/PythonLab | /Circle.py | 533 | 4.125 | 4 |
pi = 3.141
import circle
def area(radius):
"""This method computes the area of a circle. Input radius parameter."""
return pi*(radius**2)
def circumference(radius):
"""This method computes the circumference. Input radiud parameter."""
return 2*pi*radius
def sphereSurface(radius):
"""This metho... |
c5afb3bb27c4d480e6055e348ea7d8ce2a692079 | karishmasn/Python_Programming | /file4.py | 196 | 4.0625 | 4 | rate=float(input("Enter the current dollar rate:"))
dollar=int(input("Enter the number of dollars to be converted to rupee:"))
INR=dollar*rate
print("The INR for ",dollar)
print("dollar is ",INR)
|
97ddd1e9635e4dbe505d6e62142ddfaf9717ed0a | natB45/coursNSI | /Cours1NSI/Python/Cours/3Tests/code/correction/foncAlpha2.py | 353 | 3.5625 | 4 | def alpha(n):
""" Cette fonction renvoie la nieme lettre de l'alphabet,
n etant un entier compris entre 1 et 26"""
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if (n < 1) or (n > 26):
return ""
else:
return a[n-1]
# Debut des tests
assert(alpha(1) == "A")
assert(alpha(9) == "I")
assert(alpha(26... |
d0a84fcd9bce120e71c9d994b3c05e2390c0e452 | nisarggurjar/PythonRevisionSession | /Dictionary.py | 196 | 3.640625 | 4 | dic = {"Name":"Nisarg", "Languages":["Python", "Cpp", "React"]}
print(dic['Name'])
print(dic.keys())
print(dic.values())
dic["Name"] = "Nisarg Gurjar"
print(dic)
print(dic.pop("Name"))
print(dic) |
22c9c97e39387408dc572eeb096b93739d4d6f3a | sumsilverdragon/juice-bot | /project.py | 3,691 | 4.1875 | 4 | """This is a basic chat-bot that interacts with the user to help order a juice.
It can be used for any similar product or service. Customer can order multiple juices.
In the next stage of development it could help a customer with their decision,
based on emotion - a personal shopper"""
import random
from simpleimage i... |
ea981564202c555adb83d941a70953fe5052283b | amanmishra98/python-programs | /assign/6-string/remove duplicate element in string.py | 246 | 3.890625 | 4 | #remove duplicate element in string
s=input("enter a string\n")
print(s)
a=set(s)
print(a)
print(type(a))
s=str(a)
print(s)
print(type(s))
print(len(s))
'''count=0
for x in s:
count+=1
print(x)
print(count)
input()'''
|
ee16b553d4c75ff2fe11c6aa92216dc79f5ea541 | mittal-umang/Analytics | /Assignment-1/Gratuity.py | 766 | 3.921875 | 4 | # Chapter 2 Question 5
# (Financial application: calculate tips) Write a program that reads the subtotal and
# the gratuity rate and computes the gratuity and total. For example, if the user
# enters 10 for the subtotal and 15% for the gratuity rate, the program displays 1.5
# as the gratuity and 11.5 as the total.
d... |
5c4576f2dff9c1b7b8ffe5935e44d08a518dfd58 | marcelo-r/leetcode | /easy/kids-with-the-greatest-number-of-candies/solution.py | 373 | 3.9375 | 4 | from typing import List
"""
"candies": [2, 3, 5, 1, 3],
"extraCandies": 3,
"want": [True, True, True, False, True],
"""
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
maior = max(candies)
result = []
for i in candies:
result.app... |
b4728af101c51a539757448f455825649197b4dc | chandresh189/REGex-ONLINE-Training-2020 | /Rakhi Pareek/Python-Task 6/question5.py | 355 | 3.984375 | 4 | # Question - 5
"""
5. Write a Python program to generate 26 text files named A.txt, B.txt, and
so on up to Z.txt.
"""
# for list of capital alphabets
alpha = []
for i in range (0,26):
alpha.append(chr(ord('A') + i))
# for creation of files
for word in alpha:
f= open(word + '.txt', 'w')
f... |
efc2e3dad1266b4612f3056994fb35614bbfbc18 | brn016/cogs18 | /18 Projects/Project_malkuzwe_attempt_2018-12-11-20-35-45_Cogs_18_Project/Cogs_18_Project/my_module/functions.py | 2,229 | 4.6875 | 5 |
def remove_last_chara(df, column_name):
"""Removes the last character of each element in a column in a dataframe.
Parameters
----------
df : Pandas dataframe
Dataframe that contains the column we will be indexing through
column_name : string
The name of the column we will... |
a16760093890a233d22f3fef4992a6b030f9d6c4 | AlbertAC/gen_TSP | /genetic.py | 9,684 | 4 | 4 | import random
import math
'''
Laboratorio de Algoritmos genéticos:
Este archivo contiene las funciones que debe implementar para
la práctica de laboratorio.
Ejercicio 1: operador de selección. Implementar la función selectRanking()
Ejercicio 2: operador de crossover. Implementar la función orderOneCrossover()
Ejerc... |
68bf82513614dfd978a7d715dd136630abd4706e | Krish3na/Edyst-TCS-Codevita-Solutions | /Math/Games/drunkard.py | 4,768 | 3.90625 | 4 | '''
Drunkard’s Walk
In state of inebriation, a drunkard sets out to walk home, afoot. As is common knowledge, a drunkard struggles to find balance and ends up taking random steps. Not surprisingly these are steps in both forward as well as backward direction. Funnily enough, these are also repeated movements. Now, it... |
2fa939cd37006202a013763eb0d25626396d6e4a | qq279585876/algorithm | /ib/3.TwoPointer/Kth Smallest Element In The Array.py | 2,130 | 3.828125 | 4 | '''
Find the kth smallest element in an unsorted array of non-negative integers.
Definition of kth smallest element
kth smallest element is the minimum possible n such that there are atleast k
elements in the array <= n.
In other words, if the array A was sorted, then A[k - 1] ( k is 1 based, while
the arrays are 0... |
e345ba96e414f3c3038a7e35e54ba4eb99e56855 | jamesthefourth/KnowSeattleEd | /exportXMLtoFile.py | 487 | 3.59375 | 4 |
import urllib.request
from requests import get # to make GET request
#url = "http://api.greatschools.org/schools/nearby?key=rouznrbdxyk3bnblrcaxqaxx&state=WA&q=seattle&limit=5"
url = ("http://api.greatschools.org/search/schools?key=rouznrbdxyk3bnblrcaxqaxx&state=WA&q=Seattle&limit=10")
def download(url, file_name):
... |
dde0cc55ca8600293e9a53243a7eecf3004c44e7 | ulookme/neuronal_deep | /loss.py | 319 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 11:56:45 2020
@author: charleshajjar
"""
import numpy as np
# loss function and its derivative
def mse(y_true, y_pred):
return np.mean(np.power(y_true-y_pred, 2));
def mse_prime(y_true, y_pred):
return 2*(y_pred-y_true)/y_true.size;
|
78778ac82215a17f49490761fafc7ed2f194bf74 | Nadeem-Abdelkader/Student-Tutor-Matching-Old | /System/select_action.py | 2,799 | 3.6875 | 4 | from tkinter import *
from bid_on_student_request import BidOnStudent
from new_tutor_request import NewTutorRequest
from see_contracts import SeeContracts
from user_collection import UserCollection
class SelectAction:
"""
This method is respnsible for displaying the Select Action screen that greets the user ... |
c30486105bcfb566def8edd49202da8f1ba793ba | ZivMahluf/Spectral-Clustering | /Clustering.py | 18,819 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pickle
def circles_example():
"""
an example function for generating and plotting synthetic data.
"""
t = np.arange(0, 2 * np.pi, 0.03)
length = np.shape(t)
length = length[0]
circle1 = np.matrix([np.cos(t) + 0.1 * np.random.randn(... |
c475a204be3213789e30c74b8379b53a58567954 | ionu87/LearningAutomation | /findingelements/FindByIdName.py | 829 | 3.5 | 4 | from selenium import webdriver
class FindByIdName():
def test(self):
baseURL = "https://letskodeit.teachable.com/p/practice"
driver = webdriver.Chrome()
driver.get(baseURL)
elementById = driver.find_element_by_id('name')
if elementById is not None:
print('Element... |
8f0d2921f10b06e8b46f5f8ef435bdb97ec9f295 | joelrorseth/Snippets | /Python Snippets/Algorithms/Pattern Searching/kmp.py | 1,451 | 3.765625 | 4 | #
# KMP String Matching (Knuth-Morris-Pratt)
# O(m + n)
#
# Given a string 'text', determine the starting index of every occurrence
# of a string 'pattern' within 'text'. KMP is a pattern searching algorithm
# that improves upon the linear string pattern search, by avoiding repeated
# character comparisons in the subse... |
2340b02909dfef1e65161f9fdfb57c081f045220 | mingggkeee/algorithm_study | /카카오/2020 카카오/괄호 변환.py | 1,073 | 3.671875 | 4 | def pair(p):
count = 0
# "(" 와 ")"의 짝수가 맞는지 검정
for i in range(len(p)):
if p[i] == "(":
count += 1
else:
if count == 0:
return False
count -= 1
return True
def balance(p):
count = 0
# u와 v로 나누어야 될 구간 리턴
for i in range(len... |
435430c68ad332d789ea038301ebc937494d89f4 | SergKolo/pyutils | /repeat_text.py | 787 | 3.578125 | 4 | #!/usr/bin/env python3
# given a file, repeat the contents of the file
# n amount of times. Originally written for
# http://askubuntu.com/q/521465/295286
from __future__ import print_function
import sys,os
def error_out(string):
sys.stderr.write(string+"\n")
sys.exit(1)
def read_bytewise(fp):
data = fp.re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.