blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9e68c223a3b471d53635750fc17308ea1153b0b4 | skonienczwy/LearningPython | /ex0088.py | 1,250 | 3.703125 | 4 | from colorama import Fore, Back, Style
print('##Exercicio 88##')
def leiaInt(num):
while True:
try:
t = int(input(num))
return t
except ValueError as erro:
print(f'O Erro for causado por {erro.__class__}')
print(Fore.RED + 'ERRO! Digite um núme... |
dcc72e7be254ac428bf959dc971d2779b142f458 | odoommk/PythonAcademy | /Unit5_Lists And Dictionaries/lesson3.py | 496 | 4.125 | 4 | zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked
#the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] ... |
2097031a0f6124b66d23246f533411c8ce52704a | thisolivier/amazing_fish | /deck.py | 870 | 3.8125 | 4 | from random import shuffle
class Deck(object):
def __init__(self):
self.size=52
self.cards=[]
self.suits=["hearts","clubs","dimonds","spades"]
self.build()
self.shuffle()
def __repr__(self):
for card in self.cards:
print card
def build(self):
... |
dd6e8abd563d9b9165f264592da2e1006f694e6a | aidanrfoster/abe487 | /problems/hello-py/hello.py | 502 | 3.9375 | 4 | #!/usr/bin/env python3
import sys
import os
if len(sys.argv) <2:
print('Usage:', sys.argv[0], 'NAME [NAME2 ...]')
sys.exit(1)
elif len(sys.argv) ==2:
print('Hello to the', len(sys.argv[1:]),'of you:','{}!'.format(sys.argv[1]))
elif len(sys.argv) ==3:
print('Hello to the {} of you: {} and {}!' .format(len(s... |
d4fe33eaaf22d707f284edf3b6808efd49cc740a | Exodus111/Infinite-Adventure | /Engine.py | 4,315 | 3.5625 | 4 | """
2.0
A Pygame Engine.
Can be used to run any Tile based 2d Pygame game.
"""
import os, sys
import pygame, vec2d
from pygame.locals import *
from vec2d import vec2d
class Engine(object):
"""The mainloop class for a Pygame"""
def __init__(self, name, size=(640,480), mouseset=True):
os.environ["SDL_VI... |
ca9309e3114ca7699bf643dae70da316731abc94 | suizo12/hs17-bkuehnis | /source/game_data/plot/utils.py | 480 | 3.625 | 4 | def get_score(s, l):
"""
get the porcentage of value s in relation of the values of
:param s:
:param l:
:return:
"""
l = list(l)
l = sorted(l)
if s in l:
return round(l.index(s) * 100 / len(l) )
return None
def get_percent_score(s, l):
l = list(l)
l = sorted(l)... |
f718efff286d6ac941ca527ab91a5b3a102dbd35 | kapil23vt/Python-Codes-for-Software-Engineering-Roles | /permutation string.py | 346 | 3.734375 | 4 | def permute(a, left, right):
if left==right:
print (''.join(a))
else:
for i in range(left,right+1):
a[left], a[i] = a[i], a[left]
permute(a, left+1, right)
a[left], a[i] = a[i], a[left] # backtrack
string = "ABC"
n = len(string)
a = list(str... |
b7682ff8aaa5d9dc9081385fea4b101150b6c6b1 | hongxchen/algorithm007-class01 | /Week_08/G20200343040277/LeetCode_0277_191.py | 393 | 3.71875 | 4 | #编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
count += n&1
n >>= 1
print(count)
return count
|
33816ef35be76bb0b6c541269ec15b6528048156 | silviodaniel/Harvard-Project-Digital-Phenotyping | /week 1.py | 9,300 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
np.loadtxt("C:/Users/Silvio/Documents/Career/Harvard/best_text_ever.txt",dtype=int)
y = [x**2 for x in range(5)]
import math
math.pi
numbers=[2,4,6,8]#A LIST: can find how many objects in list using len
numbers[0:2]
n... |
3eb420ad18a30b0c57ff359a600ee9c4873cbd6f | diogolimalucasdev/Python-Exercicios | /19.05/converer em milimetros.py | 251 | 3.890625 | 4 | # elabboar um programa que leia um valor em metros e tranforme em milimetros
metros = float(input(" Digite um valor em metros: "))
milimetros = metros * 1000
print("o valor em metros(", metros, ") equivale a (", milimetros, ") em milimetros")
|
bc73faf7c494861611c27546fb9a880344a9cca2 | touhiduzzaman-tuhin/python-code-university-life | /Anisul/93.py | 88 | 3.703125 | 4 | import re
pattern = r"[A-Z]"
if re.match(pattern, "Aadjfdjkidd"):
print("Match")
|
95b798aac66542f624f91469e3d3548b18e119a9 | TakeshiJay/Apartement-Rental-System | /Term_Project/main.py | 34,375 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import getpass
import json
import re
from tabulate import tabulate
import datetime
class ExpenseInputScreen: # Expense input screen
def __init__(self, expense_list):
self.__year = datetime.datetime.now().year
self.__month = datetime.datetime.now().month
self.__... |
8cfdad426ca270f0aadda0db5ff12be8a5274b05 | AiZhanghan/Leetcode | /秋招/京东/0827/quick_sort.py | 1,148 | 3.578125 | 4 | class Solution:
def quick_sort(self, items):
"""
Args
items: list[int]
"""
self._quick_sort(items, 0, len(items) - 1)
def _quick_sort(self, items, start, end):
"""
Args:
items: list[int]
start: int
end: int
... |
27f964af378fc9151b23767c5b824be981119291 | rileyshahar/csworkshops | /00-principles/100-fib-fix-one.py | 1,005 | 4.1875 | 4 | """Compute the first 8 fibonacci numbers."""
def fib_step(fibs):
"""Update fibs to add the next fibonacci number."""
# f(n) = f(n-1) + f(n-2)
fibs.append(fibs[-1] + fibs[-2])
def first_n_fib(n):
"""Return a list of the first n fibonacci numbers."""
# stores the computed values for later return
... |
7f6b04ae5e797c6eb6261e6ec62dce29e3ea4d49 | meetashok/projecteuler | /20-30/problem-29.py | 343 | 3.609375 | 4 | ## Problem 29
lower_limit = 2
upper_limit = 100
def main():
powers = []
for a in range(lower_limit,upper_limit + 1):
for b in range(lower_limit, upper_limit + 1):
if a ** b not in powers:
powers.append(a**b)
return len(powers)
if __name__ == "__main__":
answer = m... |
f7eada261f0a0bf3dbdbedfddb89f2842e26f121 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2166/60688/317581.py | 264 | 4.03125 | 4 | inputstr=input();
if(inputstr=="1"):
print("7 1 4 9 2 11 10 8 3 6 5 12");
elif(inputstr=="2"):
print("2 1 4 3")
print("3 1 4 5 2")
elif(inputstr=="1/3-1/2"):
print("-1/6");
elif(inputstr=="-1/2+1/2+1/3"):
print("1/3");
else:
print(inputstr) |
130483f4f46c78c810da0eb3e30cf9829258179a | JesusGarcia143/progavanzada | /Ejercicio48.py | 1,169 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 02:06:24 2019
@author: Jesús García
"""
##Ejercicio: 48 "Signo Sodiacal Chino"
##Escriba un programa que lea un año del usuario y muestre el animal asociado
##con ese año Su programa debería funcionar correctamente durante cualquier año mayor o igual
##a cero,... |
38531023257cca81534f64ee1af1cb5bb1146781 | Tynnovators/Differentilly_private_productivity_analyzer | /logistic.py | 4,857 | 3.703125 | 4 |
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
#Steps
#STEP 1: DATA READING
df = pd.read_csv("images_analyzed_productivity1.csv")
print(df.head())
plt.figure(1)
plt.scatter(df.Age, df.Productivity, marker='+', color='red')
plt.ylabel("Productivity")
plt.xlabel("Age")
#plt.show()
plt.figu... |
649f3b5e1841109c873e5ba5617104b10accea52 | e1ijah1/LeetCode | /Array/easy/219_contains_duplicate_II.py | 779 | 3.859375 | 4 |
from typing import List
"""
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1... |
853492fbace7279cf211e9ec1cdd26a2de00cde6 | cadolphs/advent_of_code_2020 | /day08/computer.py | 1,697 | 3.546875 | 4 | from typing import Iterable
from day08.instruction import Instruction, parse_program_to_instructions
class Computer:
def __init__(self, instructions: Iterable[Instruction]):
self._accumulator = 0
self._instr_ptr = 0
self._instructions = list(instructions)
@property
def accumulator... |
24e664acd61efd6967f640698f23abd162d3f584 | moaazelsayed1/mit6.0001-psets | /ps1a.py | 627 | 4.21875 | 4 | def main():
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(
input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
target = 0.25 * total_cost
monthly_savings = (annual_salary / 12)... |
6906267b76c903ece911ceebdcf65fd661855130 | hanhanwu/Hanhan-Machine-Learning-Model-Implementation | /opt_hill_climbing.py | 1,227 | 3.90625 | 4 | '''
Created on May 7, 2016
@author: hanhanwu
Hill climbing starts from a random solution, looking for better neighbor solutions
In this process, it walks in the most steep slope till it reached a flat point
This method will find local optimum but may not be global optimum
Need to run the method several times, hopin... |
59a1ccd7edefec97bc3fd0623ef0c62c4f1d55d1 | karansthr/data-structures-and-algorithms | /tests/binary_search_tree.py | 744 | 3.78125 | 4 | import unittest
from data_structures.trees.binary_search_tree import Tree
class BinarySearchTreeTest(unittest.TestCase):
def test(self):
bst = Tree()
values = [5, 3, 1, 4, 8, 6, 10]
'''
5
/ \
3 8
/ \ / \
1 4 6 ... |
06a4bd8504e8b186a823883a590a4dd332f1b853 | Vitosh/Python_personal | /OOP/000_PreviousExam/problem001.py | 1,326 | 3.546875 | 4 | import math
my_input = input()
my_list = my_input.split()
my_queue = []
action = ['+', '-', '*', '/']
result = 0
is_first = True
for m in my_list:
if m not in action:
my_queue.append(m)
else:
if m == "+":
while len(my_queue):
if is_first:
... |
e14232bf87d76c1e1eb66f9509d2188e88896243 | hemiaoio/learn-python | /lesson-05/money_challenge_v1.0.py | 627 | 3.953125 | 4 | """
功能:52周存钱挑战
版本:V1.0
日期:2018/8/22
"""
def main():
# 每周存入的金额,初始第一周为10
money_per_week = 10
# 第N周
week_index = 1
# 递增的金额
increase_money = 10
# 总共周数
total_weeks = 52
# 账户累计
sum_moeny = 0
while(week_index <= total_weeks):
sum_moeny += money_per_week
... |
811591598c46945521d4ccb13c4d9bbc16df8fc3 | adam-weiler/GA-Reinforcing-Exercises | /exercise.py | 1,039 | 4.125 | 4 | classroom_seating = [
[None, "Pumpkin", None, None],
["Socks", None, "Mimi", None],
["Gismo", "Shadow", None, None],
["Smokey","Toast","Pacha","Mau"]
]
def find_free_seats(classroom):
new_classroom = classroom
for row_index, row in enumerate(classroom):
for col_index, column in enumerate(row):
... |
2ac14954b5f14e3dde929731fae738bcaa7cacde | shubhamoli/solutions | /leetcode/medium/144-Binary_tree_preorder.py | 1,231 | 3.859375 | 4 | """
Leetcode #144
"""
from typing import List
# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
... |
309420872569a68bb0227f91639a595bd2269ee4 | Kkkb/hello-world | /liaoxuefeng_python/my_class.py | 542 | 3.65625 | 4 | # -*- coding: utf-8 -*-
'''
请把下面的Student对象的gender字段对外隐藏起来,
用get_gender()和set_gender()代替,并检查参数有效性
'''
class Student(object):
def __init__(self, name, gender):
self.name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self, gender):
if (gender == 'male') or (gender ==... |
203e393cf70629be4bfe649735c0d0829e34660c | AniketArora/oefProgramming | /mauritsOefeningen/week1/oef4.py | 370 | 3.796875 | 4 | int1 = 45
int2 = 60
print('decimaal is: ' + str(int1) + ' en ' + str(int2))
print ('hex is: ' + hex(int1) + ' en ' + hex(int2)) #hex() wet het getal om naar een hexadecimaal
print('oct is: ' + oct(int1) + ' en ' + oct(int2)) #oct() zet het getal om naar een octadecimaal
print ('binair is: ' + bin(int1) + ' en ' ... |
01e11c1f3052128a9b66ea709caf359d790d9288 | AnujRuhela7/Python-Tutorial | /PrintNumSquare.py | 111 | 4.15625 | 4 | n = int(input("Enter how many number you want to print : "))
for n in range(n):
print((n+1)**2,end = '\t')
|
ceb77357e8d5f2d8144860cf5d5254ae8202b575 | hjabbott1089/Pelican-tamer | /loops.py | 401 | 3.875 | 4 | for i in range(1, 21, 2):
print(i, end=' ')
print()
for t in range(0, 101, 10):
print(t, end=' ')
print()
for x in range(20, 0, -1):
print(x, end=' ')
print()
STARS = int(input('Enter the amount of stars you want: '))
for x in range(STARS):
print("*", end='')
print()
for z in rang... |
032b4c8e38b4c47cb246729167940f4d531e2ac4 | Systematiik/Python-The-Hard-Way | /ex20.py | 951 | 4.125 | 4 | from sys import argv
script, input_file = argv
#this function applies a variable f to print everything that f owns
def print_all(f):
print(f.read())
#the seek function sets the variable f to the very first byte
def rewind(f):
f.seek(0)
#this function prints out one line from variable f
def print... |
1dae34c514f4d9bc6ab58a490e924d83a290d859 | CorySpitzer/tron-engine | /engines/board.py | 4,905 | 3.6875 | 4 | """
Game logic for Tron game.
Robert Xiao, Feb 2 2010
minor edits by Jim Mahoney, Jan 2014
"""
import random
class Board:
def __init__(self, w, h, start=None, layout=None, outerwall=True):
''' w: width
h: height
start:
"symrand" for symmetrically random (default... |
8794bb053a781e1747b737cb7336286ba00ec5e5 | InfiniteWing/Solves | /zerojudge.tw/c087.py | 849 | 3.703125 | 4 | import math
prime=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181]
def Prime(a,b):
global prime
if(min(a,b)==1):
return False
for p in prime:
if(a%p==0 and b%p==0):
return False
for p in prime:
if(a%p==0):
while(... |
7fe3611e3d9980a6ebd472db6ab887b9b4a076cd | verdatestudo/Algorithms_Khan | /selection_sort.py | 1,130 | 4.46875 | 4 | '''
Algorithms from Khan Academy - selection sort
https://www.khanacademy.org/computing/computer-science/algorithms
Last Updated: 2016-May-11
First Created: 2016-May-11
Python 2.7
Chris
'''
def selection_sort(my_list):
'''
There are many different ways to sort the cards.
Here's a simple one, ... |
79b0510c6eb2f97779887d14408712fd7020b9f6 | Pavithra612/DAY-3_Assignment-3-4 | /assignment4.py | 540 | 4.21875 | 4 | # Write a program to implement insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
n = int(input('enter numbeer of element : ')... |
2dbd3c06503ee05ca630704bf94c7b61abb1a6de | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4380/codes/1734_2495.py | 185 | 4.0625 | 4 | n=int(input("Digite um numero: "))
while (n!=-1):
if (n%2==0):
mensagem = "PAR"
print(mensagem)
else:
mensagem = "IMPAR"
print(mensagem)
n=int(input("Digite um numero: "))
|
690f43ebae6f4957d2a439f127d512cbd3f49cc1 | mwaskom/seaborn | /examples/timeseries_facets.py | 1,023 | 3.5625 | 4 | """
Small multiple time series
--------------------------
_thumb: .42, .58
"""
import seaborn as sns
sns.set_theme(style="dark")
flights = sns.load_dataset("flights")
# Plot each year's time series in its own facet
g = sns.relplot(
data=flights,
x="month", y="passengers", col="year", hue="year",
kind="l... |
d755be3a8232b04e6a2c799a1dbcb11effb98236 | lofues/LeetCode-Excerise | /515_在每个树行中找最大值.py | 934 | 3.8125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
if root and not isinstance(root,TreeNode):
return None
... |
19d5087f1844a42ac097f21e2d86c9322847b3ef | Kunwar-Yuvraj/CBSE-Class-12-Project-Programs | /project 5.py | 514 | 3.578125 | 4 | '''
Project question - Removes all the line that contains character 'a' in a file
and write it to another file.
'''
# solution:-
file1=open("inputfile.txt",'r+')
data1=file1.readlines()
file1.close()
file1=open("inputfile.txt",'w')
data2=[]
file2=open("outputfile.txt",'w')
data3... |
1295bf144eaff793f584678eb37052ed37f85139 | chenxu0602/LeetCode | /1460.make-two-arrays-equal-by-reversing-sub-arrays.py | 1,836 | 3.84375 | 4 | #
# @lc app=leetcode id=1460 lang=python3
#
# [1460] Make Two Arrays Equal by Reversing Sub-arrays
#
# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/description/
#
# algorithms
# Easy (72.52%)
# Likes: 261
# Dislikes: 63
# Total Accepted: 34.6K
# Total Submissions: 47.8K
# Testcase E... |
d93854bd8843fa616dedc7eb468595000e4c50ec | stevegcarpenter/hackerrank-problems-python | /nested-lists.py | 315 | 3.9375 | 4 | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/nested-list/problem
n = int(input())
students = [[input(), float(input())] for _ in range(n)]
nextlowest = sorted(list(set([score for name, score in students])))[1]
print('\n'.join([name for name, score in sorted(students) if score == nextlowest]))
|
408ca45ecbf84e4f894307966e073611f2106499 | Derfies/pglib | /pglib/generators/recursivemaze.py | 3,547 | 3.984375 | 4 | import random
import numpy as np
from regionbase import RegionBase
TILE_EMPTY = 0
TILE_CRATE = 1
class RecursiveMaze(RegionBase):
"""
Taken from: https://arcade.academy/examples/maze_recursive.html
"""
def create_empty_grid(self, width, height, default_value=TILE_EMPTY):
""" Create an em... |
66c5feb7b71b3bf0338dfd558ce704777d5c7679 | knee-rel/CSCI-Lab-3 | /lab3c.py | 1,423 | 4.125 | 4 | # Nirel Marie M. Ibarra
# 192468
# March 15, 2021
# I have not discussed the Python language code in my program
# with anyone other than my instructor or the teaching assistants
# assigned to this course
# I have not used Python language code obatained from another student
# or any other unauthorized source, either m... |
b16dbc5d0a85a90e5d4d34a97f7996cddf9505e9 | kjh03160/Tech_Course_1st_Test | /4.py | 1,955 | 3.703125 | 4 | def solution(infos, actions):
answer = []
LOGIN = False
ADD = []
for i in actions:
# if 'LOGIN' in i:
# if LOGIN == True or not i[6:] in infos:
# answer.append(False)
# elif i[6:] in infos:
# LOGIN = True
# answer.... |
92dba5b21f96b4c4fb316380dc8d1aae532a87b1 | Bharathi-raja-pbr/Python-if-else-exercises- | /2b3.py | 206 | 4.3125 | 4 | # to find the largest of two numbers
n1=int(input("enter number 1"))
n2=int(input("enter number2"))
if n1 > n2 :
print(f"{n1} is the greatest integer")
else:
print(f"{n2} is the greatest number")
|
6e026dbd2736d40281a9223d5a784c35e54496b8 | luozhiping/leetcode | /middle/longest_palindromic_subsequence.py | 972 | 3.640625 | 4 | # 516. 最长回文子序列
# https://leetcode-cn.com/problems/longest-palindromic-subsequence/
class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
length = len(s)
# bp = [[0 for _ in range(length)]... |
29734f813540db85db28e2598f3e5bb2873797d8 | 666sempron999/Abramyan-tasks- | /If(30)/6.py | 228 | 3.578125 | 4 | '''
If6 . Даны два числа. Вывести большее из них.
'''
A = int(input("Введите A: "))
B = int(input("Введите B: "))
if A > B:
print(1)
elif B > A:
print(2)
else:
pass
|
300467ba8be04f63d0259f23cd578d3ad2934364 | mrtuanphong/learning-python | /sqlite3/customers/select.py | 416 | 3.734375 | 4 | import sqlite3
# Connect to database:
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Query the database
c.execute("SELECT rowid, * FROM customers")
#c.fetchone()
#c.fetchmany(3)
#c.fetchall()
items = c.fetchall()
#print(items)
for item in items:
print(item)
#print(item[0], '\t', ... |
8da8f8c65adf5fdc5ae1fd2727711dc91f6c02d8 | shinespark/algorithm-with-python | /01_recursive_difinition/fibonacci.py | 736 | 3.890625 | 4 | # coding: utf-8
import time
# 二重再帰
def fib(n):
if n == 0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)
# 末尾再帰
def fib2(n, a1=1, a2=0):
if n < 1:
return a1
return fib2(n - 1, a1 + a2, a1)
# 繰り返し
def fib3(n):
a1, a2 = 1, 0
while n > 0:
a1, a2 = a1 + a2, a1
... |
d079e376da7e2002ea2b71cd7477df9d72688413 | AlexandrZhytenko/solve_tasks | /popular_words.py | 822 | 3.90625 | 4 | def popular_words(text, words):
dict_words = dict((key, value) for (key, value) in zip(words, len(words) * [0]))
for i in text.split():
if i.lower() in dict_words:
dict_words[i.lower()] += 1
return dict_words
# def popular_words(text, words):
# lower_count = text.lower().split().cou... |
417f1134df2cd2f9c03567d5cf93776ce82c9bc9 | pravsp/problem_solving | /Python/LinkedList/solution/deletenode.py | 868 | 3.609375 | 4 | """Delete node solution except tail."""
import __init__
from singlyLinkedList import SinglyLinkedList
from utils.ll_util import LinkedListUtil
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead
"""
... |
bf7dc609bee8abcb297665e991d1e7191f349040 | vladcipariu91/DSA-Problems | /chapter_3/heap/heap.py | 2,417 | 3.796875 | 4 | # min heap
class Heap:
def __init__(self, initial_size):
self.cbt = [None for _ in range(initial_size)]
self.next_index = 0
def insert(self, data):
self.cbt[self.next_index] = data
self.up_heapify()
self.next_index += 1
def up_heapify(self):
child_index = se... |
7c7e139997884bbb71eb5edb1ea09b6fa5e48ba6 | silastsui/advent-of-code-2017 | /8.py | 2,392 | 3.578125 | 4 | class Instruction(object):
def __init__(self, var, change, c_var, condition):
self.var = var
self.change = change
self.c_var = c_var
self.condition = condition
def clean_instr(filename):
"""
Args:
filename (str): filename
"""
with open(filename) as f:
... |
779bb7fb038868b508f80d35a4b9d39c120f0ebc | jnucanwin/LeetCode | /LeetCode/树/257. 二叉树的所有路径.py | 1,275 | 3.71875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
s = []
result = []
r = None
if not root:
return []
p = root
while p or s:
... |
d517ea380f21af405ea276c1510c6e2c0a2d8407 | hyejun18/daily-rosalind | /prepare/template_scripts/algorithmic-heights/MER.py | 735 | 3.9375 | 4 | ##################################################
# Merge Two Sorted Arrays
#
# http://rosalind.info/problems/MER/
#
# Given: A positive integer n <= 10^5 and a sorted
# array A[1..n] of integers from -10^5 to 10^5,
# a positive integer m <= 10^5 and a sorted array
# B[1..m] of integers from -10^5 to 10^5.
#
# Re... |
024d199bc065a6a86d3e21d890e996f4348eea18 | adelgar/python-for-everybody-book | /Chapter 10 (Tuples)/timeofday.py | 653 | 3.546875 | 4 | while True:
fname = input('Enter a file name: ')
try:
if fname == 'done':
break
else:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
counts = dict()
for line in fhand:
line = line.rstrip()
if line.startswith('From'):
words = line.split()
if not words[0] == 'From:':
h... |
62e92bb62b32e80aae2925e3af09e76f1b93ba44 | zhangwang0537/LeetCode-Notebook | /source/Clarification/Array/896.单调数列.py | 632 | 3.734375 | 4 | # 如果数组是单调递增或单调递减的,那么它是单调的。
#
# 如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。
#
# 当给定的数组 A 是单调数组时返回 true,否则返回 false。
# 使用all()函数
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
return (all(A[i] <= A[i+1] for i in range(len(A) - 1)) or
all(A[... |
78354023e9e6585af1c01a4d2ddcf6174e0af737 | hridayjham/A2 | /A2/src/BodyT.py | 2,132 | 4.03125 | 4 | ## @file BodyT.py
# @author Hriday Jham
# @brief Contains the BodyT type to represent the object body
# @date 02/16/2021
from Shape import Shape
from math import pow
## @brief BodyT is used to represent the Body of an object.
class BodyT(Shape):
## @brief constructor for class BodyT. BodyT is a set of shapes... |
619b22898c8b4c21682eba0b95c86f67e456c99f | Software05/Github | /Modulo-for/app1.py | 456 | 4.3125 | 4 | # break - ejemplo
print("La instrucción de ruptura:")
for i in range(1,6):
if i == 3:
break
print("Dentro del ciclo.", i)
print("Fuera del ciclo.")
# continua - ejemplo
print("\nLa instrucción continue:")
for i in range(1,6):
if i == 3:
continue
print("Dentro del ciclo.", i)
print("Fu... |
dbfada8c8a029e27495c98d2dd3692f03f79b618 | anaswara-97/python_project | /exam2/lmb_fun.py | 96 | 3.5 | 4 | num = [16]
if(list(filter(lambda x: x % 2 == 0,num))):
print("even")
else:
print("odd")
|
26e7a5f0ebdd5157c53a8e3b86231b646696ea70 | singhchaman/MIT600x | /MITx 6.00.1x/week 2/ps1.py | 503 | 3.78125 | 4 | c=0
for i in s:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
c=c+1
print "Number of vowels:", c
c=0
for i in range(1,len(s)-1):
if s[i-1:i+2]=='bob':
c=c+1
print "Number of vowels:", c
curString = s[0]
longest = s[0]
for i in range(1, len(s)):
if s[i] >= curString[-1]:
curS... |
43e7a79efb891b703ed01d5e0fe0c6773e4b4d53 | sepulenie/codewars | /codewars_5.py | 140 | 3.5 | 4 | def solution(string, ending):
print( ending in string and string[len(string)-1]==ending[len(ending)-1])
pass
solution('lol', 'oy') |
a8cd09dc58e4dd1a2e8f39da1e07d8cf0d289377 | glonek47/gitarasiema | /5.1.py | 212 | 3.890625 | 4 | while True:
a = float(input("Podaj pierwszą liczbę: "))
b = float(input("Podaj drugą liczbę liczbę: "))
if a < 0 or b < 0:
continue
else:
print("Średnia to: ", (a+b)/2) |
d4491d836d9336a1baaca1fd9e2eccae4811198a | TCReaper/Computing | /Computing Revision/2015 DHS Prelim/ISBN Fun.py | 8,331 | 3.96875 | 4 |
################################### Task 3.1 #############
def ISBN_Check_Digit(isbn):
isbnstring = isbn.replace('-','')
if check_type(isbnstring) == 13:
isbn = isbnstring[:-1]
switch = 0
total = 0
for i in isbn:
if switch == 0:
... |
f7a128d6f865414ac0601e5d2cc3124a40f35cad | likhitha5101/DAA | /Assignment-7/dijkstra.py | 4,198 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## CS1403 — Design and Analysis of Algorithms
# ### 1. Given a weighted graph G = (V, E), and a distinguished vertex s ∈ V (source vertex), find the shortest weighted path from s from every other vertex in G.
# In[29]:
from collections import defaultdict
import sys
class ... |
7dd33202d9970365080240a19646694a5dc9d176 | SherMM/rosalind-python | /rna.py | 119 | 3.59375 | 4 | def dnaToRNA(dna):
rna = ""
for letter in dna:
if letter == "T":
rna += "U"
else:
rna += letter
return rna |
e5d27134c990fabe70bdcf84bc4b0d21686f0c88 | Arktiica/edhesivePython | /Unit 7 Functions/7_4CodePractice-calcGPAWeighted.py | 472 | 4 | 4 | def GPAcalc(g, w):
if g.lower() == 'a':
return 4 + w
elif g.lower() == 'b':
return 3 + w
elif g.lower() == 'c':
return 2 + w
elif g.lower() == 'd':
return 1 + w
elif g.lower() == 'f':
return 0 + w
else:
return "Invalid"
msg = input("... |
40f1e9408b95e121c3c42090720ae7c0e72f8945 | dmikii/pcc2e-work | /Chapter7/dinner_seating.py | 187 | 4.21875 | 4 | table = input("How many people will be dining this evening? ")
table = int(table)
if table > 8:
print("Sorry, but you'll have to wait for a table.")
else:
print("Your table is ready.") |
07a9a14b86570c3e48aede73674f3085849eb2bd | Nagendra17423/Movie-Recommendation-System | /options/tage.py | 433 | 3.625 | 4 | import pandas as pd
from math import pow, sqrt
movies=pd.read_csv("movies.csv")
tags=pd.read_csv("tags.csv")
tags=pd.merge(movies,tags).drop(['timestamp','movieId','title','genres'],axis=1).sort_values(by=['userId'])
# tags
i=int(input("Enter the user id"))
x=tags.loc[tags['userId'] == i]
# x
t_count = x['tag'].value_... |
bcc767f1e513482a6f27b4cdb15fd0a298c4b999 | bangerterdallas/portfolio | /List_Comprehension_Bubble_Sort/assn15-task2.py | 1,103 | 4.1875 | 4 | def bubbleSort(inputList):
loop = True
while loop:
loop = False
for j in range(len(inputList) - 1):
if inputList[j] > inputList[j + 1]:
inputList[j], inputList[j + 1] = inputList[j + 1], inputList[j]
loop = True
def main():
numberList = []... |
70166884f504a8224d1f9d5e14b95a3a49b8726a | pravinpande/Python | /ReverseString.py | 429 | 4.125 | 4 | #reverse string
def reverse_join(s):
return " ".join(reversed(s.split()))
print(reverse_join('This is a string'))
def reverse_while(s):
length = len(s)
spaces = [' ']
word = []
i = 0
while i < length:
if s[i] not in spaces:
word_start = i
while i < length and s[i] not in spaces:
i += 1
word.... |
915878cafa68b9932fb96250e3bd1a866c3661bd | gachikuku/simple_programming_python | /LS12.py | 328 | 4.375 | 4 | #!/usr/bin/env python
"""
12. Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. You can do this quicker than concatenating them followed by a sort.
"""
def rotate(x,k):
return x[k:] + x[:k]
example = [1,2,3,4,5]
k = 2
print(rotate(example... |
e286fb181dffaa32a552e6fa55c8c905228781fc | tuomas56/random-python-stuff | /fraction.py | 7,419 | 4.0625 | 4 | import numbers
#module Fractions
#contains classes and functions for dealing with fractions
#@author Tuomas Laakkonen
#@date 1418054074 8/12/14
#@copyright Tuomas Laakkonen (c) 2014
#@license GPLv3
#contains fields for numerator and denominator and methods to simplify
class Fraction(numbers.Rational):
def __init__(... |
d2f251040a789bb6bc0dfd34f191a37963774236 | HBalija/data-structures-and-algorithms | /04-sorting-algorithms/03-insertion-sort/03-insertion-sort.py | 505 | 4.1875 | 4 | #!/usr/bin/env python3
def insertion_sort(lst):
# start from second element
for i in range(1, len(lst)):
current_value = lst[i]
# work backwards
j = i - 1
while j >= 0 and lst[j] > current_value:
# while in loop, copy values to lst[j + 1] position
lst[... |
05f3604967ab4e0d0ebc2fb7162395a76ba84d56 | bamfdonahoo/ProjectEuler | /pe002.py | 806 | 3.984375 | 4 | ### Project Euler Problem 002
##
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, f... |
045addfb678e8a4c3606cdc31a028d1e8a27a3e6 | ANTsX/ANTsPyNet | /antspynet/utilities/cropping_and_padding_utilities.py | 3,104 | 3.59375 | 4 | import ants
import numpy as np
import math
def crop_image_center(image,
crop_size):
"""
Crop the center of an image.
Arguments
---------
image : ANTsImage
Input image
crop_size: n-D tuple
Width, height, depth (if 3-D), and time (if 4-D) of crop region.
... |
734f158b54c8d856de0a2e81e59397b69399ddbf | TeoBlock/cti110 | /M5T2_McIntireTheodore.py | 1,073 | 4.34375 | 4 | # CTI-110
# Module 5 Tutorial 2
# Theodore McIntire
# 12 October 2017
# This program totals the number of bugs collected in a week
#def main() uses a for loop
def main():
# This program uses these variables
# ? ? ? I DO NOT UNDERSTAND WHY THIS PROGRAM DOES NOT RUN
# IF THESE VARIABLES ARE DEFIN... |
e99c494aa951ec405b8cfa9e7b8164ecc7d4d443 | akshirapov/automate-the-boring-stuff | /Projects/identifying-photo-folders/identifying_photo_folders.py | 912 | 3.828125 | 4 | #! python3
# identifying_photo_folders.py - Scans the entire hard drive and finds
# photo folders.Photo folders is that it's any folder, where more than
# half of the files are photos.
import os
from PIL import Image
for root, dirs, files in os.walk('/home'):
num_photo_files = 0
num_non_photo_files = 0
... |
ee036f4ff4f0dfea359b35f0584174e384628f79 | vmteja/Aihw3 | /model_helper_funcs.py | 2,992 | 3.796875 | 4 |
import random
from random import shuffle
import math
import gc #garbage collector
def randomize_data(data):
"""
randomly re-arrange the data in the list
"""
# shuffle(data)
l = len(data)
for i, card in enumerate(data):
swapi = random.randrange(i, l)
data[i], data[swapi] = dat... |
9479a7c0d1a18507c0a1392654f4c34f7ad12d54 | unspoken666/Code | /python/PythonDraw.py | 2,156 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#method one
#PythonDraw.py
import turtle
turtle.setup(650,350,200,200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
turtle.circle(40,80)
turtle.circle(-40,80)
turtle.circle(... |
578260161ba8f5285dddaa588c5739498e072562 | AxelRaze/Arreglo5Mult | /Arreglo5.py | 1,612 | 3.515625 | 4 |
class Arreglo5:
__Arreglo = []
__sumafilas = int(0)
__sumacolumnas = int(0)
__columnas = ''
__filas = int(0)
f = int(0)
c = int(0)
def crearDimensiones(self, f, c):
for a in range(f):
self.__Arreglo.append([0] * c)
print(self.__Arreglo)
d... |
3d8d2b4e44f047b5f4bfb149381140ac51a30299 | jleihe/Sandbox | /python/practice/calc/start.py | 460 | 4.0625 | 4 | # File Name: calc.py
# Written By: Joshua Leihe
# Purpose: Create a simple python script that takes a string input and translates it to a mathematical equation. The script should then return the result (or an explanation as to why there was an error).
from utils import commands
print "\nWelcome to Calc 0.1!"
print "... |
5b4711b26f45c4e0e07fff3d6e4cf9f0e994576b | wzbbbb/LeetCode-OJ | /Sudoku Solver.py | 1,395 | 3.5625 | 4 | class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
def chk(self,board,i,j, num):
b,sz=board,9
if str(num) in b[i]: return False
for k in range(sz):
if str(num) == b[k][j]: return False
if i in ... |
f986fb948699d322c26bc4fd0fd456eb4b0f45ef | khwla23/Piaic | /start2.py | 287 | 4.09375 | 4 | user_name = input(" Enter your Password: ")
length = len(user_name)
if length <= 3:
print(" Your password is too weak")
print(" try again")
elif (length>3 and length<10) :
print(" Your password is Good and long")
elif (length > 10 ) :
print (" Your password is strong")
|
76226bb5247eeb1f19629632be91e220e14399d1 | mnevadom/pythonhelp | /2_condicionales/Ejercicio1.py | 441 | 4.125 | 4 | '''
Ejercicio 1:
Hacer un programa que pida 2 números y se de cuenta cuál de ellos es par,
o si ambos lo son.
'''
num1 = int(input("Digite un numero: "))
num2 = int(input("Digite otro numero: "))
if num1%2==0 and num2%2==0:
print("Ambos numeros son pares")
elif num1%2==0 and num2%2!=0:
print(f"{nu... |
2c6fbaf8105fdb2756c06b29f1350d959b53c436 | phuonghle/lehoaiphuong-fundamentals-c4e19 | /Session02/session02 assignment/table_10_n.py | 464 | 4 | 4 | # Ask users to enter a number n, then print n x n 1’s and 0’s, consecutively
n = int(input("Enter a number: "))
for i in range(n):
if i % 2 == 0 :
for j in range(n):
if j % 2 == 1:
print(0, end=" ")
else:
print(1, end= " ")
else:
for j ... |
e5439b19866c0d71c19c9a2cf96854e37a147500 | GuhanSGCIT/Trees-and-Graphs-problem | /Factorial.py | 1,546 | 3.828125 | 4 | """
A factorial of a non-negative integer is defined as the product of all numbers from 1 to N inclusive.
The factorial of N is denoted by N!. By convention, 0!=1.
For example, 5!=5×4×3×2×1=120.
Your task is simple. You are given N! , where you have to find N . If multiple values exist for a single factorial,
... |
ff723868b2ebda7484699785dfa6c905f2ccbe10 | maxvillev/resbaz2021 | /hellopanda.py | 319 | 3.90625 | 4 | #
# hellopanda.py - using pandas to read and plot a csv file
#
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("kungfu.csv", skiprows=3)
print("\n*** Po and the Furious Five ***\n")
print(df)
df.plot(x="Name",kind="bar")
plt.title("Po and the Furious Five")
#plt.savefig("kungfu.png")
plt.show()
|
20db25b4f726b986d5ad59109bcd099e8128121a | Khalid-Sultan/Section-2 | /recursive binary.py | 293 | 4.0625 | 4 | def main():
for value in range (10,48):
print("The binary value of",value,"base 10 =",decimalToBinary(value),"base 2")
def decimalToBinary(value):
result=""
while value!=0:
bit=value%2
result=str(bit)+result
value=value//2
return result
main()
|
22b74e7b62bebde25f095665026f8ae712d00423 | n1na-j/weekly-assignments-fds | /Week 2/dict_loginsystem.py | 1,712 | 4.15625 | 4 | # Login accounts
user_login_accounts = {
1: {"first name": "Jughead", "last name": "Jones", "email address": "jughead@riverdale.com", "password": "jughead_riverdale1"},
2: {"first name": "Archie", "last name": "Andrews", "email address": "archie@riverdale.com", "password": "archie_riverdale2"},
3: {"first name": "Veron... |
1f511633739c6e1b48256e86cf84cea276d9e453 | Jabuf/projecteuler | /problems/problem3/Problem3.py | 679 | 3.609375 | 4 | """
https://projecteuler.net/problem=3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
from locals import *
def solution(x):
largest_prime_found = 0
first_prime = 2
biggest_prime = first_prime
primes = [first_prime]
root = sqrt(x)
... |
8e5b727f98616af771e09faba1390cc1e0985a95 | aaroncymor/python-data-structures-and-algorithms | /Array/compress.py | 2,349 | 4.09375 | 4 | def compress(s):
"""
1st step: get all unique characters.
e.g., AABBCCDDaabbccdd = ABCDabcd AABBAA = ABA
"""
unique = ""
temp = ""
for i in range(len(s)):
if i == 0:
unique += s[i]
temp = s[i]
if temp == s[i]:
pass
else:
unique += s[i]
temp = s[i]
"""
2nd step: for each ... |
b8e0e77113625a64e5308b81e6290b5eb236215f | OptimisticPessimist/Teaching-Assistant-Python | /src/solution.py | 198 | 3.671875 | 4 | def add(a, b):
# return 3 # 最初は3を返すだけで a=1, b=2 の戻り値 3 を実現できる
return a + b # `a + b` でaとbがどんな値でもaとbの和を返すようになる
|
6877f2e6339a07f057ab632beb8f54772b7fdd1a | DVDBZN/Schoolwork | /CS136 Database Programming With SQL/PythonPrograms/PRA7 - Age Classifier/Python_AgeClassifier.py | 2,707 | 4.3125 | 4 | #Variables for calculation
baby = 0
toddler = 1
infant = 3
child = 5
teenager = 13
youngAdult = 20
adult = 31
seniorCitizen = 61
centennial = 100
recordHolder = 125
immortal = 1000
category = 0
#User input
age = int(raw_input("Enter your age: "))
#Find which range age fits into and sets category
if age <... |
b1ebe5b9db8047242770616760cdab3db04ef0c7 | kinsonpoon/CUHK | /csci3320/asg2/ex1.py | 2,917 | 3.8125 | 4 | import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
def create_data(x1, x2, x3):
x4 = -4.0 * x1
x5 = 10 * x1 + 10
x6 = -1 * x2 / 2
x7 = np.multiply(x2, x2)
x8 = -1 * x3 / 10
x9 = 2.0 * x3 + 2.0
X = np.hsta... |
507fffc5a595ca363cf60da69aed6c61b27547a0 | coledixon/Python-projects | /random_small_projects/Pokemon Game.py | 3,359 | 3.953125 | 4 | import time
global gold
global poke
gold = 0
poke = 0
def start():
print("\t\tGOTTA CATCH 'EM ALL!")
print("\n")
name = input("INPUT YOUR NAME: ")
print("\t\tINITIALIZING...")
time.sleep(1)
print("Hello, %s. Let's play a game." % name)
time.sleep(1)
print("The object of this game is to ... |
55bc2960127b8a1ea4fe127b6628d53175d3de2f | SANDIPAN22/DSA | /greedyAlgo/coin change.py | 295 | 4.03125 | 4 | ## MINIMUM NUMBER COIN TO FULL FILL THE TOTAL VALUE
def coinChange(coins,value):
coins.sort(reverse=True)
while value:
for j in coins:
if value>=j:
print(j)
value-=j
break
coins=[1,2,5,20,50,100]
coinChange(coins,201) |
9acf48ee3199b69a0fa34542617acf5532a37b2b | will-hossack/Poptics | /examples/surface/SurfacePlot.py | 691 | 3.625 | 4 | """
Example program to create and display a few test surfaces
"""
from poptics.surface import CircularAperture, IrisAperture, SphericalSurface, ImagePlane
import matplotlib.pyplot as plt
def main():
# Make a set of surface
op = ImagePlane(-100,30)
ca = CircularAperture(-10,20)
ia = IrisAp... |
0af6f2a775a95f9d0869f635fe2c70746e087990 | JM0222/Algorithm-Study | /study-07.py | 598 | 3.65625 | 4 | # https://www.acmicpc.net/problem/9012
# 시간: 15분
n = int(input())
def vps(a):
stack = []
for i in a: # 문자열 순회하면서 '(' 나오면 스택에 append)
if i == "(":
stack.append(i)
else:
if stack: # ')' 나오면 pop (스택이 존재할경우)
stack.pop()
else:
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.