blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
da2e163239f8f68490f9d875aee5f84fb7ae70dd | DaviSilva70/Python | /Exercicio_09.py | 685 | 4.3125 | 4 | ''' Faça um Programa que leia um numero inteiro qualquer e mostre sua tela a Tabuada '''
Numero = int(input('Digite Para Ver Sua Taboada: '))
print('_'*30)
print('{} x {:2} = {}'.format(Numero,1,Numero*1))
print('{} x {:2} = {}'.format(Numero,2,Numero*2))
print('{} x {:2} = {}'.format(Numero,3,Numero*3))
print('{... |
585d38fc8d5a14492b9f325ce782ac3c670b0aeb | jingxiufenghua/algorithm_homework | /leetcode/leetcode872.py | 941 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :algorithm_homework
@File :leetcode872.py
@IDE :PyCharm
@Author :无名
@Date :2021/5/10 15:42
'''
from typing import List
# 872. 叶子相似的树
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
... |
02625f09bfa2b593a05a1fdcf58b7fdf5b0950cc | Robson75/Exercism | /robot_name.py | 827 | 3.9375 | 4 | import string
import random
robot_names = set()
class Robot:
ROBOT_NAME_LETTERS = 2
ROBOT_NAME_NUMBERS = 3
def __init__(self):
self.name = ""
self.create_new_name()
def create_new_name(self):
upper_alphabet = string.ascii_uppercase
naming_successful = False
w... |
8ca46435e333b77b1493096a03951516ee8b8b98 | singhdhananjay/TestRepo | /Demo/Generator.py | 491 | 3.859375 | 4 | import time
# myList=[x**2 for x in range(10)]
# disctionary ={x: x+1 for x in range(0, 2)}
# print(myList)
def First():
print("First")
def Second():
print("Second")
def Third():
print("Third")
def Gen():
First()
yield
Second()
yield
Third()
# for x in Gen():
# pass
# var=Gen()... |
da91e59358b9ffd3dd092fada854e905fbc7a295 | MrJapa/List-Queue-Stack | /__pycache__/queue.py | 1,295 | 4.21875 | 4 | from time import sleep
class Queue:
def __init__(self):
self.elements = []
def enqueue(self, data):
self.elements.append(data)
return data
def dequeue(self):
return self.elements.pop(0)
def rear(self):
return self.elements[-1]
def front(self):
return self.elements[0]
def is_empty(self):
return... |
42dfbdf860d02bf9cfc1473823926dc52b91b24b | waltr21/BandPanel | /Square.py | 2,406 | 3.6875 | 4 | import random
class Square:
def __init__(self, w, h, c, p):
# Top left x/y coordinates of the square.
self.x = random.randint(0,p.width)
self.y = random.randint(0,p.height)
# Dimensions of the square
self.width = w
self.height = h
# Reference to the panel o... |
700330a45909d295f8782464b3463e6764590ebf | dikshaa1702/ml | /day7/Day_07_Code_Challenge.py | 2,767 | 3.609375 | 4 | """
Code Challenge
Name:
Student and Faculty JSON
Filename:
student.json
faculty.json
Problem Statement:
Create a student and Faculty JSON object and get it verified using jsonlint.com
Write a JSON for faculty profile.
The JSON should have profile of minimum 2 faculty members.
The... |
f02818ec0ed8ec61986d18cddfda76a69117639d | pisskidney/leetcode | /medium/61.py | 1,136 | 3.796875 | 4 | #!/usr/bin/python
from typing import Optional
"""
61. Rotate List
https://leetcode.com/problems/rotate-list/
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getlen(root: ListNode) -> int:
n = 1
p = root
while p.next:
n += 1
... |
da2d8244b7b8f3b28f1713047eacd7649cdf404c | alexeib2014/Tests | /CodingPuzzle/puzzle.py | 4,430 | 3.796875 | 4 | DEBUG = False
class PuzzleSolver(object):
WORDS = ['OX', 'CAT', 'TOY', 'AT', 'DOG', 'CATAPULT', 'T']
def is_word(self, word):
"""
Returns true of word is in the dictionary, false otherwise.
"""
return word in self.WORDS
def log(self, message):
"""
Show me... |
82f41dcec66b4fe078a1a2d67b92f33fbdab956a | aish2028/M_4 | /ex3.py | 289 | 3.9375 | 4 | def cast_vote(age):
assert age>=18,"Age should not be <18,it was:{age}"
print("thank you for voting....")
try:
age=int(input("enter the age:"))
cast_vote(age)
except AssertionError as a:
print(a)
else:
print("you entered valid age...")
finally:
print("End....") |
b287530b7bf4a584f49a1cdffcb861fd186b2e76 | Jinnzenn/MLprojects | /[course] Machine Learning by Andrew Ng/1 LinearRegression/gradientDescent.py | 1,008 | 3.796875 | 4 | import numpy as np
from computeCost import *
def gradient_descent(X, y, theta, alpha, num_iters):
m = y.size #样本数
J_history = np.zeros(num_iters) #每一次迭代都有一个代价函数值
for i in range(0, num_iters): #num_iters次迭代优化
theta=theta-(alpha/m)*(h(X,theta)-y).dot(X)
J_history[i] = compute_cost(... |
caf6ad8b99e8456c0dadb21f390b026af41ad95d | CaizhiXu/LeetCode-Solutions-Python-Weimin | /0142. Linked List Cycle II.py | 1,219 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# method 2
# without using extra space, time O(n), space O(1)
class Solution2(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ... |
42dd7e48d21ecf750ae7f3b878d67493444fb81f | zoepan00/DSCI_522_group-314 | /src/dl_xls_to_csv.py | 1,286 | 3.65625 | 4 | # author: Elliott Ribner
# date: 2020-01-20
'''This script take a url and downloads a csv in the data directory. You should input url that is of .xls type.
Has default url value of default credit dataset if you do not send the url param as a command line argument.
Override the default by sending in a url like exempli... |
ea333af03875c5a59a6184ed8fb50b25da4a3541 | Zoe0123/K-Nearest-Neighbor-and-Cross-Validation | /knn.py | 3,763 | 3.546875 | 4 | from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
SEED = 36
def load_data(real_news_path: str, fake_news_path: str) -> tuple:
"""Loads files in <re... |
797e29c2b1756195f571361aee6c6acfe1ff7bcb | jerrylance/LeetCode | /922.Sort Array By Parity II/922.Sort Array By Parity II.py | 1,970 | 3.75 | 4 | # LeetCode Solution
# Zeyu Liu
# 2019.5.5
# 922.Sort Array By Parity II
from typing import List
# method 1 O(n)space, one pointer, even和odd分别作为索引迭代
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
res = [0] * len(A)
even = 0
odd = 1
for i in A:
... |
e37278d8e5bc4ede5dbaeb6069ed5f3c209c6134 | noisebridge/PythonClass | /guest-talks/20180430-concurrency/yielding.py | 617 | 3.578125 | 4 | def push_and_print(q):
while True:
x = (yield)
if x == '':
return
print('push_and_print: {}'.format(x))
q.append(x)
q = []
p = push_and_print(q)
try:
# p has to be primed in order to advance to the first `yield`
p.send(None)
print(q) # []
p.send('a') #... |
1f46ce3b54efb40f17ce59654b270d13a71a2b96 | p1x31/ctci-python | /yandex/yandex_43412_ml/isdisjoint_a.py | 328 | 3.75 | 4 | def is_quest_possible(n, quests):
npc_set = set(range(n))
quest_set = set(quests)
if npc_set.isdisjoint(quest_set):
return True
else:
return False
# Example usage
n = int(input())
quests = list(map(int, input().split()))
if is_quest_possible(n, quests):
print("Yes")
else:
pri... |
6223117ee8da5fbc60047bc79cce4e34e55ed615 | allwak/algorithms | /Sprint13/Theme2_Reursions/2j.py | 1,102 | 3.625 | 4 | # 0
# 01
# 0110
# 01101001
# 0110100110010110
# 01101001100101101001011001101001
#%%
def search(n, k):
if n == 1: # "0"
return "0"
if n == 2: # "01"
if k == 1:
return "0"
else: # k == 2
return "1"
if k <= 2 ** (n-2):
return search(n-1, k) # если k в... |
a3495a1146413dfc124d388ec4a36a1b1d30eab8 | MindaugasJ88/Python | /Words_guessing_game.py | 3,626 | 4.21875 | 4 | # WORDS GUESSING GAME
# User will be guessing the letters of words and will have total 6 wrong attempts
# If user guesses the words within 6 wrong attempts - he wins, if not - loses
# Words will be selected randomly from the list
# User will be able to play again, and the words from the list will not repeat
imp... |
bbe0a8c069b05e3713275d431fa5e392a1868652 | 5pence/chunks2 | /mean/mean.py | 641 | 4.0625 | 4 | """Write a function that takes a sequence of items and returns the running average, so for example this:
running_mean([1, 2, 3])
returns:
[1, 1.5, 2]
You can assume all items are numeric so no type casting is needed.
Round the mean values to 2 decimals (4.33333 -> 4.33). See the tests for more info.
Do use a functio... |
4a50ab5778200e8d1068694c87cbcee4ea5aa2d6 | levineol/MIS304 | /circle copy.py | 484 | 3.65625 | 4 | #Class header
PI = 3.14
class Circle:
#Define __init__
def __init__(self):
#Define attributes
self.radius = 1
self.color = "Blue"
self.border = 1
#Define calc_area method
def calc_area(self):
area = PI * self.radius**2
return area
#Define calc_circ... |
11476afc5b1c8382cca5e84bd1e848b9f3d4d156 | vishrutkmr7/DailyPracticeProblemsDIP | /2022/12 December/db12202022.py | 637 | 3.859375 | 4 | """
Given an array of integers, nums, every value appears three times except one value which only appears
once. Return the value that only appears once.
Ex: Given the following array nums…
nums = [1, 2, 2, 2, 3, 3, 3], return 1.
Ex: Given the following array nums…
nums = [3, 3, 2, 5, 2, 2, 5, 3, 9, 5], return 9.
"""... |
ae87f452512c0848501a62ddceac5e6030962a11 | mmhkhan/hackerrank_codes | /ProgrammersDay.py | 319 | 3.578125 | 4 | year = int(input().strip())
if year<1918:
if year%4==0:
s = '12.09.'+str(year)
else:
s = '13.09.'+str(year)
elif year==1918: s='26.09.'+str(year)
else:
if year%400==0 or (year%4==0 and year%100!=0):
s = '12.09.'+str(year)
else:
s = '13.09.'+str(year)
print(s) |
327809d36cd134c2db8fd69a9dfcfffc0bf7ad70 | Kayvee08/Algorithms-Python | /Sieve_of_Eratosthenes.py | 1,126 | 4.0625 | 4 | #The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million
'''at the beginning we write down all numbers between 2 and n. We mark all proper multiples of 2 (since 2 is the
smallest prime number) as composite. A proper multiple of a number x, is a num... |
cb518747ddc8dcad26105663c581e088841e373c | ijhajj/Django-RestApi-Celery-RabbitMQ-Redis | /django15_project/my_django15_project/queueProdCons.py | 1,658 | 3.703125 | 4 | import threading
import time
import queue
import random
_queue = queue.Queue(10)#declared a Queue with max size of 10
# As inbuilt queue DataStructures is used all conditional checks will no longer be required
#MAX_ITEMS = 10
#condition = threading.Condition()
class ProducerThread(threading.Thread):
def run(self... |
64393d7f05416372b71c29a925431607541aba28 | mrmukto/Python-Practise | /compare.py | 306 | 3.6875 | 4 | nimberofdegit = 0
numofchracter = 0
textt = input()
for x in textt:
x = x.lower()
if textt >= 'a' and textt <= "z":
numofchracter = numofchracter +1
elif (textt >= '1' and textt <= '9'):
nimberofdegit = nimberofdegit + 1
print(numofchracter)
print(nimberofdegit)
|
4409e26ba840b41b62d7f90ac39d54076f04cee6 | ksayee/programming_assignments | /python/CodingExercises/DailyCodingProblem-70.py | 724 | 3.953125 | 4 | '''
This problem was asked by Microsoft.
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number.
For example, given 1, you should return 19. Given 2, you should return 28.
'''
def DailyCodingProblem70(n):
st=10
cnt=0
fnl_lst=[]
wh... |
602009d75835f64896cb7c42c199d2aef4c43154 | coddingtonbear/python-measurement | /measurement/measures/electromagnetism.py | 2,284 | 3.59375 | 4 | from measurement.base import AbstractMeasure, MetricUnit
__all__ = [
"Capacitance",
"Current",
"ElectricPower",
"Inductance",
"Resistance",
"Voltage",
]
class Capacitance(AbstractMeasure):
farad = MetricUnit("1", ["F", "Farad"], ["F"], ["farad"])
class Current(AbstractMeasure):
ampe... |
25360cdf85c66033734f55cd54914cec55693e9e | pirent/python-playground | /automate_stuffs/chapter5/fantasy_inventory.py | 638 | 3.9375 | 4 | def displayInventory(inventory):
total = 0
print('Inventory:')
for k,v in inventory.items():
print(str(v) + ' ' + k)
total += v
print('Total number of items: ' + str(total))
def addToInventory(inventory, addedItems):
for item in addedItems:
current = inventory.setdefault(item, 0)
inventory[it... |
6959de82ae327f4d489fa73b8420a33c95ab28db | fardeen9983/Ultimate-Dux | /Languages/Python/Basics/GettingStarted/user_input.py | 359 | 4.34375 | 4 | # Take input from user to perform some operation
# Take string input
name = input("Enter name\n")
print(name)
# For any other type of data like integers cast the input method's output to desired type
age = int(input("Enter age\n"))
print("Age : ", age)
# For decimal values use float instead of int
print(f... |
9d169cc1ead97b8003e5c606c778de315d3c3d5d | snehasumare/Assignments_02_05_2021 | /restaurant_bill.py | 170 | 3.890625 | 4 | bill_amount = int(input("Enter Bill amount:"))
gst_percent = float(input("Enter gst percent:"))
total_bill = bill_amount + (bill_amount*gst_percent/100)
print(total_bill) |
6d4df067c431c230e1c03cd01fd033efb4eba39f | ARC-Computer-Science-Club/Code-Review | /Project_Euler/Pine/Problem_3.py | 628 | 3.578125 | 4 | # largest prime factor of the number 600851475143
# Person addition: Must work with any given int
from math import *
NUM = 600851475143
MAX = trunc(sqrt(NUM)) # largest possible factor of the given number
factor = []
factor2 = []
maxPrime = 2
isPrime = True
for i in range(2, MAX):
if NUM % i == 0:
factor.... |
ae73d6bf144765163749904a49a317d9a5b2d43c | chandanbrahma/Linear-regression | /Salary_Data.py | 1,458 | 4.09375 | 4 | ## importing data
import pandas as pd
data= pd.read_csv('E:\\assignment\\simplelinearregression\\Salary_Data.csv')
data.head()
data.info()
data.describe()
## so we do have 2 columns with 30 rows and we need to predict the salary hike
import matplotlib.pyplot as plt
##ploting the dependent variable
plt.h... |
64b9fb900ef32b855f310f5184aecdbf12ffe730 | fly2rain/LeetCode | /fraction-to-recurring-decimal/fraction-to-recurring-decimal.py | 1,874 | 3.78125 | 4 |
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
def abs(num):
return num if num > 0 else -num
def fractionUnder1(numerator, denominator):
if... |
79d5d5ef0a51ed70cd053648d70baa192cb70bc7 | hamza-yusuff/Python_prac | /python projects/sum prime.py | 474 | 3.703125 | 4 | def primebetter2(n):
if n%2==0:
return False
else:
maximum=n**0.5+1
for x in range(3,int(maximum),2):
if n%x==0:
return False
break
else:
return True
def divisor(n):
dev=[]
for k in range(1,n+1):
if n%k==0:
dev.appen... |
71b33adae26b24a967f66abd27caa8d9dec9f6f1 | mrucal/PTC | /Sesiones/ST1/persona.py | 1,847 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 4 13:57:27 2017
@author: Mario
"""
class Persona:
def __init__(self, nombre, apellido, nacimiento, fallecimiento = (-1,-1,-1), domicilio=''):
self.nombre = nombre
self.apellido = apellido
self.nacimiento = nacimiento
self.fallec... |
6203ad93e382d511275b35754fec57207504d8b6 | jonathansilveira1987/EXERCICIOS_ESTRUTURA_SEQUENCIAL | /exercicio4.py | 449 | 3.53125 | 4 | # 4. Faça um Programa que peça as 4 notas bimestrais e mostre a média.
# Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01
media1 = float(input("Digite a primeira média: "))
media2 = float(input("Digite a segunda média: "))
media3 = float(input("Digite a terceira média: "))
media4 = float(input("Digite a ... |
91d6bbcbd0fbf686eaa86a0401c77e829e6c398b | ssumitk14/python-OOPs | /Inheritance.py | 429 | 3.65625 | 4 | class Dog:
def __init__(self,name,age):
self.name = name
self.age = age
def speak(self):
print("Bark")
def justPrint(self):
print("Printing from Parent Class")
class Cat(Dog):
def __init__(self,name,age,color):
super().__init__(name,age)
self.color = co... |
78bec07654ede0247da80a2c7743651dcc88d9c5 | bluvory/Com_programming1 | /midterm/0327_3.py | 366 | 3.75 | 4 | a = 10
b = 5
a += 100
b **= 3
print(a)
print(b)
x = 6
y = 8
print("6 > 8 ?", x > y)
print("6 = 8 ?", x == y)
print("6 != 8 ?", x != y)
print("안녕" * 10)
if x % 2 == 0:
print(x, "짝수이다")
else:
print(x, "홀수이다")
number = int(input("세 자리 정수를 입력하시오"))
n1 = number // 100
n2 = number % 100 // 10
n3 = number % 10... |
969f81fffd179773259451a93a641e08aa8d45d6 | harikrishna-vadlakonda/Patterns | /Alphabet N.py | 479 | 3.9375 | 4 | for row in range(6):
for col in range(6):
if row in {0,5} and col in {0,5}:
print('*',end=' ')
elif row==1 and col in {0,1,5}:
print('*',end=' ')
elif row ==2 and col in {0,2,5}:
print('*',end=' ')
elif row == 3 and col in{0,3,5}:
... |
3b8abd73c537c0d17fea2dec63dd0a1cfd241815 | martin-martin/nlpython | /exercises/identity.py | 4,878 | 4.71875 | 5 | # The __init__() function
# so in the last exercise we created this class planet. And based on this
# class, we created an object , which had all these attributes and a method
# as well. But we said if we created a new instance, it would have all the same
# property values.
# So what's the point of creating multip... |
6aa8e43724deffe8c2f3b71671fff664b834bc75 | DylanJones/othello | /oldstuff/ai_bad.py | 8,358 | 3.90625 | 4 | #!/usr/bin/env python3
"""
This module contains the various decision making functions.
"""
from helpers import *
from heuristics import score
from random import choice, shuffle
import time
def random(board, color):
"""Make a random move."""
moves = legal_moves(board, color)
return choice(moves)
def huma... |
5521365b4642e8079f89ccccad65a9b2cb8ed738 | ArturSkrzeta/Object-Oriented-Design-with-UML-and-Python-Implementation | /course_project/address.py | 347 | 3.6875 | 4 |
class Address():
def __init__(self, id, country, city, street, postal):
self.id = id
self.country = country
self.city = city
self.street = street
self.postal = postal
def __repr__(self):
return f"Address '{self.id}' -> {self.country}, {self.city} {se... |
37d7b94d22f4d1a9b53accdc5c444a749500adfd | karthikpalavalli/Puzzles | /leetcode/average_levels_in_binary_tree.py | 930 | 3.78125 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
return []
current_no... |
43f8bcbb7f603bd3f867b7d5caf930b8cdfdb2d7 | emredog/cs231n | /assignment1/cs231n/classifiers/softmax.py | 4,642 | 3.875 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X:... |
4907df3ff4dbe887700088a5fe9abe37cff7d708 | tronje/GWV | /04/searching/searching.py | 3,251 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
"""Various search functions
"""
def bfs(env, start, goal='g', wall='x'):
"""Breadth first search, starting at `start`, ending at `goal`.
Params:
-------
env : list
2-D list representing the PlayingField to be searched
shall c... |
ccf6a2a6e9c3488ffd61933b7c4ee006445a98ff | EricHenry/practice_projects | /python/udemy/4-iteratorChallenge.py | 572 | 4.34375 | 4 | # create a list of items (you may use strings or numbers in the list),
# then create an iterator using the iter() function.
#
# use a for loop to loop "n" times, where "n" is the number of items in your list
# each time round the loop, use next() on your list to print the next item.
#
# hint: use the len() function rat... |
e6592728ae776dcfc4107e38cad1fd55d8b5df46 | 553672759/xxgit | /python/old/exercise/0012.py | 748 | 3.59375 | 4 | #coding:utf8
'''
Created on 2017-1-11
@author: xx
第 0012 题: 敏感词文本文件 filtered_words.txt,
里面的内容 和 0011题一样,当用户输入敏感词语,
则用 星号 * 替换,例如当用户输入「北京是个好城市」,
则变成「**是个好城市」。
'''
import re
def checkwords(ipstr):
word_list=[]
with open('filter_words.txt','r') as f:
for line in f:
word_list.append(line.str... |
5fdbd8a73f6166c8e51528ed20377b4dd0f0e4ac | lindameh/cpy5p4 | /q6_compute_sum.py | 133 | 3.59375 | 4 | def sum_digits(n):
if n // 10 == 0:
return n
else:
return n % 10 + sum_digits(n//10)
print(sum_digits(234))
|
3dd9503fc612276ffbdcc76cc39a772ec6d72134 | knking/JumbleWord | /JumbleWord.py | 1,485 | 3.734375 | 4 | import tkinter
from tkinter import *
import random
from tkinter import messagebox
from random import shuffle
answer=["google","facebook","instagram","book","krishna","yellow","king","chicken","fruits","june","king"]
words=[]
for i in answer:
word=list(i)
shuffle(word)
words.append(word)
num=random.ra... |
6ef8aeeb69228294663377daa8added5bd261cc7 | alanduda/python-solutions | /URI/Iniciante/Produto Simples.PY | 96 | 3.5 | 4 | number1 = int(input())
number2 = int(input())
PROD = number1 * number2
print(f'PROD = {PROD}')
|
e6a63d72456f2dd7eaf5bfcb1369068c6f2aea62 | StuartSpiegel/Trixie-1.3-0 | /colorRange.py | 1,241 | 3.890625 | 4 | from random import random
# Generates a random String representing a color in HEX
# def generateRandomColorHex():
# number_of_colors = 8
# color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
# for i in range(number_of_colors)]
# print(color)
# return color
# This block shows a chart for te... |
d141339186397fdf323cb61e176b065f6e6c7321 | z-torn/tornconsole | /window.py | 3,049 | 4.09375 | 4 | """
Main Window class definition that is parent of other windows
within the app
"""
import curses
import time
class Window:
h = None
w = None
y = None
x = None
def __init__(self, main, name, h, w, y, x):
self.name = name
self.window = curses.newwin(h, w, y, x)
self.main = ... |
0324aa547e2821c715030b3f15d5d6a87c1071bf | NazGy/csc401_A3 | /code/a3_levenshtein.py | 4,944 | 3.515625 | 4 | import os
import numpy as np
dataDir = '/u/cs401/A3/data/'
def Levenshtein(r, h):
"""
Calculation of WER with Levenshtein distance.
... |
eef4284a619ffc54d8ca328198dfe859ac1d9c10 | aistoume/Leetcode | /AnswerCode/515FindLargestValueinEachTreeRow.py | 950 | 3.90625 | 4 | ### Youbin 2017/06/29
### 515 Find Largest Value in Each Tree Row
# 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 largestValues(self, root):
if root==None:
return []
que = deque([[root, 0... |
7ff4eedd60e3eba4bf491cb83ffd65605042d5ea | ankitak2016/CPE123 | /Lab6/vigenere_decryption.py | 1,316 | 3.71875 | 4 |
def main():
f = open("vigenere_test.txt")
plaintext = f.readline()
numkeychar = 0
key = "turing"
finalcipher = ""
for a in plaintext:
finalcipher = finalcipher + caesar_decrypt(a,key[numkeychar])
if(not (ord(a)>=65 and ord(a)<=90 or ord(a)>=97 and ord(a)<=122)):
cont... |
ab89a906aedbe8bcde3b3d90422513a2ce7026bf | efecntrk/python_programming | /unit-2/guessgame.py | 986 | 4.375 | 4 | '''
#guessing game
-get a random number between 1 and 10
-prompt the user for to guess the number-
-loop while the user guess is not equal to your number
if the users guess is less than the number print 'too small'
if the users guess is greater than the number print'too big'
= print 'you are correct when the u... |
4faca1a50d72f532e1a3f771d7480e5ae31e89f0 | obarquero/deep_learning_udacity | /softmax.py | 974 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 28 14:21:31 2016
Softmax exercise:
Wikipedia definition: In mathematics, in particular probability theory and
related fields, the softmax function, or normalized exponential,[1]:198 is a
generalization of the logistic function that "squashes" a K-dimensional vector
\ma... |
94e4ef5b0ea0de0c0745b9f14c46ba5ba8edf329 | kacpertopol/kacpertopol.github.io | /start/pl/010_Nauczanie/003_Algebra_i_Geometria/002_Zestawy_zadań/001_Zestaw_1/dual.py | 3,297 | 4 | 4 | #!/usr/bin/env python3
# klasa implementująca liczby dualne
#
# Dual(a , b) <-> a + b * epsilon
class Dual:
def __init__(self , one , epsilon):
self.one = one
self.epsilon = epsilon
def __add__(self , other):
if(isinstance(other , Dual)):
newone = self.one + other.one
... |
e72fccb616badf3441c1859d188699f9fb41c2fb | guotaosun/dcn_rem | /dcngui.py | 1,225 | 3.609375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we create a simple
window in PyQt5.
author: sungt
last edited: January 20200403
"""
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __... |
5475d7f0a8206f59cf6cb67961dab3db1e72b55d | piyush09/LeetCode | /Basic Calculator II.py | 1,949 | 3.859375 | 4 | """
Algo: Iterate through the string and use stack to calculate all the in between values.
Calculate between values such as product, division, negative numbers and positive numbers.
Maintain sign in order to operate it on the next numeric character value.
Append them into the stack, which could be sum... |
5182737722a0d9c6cc35da8b0ee8c6296bf01365 | saviaga/BinaryTrees | /transpose-matrix/transpose-matrix.py | 561 | 3.609375 | 4 | import numpy as np
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
#x axis - > y axis
#. [0,0] [0,1][0,2] [0,0][1,0][2,0]
# [[1,2,3], [[1,4,7],
# [4,5,6], [2,5,8],
# [7,8,9]] [3,6,9]]
#
cols = len(A[0])
... |
efde0daa9f5034326efd4dfa26e693c694e15736 | Dragon631/Python_Learning | /Built-in module/pickle_module.py | 782 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pickle
str = "Hello world!"
# pickle.dumps 返回一个序列化后的对象,作为字节对象bytes objects
pkd = pickle.dumps(str)
print(pkd)
# pickle.loads 序列化数据转成字符串
pkl = pickle.loads(pkd)
print(pkl)
# pickle.dump 序列化对象,并将其写入文件对象中
# f = open('pkdFile.txt', 'wb')
# pickle.dump(str, f)
# f.clo... |
22a77f736a0b59fc7d0af7750ac1372cd0711fbc | suxin1/Algorithm | /Python/optimization/dynamic_programing/test_knapsack.py | 2,002 | 3.65625 | 4 | import random
import time
from knapsack_problem import Item, solve, fast_solve, greedy, value, weightInverse, density
def buildItems():
names = ['clock', 'painting', 'radio', 'vase', 'book', 'computer']
vals = [175, 90, 20, 50, 10, 200]
weights = [10, 9, 4, 2, 1, 20]
items = [Item(names[i], vals[i], w... |
a708b4695c8a7819cd8abf00e73f91a986c5646e | MagdalenaSvilenova/Programming-Basics-Python | /Conditional Statements Advanced/For-Loop/Left and right sum.py | 262 | 3.625 | 4 | n = int(input())
left = 0
right = 0
for i in range(n):
left += int(input())
for i in range(n):
right += int(input())
if left == right:
print(f'Yes, sum = {left}')
else:
diff = abs(left - right)
print(f'No, diff = {diff}')
|
5da56bc52d63fb4b98f6ba703d50e946e8437751 | kzh980999074/my_leetcode | /src/List/18. 4Sum.py | 1,428 | 3.90625 | 4 | '''
iven an array nums of n integers and an integer target, are there elements a, b, c, and d
in nums such that a + b + c + d = target? Find all unique quadruplets
in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2... |
61e64d170c7e9835dc270c4e0757079494860f05 | brisa-araujo/final-project-NLP | /01_Code/01 Data Cleaning.py | 14,208 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import re
import string
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
# In[2]:
#function to label encoding a column based on a dictionary
def classifier(s, dictionary):
for k, v in dictionary.items():
if s in v:
... |
740ec2b2458ce74785cf1d2583f5bef639026d18 | MDBarbier/Python | /TextAdventure/game_controller.py | 1,374 | 3.5625 | 4 | #!/user/bin/python3
import HelperFunctions
import dice
from pprint import pprint
def start_game():
HelperFunctions.new_line(1)
print('Welcome to the TAG (Text Adventure Game)')
HelperFunctions.new_line(2)
name = HelperFunctions.get_name()
HelperFunctions.new_line(1)
character = roll_character(... |
80036981e6ee22a76be0b7057333976fd40a8d80 | bakuganin/python | /Python/If/all.py | 5,864 | 3.953125 | 4 | #1
print("Введите 2 числа:")
x = int(input())
y = int(input())
if x > y:
print(x)
else:
print(y)
#2
print("Введите число:")
x = int(input())
if x > 0:
print(1)
elif x < 0:
print(-1)
else:
print(0)
#3
print("Введите 4 различных числа:")
x1 = int(input())
x2 = int(input())
y... |
68b2247802f916167b98a453838ac97e9ca665ef | Kevin202044956/CS1110 | /bmr.py | 94 | 3.515625 | 4 | grade_book = {}
grade_book['grade'] = list()
grade_book['grade'].append(3)
print(grade_book) |
f6e902fe56fe90d79dcb3977723db2f7046d4077 | kidkoder432/scripts | /Python/friendtest.py | 1,089 | 3.890625 | 4 | #friendliness test - how friendly are two people?
while True:
ci = 0
person1 = input('What is your name? > ')
person2 = input('What is your friend\'s name? > ')
print('Now we look at your interests. Enter these as words followed by spaces. For example, "reading math science"')
p1interests = ... |
ede95d60db181fe26d45187a088643bde65c27e2 | vigith/Code4Fun | /Project-Euler/p30.py | 1,017 | 3.640625 | 4 | # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
# 1634 = 1^(4) + 6^(4) + 3^(4) + 4^(4)
# 8208 = 8^(4) + 2^(4) + 0^(4) + 8^(4)
# 9474 = 9^(4) + 4^(4) + 7^(4) + 4^(4)
# As 1 = 1^(4) is not a sum it is not included.
# The sum of these numbers is 1... |
94f6eb78515bac25042bfb7a21563ec1bba8beb3 | adharmad/project-euler | /python/4.py | 578 | 3.875 | 4 | # A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 x 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
#
# https://projecteuler.net/problem=4
import string, sys
import commonutils
def main():
largest... |
e72b912e96b4fef88bdbfb1be8e8665618ee5c62 | elfgzp/Leetcode | /49.group-anagrams.py | 1,658 | 3.765625 | 4 | #
# @lc app=leetcode.cn id=49 lang=python3
#
# [49] 字母异位词分组
#
# https://leetcode-cn.com/problems/group-anagrams/description/
#
# algorithms
# Medium (53.98%)
# Total Accepted: 14K
# Total Submissions: 25.5K
# Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
#
# 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
#... |
3cd1c118bf650ec078744f60f2ab659f7e62d300 | ali4413/MCL-DSCI-511-programming-in-python | /exercises/exc_02_26.py | 522 | 3.765625 | 4 | import pandas as pd
pokemon = pd.read_csv('data/pokemon.csv', index_col=0)
pokemon = pokemon.loc[ : , 'attack': 'type']
# Make a groupby object on the column type
# Find the mean value of each column for each pokemon type using .mean()
# Save the resulting dataframe as type_means
# ____ = ____.____(____).____()
# ... |
00d36e2c707ec24c5598b3024729f234bae38ea4 | Krope/Udemy_beginners | /ex_3/test.py | 417 | 4.40625 | 4 | how_far = input("How far you want to travel: ")
try:
distance = int(how_far)
except:
print('Please, input correct number')
if distance <= 3:
print('Вы можете пройти этот путь пешком.')
elif distance >= 3 and distance <= 300:
print('You can drive this path.')
elif distance >= 300:
print... |
9e8f6697e9e32dfefe4635dcf3326809af3a2230 | Sjaiswal1911/PS1 | /python/Phonebook/driver_final.py | 1,287 | 4 | 4 | from Phone_book import Phonebook
decision = input("Do you wanna use the current DB ? \n Y/N:")
if decision == 'Y' or decision == 'y':
mode = 1
else :
mode = 0
pb = Phonebook(mode)
stmt = """Enter the proper index to utilise functions
1 : Add a new number
2 : Update a new Number
3 :... |
ce0609ca7be3b2cc0db90bc56629447aad02701e | pouyaneh/adad-chap-kon | /adad chap kon.py | 128 | 3.921875 | 4 | num = input()
for i in num:
print(i + ':', end=' ')
for _ in range(int(i)):
print(i , end='')
print()
|
16d0ff39b96515ae0026c0e3472e9aea2bc2c2cc | neuralfilter/hackerrank | /code_forces/astringtask.py | 249 | 3.828125 | 4 | l = raw_input()
l = l.lower()
listedl = list(l)
counter = 0
vowels = ["a", "o", "y", "e", "u", "i"]
newarr = []
for i in range(len(l)):
if(l[i] not in vowels):
newarr.append( ".")
newarr.append(listedl[i])
print(''.join(newarr))
|
4f99fb3c135299a84a3ec75fe5f2b11a7c852e54 | badamiak/learn-python-the-hard-way | /ex39_2.py | 1,157 | 4.15625 | 4 | states = {
"Oregon" : "OR",
"Florida": "FL",
"California": "CA",
"New York" : "NY",
"Michigan" : "MI"
}
cities = {
"CA" : "San Francisco",
"MI" : "Detroit",
"FL" : "Jacksonville"
}
cities["NY"] = "New York"
cities["OR"] = "Portland"
print("-"*10)
print(f"NY State ha... |
27ace62a33d570435d54d96554ef7366f3f91079 | adnanaq/Data-Structure-and-Algorithm | /breadth_first_search.py | 781 | 3.921875 | 4 | # Pesudo Code
def (Graph, started_node) # G is graph and s is source, starting node
let Q be the queue
# enqueuing the first/source node to start the search from
Q.enqueue(started_node)
started_node.visited = True # marking the source node to True as we visit it
while Q is not empty: # while there is node/ne... |
0ad9932ce9919bb110433deaab1fec861b6347b0 | Beadsworth/ProjectEuler | /src/solutions/Prob27.py | 1,572 | 3.90625 | 4 | import src.EulerHelpers as Euler
def quad(a, b, n):
"""quad form from problem"""
return n**2 + a*n + b
def quad_is_prime(a, b, n):
"""return True/False on whether quad is prime (must be positive to be prime)"""
return quad(a, b, n) > 1 and Euler.is_prime(quad(a, b, n))
def get_prime_pairs(pairs, ... |
3b15fa7de597e3059f7a7bb44332aabe171fedf0 | Miguel-leon2000/Algoritmos_de_busqueda | /ConsultaDeDatos.py | 482 | 3.75 | 4 | class BusquedaSecuencial:
"""
Metodo que realiza una busqueda secuencial, para
encontrar un telefono cualquiera, ya que si existe devuelve un True
y si no existe un False.
"""
def busqueda(self, lista, clave):
encontrado = False
for f in range(0, len(lista)):
for ... |
41629d05c332da18311341e0870a1458cdad13b8 | deenabhatt/Javascipt-part-1 | /trials.py | 1,276 | 3.796875 | 4 | """Python functions for JavaScript Trials 1."""
def output_all_items(items):
for item in items:
print(item)
def get_all_evens(nums):
even_nums = []
for num in nums:
if num % 2 == 0:
even_nums.append(num)
return even_nums
def get_odd_indices(items):
indice... |
7f0df5c40d639784b8dc8dd813ad0268f65a9ad1 | AntunesLeonardo/NumericalMethods | /IntegralGaussLegendre/IntegralGaussLegendre.py | 3,355 | 3.90625 | 4 | """
Algorithm for solving integration through Gauss-Legendre method.
The input should be the limits of the interval and the number os points to be used.
Author: AntunesLeonardo
"""
# Library import ------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrat... |
640fbeb72ebf1d51572c500d9d31b8685701845b | Code-for-All/cfapi | /utils.py | 1,051 | 3.859375 | 4 | from datetime import datetime
def is_safe_name(name):
''' Return True if the string is a safe name.
'''
return raw_name(safe_name(name)) == name
def safe_name(name):
''' Return URL-safe organization name with spaces replaced by dashes.
Slashes will be removed, which is incompatible with raw... |
c3437ced135c3a33bc264d7a3297316761b2d128 | ashirwadsangwan/Algorithms-in-CPP | /CodeForces/x.py | 468 | 3.71875 | 4 |
#def findCoin(mean, coins):
if __name__ == "__main__":
tests = int(input())
for i in range(tests):
n = int(input())
coins = input().split()
mean = (sum(int(i) for i in coins)/n)
if float(mean) > int(mean):
print("Impossible")
if coins.count(coins[0... |
b5993fc6e93ca3e43533f0cd460723b2ccc59fbe | Cadet93/Smoothstack-Assignments | /Coding Exercise 8.py | 3,423 | 4.75 | 5 | # 1. Create a function func() which prints a text ‘Hello World’
def func():
print("Hello World")
func()
# 2.Create a function which func1(name) which takes a value name and prints the output “Hi My name is Google’
def func1(name):
print(f"Hi, My name is {name}.")
func1('Google')
# 3.Define a function fu... |
73abc21cfbe7a2f6dacfa24f640de30b98a062d6 | marieli15/Curso-Phyton | /Tareas/ejercicio4.py | 430 | 3.859375 | 4 | # Ejercico hecho en clase
from funciones import Suma,Resta,multiplicacion
print("[1] Suma")
print("[2] Resta")
print("[3] Multiplicacion")
resp = input("¿Que operacion desea hacer?: ")
num1 = int(input("Escribe el primer numero :"))
num2 = int(input("Escribe el segundo numero :"))
if resp == "1":
prin... |
ca7f75892b78d69350fbff521e40a7b14c882c1b | zdyxry/LeetCode | /array/0766_toeplitz_matrix/0766_toeplitz_matrix.py | 462 | 3.796875 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0])
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] != mat... |
c648b086d6acf43042b6e9e96ec67e1373dac8cd | RapunzeI/Python | /Chapter_5/28.py | 239 | 3.53125 | 4 | def geometric(sequence):
for i in range(len(sequence)-2):
if sequence[i+1]**2!=sequence[i]*sequence[i+2]:
return False
return True
print(geometric([2,4,8,16,32,64,128,256]))
print(geometric([2,4,6,8])) |
0aad8a31458a04ad2c940ab50c329e8fb4972aa0 | kanade0404/ProgrammingAlgorithm | /AtCoder/ABC122/DoubleHelix.py | 86 | 3.625 | 4 | s = input()
print('A' if s == 'T' else 'T' if s == 'A' else 'C' if s == 'G' else 'G')
|
067794dc19bc7846e2ff926a614f35b94d8de0c9 | Dhikigame/python_study | /exception/exception.py | 347 | 3.78125 | 4 | class MyException(Exception):
pass
def div(a, b):
try:
if (b <= 0):
raise MyException("not minus") #raise:故意に例外発生
print(a / b)
except MyException as e:
print(e)
else:
print("no exception!")
finally:
print("-- end --")
div(10, -8.6)
# div(10, 3)
#... |
d3e8d521dff597b65596123d15edbb6c93ece938 | peytondodd/LotteryNumbers | /Lo.py | 2,596 | 4 | 4 | #This Python program does some calculations with the winning numbers of the Powerball lottery game.
#The file \"BasePower.txt\" has the winning numbers from 2007 to Sep 2018.
#This is not a suggestion to play lottery or to use those numbers.
#I do it to practice my GitHub and share a Python program.
#num1 to num5 are ... |
647aa5071f55f88f6cd48bd3f70f83e31ebba8bc | liamsalmon/IntroPorgramming-Labs | /Liam Salmon Homework 2.py | 3,214 | 4.40625 | 4 | # File: Homework 2
# Liam Salmon - INTRO TO PROGRAMMING - CMPT 120L 901
# Assignment 2 - Programming Problem 1
# Date - 1 March 2021
# Question: Why is it a good idea to first write out an algorithm in pseudocode rather than jumping immediately to Python code?
# Answer: Pseudocode is just precise English that describe... |
e4e12af2196e51dfbd0c1b9deea3104459ea3864 | sonam2905/My-Projects | /Python/Exercise Problems/circular_linked_list_traversal.py | 316 | 4.0625 | 4 | # Function to print nodes in a given Circular linked list
def printList(self):
temp = self.head
# If linked list is not empty
if self.head is not None:
while(True):
# Print nodes till we reach first node again
print(temp.data, end = " ")
temp = temp.next
if (temp == self.head):
break
|
203445c6cd9ff63ea1cc811ed637e2ce7b5c39d5 | remidiy/datastructs_algos | /trees/cartesian_tree.py | 650 | 3.8125 | 4 | """
Cartesian tree : is a heap ordered binary tree, where the root is greater than all the elements in the subtree
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param A : list of integers
# @return the ro... |
a7fe7cfbd0fdc7292bbda20f38275f9c8919c51b | fooyou/Exercise | /python/3rd_cook_book/Chapter_4_Iterators_Generators/iterator_protocol.py | 3,339 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# @File Name: iterator_protocol.py
# @Author: Joshua Liu
# @Email: liuchaozhen@neusoft.com
# @Create Date: 2016-01-27 15:01:21
# @Last Modified: 2016-01-27 16:01:18
# @Description:
'''
Problem: Building custom objects on which you would like to support iteration, but would like... |
595840985bbad449a86180c3eba138a93ff7835b | Vjoglekar/programs | /BinarySearch.py | 455 | 3.75 | 4 | L=[1,25,36,7,52,0]
key=7
L.sort()
print(L)
def binary_search(searchList,key):
length=len(searchList)
low=0
upper= length - 1
while(low <= upper):
middle=(low + upper)//2
if(key == searchList[middle]):
return middle
elif (key < searchList[middle]):
upper... |
c1e9b2999ce97b8c5562c939b735158c5ad788e6 | wesleymerrick/Data-Sci-Class | /DatSciInClassStuff/Feb3Exercise.py | 676 | 3.5625 | 4 | from __future__ import print_function
from bs4 import BeautifulSoup
import urllib
"""
Exercises from 2/3/17
"""
# In python, pull and print out the main body text of the following website:
# http://www.thekitchn.com/17-outrageous-recipes-for-super-bowl-sunday-227804
# Then pull and list all the links.
r = urllib.urlo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.