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 |
|---|---|---|---|---|---|---|
4c1c5fcdaba44bb8fa6a7eedd87743b7cba671cd | Arthur-AZ-Zhou/arthur_test | /python/PythonForKids/p161 Filled Oct Challenge.py | 257 | 3.875 | 4 | import turtle
t = turtle.Pen()
def octagon(size, filled):
if filled == True:
t.begin_fill()
for x in range(1,9):
t.forward(size)
t.right(45)
if filled == True:
t.end_fill()
t.color(.5, .76, .68)
octagon(40, True)
|
70f3bbb5586510f972d327672d92d6ef5533d89d | J-Mat/CS61A-Su19-1 | /typing_test/typing_test.py | 3,489 | 3.703125 | 4 | """ Typing Test implementation """
from utils import *
from ucb import main
import datetime
# BEGIN Q1-5
"*** YOUR CODE HERE ***"
def lines_from_file(path):
file=open(path)
lst=readlines(file)
for i in range(len(lst)):
lst[i]=strip(lst[i])
close(file)
return lst
def new_sample(path,i):
... |
1ffb293e9c243fa9a17777a9fc147972404f43f7 | vampireshj2013/corepython | /date.py | 1,351 | 3.5 | 4 | import datetime
import time
print datetime.date.today()
print datetime.date.fromtimestamp(time.time())
date = datetime.date(2017, 5, 9)
print date.weekday()
print date.isoweekday()
print date.isocalendar()
print date.isoformat()
print time.time()
date7 = date.replace(day=7)
timedelt = (date - date7)
print timedelt.d... |
0e0d3a7ae8736c1ed52fe5ce8080e96b0aa6b711 | vampireshj2013/corepython | /Six.py | 756 | 3.84375 | 4 | # -*- coding:utf-8 -*-
import string
import keyword
alphas = string.letters + '_'
nums = string.digits
print alphas
print 'welcom to the identifier checker v1.0'
print 'Testees must be at least 2 chars long.'
myinput = raw_input('Identifier to test? ')
valid = True
if keyword.iskeyword(myinput):
pass
else:
if... |
3dcc53f3a649fbd69e9cc87c4f5f01d9b659dc4e | vampireshj2013/corepython | /P8-8.py | 203 | 3.859375 | 4 | # -*- coding:utf-8 -*-
import math
def factors(N):
"""
:param num:
:return: N!
"""
if N == 1:
return N
else:
return N * factors(N - 1)
print factors(20)
|
09d3587ccae1d123ca007aaac141da48e77eef11 | vampireshj2013/corepython | /chapternine/test.py | 362 | 3.546875 | 4 | # -*- coding:utf-8 -8-
import os
f = open("t.txt", "r+")
print f.read()
f.seek(0)
print f.readline()
f.seek(0)
for line in f.readlines():
print line,
f.seek(0)
print "---"
for line in f:
print line
print "text():", f.tell()
f.seek(0)
print f.next()
f.seek(0)
print f.truncate(11)
f.close()
print os.linesep,... |
4caff414bf6d47d5ac8a836df0782d0f1e9136c6 | Piton2306/Study | /What quarter is the point.py | 472 | 4.0625 | 4 | """В какой четверти находится точка"""
from random import randint
x = randint(-10, 10)
y = randint(-10, 10)
print(x)
print(y)
if x > 0 and y > 0:
print('Первая')
elif x < 0 and y > 0:
print('Вторая')
elif x < 0 and y < 0:
print("Третья")
elif x > 0 and y < 0:
print("Четвертая")
elif x == 0:
print(... |
0c232865618663fd78805a5e6c96e2393335ed11 | BohdanDovhan2/Projects | /_Client_/Client.py | 6,542 | 3.609375 | 4 | from socket import *
import os
#Getting your IP address
def getIP():
IP = gethostbyname(getfqdn())
print ("Your IP address", IP)
# IP1 will be used for sending PORT commands
global IP1
IP1 = str.replace(IP,'.',',')
getIP()
#Checking if the "myftp" command was used
whil... |
64c14de2c423cebafdbd7cc8b4869bd3724c0a4e | ninsamue/sdet | /python/act_4.py | 1,487 | 4.25 | 4 | print("ROCK PAPER SCISSORS")
print("-------------------")
Name1 = input("Enter Player 1 Name : ")
Name2 = input("Enter Player 2 Name : ")
player1Score=0
player2Score=0
play="Y"
while play=="Y":
player1Choice = input(Name1+"'s choice - Enter rock/paper/scissors : ").lower()
player2Choice = inp... |
534a5558146e55ff71b8cb3374315b5b756ebdc5 | steamed-stuffed-bread/Leetcode-calender | /98_valid_binary_search_tree.py | 1,375 | 3.796875 | 4 | # medium
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if... |
67e4066043dd16be6454f3ed1110ae4c7a611a3b | steamed-stuffed-bread/Leetcode-calender | /105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py | 986 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
... |
d33834432935f39c646cb46a672be74e1bd5881f | steamed-stuffed-bread/Leetcode-calender | /81_search_in_sorted_array_ii.py | 1,133 | 3.671875 | 4 | # medium
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums:
return False
left = 0
right = len(nums)-1
while left <= right:
mid = left + (righ... |
4b8e8b24a75319c3baef451b3435afbf7ee63092 | steamed-stuffed-bread/Leetcode-calender | /145_binary_tree_postorder_traversal.py | 1,485 | 3.890625 | 4 | # hard
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
sta... |
9d3eefab5f4cb9ad799e753c40a4aa83efb580b1 | Khahory/curso_de_python_yacklyon-trabajo-py | /Video 22/Series III.py | 343 | 3.546875 | 4 | #serie a,b,a,b,a,b....
limite = int(input("Digite las veces que se repetira: "))
interructor = True
controlador = 0
letra = ""
while controlador < limite:
controlador = controlador + 1
if interructor:
letra = "A"
interructor = False
else:
letra = "B"
interructor = True
... |
238b11e4bde02d2a347d997425f9cf9a34b4fb7c | Khahory/curso_de_python_yacklyon-trabajo-py | /Numpy/Vectores numpy.py | 930 | 3.828125 | 4 | import numpy as np
a = np.array([3,6,2,6,2])
b = np.array([3,1,5,6,21])
print(a+b) # se suman con sus respectivos indices
print("\033[1;33m"+"----------------------------------------"+'\033[0;m')
a = np.array([3,6,2,6,2])
b = np.array([3,1,5,6,21])
print(a>b) # Verifica con sus respectivos indices
print("\033[1;33m... |
aea1f7fe9a7e838c9ab0b7c470b36224e6958606 | Khahory/curso_de_python_yacklyon-trabajo-py | /Video 8/Promedio.py | 185 | 3.984375 | 4 | #Encontrar el promedio
nota1 = int(input("Nota 1 \n"))
nota2 = int(input("Nota 2 \n"))
nota3 = int(input("Nota 3 \n"))
res = (nota1+nota2+nota3)/3
print ("El promedio es: " +str(res)) |
9dd95543e30029759d6146f3f799a02e1fea2ad7 | Khahory/curso_de_python_yacklyon-trabajo-py | /Video 8/Area.py | 131 | 3.703125 | 4 | #Buscar el area de un triangulo
# Datos
B = int(input("Digita la base \n"))
H = int(input("Digita la altura \n"))
print ((B*H)/2)
|
b7202390a8938818c4aab6b3d7a43cce8857672a | Amoory001/codes | /tkinter_button.py | 452 | 3.578125 | 4 | #tkinter with closing button
from tkinter import * # we import every submodule in tkinter library
root = Tk() #initialize a blank window
root.geometry('300x300') #change the dimension of our window
l=Label(root,text="Hello World") #
b=Button(root,text="close window",... |
28685fe2957391573336350939558645acab83ba | mrparkonline/ics4u_solutions | /09-30-2020/dict.py | 465 | 3.96875 | 4 | # For each numbers from 2 to N (N → integer user input)
# Create a key, value pair of its Factors
# Key 16 would have the List of → 1,2,4,8,16
def factors(num):
return [x for x in range(1,num+1) if num % x == 0]
print(factors(16))
user_input = int(input('Enter a value: '))
factor_pairs = {}
for ... |
4cc104ae49f21d9ca55166c2aa5149e646dfda4d | mrparkonline/ics4u_solutions | /10-06-2020/letterHistogram.py | 1,080 | 4.3125 | 4 | # Write a program that reads a string and returns a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored.
def letterHistogram(word):
''' letterHistogram tracks the occurance of each alpha characters
... |
5e018f447d9d13832317ee5720012440a9c73c7c | mrparkonline/ics4u_solutions | /09-14-2020/factoring.py | 731 | 4.3125 | 4 | # 09/14/2020
# Factoring Program
num = int(input('Enter a number you want the factors for: '))
# While Loop Solution
divisor = 1
while divisor <= num:
# we are checking all numbers from 1 to inputted num
if num % divisor == 0:
# when num is divided by divisor the remainder is 0
... |
78fcf013af9f568d0314b181d721acb49cb0f59a | mrparkonline/ics4u_solutions | /10-06-2020/numDict.py | 1,333 | 4.34375 | 4 | '''
Q4a) Write a Python program to sum all the items in a dictionary
Q4b) Write a Python program to multiply all the items in a dictionary
Q5a) Create a function that sorts a dictionary by key → Create a sorted list of keys.
Q5b) Create a function that sorts a dictionary by value → Create a sorted list of values.... |
3c91e7f0397bac3d0f7684e95642afbf6183a74d | mrparkonline/ics4u_solutions | /10-19-2020/binarySearch.py | 1,119 | 4.15625 | 4 | # Binary Search Non recursive
def binSearch(data, target):
left = 0
right = len(data) - 1
while left <= right:
middle = (left + right) // 2
if data[middle] == target:
return middle
elif data[middle] < target:
left = middle + 1
else:
... |
492365073001e1f7398793f8278c728477316adf | ACascarino/advent_of_code_2020 | /day13/part1.py | 387 | 3.625 | 4 | with open("day13/input.txt", "r") as f:
arrival_time = int(f.readline().rstrip("/n"))
busses = [int(bus) for bus in f.readline().rstrip("/n").replace("x", "").split(",") if bus]
minutes_until_departure = [round(abs((arrival_time % bus) - bus)) for bus in busses]
min_wait = min(minutes_until_departure)
bus = bu... |
0ee66deb2abfac67f9a7d937e18e6b0a6a974e85 | Nuddlr/Interactive-Photo-Frame | /Distancesensor.py | 2,063 | 3.59375 | 4 | import RPi.GPIO as GPIO
from time import sleep
from time import time
# Global pin variables
PIN_LED = 33
PIN_TRIGGER = 7
PIN_ECHO = 11
PWMFREQ = 75
# Function for setting up output and input pins
def sensorsetup():
# GPIO Setup procedure
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# Distance sen... |
8d462c4437599bb645996d249b2ad8c0824ab597 | vishnupraneeth/Python-Regular-Expressions | /Problem1.py | 107 | 3.9375 | 4 | # Return the first word of a given string
import re
res=re.findall(r"^\w+","I am vishnu")
print(res)
|
1f87201ac1767a8b7fcee157f81fa06d26b6ec11 | watashiSHUN/pythonScripts4fun | /oop/rectangle.py | 846 | 3.890625 | 4 | from point import Point
class Rectangle:
"create a rectangle (vertically/horizontally oriented) in XY plane"
def __init__(self, leftCorner = Point(), width = 0, height = 0):
self.leftCorner = leftCorner
self.width = width
self.height = height
def __str__(self):
return "({0}... |
41c708810d5f74d76f17aacd26c7fab8b5fac90f | watashiSHUN/pythonScripts4fun | /sonicBoomSML/matplotlibT4.py | 210 | 3.765625 | 4 | import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1,2,3,4,5]
plt.scatter(x,y,label='test',marker="X",s=100)
plt.xlabel('x axis')
plt.ylabel('y-axis')
plt.title('second tutorial')
plt.legend()
plt.show()
|
503581bdd54bc6ffcf6f16025a07da481f64e579 | sseuraeki/kakaoexam | /answer7.py | 986 | 3.515625 | 4 | import sys
import datetime
import time
start_extime = time.time()
log = sys.argv[1]
if len(sys.argv) > 2:
for i in range(2, len(sys.argv)):
log += sys.argv[i]
log = log.split(",")
log = [x.strip("[").strip("]") for x in log]
def answer7(log):
instances = []
for instance in log:
instance = instance.split(" ")... |
0c28fbaa800bb70dd4c8106a5ae231f91bc080f5 | basfl/advance_python | /asyn-producer-consumer-model/resulthandler.py | 803 | 3.609375 | 4 | import asyncio
from typing import Callable
async def handle_task_result(result_queue: asyncio.Queue, callback: Callable[[dict], None]):
"""Result item handler
This function (coroutine) will handle any results sitting in the result queue by
issuing the callback.
Just like the task worker, this coroutine... |
71c8bdc6bf5b8561a8306cf147b782a3266d8bf5 | ask-ramsankar/DataStructures-and-Algorithms | /stack/stack using LL.py | 1,217 | 4.15625 | 4 | # creates a node for stack
class Node:
def __init__(self, data, prev=None):
self.data = data
self.prev = prev
self.next = None
class Stack:
# initialize the stack object with the top node
def __init__(self, data):
self.top = Node(data)
# push the data to the... |
e3e9f201341256a05a9a6362a4498d506c269694 | ask-ramsankar/DataStructures-and-Algorithms | /sort/merge.py | 3,706 | 4.25 | 4 | from sort.utils import SortOrder
# @title Merge Sorting
# @notice This is once of the sorting algorithm which time complexity is lesser
# when compared to the linear sorting algorithms (Selection, Bubble, etc)
# @dev This algo follows the Divide and Conquer method. It divides the nodes upto single node
# then sorts b... |
6857698560aa61ddccd54c02d71f57b57be8644c | ask-ramsankar/DataStructures-and-Algorithms | /queue/queue using LL.py | 1,050 | 4.125 | 4 | # Node of the queue
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
# Initialize the queue with the first node
def __init__(self, data):
self.first = Node(data)
# add a node to the queue at last
def enqueue(self, data):
curre... |
aa2222322ebd4bad4db57668e7f90c8b6030afc1 | klaudiaCamargo/RabbitMq | /threading/iterator_generator_2.py | 1,143 | 3.875 | 4 | import random
# como funciona o FOR
# def lancar_dados(n):
# dados = [] # usar essa lista para guardar os dados
# for i in range(0, n):
# dados.append(random.randint(1, 6))
# return dados
#
# for dado in lancar_dados(10):
# print(dado)
#----------------- ITERATO... |
dfa84bc3e42bb5d88da3abbea1e98d6574746345 | adorado-tip/PRELIM_SKILLS_EXAM | /test_temperature.py | 692 | 3.5625 | 4 | from temperature import Temperature
import unittest
class TestTemperature(unittest.TestCase):
def test_input_none(self):
self.assertRaises(ValueError, Temperature)
def test_input_multiple(self):
args = (1,1)
self.assertRaises(ValueError, Temperature, *args)
def test_input_negativ... |
52e821dbc0e4559620cf7e25c76aed8262f36d90 | aJanefish/DeepLearning | /ch03/Test1.py | 1,384 | 3.53125 | 4 | """
神经网络Demo1
"""
import numpy as np
def init_network():
net_work = {}
# print(net_work)
net_work['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
net_work['B1'] = np.array([0.1, 0.2, 0.3])
net_work['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
net_work['B2'] = np.array([0.1, 0.2]... |
ce6dace638f5c869040e03df522bc478e0c762ed | DanielLerma/Dise-o-SW | /interfacesActividad.py | 1,997 | 3.625 | 4 | from abc import ABC
# Interface
class HeroActions(ABC):
def __init__(self, hp: float, mana: float, mainAttr: int, name: str) -> None:
self.hp = hp
self.mana = mana
self.mainAttr = mainAttr
self.name = name
def attack(self, enemy: str, dmg: float, dmgType: str) -> str:
#... |
00b99cbd5c3ad31e24f5326a1cafb2529be4e06a | meetunix/playground-distance | /calc-average-from-csv.py | 270 | 3.859375 | 4 | #!/usr/bin/env python3
import pandas as pd
def avg(distList):
print(len(distList))
distSum = 0
for dist in distList:
distSum += dist
return distSum/len(distList)
csvFrame = pd.read_csv('results.csv')
print(avg(list(csvFrame['distance'])))
|
49d736d6ff76a50557fa392b76d059e7f7d3ad92 | jodr5786/Python-Crash-Course | /Chapter 4/4-12.py | 289 | 4.25 | 4 | # More Loops
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
for my_food in my_foods:
print("- " + my_food)
print("\nMy friend's favorite foods are:")
for friend_food in friend_foods:
print("- " + friend_food) |
190164641638a1463cb1c9a375ade2c0b2df54a0 | jodr5786/Python-Crash-Course | /Chapter 4/4-6.py | 99 | 3.6875 | 4 | # Odd Numbers
oddNumbers = list(range(1,20,2))
for oddNumber in oddNumbers:
print(oddNumber) |
9e3fa8c5cc556234674f61f1f3499c774f0e8b64 | jodr5786/Python-Crash-Course | /Chapter 9/9-1_Restaurant.py | 794 | 3.890625 | 4 | class Restaurant():
"""Restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize the restaurant_name and cuisine_type attributes."""
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type
def describe_restaurant(self):
... |
75f42861847f6ffbdcd4c822635047bc6408329c | jodr5786/Python-Crash-Course | /Chapter 8/8-7_Album.py | 513 | 3.90625 | 4 | def make_album(artist_name, album_title, number_tracks=''):
"""Return a dictionary of album information."""
album_dict = {
'artist': artist_name,
'title': album_title,
}
if number_tracks:
album_dict['tracks'] = number_tracks
return album_dict
album = make_albu... |
e3de0c80f77e36a1d86ae6e70add811f18c69e4f | jodr5786/Python-Crash-Course | /Chapter 6/6-10_Favorite_Numbers.py | 315 | 3.8125 | 4 | favorite_numbers = {
'sam': [5, 10],
'larry': [22, 37],
'greg': [13, 21],
'elen': [12, 45],
'tim': [54, 56],
}
for name, numbers in favorite_numbers.items():
print("\n" + name.title() + "'s favorite numbers are: ")
for number in numbers:
print("- " + str(number))
|
1d86a1f0c018922cff28368903e4a99a1eea139f | jodr5786/Python-Crash-Course | /Chapter 4/4-10.py | 329 | 4.1875 | 4 | # Slices
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'fish', 'lobster']
friend_foods = my_foods[:]
print("\nThe first 3 items in my list are:")
print(my_foods[:3])
print("\nThe items in the middle of my list are:")
print(my_foods[1:5])
print("\nThe last 3 items in the list are:")
print(my_fo... |
6579f816f8f44ff8e9467ecd9cfbc9516c5d0423 | noahtigner/InterviewPrep | /CrackingTheCodingInterview/1-ArraysAndStrings/1.2-checkPermutation.py | 832 | 3.765625 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
# Initial
# time: O(nlogn), space: O(n)
def checkPermutation1(a, b):
if len(a) != len(b):
return False
a_srtd = "".join(sorted(a)) # O(nlogn)
b_srtd = "".join(sorted(b)) # O(nlogn)
for i in range(len(a)): #... |
db80e47c9f17fa0594917b5ab4c482c7a0f47e30 | noahtigner/InterviewPrep | /CrackingTheCodingInterview/2-LinkedLists/2.6-palindrome.py | 2,456 | 4 | 4 | import copy
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Singly Linked
def __init__(self):
self.head = None
def insert(self, data):
# O(1)
if not self.head:
self.head = Node(data)
else:
... |
0fc4f859e6d60da22006879b49579dbeb0dd8f6c | noahtigner/InterviewPrep | /CrackingTheCodingInterview/2-LinkedLists/2.4-partition.py | 1,449 | 4.25 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Singly Linked
def __init__(self):
self.head = None
def insert(self, data):
# O(1)
if not self.head:
self.head = Node(data)
else:
n = self... |
db4922d11ef7eaa11633338ce7d91c87e0c98e65 | noahtigner/InterviewPrep | /CrackingTheCodingInterview/2-LinkedLists/2.5-sumLists.py | 1,752 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Singly Linked
def __init__(self):
self.head = None
def insert(self, data):
# O(1)
if not self.head:
self.head = Node(data)
else:
n = self... |
5dbc4a64adf940e7cddf09b2bca2eafe21663a35 | NAGESH-KJ/DATA-ANALYTICS-PROJECT | /NaiveBayesModel.py | 4,677 | 3.59375 | 4 |
# coding: utf-8
# In[83]:
import pandas as pd
df = pd.read_csv("D:\DA_ASSIGNMENT\PROJECT\project.csv",parse_dates =["date"],index_col ="date")
# In[ ]:
#we will build a naive bayes classifier for classifying desc into type categories.
# In[109]:
#we will add a column encoding the type as an integer because ... |
d05c95f40e2772976b96af80d76c5db42ff33080 | dhskohjingyu/python2013lab2 | /count_votes.py | 1,546 | 3.6875 | 4 | def count_votes():
# Open VOTES.DAT
votes = {'PAP':0, 'RP':0, 'SDA':0, 'WP':0, 'SPOILT':0}
try:
infile = open("VOTES.DAT", "r")
for line in infile:
# remove newline from line
line = line.rstrip('\n')
# check if line is valid
if line == 'PAP,... |
221e50240c25b8a683adaa8335cc0887db6c851c | dcmoss87/Hadoop-MapReduce-Replication | /src/MapReduce.py | 2,798 | 3.703125 | 4 | import csv
import os
from collections import defaultdict
def mapper(list1, filename):#maps key, value pairs into a list of lists
with open(filename, 'r', newline='') as f:
reader = csv.reader(f, delimiter=',')
rows = [[row[0], int(row[1])] for row in reader if row]#converts the numeric values from str... |
e5a3ba383c9fff177c41819df229df67e5201d34 | 1411279054/Python-Learning | /Data-Structures&Althorithms/python数据结构与算法/第四章递归课后习题/C-4.19.py | 439 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/1/30 11:48
# @Author : LiChao
# @File : C-4.19.py
def change_odd_even(lists,i,j):
if i >= j:
return None
else :
while i< j and lists[i]%2==1:
i += 1
while i< j and lists[j]%2==0:
j -=1
lists[i],lists[j] =lists[j],l... |
a144ce02685932552a3379d5b6997b3fa01504b4 | 1411279054/Python-Learning | /Data-Structures&Althorithms/力扣算法/四月份算法题/旋转矩阵.py | 1,679 | 4.15625 | 4 | ## 题目:旋转矩阵()
import pandas
import copy
class Solution:
##利用pandas求解
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
matrix2 = pandas.DataFrame(matrix)
num = matrix2[0].size
for i in range(num):
matrix[i] =matr... |
cc5f0d46ec8a9972407b0d99636bf12e4d1b443e | 1411279054/Python-Learning | /Data-Structures&Althorithms/python数据结构与算法/第一章python入门课后练习/C-1.35.py | 1,559 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/2 12:15
# @Author : LiChao
# @File : C-1.35.py
import random
def birthday_question(n):
big_month = [1,3,5,7,8,10,12]
small_month = [4,6,9,11]
lists =[]
month_list = random.choices([1,2,3,4,5,6,7,8,9,10,11,12],k=n)
for i in range(n):
if month_list... |
0e876b43d757457798fddbfea41224eb6cb14f85 | 1411279054/Python-Learning | /Data-Structures&Althorithms/力扣算法/十月份算法题/(10.4) 2.两数相加.py | 1,156 | 3.625 | 4 | class ListNode:
def __init__(self, item):
self.val = item
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
p,q = l1,l2
new_ld = ListNode(0)
pt = new_ld
carry = 0
while p != None or q != None:
a ... |
76a5cef3058cfd911acea25a61957933177b1ce3 | codehearts/platformer | /platformer/game/easing/linear.py | 4,265 | 4.125 | 4 | class Linear(object):
"""An easing transition which moves at a constant rate.
Attributes:
start (float): The starting value of the transition.
end (float): The final value of the transition.
duration (float): The amount of time (in seconds) that the transition will last for.
ease_power (float): Determines ho... |
0c0eef25797864e8f2d50572b1bbd3c8ac07577e | s15007/algorytm_designpattern | /power.py | 986 | 4.09375 | 4 | #!/usr/bin/env python
import time
import random
X = random.randint(3, 9)
LOOP_COUNT = 5000
def power(x, n):
ans = 1
for _ in range(n):
ans *= x
return ans
def power2(x, n):
if n == 0:
return 1
if n == 1:
return x
tmp = power2(x, n // 2)
if n % 2 == 0:
return tmp * tmp
return tmp * tmp * x
... |
9073f99a3d78244b516d34730f0321e01e80f341 | ravindra-lakal/Python_new | /mak.py | 912 | 4.3125 | 4 | ###################################
#1 Find the last element of a list.
list = ['a','b','c','d']
#validation list =[]
print list[-1:]
#print "list[4]",list[4]
#2 Find the last but one element of a list.
list =['z','w','e','i','t','l','e','t','z','t','e','s']
#validation list=[1]
print list[-2:-1]
#3 1.03 (*) ... |
b79514027f478235ea4576fc4b76b3a774d191c4 | p2008/Warsztaty_1 | /Gra_w_zgadywanie_liczb.py | 896 | 3.828125 | 4 | import random
"""Program ask user for number in range of 0-100.
If True compares given number with random number giving information less/more"""
if __name__ == '__main__':
max_int = 100
min_int = 0
random_number = random.randint(min_int, max_int)
while True:
user_input = input("Zgadnij liczbę:... |
b2a46a2ae98324d1c8be8586fab2deef1d9f4686 | 1098813507/Taller-de-Algoritmos | /3.py | 169 | 4 | 4 | print("imprimir el cuadrado de un numero")
numero=(input("digite un numero"))
print(numero)
cuadrado=pow(numero)
print("el cuadrado de"+str(numero)+"es"+str(cuadrado))
|
76f80e71ca2bef0475474878c4b09ee3e661f166 | 1098813507/Taller-de-Algoritmos | /30.py | 244 | 3.6875 | 4 | print("iva de una venta")
venta=float(input("digite el valor del producto"))
iva=venta*0.19
ventatotal=int(venta + iva )
desvento=venta*0.05
ventadescuento=int(ventadescuento)
if venta<150000:
print("el precio a pagar es de"+ str(ventatotal)) |
b92253059318d8221a4ee8a74d89b66696769344 | 1098813507/Taller-de-Algoritmos | /24.py | 626 | 3.875 | 4 | print("menor cantidad de dinero")
d=int(input)"digita la cantida de dinero")
d1=int(d%100000)
d2=d=(d1*100000)
d3=int(d3*50000)
d4=d2-(d3*50000)
d5=int(d4%20000)
d6=d4-(d5-20000)
d7=int(d6%10000)
d8=d6-(d7*10000)
d9=int(d8%50000)
d10=d8-(d9*5000)
d11=int(d10%2000)
d12=d10-(d11*2000)
d13=int(d12*2000)
d14=d12-(d13*1000... |
6ca1bc383c3f2a4f2f0d5a7595097f84e6147b9c | 1098813507/Taller-de-Algoritmos | /26.py | 241 | 3.84375 | 4 | print("numeros booleanos")
a=true or false
b= false or true
c= true and true
d= false and true
e= (false and false)or (true and true)
f= (false or false) and (true and true)
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print("end") |
3ba21d7029380032b8d1de50d0153726a4f72f96 | 1098813507/Taller-de-Algoritmos | /27.py | 160 | 3.765625 | 4 | print("par o impar")
num=int(input("digite un numero"))
if num % 2 = 0:
print("el numero"str(num)+"es impar")
else
print("el numero"+str(num)+"es impar") |
1bfd8e33ae5066e81621649aa49a24d5861a97cd | 1098813507/Taller-de-Algoritmos | /25.py | 209 | 3.734375 | 4 | print("invertir un numero de 4 cifras")
a=int(input("digita un numero de 4 cifras"))
b=int(a%1000)
c=a-(b*1000)
d=int(c%100)
e=c-(d*100)
f=int(e%10)
g=e-(f*10)
print(str(g)+str(f)+str(d)+str(b))
print("end") |
6598d8be020782403264857da1d78cd048d8c04d | 1098813507/Taller-de-Algoritmos | /13.py | 213 | 3.671875 | 4 | v1 int(input("digite valor variable"))
v2 int(input("digite valor variable2"))
v1==v2
v2==v1
print("el valor de variable uno era,v1, y ahora es v2")
print("el valor de la variable 2 era,v2 y ahora es v1") |
f81ccde2dd2d2acf91e8f5e82fa9fa1c755624a0 | 1098813507/Taller-de-Algoritmos | /58.py | 89 | 3.859375 | 4 | print("numeros para naturales")
for num in range (1,10+1):
if num 1<==0
print (num) |
5a7d0912eda3851f93aab1ff27018a32a9df7962 | masterashu/Semester-3 | /ADSA/Lab/Lab6/dijkstra.py | 1,246 | 3.640625 | 4 | def get_weight(u,v,Edges):
for i,j,w in Edges:
if i == u and j == v:
return w
return float("Inf")
def Dijkstra(G, V):
n = len(G)
final = set()
not_final = set(G.keys())
dist = dict()
for i in G.keys():
dist[i] = float("Inf")
dist[V] = 0
... |
cb8e906ab90c7e5525f97465d9fc8d6a50d7772c | djtimo18/Coronavirus-Simulator | /coronavirus.py | 1,159 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Ecrit par Tim
"""
from math import *
#MENU DU SIMULATEUR
print("Bienvenue dans le simulateur de pandémie du nom de Coronavirus :");
print("Choisissez des variables pour la simulations :");
C = input("Nombre de contact quotidien : ");
T = input("Durée de la maladie en jours : ");
T = int(... |
855a78d607e192b3cf0f89393bdc3f45bcbcf16d | Allegheny-Computer-Science-102-F2020/cs102-F2020-slides | /src/square-function.py | 703 | 3.96875 | 4 | def square(number: int):
print(f"Called square({number})")
print(f" returning {number*number}")
return number * number
def call_twice(f, number: int):
print(f"Calling twice {f} with starting number of {number}")
return f(f(number))
number = 5
result = call_twice(square, number)
print()
print("... |
bdca0c49cb982a120be408d32e65f14b48dca1da | Allegheny-Computer-Science-102-F2020/cs102-F2020-slides | /src/dictionary-example.py | 586 | 3.78125 | 4 | # create the dictionary
mlb_team = dict(
Colorado='Rockies',
Boston='Red Sox',
Minnesota='Twins',
Milwaukee='Brewers',
Seattle='Mariners'
)
# determine details about the dictionary
print(type(mlb_team))
print(mlb_team)
# access content that exists in the dictionary
print(mlb_team['Minnesota'])
... |
f1189f2a865a8a699bdea05dd6caa801aad32aec | Allegheny-Computer-Science-102-F2020/cs102-F2020-slides | /src/finiteset-subsets.py | 549 | 3.78125 | 4 | from sympy import FiniteSet
set_one = FiniteSet(1, 2, 3)
set_two = FiniteSet(1, 2, 3)
subset = set_one.is_proper_subset(set_two)
print("Set one proper subset set two:")
print(subset)
print()
subset = set_two.is_proper_subset(set_one)
print("Set two proper subset set one:")
print(subset)
print()
set_three = Finite... |
78d323b942aa57366d3a8eb4c9f58bb439f7b66d | Allegheny-Computer-Science-102-F2020/cs102-F2020-slides | /src/fibonacci-generator.py | 233 | 4.125 | 4 | def fibonacci_generator(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b
print(fibonacci_generator)
for fibonacci_value in fibonacci_generator(10):
print(fibonacci_value, end=" ")
print()
|
4321364044f120e7b7124cbccd7ce2b3f8ced56e | Dit81/pentesttools | /Brute/brute.py | 279 | 3.609375 | 4 | import random
password = random.randint(0,999) #Генерация пароля
#print 'Password: %s' %(password)
i = 0; # Начало подбора
while (password != i):
print i
i += 1
print 'The password is: %s' %(i) #Вывод найденного пароля
|
000e177fda7bf009742ef757bdd466249e42bd9a | nyeddi/Adv-Python | /class_method_.py | 1,745 | 4.46875 | 4 | class Shape(object):
# this is an abstract class that is primarily used for inheritance defaults
# here is where you would define classmethods that can be overridden by inherited classes
@classmethod
def from_square(cls, square):
# return a default instance of cls
return cls()
c... |
6eaae7ee5811f78929f6b6fe5a0881a825a1a47d | mgmeisinger/Py3.0-Security-Suite | /Part1/authentication.py | 1,831 | 3.765625 | 4 | # Part 2, Program 1 - ID & Pwd verifier
# Final Project - Computer Security
# Author: Michael Meisinger
import hashlib # For md5 functionality
#-- Functions --#
def login():
usrName = input("Enter user name: ")
usrName = usrName.strip()
pwd = input("Enter password for " + usrName + ": ")
pwd = pwd.str... |
aaa7a7e0bf091bdd47f844696581c090b84d27a3 | dojo-recife/dojo | /10-buraco-nas-letras/test.py | 2,213 | 4.09375 | 4 | import unittest
from main import conta_buraco
# Buracos nas Letras
# Se você pensar em um papel como um plano e uma letra como uma marcação neste plano, então estas letras dividem o plano em regiões. Por exemplo, as letras A, D e O dividem o plano em 2 pois possuem um espaço confinado em seu desenho, ou um “buraco”. O... |
31834fd9a7fd38aecee2f1083b92ef8cef26b7b1 | creativeshim/python-basic | /JTP/Chap8/problem6.py | 1,158 | 3.796875 | 4 | '''
[문제6] Duplicate Numbers
0~9까지의 문자로 된 숫자를 입력받았을 때, 이 입력값이 0~9까지의 모든 숫자가 각각 한 번씩만 사용된 것인지 확인하는 함수를 작성해 보자.
입력 예시: 0123456789 01234 01234567890 6789012345 012322456789
출력 예시: true false false true false
'''
data = "012322456789"
answer = "true"
for i in range(0,10) :
sum = 0
for c in data :
if int(c... |
a49ca258170fe8fcd66ddf8529a78bf8cf12cc7a | creativeshim/python-basic | /algorithm/problems/problem3.py | 387 | 3.90625 | 4 | '''
3. 반복문을 사용하여 1부터 n까지 출력하기
con1. 1부터 순서대로 화면에 출력한다.
con2. 출력하는 숫자가 n이 되면 프로그램을 종료한다.
'''
def printNum(num):
#for문
for n in range(1,num+1):
print(n)
#while문
c = 1
while c<num+1:
print(c)
c += 1
if __name__ == "__main__":
printNum(100) |
6a957577d799acc29b563770b6cc66f26d38c149 | creativeshim/python-basic | /JTP/Chap6/problem2.py | 320 | 3.578125 | 4 | #10 미만의 자연수에서 3과 5의 배수를 구하면 3, 5, 6, 9이다. 이들의 총합은 23이다.
#1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라.
a = 1;
num = 0;
while a<1000:
if(a%3 == 0):
num += a
elif(a%5 == 0):
num += a
a = a + 1
print(num);
|
104e82e9c9e5ecde5cd8f5f9a71dfda67db674e4 | joeryan/hardway | /ex18.py | 456 | 4 | 4 | def print_two(*args):
arg1, arg2 = args
print "arg1 = %r, arg2: %r" % (arg1, arg2)
# *args is a bit pointless, we could just do this
def print_two_again(arg1, arg2):
print "arg1 = %r, arg2: %r" % (arg1, arg2)
# this takes just one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no argument... |
b92a1f108cd8d8b91fe76215aee179be207efa41 | Jioveto/Astar | /testcoord.py | 377 | 3.59375 | 4 | from coord import Coord
c = Coord(3, 4)
if c.y == 4:
print "PASS"
if c[1] == 4:
print "PASS"
try:
print c[2]
print "FAIL"
except ValueError as e:
print "PASS"
c = Coord([3, 4])
if c.y == 4:
print "PASS"
c = Coord((3, 4))
if c.x == 3:
print "PASS"
c[0] = 7
if c.x == 7:
print "PASS"
if str(c) == "(7, 4)":
... |
23ee2a6e04fcd1c4c010631d58fc57cd71ca722c | malihaiqbal/maze | /maze.py | 2,259 | 3.828125 | 4 | #program 1
print("CUBE: ")
n=int(input("enter number"))
def cube(n):
return n**3
xyz=cube(n)
print(xyz)
#program 2
print("fact")
def factorial(n):
if n==1:
return 1
return n*factorial(n-1)
fact=factorial(n)
print(fact)
#program 3
print("string\0")
string = 'ababcdab'
pattern = 'ab'
count... |
1889bde20220841ec9ae80b9dd22ddafae3cd3bc | shanyuxiyun/learning | /python/books/learningpython5/02chapter/list.py | 397 | 3.625 | 4 | #!/usr/bin/env python
# coding=utf-8
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print m
m[0][0] = 111
print m
g = (sum(row) for row in m)
print g.next()
print g.next()
print g.next()
print list(map(sum,m))
print {sum(row) for row in m} #set
print {i:sum(m[i]) for i in range(3)} #dict
print [row[1] for row in m]
print l... |
920ebd5fb884250b1288e41a88d36d14b39082b6 | kazuo-mu/at_coder_answers | /ABS/abc081a_pricing_marbles.py | 134 | 3.5 | 4 | s = input()
counter = 0
if (s[0] == '1'): counter += 1
if (s[1] == '1'): counter += 1
if (s[2] == '1'): counter += 1
print(counter) |
26ce3d11961d7ade59a12f456377cf17f782a8b0 | kazuo-mu/at_coder_answers | /ABC049/d_connectivity.py | 1,393 | 3.65625 | 4 | from collections import defaultdict
class UnionFind():
def __init__(self, n):
# 頂点の値が0から始まる前提なので注意
self.par = [i for i in range(n)]
def root(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x... |
045039d0f21e11d5b55e0efb5fd92b59afabf389 | AntonZagorodniy/Cook_book | /Cook_book.py | 2,097 | 3.59375 | 4 |
def get_cook_book():
cook_book = dict()
with open('List_of_recipes.txt', encoding='utf-8-sig') as file:
dish = ""
for l in file:
tempstr = l.strip()
if '|' in tempstr:
ingrs = tempstr.split("|")
for i, ingr in enumerate(ingrs)... |
d06cdae07346ea681a2b4a9069093625521d1e0c | kami71539/Python-Applications | /Turtle race.py | 1,315 | 3.578125 | 4 | from turtle import*
import random
speed(0)
a=1
penup()
goto(-180,0)
right(90)
for i in range(11,1,-1):
pendown()
write(a,align='center')
for j in range(30):
forward(5)
penup()
forward(5)
pendown()
penup()
goto(-15*i,0)
penup()
a+=1
red=Turtle()
red.penup()
red.colo... |
50d18cb1e882f6f6126e5b09e9f97103bb268019 | bmanturner/CS303-python | /lab6/priorityqueue.py | 2,376 | 4 | 4 | class item(object):
def __init__(self, int):
self.priority = int
def compareTo(self, comparator):
if self.priority <= comparator.priority:
return True
else:
return False
def equals(self, item):
if self == item:
return True
else:
return False
class PriorityQueue(object):
def __init__(self):... |
bfa6128cb0af6c69eec43a9063ed2a9f54a044de | charlie93321/new-python-tools | /com/dxm/google_xml_util/time222.py | 352 | 3.65625 | 4 | from datetime import datetime, timezone, timedelta
# 创建时区UTC+00:00
tz_utc = timezone(timedelta(hours=0))
# 获得带时区的UTC时间
current_time_utc = datetime.utcnow().replace(tzinfo=tz_utc,microsecond=0)
timestr = current_time_utc.strftime("%Y-%m-%dT%H:%M:%S%z")
new_time_str="{}:{}".format(timestr[0:-2],timestr[-2:])
print(new_ti... |
c21643f5c58676f77da8ffbc14d3dc488c5b0d8e | saadkang/PyCharmLearning | /basicsyntax/indexvstring.py | 2,088 | 4.40625 | 4 | """
We will see how the index works in python
"""
nameOfAString = "This is for educational purposes only"
# The : in the [] is has no starting and ending index so it will print the whole String
print("There is nothing before or after the : so it will print complete String: "+nameOfAString[:])
# In the example below ... |
4ade5b9723e9c325292ff3db23f065fef3fe788b | saadkang/PyCharmLearning | /Classes/classdemo1.py | 366 | 3.578125 | 4 | """
Object Oriented Programming
"""
s = "This is a String"
a = "This is another String"
s.upper()
a.lower()
# The instructor has single quotes inside the type() method, but I'm going to try it without and see if I get the same
# result
print(type(a))
print(type(s))
# And turns out it does give me the same result, so ... |
445befab60ef2ad7e87ec1b5ce54925ace4977b8 | saadkang/PyCharmLearning | /basicsyntax/tuplesdemo.py | 1,493 | 4.5 | 4 | """
Tuple
Like list but they are immutable
that means you can't change them
"""
# What the above line in green is trying to say is that list (also called Array in Java) can be changed
# Like in the example below:
# The list or Array is defined by the []
my_list = [1, 2, 3]
print(my_list)
my_list[0] = 0
print(my_list)
... |
0bb7a577e6dc036a4607eaac1f46ebb10d066b54 | saadkang/PyCharmLearning | /basicsyntax/list_demo.py | 467 | 4.1875 | 4 | """
Now, we are going to talk about the list in python
"""
cars = ["BMW", "Honda", "Audi"]
empty_list = []
print(empty_list)
print(cars)
print("*"*20)
print(cars[0])
print("*"*20)
print(cars[1])
print("*"*20)
print(cars[2])
print("*"*20)
numList = [1, 2, 3]
sumList = numList[0] + numList[1]
print(sumList)
print("*"*20... |
a5ce7eb414b01998107f3c617438628aeee33d33 | sxmeng2017/GarageCollection | /object.py | 283 | 3.671875 | 4 | class object:
def __init__(self, address, child, size):
self.address = address
#self.parent = parent
self.size = size
self.child = child
self.mark = False
def __str__(self):
return f"address:{self.address}, size:{self.size}"
|
4e4578a834a9bab8b64db8f4c3f67cc28b0dbf18 | mayuriindalkar/operator | /task1.py | 183 | 3.734375 | 4 | water=int(input("enter water"))
if water<1:
print("need water")
elif water>1 and water<10:
print("no need")
else:
a="kavi"
b="3+4j"
c=13
d="4+1"
e=4.1
print(a+b+c+d) |
9d384ca548577e4f6b339e1ca75912994489ad12 | Andkleven/INF200-2019-Exersices | /src/anders_mathiesen_ex/ex01/tidy_code.py | 1,093 | 4 | 4 | # -*- coding: utf-8 -*-
from random import randint
__author__ = 'Anders Mathiesen'
__email__ = 'andermat@nmbu.no'
def get_guess_bigger_then_or_lik_1():
number = 0
while number < 1:
number = input('Your guess bigger then or lik 1: ')
try:
number = int(number)
except ValueE... |
6d35e8b7747962a126eecaa0a9acb6746c91c881 | arnottrcaiado/curso-python-senac | /aula5/aula5-ex4.py | 416 | 4.03125 | 4 | # aula5 - ex4 - Arnott Ramos Caiado
# Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’,
# se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
def positivo_negativo ( numero ):
if numero >0 :
return ('P')
else:
retu... |
d2ef76fc270600890e16f9a512aaf7fb3d44d557 | arnottrcaiado/curso-python-senac | /aula1/aula1-ex6.py | 211 | 3.921875 | 4 | # aula1 - exe 6 - Arnott Ramos Caiado
# calculo da área de um circulo
pi = 3.1416
area = 0
raio = float(input("\n Calculo da area de um circulo. Favor entrar com o Raio:"))
area = 2* pi * raio
print( "\n Area = ", area)
|
5feabc23136cb75b574ee6bc715bc05b25ef4608 | arnottrcaiado/curso-python-senac | /aula3/aula3-exercicios-aula-ex1.py | 283 | 4 | 4 | # aula3 - exercicio aula - Arnott Ramos Caiado
# ex 1 - pede nota e continua enquanto nota invalida
continua = True
while continua :
nota = int(input("\n Entre com nota de 0 a 10: "))
if nota >=0 and nota <= 10 :
continua = False
elif :
print( "\n Nota invalida !")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.