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 |
|---|---|---|---|---|---|---|
8268b9c5b73a33f800847d3e9006d771f588457c | serasaheera/ICT-CALICUT | /python/operations.py | 158 | 4 | 4 | a=int(input("enter a number"))
print a
b=int(input("enter a number"))
print b
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a//b)
print(a**b)
|
7ab8473631f80c69a5ec1a953de0964ca6cc0a9a | serasaheera/ICT-CALICUT | /python/identity.py | 69 | 3.84375 | 4 | x1=5
y1=5
x2="Hello"
y2="Hello"
print(x1 is not y1)
print(x2 is y2)
|
12486331dd1231195c8d5f043097d88fc3785aa2 | serasaheera/ICT-CALICUT | /python/forloop.py | 67 | 3.796875 | 4 | a=int(input("enter a number"))
while a!=0:
print "tick", a
a=a-1
|
a9e34edfcc8e1aae24613a2e286a6e34ef0ec5d5 | marslwxc/read-project | /Python高级编程和异步IO并发编程/Chapter08/metaclass_test.py | 968 | 4.125 | 4 | # 类也是对象,type是创建类的类
def create_class(name):
if name == 'user':
class User:
def __str__(self):
return "user"
return User
elif name == "company":
class Company:
def __str__(self):
return "company"
return Company
# type动态创建类
c... |
086a9d173ed3e63778658acb1b08f31c5adacf90 | leo-sandler/ICS4U_Unit_4_Algorithms_Leo_Sandler | /Lesson_4.1/4.1_Recursion_and_Searching.py | 1,826 | 4.21875 | 4 | import math
# Pseudo code for summing all numbers from one to 100.
# Initialize count variable, at 1
# for 101 loops
# Add loop number to the count, with reiterating increase
# Real code
count = 0
for x in range(101):
count += x
# print(count)
# Recursion is calling the same function within itself.
# Recursi... |
2d8ce95f5dc289ea421d79b38e2bfae68a03d247 | leo-sandler/ICS4U_Unit_4_Algorithms_Leo_Sandler | /Unit_4_Questions/Questions_Data_Type_Classes.py | 1,544 | 3.921875 | 4 | class Stack: # FILO
def __init__(self):
self.data = []
def is_empty(self):
if self.data == []:
return True
else:
return False
def push(self, value):
self.data.insert(0, value)
def pop(self):
del self.data[0]
def peek(self):
... |
81ffece1b8181d35c1ee4b81d4dbf42cdc454f86 | tomasderner97/customutils2 | /core/_vector.py | 4,531 | 3.8125 | 4 | from math import acos, degrees, sin, cos, radians
class Vector2D:
def __init__(self, x, y):
self._x = x
self._y = y
self._abs = None
@property
def x(self):
return self._x
@property
def y(self):
return self._y
def normalized(self):
norm =... |
9640ac1f8650123214b23c07b926ff57342873ee | sachinyadav3496/InternshipBatch2020 | /Techno_Intern_Batch/mytkapps/diaglog.py | 976 | 3.65625 | 4 | from tkinter import *
from tkinter.messagebox import showinfo, showwarning, askyesnocancel
root = Tk()
lb = Label(root, text="Hello World", font=50)
lb.pack(fill=BOTH, expand=YES)
def some_ask():
ans = askyesnocancel(title="Continue", message="do you want to close it ? ")
if ans:
root.quit()
def s... |
4001544243776781f2613214c7e8831ae5cb7699 | sachinyadav3496/InternshipBatch2020 | /InternBatch/python/personal.py | 463 | 3.75 | 4 | """
personal is a module having these functions
hello
add
pat
"""
def hello(name):
"""hello(name) -> greet using name"""
print("Hello ", name)
def add(x, y):
"""add(x, y) -> return x + y"""
return x + y
def pat(nrows):
"""
pat(nrows) prints normal pattern
"""
... |
809831a0c478fb2e0d45d060933425dc9307d01f | Bghf/pluto | /pluto.py | 5,054 | 3.953125 | 4 | import unittest
from unittest import TestCase
class Direction:
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
@staticmethod
def next_clockwise(direction):
return (direction + 1) % 4
@staticmethod
def next_anticlockwise(direction):
return Direction.WEST if direction == Direction.NORTH else... |
2d331caaecc21aa5cc209f6d9cf7518b6eef5060 | multiscale/muscle3 | /libmuscle/python/libmuscle/endpoint.py | 3,347 | 3.78125 | 4 | from typing import List
from ymmsl import Identifier, Reference
class Endpoint:
"""Place that a message is sent from and to.
In the model description, we have kernels with ports connected by
conduits. However, these kernels may be replicated, in which case
there are many instances of them at run tim... |
403d766f83262d209ffcfc396367b5d43faf7948 | ajithkjames/python-examples | /amstronng.py | 204 | 3.5 | 4 | print ("hai")
class FindAmstrongNumbers(object):
def amstrong():
for i in range(1,10000):
pows=[int(a)**len(str(i)) for a in str(i)]
if sum(pows)==i:
print (i)
FindAmstrongNumbers.amstrong() |
ea68838d688ef6bb4399fbe52fbfe208ddd481fd | Shmart-app/back-end | /data_mining.py | 763 | 3.546875 | 4 | from typing import List,TextIO
#file = open('HTV_DATA.csv') #sample data file can be changed
def csv_to_list(csv_file: TextIO) -> List[List[str]]:
csv_file.readline()
data = []
for line in csv_file:
data.append(line.strip().split(','))
return data
def give_recommended_produc... |
6ad153d3665d78ca1df8de522af0f48e2777aedc | mikitkanakia/Click-Through-Rate-Prediction | /click_through_rate_prediction.py | 33,201 | 3.578125 | 4 | # Databricks notebook source
# MAGIC %md # **Click-Through Rate Prediction**
# MAGIC #### The project covers the steps for creating a click-through rate (CTR) prediction pipeline. [Criteo Labs](http://labs.criteo.com/) dataset that was used for a recent [Kaggle competition](https://www.kaggle.com/c/criteo-display-ad-ch... |
c6e2fcc274fd5a5081afc56e5ee9c028a65a82e0 | BrunoDuzanjo/bruno-dos-anjos-poo-python-ifce-p7 | /Atividades[Presença]- Etapa 1/E1-Atividade-03/MegaSena.py | 374 | 3.578125 | 4 | import random
def repetido():
if len(sorteadoLista) != len(set(sorteadoLista)):
sorteadoLista2 = set(sorteadoLista)
sorteadoLista = []
sorteadoLista2 = []
while len(sorteadoLista2) < 6:
sorteado = random.randrange(1,61)
sorteadoLista.append(sorteado)
repetido()
sorteadoLista2... |
6b2041e4f89ecd489a4d4ecdf3b2f993938d9f92 | ipekdedekoy/dagitik | /odev1.py | 1,881 | 3.53125 | 4 | import random
import matplotlib.pyplot as plt
#mu ve sigma sayilarina atama;
mu1 = random.uniform(-5.0,5.0)
mu2 = random.uniform(-5.0,5.0)
sigma1 = random.uniform(0.5,1.5)
sigma2 = random.uniform(0.5,1.5)
#mu ve sigma sayilarinin testi;
print("mu1: "+str(mu1))
print("sigma1: "+str(sigma1))
print("mu2: "+str(mu2))
pr... |
83971e63972f9a21edf9f355529cab109502a54d | sanketha1990/python-basics | /pythonHelloWorld/com/python/learner/ComparisionOperatorInPython.py | 410 | 4.46875 | 4 | temperature=30
if temperature > 30: # == , !=,
print('its hot day !')
else:
print('it is not hot day !')
print('=============================================')
name=input('Please enter your name .. ')
name_len=len(name)
if name_len <= 3:
print('Name should be gretter thant 3 charecter !')
elif name_len >=5... |
3bd79e475b9126e7e025c0e9b00f60b3e4760ac2 | sanketha1990/python-basics | /pythonHelloWorld/com/python/learner/com/python/learner/advance/Converters.py | 174 | 3.796875 | 4 | def covert_lbs_kg(weight):
print('convert from lbs to KG')
return weight*0.45
def convert_kg_lbs(weight):
print('convert from kg to lbs')
return weight/0.45 |
3ac15db522609f64dfbc8737c19e5aa3fb3cbf68 | PCA1610/Smartninja | /Uebung15/GUI/fizzbzz.py | 715 | 3.625 | 4 | import Tkinter
import tkMessageBox
window = Tkinter.Tk()
# greeting text
greeting = Tkinter.Label(window, text="Enter a Number between 1 and 100")
greeting.pack()
# guess entry field
number1 = Tkinter.Entry(window)
number1.pack()
# check guess
def fizz_funk():
for x in range(1, int(number1.get()) + 1):
... |
97d7d41fa4a62a35edbd225c180712fc43a2c421 | PCA1610/Smartninja | /Uebung08/converter.py | 467 | 3.859375 | 4 | print "Mit diesem Programm kann man Kilometer in Meilen umrechnen."
question = 0
while True:
userZahl = int(raw_input("Gib eine Entfernung in Kilometer ein, die du in Meilen umrechnen willst: "))
userZahlinMeilen = userZahl / 1.609
print str(userZahl) + " sind " + str(userZahlinMeilen) + " in Meilen."
... |
f219f4636dba5cad0653d026e4e907c0211a33bd | PCA1610/Smartninja | /Uebung07/numberGuess.py | 558 | 3.984375 | 4 | import random
def main():
rant_value = random.randint(1, 100)
for x in range(0, 7):
guess = int(raw_input("Guess the secret number (between 1 and 100): "))
if guess == rant_value:
print "You guessed it - congratulations! It's number %d :)" % (rant_value)
break
... |
f50cae589679c208c2b547fcd2820f805045741a | GaoFan98/MLBootcamp | /1 Linear Regression/exercise.py | 2,206 | 3.859375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
customers = pd.read_csv('Ecommerce Customers')
# SHOWS EVERYTHING ON GRAPHS
# sns.pairplot(cust... |
1afba2688e03431f26486ec776da102e30cbb03e | heloisaGuimaraes/grafos-atividades | /Atividade 05/cod05.py | 2,564 | 3.71875 | 4 | import random
lista_adj = [] # Lista de adjacencias do grafo inicial
caminho = [] # Lista de caminhos mapeados disponíveis para a árvore de custo minimo
arv_ger_min = [] # Esqueleto da árvore de custo minimo
qtd_arestas = 0 # Número de arestas da árvore nova
custo_total = 0 # ... |
6288bba8ab5090fb09a24aa541884141e9cb3f6b | JackM400/Xs_and_Os | /board.py | 4,321 | 3.6875 | 4 | # JackM400
# jack.millar400@gmail.com
# holds game board state
GameBoard = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
gameHasNext = True
player1 = ""
player2 = ""
gameWinner = None
turnPlayer = "X"
# main function
def playGame():
getPlayerName()
playerDeclaration() # print play... |
aa563964eed670f7e079d220f32d036164bb420e | DmitryAPetrov/python | /DZ1.py | 1,372 | 3.984375 | 4 |
##----------------------Задание №1----------------------
# nameUser = input("Введите свое имя: ")
# surnameUser =input("Введите свою фамилию: ")
# print(f"Добрый день {nameUser} {surnameUser}")
##----------------------Задание №2----------------------
# second = int(input("Введите длительность времени в секундах: ... |
eb7420d2c363291f934207cc92791906c62d4205 | omerdagistanli/CS50-Introduction_to_Computer_Science | /Python Ödev Çözümleri/CS50-Kkart.py | 1,172 | 3.5625 | 4 | s = input("Number: ")
while s.isdigit() == False:
s = input("Number: ")
kkListe = []
for i in range(len(s)):
kkListe += [s[i]]
kkListe.reverse()
tnListe = []
for j in range(1, len(kkListe), 2):
tnListe += [kkListe[j]]
cnListe = []
for a in range(0, len(kkListe), 2):
cnListe += [kkLis... |
40b3d25856fe31f927c2b09b0c7a39c15fbd9245 | dhruvparekh01/3552_A01157984 | /Labs/Lab4/user.py | 869 | 3.890625 | 4 | class User:
def __init__(self, name, age, acc_number, bank_name, bank_balance, all_budgets):
"""
Initialize the user object
:param name: (String) The name of the user
:param age: (int) The age of the user
:param acc_number: (String) The bank account number of the user
... |
5f341077abe9665bdd922099b80f6ca9c91728d5 | maxmyk/Lab6 | /target_game.py | 2,878 | 4.0625 | 4 | """
Target game
"""
from typing import List
"""
Importing Lists
"""
def generate_grid() -> List[List[str]]:
"""
Generates list of lists of letters - i.e. grid for the game.
e.g. [['I', 'G', 'E'], ['P', 'I', 'S'], ['W', 'M', 'G']]
"""
from random import randint
grid = [[]]
for i in range(3... |
46661ff4fdeced4d8b095c95d50ae1d941b395ef | maxmyk/Lab6 | /one_month_calendar.py | 3,850 | 4.3125 | 4 | """
Module prints out calendars
"""
#from math import floor
"""
Importing floor function
"""
def weekday_name(number: int) -> str:
"""
Returns a string representing a weekday
(one of "mon", "tue", "wed", "thu", "fri", "sat", "sun")
number : an integer in range [0, 6]
>>> weekday_name(3)
'thu'... |
9abd108e7e72f6a0db7a2fcb2da64fbb97575d61 | conor-mcmullan/Scoring-Player-System | /scoring_system.py | 3,982 | 3.78125 | 4 | import thread
score_system = {}
def set_player_list(player_count):
score_system.clear()
for player in xrange(player_count):
score_system.update({chr(ord('a')+player): 0})
def print_scoreboard():
for key in sorted(score_system):
if key is sorted(score_system)[-1]: v = "%s: %s"
el... |
7dc735f3e33dbc3338b73bf2670d08105b0235a9 | davetheman23/tic-tac-toe | /src/algorithm/analysis/analyze_minimax.py | 2,752 | 3.984375 | 4 | import random
import time
from src.algorithm.minimax import MinimaxAlgorithm, Game
if __name__ == '__main__':
class Player:
def __init__(self, winning_reward):
self.winning_reward = winning_reward
def __str__(self):
return "'({}) Reward Player'".format(self.get_winning_r... |
48f89d0589870b44c3344573254252a2ba25c386 | abhishekv362/Neural-Networks | /Perceptron/Implementation.py | 2,991 | 3.640625 | 4 | import sklearn.datasets
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# importing animated_plot function from locally defined script animation.py
from animation import animated_plot
# Loading Data
... |
5fcb6c1685af9be8f68197cb97841db075567eab | talbotlawrence/python-lists | /planets.py | 697 | 3.65625 | 4 | planet_list = ["Mercury", "Mars"]
new_planets = ["Jupiter", "Saturn"]
for planet in new_planets:
planet_list.append(planet)
print(planet_list)
planet_list.extend(['Uranus','Neptune'])
print(planet_list)
planet_list.insert(1, 'Earth')
planet_list.insert(1, 'Venus')
planet_list.append('Pluto')
print(planet_list)
roc... |
4029bffb7e8bed71a9424781514b3cd034b274ef | jrm5100/advent-of-code-python | /2018/14/solution.py | 1,582 | 3.8125 | 4 | #!/usr/bin/python3
##############
# Load input #
##############
# Initialize data
board = "37"
elf1 = 0
elf2 = 1
##############
# Solution 1 #
##############
def next_10(board: str, elf1: int, elf2: int, prior_recipes: int) -> str:
"""Return the 10 scores appearing after the given number of scores"""
while ... |
27660bcbec2f6594fe780060305937becd596a51 | alieskici/Project-Euler | /problem_4.py | 560 | 3.8125 | 4 | """
Largest palindrome product
https: // projecteuler.net / problem = 4
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def P(a): return a == a[::... |
767458a5ce11bdbd468d5978350d526bff423a71 | ncullen93/pytorch | /torch/nn/modules/sparse.py | 9,363 | 3.671875 | 4 | import torch
from torch.nn.parameter import Parameter
from .module import Module
class Embedding(Module):
r"""A simple lookup table that stores embeddings of a fixed dictionary and size.
This module is often used to store word embeddings and retrieve them using indices.
The input to the module is a list... |
07c5d362279a97b82ea87639ceefc126938d9535 | bijayofficial/College_webDev | /college/class 6/uc_lc.py | 208 | 4.125 | 4 | a=input("enter the character")
if(a>'A' and a<='Z'):
print("upper case")
elif(a>'a' and a<='z'):
print("lower case")
elif(a>='0' and a<='9'):
print("number")
else:
print("Symbols") |
bc0237b5b7ad679068c608b10a522c79423ca44a | alexisfaison/Lab1 | /Programming Assignment 1.py | 1,021 | 4.1875 | 4 | # Name: Alexis Faison
# Course: CS151, Prof. Mehri
# Date: 10/5/21
# Programming Assignment: 1
# Program Inputs: The length, width, and height of a room in feet.
# Program Outputs: The area and the amount of paint and primer needed to cover the room.
import math
#initialize variables
width_wall = 0.0
length_wall = 0.... |
2ac182b1535d10f8f593f8cd188422a701e69311 | lkqllx/playground | /mental_math/generate_mental_math.py | 1,023 | 3.984375 | 4 | """This program was used to generate random math question for interview"""
import random
from docx import Document
from docx.shared import Pt
def generate_math_pdf(opt: str, num1_len: int , num2_len: int, path: str, font: int = 16):
document = Document()
obj_styles = document.styles['Normal']
obj_font = o... |
2ab4002e35104ba23e9497f98aa8077dce4b3c13 | Junnicesu/Leetcode | /python/SortSearch_q1(Merge2List)_sjRight_notPerfect.py | 1,087 | 3.65625 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if m == 0:
for id in range(n):
nums1[id] = nums2[id]
return
if n == 0:... |
7f8d1b677a0ac91d3432687c8a25fe752e876953 | Junnicesu/Leetcode | /python/linkedList_q4(Merge)_sjFirstAccepted.py | 1,235 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
newL = l1 if l1 else None
toMergeL = l2 if l2 else None
if n... |
7d1067ba034d7abf710a243062932b35adccceea | Junnicesu/Leetcode | /python/tree_q4(Symmetric)-reversed.py | 823 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
curRow = []
if root:
curRow = [ro... |
c108884a7e82a8867eedce7a63fe0cc5521eda7b | Junnicesu/Leetcode | /python/tree_q4(Symmetric).py | 1,263 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
curRow = []
if root:
curRow = [ro... |
04892d39e34d0f23002fc05201b6b7ece9fd4b36 | edwardday7/doubly-linked-list | /doubly_linked_list.py | 952 | 3.859375 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __repr__(self):
if self.head is None:
return "List... |
c566f5a501c3836a02acec1ecdbbdebad233eee3 | AAKANSHA773/Basic-of-python | /6.dictionary.py | 742 | 4.15625 | 4 | d2=dict()
print("empty dictionary",d2)
d1={}
print("empty dictionary repersant",d1)
d={'1':"one"}
print("key and value",d)
d3={'1':"one",'2':"two",'3':"third",'4':"string"}
print(d3)
d3['1']='100'#chnage the value of index one element
print(d3)
d3[1]=[1,2,3] #give value in the from of list
print(d3)
print("two" i... |
516c4850d92ba71e765e48f6523e1fd1b1bf064f | KarAbhishek/MSBIC | /BioInformatics/Week1/Frequent_Words.py | 790 | 3.59375 | 4 | import sys
def pattern_count(text, pattern):
count = 0
for i in range(len(text) - len(pattern) + 1):
if text[i:i + len(pattern)] == pattern:
count += 1
return count
def count_dict(text, k):
count = {}
for i in range(len(text) - k + 1):
pattern = text[i:i... |
cac06b6194b85f10a1b7de810ffc51d19c3e5167 | AndrewQTUD/PythonHome | /cars.py | 148 | 4.0625 | 4 | cars = ["Audi", "BMW", "Honda", "Toyota", "Subaru"]
for c in cars:
if c == "Honda":
print(c.upper())
else:
print(c.title()) |
6868db80d83090c0cbbf43857b748b846d2391bd | joelclaudio/pixelio-api | /application/logic/utils/coroutines.py | 233 | 3.640625 | 4 | import time
def waitseconds(seconds):
starttime = time.time()
print("I need to wait "+str(seconds))
while True:
yield None
diff = time.time() - starttime
if diff >= seconds:
return |
953dae9ca9e2123b1161d0743ccdc55881fb11cb | KangGwanwoo/PythonStudy_Basics | /000 fundamentais.py | 708 | 3.921875 | 4 | #!/usr/bin/env python3
import random
def good():
print("I had a good year")
def bad():
print("I had a bad year")
def main():
lifespan = 80
age = 1
good_year_count = 0
while age <= lifespan:
print("I'm {age} year(s) old".format(age=age))
goodyear = random.choice([True,False])
if goodyear:
good_ye... |
d7a6eefacfa6be25eaaac635ab2e235310644355 | KangGwanwoo/PythonStudy_Basics | /010 list comprehension.py | 334 | 3.734375 | 4 | #!/usr/bin/env python3
# list comprehension 배열 이해 ?
def main():
"""program entry point
"""
years_to_print = [str(y) for y in range(1800,2014,1)]
print(years_to_print)
print("\n\t")
print(" ".join(years_to_print))
print("=".join(years_to_print))
print("\t".join(years_to_print))
if __name__ == '__main__':
... |
482c3b26b07c452233468663698ed9e09ca8e487 | bennergarrett/learning_resources | /python/data_structs/data_struct_algorithms/arrays/anagrams_problem.py | 192 | 3.703125 | 4 |
##s is input
##t is what s is tested against for anagram
def anagram(s, t):
s=s.tolower().strip().replace(" ", "")
print(s)
if __name__ == '__main__':
anagram('dog', 'god')
|
f6ea2ece3af17c6f1b4d6bbdf1e2e226fdf5abbc | rpivo/leetcode-answers | /count-substrings-with-only-one-distinct-letter-24ms-14.2mb.py | 687 | 3.5 | 4 | # declare class Solution
class Solution:
# define function countLetters, which takes in the class instance (self), and a string named s,
# and returns an integer
def countLetters(self, s: str) -> int:
# create variable total and set it to 1
total = 1
# create variable count and set it to 1
count ... |
466cfcf36e5b0ddd618e2539e8c43727f11b7737 | rpivo/leetcode-answers | /sorting-the-sentence.py | 224 | 3.671875 | 4 | class Solution:
def sortSentence(self, s: str) -> str:
d = {word[-1]: word[:-1] for word in s.split(' ')}
d_sorted = dict(sorted(d.items()))
return ' '.join([word for word in d_sorted.values()])
|
f64a0f89fbfa33ffe23d86e6d91d95285dd9610d | rpivo/leetcode-answers | /check-if-word-equals-summation-of-two-words-2.py | 1,891 | 3.703125 | 4 | # define class Solution
class Solution:
# define function isSumEqual, which takes in the class instance (self),
# string firstWord, string secondWord, string targetWord, and returns a
# boolean.
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
# create dictionary v... |
815e01526a996439f32ab922e0132a47ed4eb078 | rpivo/leetcode-answers | /number-of-steps-to-reduce-a-number-to-zero-40ms-14mbv2.py | 1,042 | 3.859375 | 4 | class Solution:
# define function numberOfSteps, that takes in the class instance, and an int call num, and returns an int
def numberOfSteps(self, num: int) -> int:
# create a variable called count and initialize it to 0
count = 0
# the bin() method converts and returns the binary equivalent string of a... |
5cacacf3aca683b9bfaaffefff07e4bef474aee3 | rpivo/leetcode-answers | /split-a-string-in-balanced-strings-32ms-13.9mb.py | 985 | 3.84375 | 4 | class Solution:
# define function balancedStringSplit that takes in the class instance, a string called s, and
# returns an integer
def balancedStringSplit(self, s: str) -> int:
# create variable startChar and initialize it to the first character on string s
startChar = s[0]
# create a variable count... |
ac570cb036bc41d2dee4793c584568c3064b4522 | rpivo/leetcode-answers | /find-anagram-mappings-88ms-13.8mb.py | 476 | 3.828125 | 4 | class Solution:
# define function anagramMappings that takes in the class instance, a list of integers called A,
# a list of integers called B, and returns a list of intgers
def anagramMappings(self, A: List[int], B: List[int]) -> List[int]:
# using list comprehension, return a list. go through each item in ... |
4390ccb359c730c08efcf1aa81734723c82e820d | rpivo/leetcode-answers | /flipping-an-image-100ms-14.4mb.py | 750 | 3.578125 | 4 | # define class Solution
class Solution:
# define function flipAndInvertImage, which takes in the class instance (self), and a list of
# lists of integers called A, and returns a list of lists of integers
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
# create variable B and set it equal... |
28da6f12258b1a61bb715220f692c6430e214dae | rpivo/leetcode-answers | /remove-vowels-from-a-string-48ms-13.8mb.py | 387 | 3.65625 | 4 | class Solution:
# define removeVowels(), which takes in class instance and string S, and returns a string
def removeVowels(self, S: str) -> str:
# create ans, which is a list
# for single item c in string S, return c if c is not in the string 'aeiou'
ans = [c for c in S if c not in 'aeiou']
# return... |
bffc989252dd80ffd1f080899839788fb2f3d908 | ducdonghiem/ducdonghiem-fundamental-C4T4 | /Session06/turtle2.py | 237 | 3.796875 | 4 | from turtle import*
# speed(-1)
color("red")
for i in range(4, 10):
for j in range(i):
forward(100)
left(360//i)
if j%2==0:
color("blue")
else:
color("red")
mainloop()
|
6688f9571f10970d05462e63aec2913afb5cd68a | dexamusx/thPyCh2 | /thPyCh2.py | 3,751 | 4.6875 | 5 | import math
#Exercise 1
#Repeating my advice from the previous chapter, whenever you learn a new feature,
#you should try it out in interactive mode and make errors on purpose to see what goes wrong.
#We’ve seen that n = 42 is legal. What about 42 = n? How about x = y = 1?
#In some languages every statement ends w... |
008daedf6c0669bcb66ebe6f18608330e50f6c43 | ElomaaTapio/ot-harjoitustyo | /src/logic/gridlogic.py | 7,112 | 3.984375 | 4 | from random import randint
from logic.square import Square
class MSGrid:
"""Grid of Square objects that represents the game.
Functions for changing square values and calculating paths:
Attributes:
grid: Two dimensional set of dictionaries.
mines: Amount of mines the grid should contain.
... |
2cd022e6544fa69f92c9b8f671d99428aa7a08c4 | Yajie-Chu/cs242 | /Assignment2.0/New folder/Graph.py | 3,883 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
@author: aldos
"""
from Node import Node
import heapq
class Graph(object):
def __init__(self):
self.nodelist = []
self.edgelist = []
'''
Function that return nodelist
'''
def get_node(self):
return self.nodelist
'''
Function... |
4b4c476a8104d7cdce462a714f64de84f86d8d4d | osmya/codesignal | /rotateImage.py | 2,115 | 3.75 | 4 | #############
####LIKE#####
#############
# list comprehension like the most
def rotateImage(a): # did similar in data notebook
return [[x[i] for x in a][::-1] for i in range(len(a))]
# returns values from a reversed for index in range lenght of array (end-point)
# my origianl sol
def rotateImage(a): # i did no... |
2a3c218297777c33de172af8f6e6455cddddd9ab | vic30004/Youtube-Dowloader-Py | /app.py | 1,448 | 3.53125 | 4 | from tkinter import Tk, Button, Label, StringVar, Entry
from tkinter.filedialog import askdirectory
from tkinter import messagebox
from pytube import YouTube
# This is the interface
root = Tk()
root.title('Youtube Downloader')
root.configure(background="#333")
root.minsize(width=420, height=100)
# Main Functions
de... |
a1ccde3cf4bf92d7bd86e141e969744d1895c60b | vscalado/MySQL-with-Python | /SQLite/DB_SQLite3.py | 1,229 | 3.625 | 4 | import sqlite3
import time
import datetime
import random
conn = sqlite3.connect('tutorial1.db')
c = conn.cursor()
def create_table(): #Cria uma nova tabela no banco de Dados tutorial1.db
c.execute("CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)")
#A nova tabela tem o n... |
a9f9e683384aaba7d4d0c6c382dd6837a3399608 | BRETT-B/number_guess | /guessing_game.py | 861 | 3.546875 | 4 | import random
import subprocess
low = 1
high = 50
limit = 5
print("Guess a number between {} and {}".format(low, high))
print("You have {} guesses to get the correct number".format(limit))
number = random.randint(low, high)
current = 0
while current < limit:
current += 1
guess_number = int(input('What is your gue... |
673d84919b059bb2a928f03453d5256ec83f040c | n1lux/python_coding_studies | /poo/iterators.py | 506 | 4.0625 | 4 | """
Class as iterator, implement methods __iter__, __next__
"""
class Fibonacci:
"""
__iter()__ -> iter(instance)
"""
def __init__(self, max_iter):
self._max = max_iter
def __iter__(self):
self.x, self.y = 1, 1
return self
def __next__(self):
fib = self.x
... |
d7ac845319b598bd64e1a14deb59cf6447e45fcb | n1lux/python_coding_studies | /poo/metaclass.py | 573 | 3.703125 | 4 | """
instance -> class -> metaclass
MyClass = metaclass()
myobject = MyClass()
ex:
class MyClass(object):
var = True
MyClass = type('MyClass', (), {'var': True})
"""
class MyMetaClass(type):
def __new__(cls, clsname, superclass, attributedict):
print("clsname: ", clsname)
print("superclass: "... |
0f662c6750f4e56b67eb4c73f495dc70b96c1bf7 | pallavibhagat/Problems | /problem2.py | 376 | 4.4375 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The
sum of these multiples is 23. Write a program to find the sum of all the multiples of 3 or 5 below
1000.
"""
def multiple():
sum = 0
for i in range(1,1000):
if i%3==0 or i%5==0:
sum +=i
... |
51f65a2c204b11cadf8163ce5e7497f3978a0502 | naruephat/python | /2.1.py | 100 | 3.796875 | 4 | num1=input("first number\n")
num2=input('second num\n')
print("%s ="%num1,"%s : "%num2, num1==num2)
|
07fd949d9ae8443e209b340a80351efb3fc05f58 | Loud-Cat/FunctionBuilder | /MathWindow.py | 3,196 | 3.65625 | 4 | from matplotlib import pyplot as plt
from math import *
from tkinter import *
from tkinter.font import Font
pad = lambda x=10,y=10: {"ipadx":x, "ipady":y}
class Window():
def __init__(self):
self.title_t = self.func_t = ""
self.numbers = []
self.bad = None
self.... |
fe824dc7061a4bad577456c518720f5906e631f3 | AndroidUnissula/seri-belajar-python | /numbers.py | 243 | 3.734375 | 4 | a = 5
b = 3
c = 4.0
# penjumlahan
d = a + b
print("Penjumlahan a + b = ", d)
# pengurangan
d = a - b
print("pengurangan a - b = ", d)
# Perkalian
d = a * b
print("Perkalian a * b = ", d)
# Pembagian
d = a / b
print("Pembagian a / b = ", d) |
79b77f7ec6b7ec9b55433ef75ba2ce3c08b4b58d | razyesh/Chat-Application-with-Python | /client.py | 1,293 | 3.796875 | 4 | import socket
print('Client Server...')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #AF_INET = IPV4, SOCK_STREAM = TCP Protocol
"""
Here client and server are in same computer, so we use gethostname() function
"""
host = socket.gethostname() #return name of the server
ip = socket.gethostbyname(host) #r... |
2133af4c52bba08fd49755539e15512f1ee865e5 | DipakTech/Python-basic | /app.py | 2,827 | 4.15625 | 4 | # print('hello world')
# python variables
# one=1
# two=2
# some_number=1000
# print(one,two,some_number)
# booleans
# true_boolean=True
# false_boolean=False
# # string
# my_name='diapk'
# # float
# book_price=12.3
# print(true_boolean,false_boolean,my_name,book_price)
# if True:
# prin... |
835211b261a2bfdfd590cf85ec572a905f88c4e9 | danTaler/Python_examples | /lambda.py | 1,273 | 3.921875 | 4 | #------------------------------------------------------
# Example 1
#
people = [
{"name":"Harry", "house":"Gryffindor"},
{"name":"Cho", "house":"Rav"},
{"name":"Drac", "house":"Sly"}
]
def f(y):
return y["name"]
people.sort(key=f)
#print(people)
#----------------------------------------------------... |
563f66175fa4dd2ba4ca8fc54b04e56996be5232 | AlexF99/allPython | /small-projects/search-list.py | 758 | 4.09375 | 4 | # search list
minha_lista = [['alexandre', 'freitas'], ['alexandre', 'oliveira'], ['julia', 'paganelli'], ['andre', 'paganelli']]
def search_list_by_first_name(first_name):
for x in range(len(minha_lista)):
if (first_name in minha_lista[x][0]):
print(minha_lista[x])
def search_list_by_last_na... |
13296dedcf9a804255bc8827be21623016a88770 | AlexF99/allPython | /small-projects/TicTacToe/main.py | 2,497 | 3.703125 | 4 | #coding utf-8
# definitions
number_rows_columns = 9
score_to_win = 3
player_a_wins = ["X", "X", "X"]
player_b_wins = ["O", "O", "O"]
player_id = {"A": "X", "B":"O"}
matrix = [["?", "?", "?"],
["?", "?", "?"],
["?", "?", "?"]]
indic = range(len(matrix))
# actual code
def winner_checker... |
77f281e7a84bed50cdfc8c93eff00bd72067c29a | casseyshao/CSC190 | /lab5/graph_test.py | 1,535 | 4.0625 | 4 | # Lab 5
from graph import *
# testing
g = graph()
# test adding vertices
rVal = g.addVertex(5)
print("Number of vertices in graph:",rVal)
print("Initial graph:",g.store)
# test adding edges
g.addEdge(4,0,True,1)
g.addEdge(1,4,False,1)
g.addEdge(1,3,False,1)
g.addEdge(1,2,True,1)
g.addEdge(2,3,True,1)
g.addEdge(3,4,... |
937860591df5fd52058a7c8702c97c36db3bdb0e | vishukamble/Python-data-analysis | /Pandas/reIndexing.py | 816 | 3.90625 | 4 | # __author__ = Vishu Kamble
"""
A python program to learn reindexing
"""
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from numpy.random import randn
series = Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])
print "Series: ", series
series2 = series.reindex(['A', 'B', 'C', 'D', 'E', 'F... |
2fa88d7e8f016e6ca19b0aaebd240db673a28db6 | AMANKANOJIYA/Numerical-Method-Solution-Generator | /modified_eular.py | 881 | 3.515625 | 4 | def eular_mod(x,y):
function=x+y #you can change your function from here
return function
x_0=eval(input("Enter the value of X-0 :=> "))
y_0=eval(input("Enter the value of Y-0 :=> "))
find_y=eval(input("Enter the value of X_given :=> "))
itration=int(input("Number of itration if any else Type (0) :=> "))
def eu... |
11ec6fdef0a40e7231fc57fef60a5d22a0dbcf63 | kaungkyawkhant/pythonAlgorigthmlab | /kkStringEncryptor.py | 384 | 3.859375 | 4 | def getConvertedString(letter, key):
newLetter = ord(letter) + key
return chr(newLetter) if newLetter <= 122 else chr(96 + newLetter % 122)
def caesarEncryptor(string, key):
resultString = []
newKey = key % 26
for char in string:
resultString.append(getConvertedString(char, newKey))
re... |
a4ff54bc45f7980b66e286f4c48a563d9dc0b1f0 | mayank1304/udacity | /projects/datasets_questions/explore_enron_data.py | 4,340 | 3.78125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
594ecddbd2160fc5cfc4089cf682500df9fe4632 | DmytroObertan/University | /training.py | 1,131 | 3.609375 | 4 | from functools import wraps
from abc import ABCMeta, abstractmethod
class Base():
def foo(self):
print 'foo'
class Base1():
@staticmethod
def foo1():
print 'foo1'
class Papa(Base, Base1):
pass
if __name__ == '__main__':
l = Papa()
l.foo()
l.foo1()
# class Meta(type):... |
631e82cae23e6386bfda60b8c28ab046865df5c6 | DmytroObertan/University | /Algorithms/merge_sort.py | 685 | 4 | 4 | def mergesort(inp):
if len(inp) == 1:
return inp
middle = int(len(inp) / 2)
left = mergesort(inp[:middle])
right = mergesort(inp[middle:])
return merge(left, right)
def merge(left, right):
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] > righ... |
c7c9027bd91148ce05c8d2b82ec1b9ac03f4dba3 | ChrisLeeSlacker/GuessingGame | /Menu.py | 886 | 3.625 | 4 | # Imports
import sys
# Menu
def menu():
print('\n************MAIN MENU*************')
choice = input('''
A: 1-100
B: 1-10
C: NONE
Q: Quit
Please enter your choice: ''')
print('**********************************')
choice = choice.lower... |
7e1c940f14a416d061f96ef86de11218e87f4836 | demxic/Orgutrip | /model/city.py | 706 | 4.03125 | 4 | class Airport(object):
"""An Airport class holds valuable information to interact with
the 3-letter code cities defined by iata."""
def __init__(self, iata, name, short_name, country_code, country_name,
tz_region, viat_payscale):
"""
Provide all required fields to create an... |
6738485272ef0fb45bd370743fb026cced47ce7c | riichard-lii/HCPC | /Meeting 3/A.py | 1,409 | 3.671875 | 4 | record = input()
rank = 25
stars = 0
previous = False
streak = False
for i in record:
if i == 'W':
stars += 1
if rank > 5 and previous:
if streak:
stars += 1
else:
streak = True
else: previous = True
if 21 <= rank <= 25:
... |
2627aa4ca3c4eeb123bda1acac5f970273b42131 | micatron/name-generator | /name-gen.py | 932 | 3.828125 | 4 | #Random name generator
import random
def loadTable(letterType, characterTable):
#get specified csv and make a list
return(characterList)
def nameGen(consonants, vowels, characters):
startType = random.randint(0, 1)
#start consonant or vowel depending on startType
#alternate appending letters until... |
748b373f532ae1047f0e9011383bd624eb69ce07 | AlphaCoderX/MyPythonRepo | /Assignment 3/TempFinal.py | 1,716 | 3.703125 | 4 | #Programmer Raphael Heinen
#Date 2/2/17
#Version 2.0
import functions
data = []
file = open('temp.txt','r')
#opens and adds the text file to a list
def readTemps():
for temp in file.read().split():
data.append(float(temp))
return data
#calculates and returns average
def calcAvg(temp,... |
104fac3bec6c7975673715d7a3d2594d6d8e9d63 | AlphaCoderX/MyPythonRepo | /Assignment 1/RecipeConverter.py | 1,157 | 4.125 | 4 | #Programmer Raphael Heinen
#Date 1/19/17
#Version 1.0
print "-- Original Recipe --"
print "Enter the amount of flour (cups): ",
flour = raw_input()
print "Enter the amount of water (cups): ",
water = raw_input()
print "Enter the amount of salt (teaspoons): ",
salt = raw_input()
print "Enter the amount of yeast (teaspoo... |
dec24bf04a92e02f187765c622fbac04782eccb9 | sneaky-patriki/osiris-backend | /Submissions/20.0.py | 356 | 4.0625 | 4 | from math import pi
class Circle:
def __init__(self, centre, radius):
self.centre = centre
self.radius = radius
def circumference(self):
return 2 * pi * self.radius
def area(self):
return pi * (self.radius ** 2)
c = Circle((0, 0), 5)
print(c.radius)
print(c.centre)
print(... |
bf0cc81531e2074bad55da39c9529553a42c9115 | payaaaaaa/AAE-group-1 | /GroupLeader.py | 711 | 3.671875 | 4 | def function1(): print('function1') #To be edited by member 1, Replace this line with your actual function code
def function2(): print('function2') #To be edited by member 2, Replace this line with your actual function code
def function3(): print('function3') #To be edited by member 3, Replace this line with your... |
463fab4b59fd21609889666840b14b98e01a80bf | helloallentsai/leetcode-python | /1295. Find Numbers with Even Number of Digits.py | 958 | 4.21875 | 4 | # Given an array nums of integers, return how many of them contain an even number of digits.
# Example 1:
# Input: nums = [12,345,2,6,7896]
# Output: 2
# Explanation:
# 12 contains 2 digits (even number of digits).
# 345 contains 3 digits (odd number of digits).
# 2 contains 1 digit (odd number of digits).
# 6 conta... |
9e41e1520020e7de9211912b261eaebd0f88b90c | seekindark/helloworld | /python/py-study/testdict.py | 408 | 3.828125 | 4 | # {}
d = dict()
# {'a': 1, 'test': 'Monday', 'abc': 3}
d1 = dict(a=1, test='Monday', abc=3)
print(d)
print(d1)
# {'one': 1, 'two': 2, 'three': 3} 可迭代对象方式来构造字典
d3 = dict([('one', 1), ('two', 2), ('three', 3)])
print(d3)
# {'one': 1, 'two': 2, 'three': 3, 4: 4} 映射函数方式来构造字典
d4 = dict(zip(['one', 'two', 'thr... |
1934cd000cca0cbf14f5b286dbbf8c65fecc7f1f | seekindark/helloworld | /python/py-study/test-class-var.py | 1,515 | 4.125 | 4 | class A:
# x = [] # 定义在这里,表示类变量, 被所有实例化的对象公共使用
# y = 0
def __init__(self):
self.x = []
self.y = 0
pass
def add(self):
self.x.append('1')
self.y+=1
a = A()
a.add()
print("第一次示例化 CLASS A:")
print('a.x, a.y = ', a.x, ', ', a.y)
#print('A.x, ... |
6c0da654abdc01986b10d70f380f02b0f7800d29 | seekindark/helloworld | /python/py-study/testlist.py | 1,968 | 4.375 | 4 | #
# define a function to print the items of the list
#
def showlist(team):
i = 0
for item in team:
# end= "" will not generate '\n' automatically
print("list[%d]=%s" % (i, item), end=" ")
i += 1
print("\n-------------------")
team = ['alice', 'bob', 'tom']
print... |
3ca14e3cd76bd83933c6085e7cc8b95204382728 | ciscox83/secretsanta | /SecretSanta.py | 2,627 | 3.53125 | 4 | """
Created on 4 December 2016
@author: Christian Sisti
Given a list of Name -> emails it send email to each of the participants
of the Secret Santa telling the person to buy the gift.
"""
import csv
import copy
import random
import smtplib
from email.mime.text import MIMEText
from string import Template
EMAIL_FR... |
5d11ad07422ea06e78ba92503e7730c0c378e5fc | vix98sd/ID3_algorithm_prediction | /Tree.py | 824 | 3.546875 | 4 | from Node_type import Node_type
from Node import Node
class Tree:
def __init__(self):
self.__root = None
def get_root(self):
return self.__root
def set_root(self, node):
self.__root = node
def count_nodes(self, node):
if node is None:
return 0
... |
8a355df135b225638e29fec63264986d13d5a829 | Lindajeanph/Python_Projects | /Python_Projects/assignment4.py | 816 | 3.984375 | 4 | from abc import ABC, abstractmethod
class car(ABC):
def paySlip(self, amount):
print("Your purchase amount: ", amount)
@abstractmethod
def payment(self, amount):
pass
class DebitCardPayment(car):
def payment(self, amount):
print('Your purchase amo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.