blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
050d1a40cd52edbaa112f07caaf261aa4b1d929b | tedtedted/Project-Euler | /004.py | 569 | 4.25 | 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.
"""
palindromes = []
def is_palindrome(num):
string = str(num)
first = string[:]
last = st... |
157c747b2a2bec43efcdc6e91ef94948c667fa7e | llgeek/leetcode | /1110_DeleteNodesAndReturnForest/solution.py | 832 | 3.859375 | 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 delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
self.res = []
to_delete = set(to_delete)
... |
af62bbac155000eaa0994bc376ab5e8324e70f0d | bobur554396/PPII2021Spring | /w3/5.py | 280 | 3.75 | 4 | class Person:
# constructor
def __init__(self, n, a):
# print('Person class constructor called')
self.name = n
self.age = a
def show(self):
print(f'{self.name} -> {self.age}')
p = Person('Person1', 20)
# print(p.name)
# print(p.age)
p.show()
# del p
|
789d310d610b6fbf24038431ea26f52ce51e09a1 | NiamhOF/python-practicals | /practical-18/p18p2.py | 830 | 4.03125 | 4 | '''
Practical 18, Exercise 2
Define a function isCode
assign numcode the value 0
if the length of the string is less than 4
print an error
for all characters in the range 1 to the length of the string:
starting from the first letter in the string check if the next 4 letter are code
... |
b6a12eed08ecbd31ac9670ac8fd8980aa12e6f92 | WilliamW5/Tkinter | /frames.py | 455 | 3.609375 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Frames')
root.iconbitmap('Images\WillRagB.ico')
# puts padding inside of the frame
frame = LabelFrame(root, text="This is my Frame...", padx=50, pady=50)
# packs inside of the outside container
frame.pack(padx=100, pady=100)
b = Button(fra... |
3caec0bde19fc149c0d1d0cecfcfff3fac0c7301 | sach999/ScriptingLab | /ScriptingLab/SEE/6b.py | 899 | 3.609375 | 4 | from operator import itemgetter
sentences = []
class rev:
def __init__(self, sentence):
self.sentence = sentence
def reverse(self):
temp = ""
temparr = []
temparr = self.sentence.split(" ")
temparr.reverse()
for i in temparr:
temp ... |
022bacc77140c5477266cf59e392eb0310b5e7d0 | Ketulia/199-SCHOOL-Introduction-to-Python-for-kids- | /2021-2022/VIII კლასი/8_1/004 (10.11.21)/4_1.py | 553 | 3.875 | 4 | num1 = 3
num2 = 5.78
num3 = 2 + 3j # 'Class <Complex>'
##print(num1, type(num1))
##print(num2, type(num2))
##print(num3, type(num3))
# -----------
##num1 = float(num1)
##print(num1, type(num1))
##
##num2 = int(num2)
##print(num2, type(num2))
# ---------
# real imag
print(num3)
x1 = num3.real
x2 = num3.i... |
bae8e0cb20ba424bb63249a76939811fdd34d972 | Shihabsarker93/BRACU-CSE111 | /Assignment 05/Problem 08.py | 885 | 3.703125 | 4 | # task-8
class Coordinates:
def __init__(self, x_axis, y_axis):
self.x_axis = x_axis
self.y_axis = y_axis
def detail(self):
return (self.x_axis, self.y_axis)
def __sub__(self, other):
a = self.x_axis - other.x_axis
b = self.y_axis - other.y_axis
return Coord... |
36e561aa03f15656d5c234a76b54b975b264c0b0 | buhuipao/LeetCode | /2017/graph/bfs/populating-next-right-pointers-in-each-node-ii.py | 1,310 | 4.125 | 4 | # _*_ coding: utf-8
'''
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/... |
f363b11eaf365e8e5affbbdc4707cd1a6877ea53 | chaitanyakulkarni21/Python | /Balguruswamy/1_Intro_To_Python/ReviewExercises/Prob9.py | 176 | 4.28125 | 4 | #WAP to demostrate While loop with else
count = 0
while count < 3:
print("Inside while loop...")
print(count)
count = count + 1
else:
print('Inside else statement...')
|
a7e0e2b3fadf2567b40b376867ab8b4684282607 | aalyar/Alya-Ramadhani_I0320123_Mas-Abyan_Tugas6 | /I0320123_Soal2_Tugas6.py | 284 | 3.6875 | 4 | nilai = int(input("\nMasukkan jumlah data: "))
print()
data = []
jumlah = 0
for i in range(0, nilai):
temp = int(input("Masukkan nilai ke-%d: " % (i+1)))
data.append(temp)
jumlah += data[i]
rata_rata = jumlah / nilai
print("\nNilai rata-rata = %0.2f" % rata_rata)
|
fcdcb843272006229c80b2c9f1af0d4d5a601d3b | ComputingTelU/SG-Basic-Prerequisite-Gen5.0-Batch2 | /DENI SAPUTRA HERMAWAN/DENI SAPUTRA_jawaban2.py | 745 | 3.75 | 4 | import re
#Deni Saputra
def case_email():
email = re.findall('\S+@\S+',a)
print(email)
def case_uang():
email = re.findall('[0-9]+',a)
b = [int(x)for x in email]
k = re.split(r'\s',a)
jum = 0
for i in k:
if i == "Ribu":
jum = jum + 1
elif i == "Juta":
jum = jum + 2
if jum == 1:
print(b[0]*1000)
... |
64decdde3ee3d645252d0bd34b7e208dc4e0c626 | cravo123/LeetCode | /Algorithms/0356 Line Reflection.py | 1,089 | 3.65625 | 4 | # Solution 1, try to find middle x, and then prove it right
class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
if not points:
return True
d = set((x, y) for x, y in points)
# determine x_mid first
xs = list(set([x for x, _ in points])... |
ebb820d37fde39709f415b0f15be5f3b7a3213b2 | KavilanNaidoo/Lists | /spotcheck(1).py | 691 | 3.828125 | 4 | def initialise_frequency_array():
array = []
return array
def simulate_die_throwing(array):
import random
for count in range(6):
number = random.randint(1,6)
array.append(number)
return array
def display_result_array(array,number):
count = 0
count1 = 0
pri... |
870184e4e0f74a66ecdd724ce26c83d74553c34e | wilbertgeng/LeetCode_exercise | /92.py | 1,559 | 3.71875 | 4 | """92. Reverse Linked List II"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int... |
79c7d89e76247651dc8fe38b3a592a12e4275488 | waggertron/py_exercises | /sorting.py | 2,021 | 3.796875 | 4 | nums = [10, 9, 1, 7, 2, 6, 5, 4, 3, 0]
nums_small = nums[:4]
nums_empty = []
# bogo sort
def bogo_sort(nums):
nums = nums[:]
import random
l = len(nums)
while True:
random.shuffle(nums)
ordered = True
for i in range(1, l):
if nums[i - 1] > nums[i]:
o... |
fcfa703888d4d4ec7876804ea8fe879eac14a6f5 | taalaybolotbekov/chapter1.5-init | /task7/task7.py | 100 | 3.6875 | 4 | for i in range(1,7):
if i == 3:
continue
elif i == 6:
continue
print(i)
|
9e60d8b0e65659ea5b5f8f45d364b6d2f4e11b10 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question48_最长不含重复字符的字符串.py | 629 | 3.765625 | 4 | def solution(string):
position = [-1 for _ in range(26)]
current_length = 0
max_length = 0
for i in range(len(string)):
if current_length == 0:
current_length = 1
else:
if position[ord(string[i])-ord('a')] < 0 or (i-position[ord(string[i])-ord('a')])>current_leng... |
39448aa5caf1b5a0751bac3b70adce7435a0fbd3 | codedeb/OOPS-DESIgn | /cards.py | 1,172 | 3.78125 | 4 | import random
class Card():
def __init__(self,suit, value):
self.suit = suit
self.value = value
def show(self):
print(f'{self.value} of {self.suit}')
class Deck():
def __init__(self):
self.cards = []
self.build()
def build(self):
for card in ['Spade... |
a72142c8e509519bd61409030288eb8445593765 | wh2per/Programmers-Algorithm | /Programmers/Lv1/Lv1_나누어떨어지는숫자배열.py | 229 | 3.75 | 4 | def solution(arr, divisor):
answer = []
arr.sort()
for a in arr:
if a%divisor==0:
answer.append(a)
if len(answer)==0:
answer.append(-1)
return answer
print(solution([3,2,6],10)) |
61474798df10e9d5b2fd7c963d269c372bd8add4 | lastmayday/Euler | /46.py | 1,099 | 3.8125 | 4 | #-*- coding:utf-8 -*-
#! /usr/bin/env python
"""
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false.
What ... |
bd06acf4c0bde80da5e2b87a47991d96dce87a3e | mayankbakhru/random_pycode | /socks.py | 993 | 3.796875 | 4 | def main():
total_socks = int(input())
colors = list(map(int, input().rstrip().split()))
if len(colors) != total_socks:
print ("error")
return 0
if not(1<=total_socks<=100) or not(1<=len(colors)<=100):
print("error")
return 0
numPairs = pair_up(total_socks,colors)
... |
3b61029b4cb0dc8149e155356b857f6932c20bc6 | wxke/LeetCode-python | /46 全排列.py | 351 | 3.765625 | 4 | 全排列
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# a = list(itertools.permutations(nums,len(nums)))
# list1 = []
# for i in a:
# list1.append(list(i))
return list(itertools.permut... |
9fd9471de4bc966cea9bcba6ff38f7e9b18175ca | kguarian/Classification-Algorithms | /knn/k-NN/get_data.py | 4,353 | 3.546875 | 4 | import numpy as np
from sklearn.datasets import load_breast_cancer
df = load_breast_cancer()
print("cancer keys: ", df.keys())
print("cancer feature names: ", df["feature_names"])
print("cancer data: ", df["data"])
# both lists of indices
neighborhood = None
indices = None
# unoptimized.
def shiftRight(array, star... |
dea20be5f3dc3675a907f0f491fef7ba03109fc1 | agomeso/Python-Challenge | /PyPoll/main.py | 2,018 | 3.875 | 4 | import csv
file_path = "./Resources/election_data.csv"
total_votes = 0
election = {"Voter ID": "", "County": "", "Candidate": ""}
got_votes = {}
output_file = "./Analysis/output.txt"
with open(file_path) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfil... |
1593b1347d0e12c2826ed1b3cc97940521b0784e | Athena1004/python_na | /venv/Scripts/nana/multi_inherit.py | 343 | 3.59375 | 4 | #菱形继承实例
class A():
pass
class B(A):
pass
class C(A):
pass
class D(B,C):
pass
#构造函数的调用顺序
class A():
pass
class B(A):
def __init__(self):
print("B")
class C(B):#此时查找C的构造函数,如果没有,则向上按照MRO顺序查找父类,直到找到为止
pass
c = C() |
3745f30adedea7e9bf2393f85ae024f62b76e920 | AkiraKane/CityUniversity2014 | /Useful_Scripts/Remove_Punctuation.py | 259 | 4.25 | 4 | import string
list1 = ['da"!!!n', 'job??', 'dan#][ny']
def punctuationWord(x):
# Remove Punctuation from Word
for letter in string.punctuation:
x = x.replace(letter, '')
return str(x)
for word in list1:
print punctuationWord(word)
|
84a51ac0305ba889c1da2f12694be9834624b36d | Magdatm/isapykrk6 | /Day6/figures_calc.py | 499 | 3.84375 | 4 | # funkcja z dwoma parametrami boku prostokata, funkcja zwraca pole prostokata
def calculate_rectangular_area(side1, side2):
"""
Calculates area of rectangular.
:param side1: integer, greater than 0
:param side2: integer, greater than 0
:return: area based on multiplication of sides
"""
ret... |
a2ba015239b620b4165e7e728ff387263baf6fd7 | TraductoresSeccion2/pruebaKeila | /k2.py | 258 | 3.796875 | 4 | numeros=input("ingrse un numero")
numeros2=input("ingrse un numero2")
print"ingrse 1 para sumar 2 para restar"
respuesta=input(">>")
if respuesta==1:
print"el resultado "+str(numeros+numeros2)
if respuesta==2:
print"el resultado"+str(numeros-numeros2)
|
fbbb8779ac7aebf5cb0b24c3dc1953b7da0906df | hhugoac/CodeFightsPython | /CodeFights/newNumeralSystem.py | 300 | 3.546875 | 4 | def newNumeralSystem(number):
alphabet='ABCDEFGHIJKLMNOPQRSTUVWXY'
ind=alphabet.index(number)+1
ind1=alphabet.index(number)+1
if ind%2==0:
ind=ind/2
else:
ind=ind/2+1
lista=[]
for i in alphabet[:ind]:
lista.append(i+" + "+alphabet[ind1-1])
ind=ind-1
ind1=ind1-1
return lista
|
e2f7d94c200640b462122246c85776e42b9cce93 | idsdlab/basicai_sp21 | /lab_07_logistic_regression/lab-06_logistic_regression_plot.py | 1,630 | 3.5625 | 4 | import numpy as np
from matplotlib import pyplot as plt
# Score
# 0 : Fail, 1 : Pass
data = np.array([
[45, 0],
[50, 0],
[55, 0],
[60, 1],
[65, 1],
[70, 1]
])
# text file input/output
# x = data[:, 0] / 100
x = data[:, 0]
y = data[:, 1]
def sigmoid(x): # 시그모이드 함수 정의
return 1/(1+np.exp(-... |
f44a1f7c8435960f1bdca27692924db5732200a2 | rohit-sonawane/abc-bank-python | /abcbank/bank.py | 815 | 3.796875 | 4 | class Bank:
def __init__(self):
self.customers = []
def addCustomer(self, customer):
self.customers.append(customer)
def customerSummary(self):
summary = "Customer Summary"
for customer in self.customers:
summary = summary + "\n - " + customer.name + " (" + self.... |
bfc04236fc65f8118edebadd41f0a983a23a7917 | sgowris2/coding-practice | /is_palindrome_permutation.py | 1,697 | 4.125 | 4 | # Write an efficient function that checks whether any permutation of an input string is a palindrome.
# Assumptions -
# 1. Only lower case letters.
# 2. Input is always valid, i.e. no empty strings.
# Solution -
# 1. If only one letter, return True.
# 2. If odd number of letters:
# return True if every letter except... |
b1127cfae05b2abf032d742c168903531140f4ae | chaoluo1982/HelloWorld | /test.py | 205 | 3.890625 | 4 | list1= [1,2,3,4]
print (list1[0])
dictionary1 = {"name":"chao","age":"35"}
print (dictionary1.keys())
tuple1= (1,2,3,4)
print (tuple1)
print ("HelloWord1!")
print ("HelloWord2!")
print ("HelloWord3!")
|
ea74c41b820db70531bfbdd4e636c9aa04106816 | AbsolutN/Labb-4 | /LinkedQ.py | 1,813 | 3.5625 | 4 | class Node:
# class för att skapa noder till min linkedQ kö
def __init__(self, value):
# håller koll på värdet (value) av noden samt referens till nästa (next) nod
self.value = value
self.next = None
class LinkedQ:
def __init__(self):
# håller koll på första och sista vär... |
892997793cae1df90559d1c31af78103bb012d05 | roman-bachmann/Mini-DL-Framework | /src/activations.py | 1,829 | 3.984375 | 4 | from module import Module
def relu(input, inplace=False):
'''
Computes ReLU(x)= max(0, x) on an input tensor
Args:
input (FloatTensor): Any FloatTensor to apply ReLU activation on
inplace (bool, optional): Will operate inplace if True
'''
mask = input < 0
if inplace:
... |
39e108cc35cb079f0c0f68ba4e5096b27da82b60 | SzymonSzott/ns-3-netfrastructure | /plot-he-wifi-performance.py | 967 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""nETFRAStructure example Python plotting script
- Description: Plots results of the `he-wifi-performance` ns-3 scenario
- Author: Szymon Szott <szott@kt.agh.edu.pl>
- Website: https://github.com/SzymonSzott/ns-3-netfrastructure
- Date: 2020-06-13
"""
import pan... |
7fad64f829c3e47ca252bb78f39298821e3688e4 | thelsandroantunes/EST-UEA | /LPI/Listas/L3_LPI - funções/exe21l3.py | 892 | 4.1875 | 4 | # Autor: Thelsandro Antunes
# Data: 03/07/2017
# EST-UEA
# Disciplina: LP1
# Professora: Elloa B. Guedes
# 3 Lista de Exercicios (09/04/2015)
# Questao 21: Escreva uma funcao regraMPB que recebe como argumento uma palavra
# qualquer e retorne a palavra invalida caso verifique o uso da letra 'n'
# ... |
f000c8029f82c5f884930211fd8d0c4f35d7f63e | divyanshAgarwal123/PythonProjects | /aptech learning/pyhton idle codes/dict 6.py | 170 | 4.0625 | 4 | data1={100:'ramesh',101:'suraj',102:'alok'}
print(data1)
print(len(data1))
if len(data1) > 10:
print("it is greater then 10")
else:
print("it is smaller then 10") |
978b05b27ae2daac36e613f5490fb59745f57719 | Pedrohjsg/Edu | /librerias/funciones.py | 793 | 3.734375 | 4 | #-*- coding: utf-8 -*-
"""
FUNCIONES:
---------------------------------
def funcion1():
comando1
comando2
[return valor] #Solo para funciones que devuelven un valor
"""
def imprimir(): #Procedimiento
print "hola"
def funcion_holamundo(): #Funcion
return "Hola Mundo"
def nombre(nombre,apellido):
print nomb... |
085baa638935fd76b043950a92dbc9c6f5c94bb9 | chjmil/AdventOfCode2020 | /Day05/binary_boarding.py | 2,328 | 3.921875 | 4 | import argparse
import os
import re
def get_seat_id(input: str):
"""
String contains F, B, R, and L. Convert it to a binary and then to decimal
F means it is the lower half, B means it is the upper half
R means upper half, L means lower half
"""
binary_input = re.sub('F|L', '0', input)
bina... |
e5494f2f0b1a71554be84fe1427883dfc39323b0 | DitooAZ/Python-Games | /Space_Invaders/space_invaders.py | 6,878 | 3.921875 | 4 | # Space Invaders
import turtle
import os
import math
import random # To make the enemy start from random positions
# Set up the screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
wn.bgpic("space_invader_background.gif")
# Register the shapes
turtle.register_shape("invader.gif")
turtle.registe... |
2739d6a85e3539880d9f8773c16c10c30d85742a | MurluKrishna4352/Python-Learning | /def - calculator.py | 1,702 | 4.21875 | 4 | # def function
# calculator
print("HELLO WORLD !!!\n\n")
print("-----> Enter + for addition\n")
print("-----> Enter - for subtraction\n")
print("-----> Enter * for multiplication\n")
print("-----> Enter / for division\n")
#inputs
# addition function
def sum(x , y):
if (input_condition == "+")... |
598fdc0e1c437fb4eeb5a1fd0ada790a2cc4a11f | alexshore/chessai | /Bishop.py | 1,341 | 3.578125 | 4 | # Importing required custom modules.
from Coordinate import Coordinate as C
from Piece import Piece
# Defines widely used global constants.
WHITE = True
BLACK = False
# Starts the definition of the class 'Bishop' using inheritence.
class Bishop(Piece):
# Defines the string representation and the piece value.
... |
b681ebb3c83167b573a3fa9078f8b7d19000c3d8 | SargRub/MachineLearning | /homework_1/main.py | 132 | 3.53125 | 4 | language = input()
with open(f'{language}.text', 'r') as file:
data = file.readlines()
for line in data:
print(line) |
f3fb0dc1537312ac437db62586f240cc8b2ee970 | tengkuhanis/learningpython | /jiman_Quiz_1.py | 2,003 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self):
self.head = None
def AbirLinkedList(self, A, I):
curA = A.head
curI = I.head
while curA and curI:
... |
40b1a0d8c5a2387167eadbb3cd93cb5a4d406c2d | tmr232/ProjectEuler | /problem23.py | 666 | 3.65625 | 4 | from itertools import count, takewhile, combinations_with_replacement
from utils import get_proper_divisors, take
MAX = 28123+10
def is_abundant(number):
return sum(get_proper_divisors(number)) > number
def iter_abundant_numbers():
return (n for n in count() if is_abundant(n))
def main():
print tak... |
cd6ef61aa230a7888ef6c706d77808930789530a | jojonki/atcoder | /abc/abc170a.py | 130 | 3.59375 | 4 | def main():
for i, x in enumerate(input().split()):
if x == '0':
print(i + 1)
return
main()
|
f999d0efe89824d870fcfd20efa1dee625c2ccc6 | liuliuch/robot_test | /testsuite/python/test.py | 411 | 3.640625 | 4 | def shiftingLetters(S, shifts):
"""
:type S: str
:type shifts: List[int]
:rtype: str
"""
# new = S
for i in range (len(shifts)- 1, -1, -1):
for j in range (0, i+1):
char = chr((ord(S[j]) - ord('a') + shifts[i]) % 26+ord('a'))
print(char)
S = S[:j]... |
d25966e165adba86684bfb09c8d45d04365a126c | alessandroliafook/P1 | /unidade4/samu/samu.py | 538 | 3.5 | 4 | # coding: utf-8
# Atendimentos no SAMU
# (C) / Alessandro Santos, 2015 / UFCG - PROGRAMAÇÃO 1
total_atendimentos = 0
atendimentos_mes = []
for i in range(12):
atendimentos = int(raw_input())
total_atendimentos += atendimentos
atendimentos_mes.append(atendimentos)
media_atendimentos = total_atendimentos / 12.0
pr... |
2f57565a11769a916681c3294de2771c1eb729cd | Anjualbin/workdirectory | /OOP/multilevelinher.py | 415 | 3.609375 | 4 |
class Person:
def pvalue(self,name,age):
self.name=name
self.age=age
class Child(Person):
def cvalue(self,address):
self.address=address
print(self.name,self.address)
class student(Child):
def info(self):
print(self.name)
print(self.address)
ch=Child()
ch.... |
45932ddd36dd554da89ddfd44ba8b57b652263cc | henrikmathiesen/python-first-step | /iv_gr.py | 545 | 3.578125 | 4 | #
# Input
print("Enter name")
name = input()
print("Enter EPS")
eps = input()
print("Enter growth rate")
gr = input()
print("Enter current PPS")
pps = input()
#
# Constants
noGrPe = 0.085
rrOfR = 0.03
#
# Convert input
eps = float(eps)
gr = float(gr)
gr = gr / 100
pps = float(pps)
#
# Calculate
iv = (eps * (n... |
26b4746736dd13c1bca90c1a40ea1178f3e12665 | yonatanGal/Recursion-Exercise | /Recursion.py | 4,783 | 4.125 | 4 |
def print_to_n(n):
""" this function prints all the integers from 1 to n"""
if n < 1:
return
elif n >= 1:
print_to_n(n-1)
print(n)
def print_reversed(n):
""" this function prints all the integers from n to 1"""
if n < 1:
return
if n >= 1:
print(n)
... |
af8a72b2a9ad371110fab20f2f37c1fe9aefe3c4 | FabioAguera/IoT | /Ex2_par.py | 143 | 3.65625 | 4 | def epar():
num = float(raw_input())
x = num%2
if (x == 0):
print " par"
else:
print "no par"
|
c564298f9db388be848984bafb39d840bbf5fb73 | sudheemujum/Python-3 | /dict_find_key_value.py | 442 | 3.984375 | 4 | d={100:'A',200:'A',300:'A',400:'D'}
key=int(input('Enter key to get value:'))
if key in d:
print('The corresponding value is:', d.get(key),d[key])
else:
print('Entered key is not available')
value=input('Enter the values to get key:')
available=False
for k,v in d.items():
if v==value:
print('Th... |
716edbaef1bdda0e1854caaf7d40f39ff9e4a4b0 | daniel-reich/ubiquitous-fiesta | /7ECZC8CBEhy5QkvN3_22.py | 145 | 3.671875 | 4 |
def how_many_walls(n, w, h):
area=w*h
if area<n:
walls=n/area
return int(walls)
elif area==n:
return 1
else:
return 0
|
04240f49d75821619da4313f15ec304866baeb90 | obawany/hackathon-uOttawa-CSSA | /NextSequence.py | 3,539 | 3.734375 | 4 | class NextSequence:
# operation = ["*", "+","-","/","^"]
sequence = []
2, 4, 6, 8
def __init__(self):
print("Start")
def ask_sequence(self):
temp = input("Input your sequence, make sure your numbers are split by ',' with no spaces\n")
self.sequence = temp.split(",")
... |
b6b8e982709ab893897efa7eef402499c5b598ac | akochetov/maze | /misc/orientation.py | 1,753 | 4.34375 | 4 | class Orientation:
"""
Orientation of maze, car etc. Means west, east, south and north.
To be replaced with angle against north in the future
"""
def __init__(self):
"""
Dummy init to eliminate warnings
"""
pass
WEST = 'WEST'
EAST = 'EAST'
SOUTH = 'SOUTH'... |
6d8ff57c5bf8f96e7e88eb2c5cddecb93352b078 | Vexild/python---simple-bank-account-manager | /python2.py | 918 | 3.890625 | 4 | #luodaan lista tilitapahtumista
tilitapahtumat = []
#ja lista sallituista operaattoreista
sallitutOperaattorit = set(['o','p','O','P'])
def Task2Function():
saldo = 0
while True:
userInput = input("Anna toiminto: ")
toimitus = userInput[0:1]
summa = userInput[1:]
print("Antamasi... |
951d0fa87641f3b6365238b7dad5d6f118a7bcba | packetscaper/algos | /linkedlist.py | 2,038 | 3.921875 | 4 |
class Node():
def __init__(self,data=None,next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self,new_next):
self.next_node = new_next
class Lin... |
2363ebb4d0cb3b6ffd45f838b4e077ae8472efba | WildDogOdyssey/bitesofpy | /49/packt.py | 1,102 | 3.578125 | 4 | from collections import namedtuple
from bs4 import BeautifulSoup as Soup
import requests
PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html'
CONTENT = requests.get(PACKT).text
# =============================================================================
# with open('packet.html', 'r') as r:... |
0d8d92882f5ae73c5e0331d4909fc18495c4e7eb | vsdrun/lc_public | /co_linkedin/68_Text_Justification.py | 3,757 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/text-justification/description/
Given an array of words and a length L,
format the text such that each line has exactly L
characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is,
pack... |
3518cdb1dfc46e9248e59481d60bffa9e0ffcd9d | renu0028/PythonScripts | /upper.py | 137 | 3.75 | 4 | l=[]
print("Enter multiple lines: ")
while True:
line=input()
if line:
l.append(line)
else:
break
s="\n".join(l)
print(s.upper())
|
c69d8515bc4054873d41bfb1158909295d68168e | shangxiwu/services | /Module_10_DNN神經網路介紹/corelab_10.2_sol.py | 561 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # MNIST資料集的操作
# In[1]:
from tensorflow.examples.tutorials.mnist import input_data
# ## 請將MNIST資料集讀取進來,取出第一筆資料印出,並以簡單判斷式判斷該資料為哪個數字
# In[2]:
# Load mnist dataset
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
batch_xs, batch_ys = mnist.train.next_batch(1)
... |
00928bceaabe5fd4ebc691b89ef4e60bf114fbb4 | jekhokie/scriptbox | /python--learnings/coding-practice/key_with_max_dict_value.py | 367 | 4.1875 | 4 | #!/usr/bin/env python
#
# Find and print the dictionary key with the maximum same value.
#
def largest_value(my_dict):
print(max(my_dict.items(), key=lambda x: x[1])[0])
if __name__ == '__main__':
print("Should print: {}".format(1))
largest_value({1: 5, 2: 3, 3: 2})
print("Should print: {}".format(6)... |
4d4ca4f3fa3e7bdcb90386245e60be758249f97e | srdoty/crypto-hw11 | /represent.py | 1,700 | 4.28125 | 4 | # Convert strings to integer representations and back again to
# strings. This is needed for implementing all public-key
# cryptosystems, which assume the plaintext is representated by
# some integer.
URADIX = 1114112 # The unicode upper range limit (CONSTANT)
def rep(string):
"""returns an integer representation... |
d2d4b26bad7a7c6a0e633b3d6dac0c5e6a9ee113 | suprajaarthi/Favourite-Snippets | /order of occurence.py | 411 | 3.59375 | 4 | def isSubSequence(str1,str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j<m and i<n:
if str1[j] == str2[i]:
j = j+1
i = i + 1
else:
i = i + 1
return j==m
# Driver Program
str1 = "skillrack"
str2 = "superkoolfil... |
b10619b16b03c0b849be4a232e8ae01184564f47 | Morael/CoffeeMachine | /Coffee Machine/task/machine/coffee_machine.py | 5,570 | 3.890625 | 4 | class CoffeeMachine:
def __init__(self):
self.machine_has = {"water": 400, "milk": 540, "coffee beans": 120, "disposable cups": 9, "money": 550}
self.espresso_needs = {"water": 250, "milk": 0, "coffee beans": 16, "disposable cup": 1, "cost": 4}
self.latte_needs = {"water": 350, "milk": 75, "... |
9807e8b9fcfc63246f1d287d6d5a6dd48efe3a91 | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | /Chapter_10/ch10_ex1.py | 23,807 | 3.859375 | 4 | #!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 10. Example 1. JSON
"""
# Persistence Classes
# ========================================
# A detail class for micro-blog posts
from typing import List, Optional, Dict, Any, Default... |
da91a0b01674fd79aee23c93acd3e452a3d334d4 | 6306022610113/INEPython | /week3/if_elif3.py | 347 | 4.25 | 4 | inchar = input("Input one character:")
if inchar >= 'A' and inchar <= 'Z':
print("You input Upper case Letter ", inchar)
elif inchar >= 'a' and inchar <= 'z' :
print("You input Lower Case Letter" ,inchar)
elif inchar >= '0' and inchar <= '9':
print("You input Number" ,inchar)
else :
print("It's not a l... |
170047a8098af321aba57d75319bdd1524efa6fe | chenliu0831/Hackathon | /mergesortlist.py | 290 | 3.765625 | 4 | def mergeTwosortedlist(l1,l2):
res=[]
i1=0
i2=0
while i1<len(l1) and i2 <len(l2):
if l1[i1] <=l2[i2]:
res.append(l1[i1])
i1+=1
else:
res.append(l2[i2])
i2+=1
while i1<len(l1):
res.append(l1[i1])
i1+=1
while i2<len(l2):
res.append(l2[i2])
i2+=1
return res
|
f49654a90459ad6aafbd485c1c26cd8af9b6390f | gmlwndlaek/p1_201110251 | /w9Main.py | 286 | 3.53125 | 4 | def charCount(word):
w= word
d=dict()
for c in w:
if c not in d:
d[c]=1
else:
d[c]=d[c]+1
print d
def lab9():
charCount('sangmyung')
def main():
lab9()
if __name__=="__main__":
main()
|
8e4465f9254d7febf1990abfb7b4d55a8d76215e | rolika/quipu | /scripts/menu.py | 19,410 | 3.515625 | 4 | from tkinter import *
import szemelyurlap
import szervezeturlap
import projekturlap
import ajanlatkeresurlap
import ajanlaturlap
class Fomenu(Frame):
"""A főmenüből történik az alkalmazás kezelése."""
def __init__(self, master=None, kon=None, **kw) -> Frame:
"""A főmenü saját tkinter.Frame-ben kap hel... |
54c174d41a205e20c5e428b93234c4bd7e3c2a45 | ahmad-elkhawaldeh/ICS3U-Unit6-03-py | /small.py | 658 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Ahmad
# Created on: Jan 2021
# This program uses an array
from random import randint
def find_smallest(array):
smallest = array[0]
for num in array:
if num < smallest:
smallest = num
return smallest
def main():
array = []
for loop in ra... |
4683696d065d888e9a452c6340437b43fc71d74b | jz33/LeetCodeSolutions | /T-1055 Shortest Way to Form String.py | 2,160 | 4.0625 | 4 | '''
1055. Shortest Way to Form String
https://leetcode.com/problems/shortest-way-to-form-string/
From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).
Given two strings source and target, return the minimum number of subsequences of source such that t... |
3b46a3202e489991a16d81f98c329c3e67a6fe45 | gonchigor/ormedia | /lesson5/orange.py | 497 | 3.84375 | 4 | class Orange:
def __init__(self, w, c):
self.weight = w
self.color = c
self.mold = 0
print('Создано')
def rot(self, days, temp):
self.mold = days * temp
or1 = Orange(10, 'dark orange')
print(or1)
or1.weight = 228
or1.color = 'pink orange'
print(or1.weight)
print(or1.co... |
84cfd6d481be7f9acd576b6ef9be231aa1cfdf40 | AKHeit/LeetCode | /Algorithms_LinkedLists/Code/143_ReorderList/v0_save0.py | 2,937 | 3.734375 | 4 | """
Problem: 143 Reorder List
Level: Medium
Tags: Linked List
Technique:
Status:
Problem Description:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example: Given {1,2,3,4}, reorder it to {1,4,2,3}
Lesson: ... |
15c7cd091e8f9fed767ceb2fabd8fb053a66b85a | tares003/CWVotingSystem | /voting_system/models.py | 4,522 | 3.6875 | 4 | """
class of student
Students eligible to vote are also stored on a simple text file called StudentVoters.txt. The contents of this file are
simply records, on separate lines, each containing the student user login ID and password name and separated by a
single space or comma.
"""
class login_management:
def __in... |
9a5c2495e7f7fca9a8d269c97928e98c1f0971ad | HesterHuisman/BasicTrack | /Week 4/4.9/Assignment 4.3.py | 289 | 3.65625 | 4 | import turtle
def draw_poly(t, n, sz):
for _ in range(n):
t.forward(sz)
angle = 360/n
t.left(angle)
paper = turtle.Screen()
paper.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
draw_poly(tess, 8, 50)
paper.mainloop()
|
c0332ac07f302ba921233f2ba5beb0b53dbd4497 | alirezaaali/LearnPyhthon | /Begginer/forLoop_samples.py | 443 | 4.125 | 4 | '''
Here is some useful methods
You can find more information in
https://www.w3schools.com/python/python_for_loops.asp
'''
# Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
# simple
# for x in range(11):
# print(x)
# complex
# for x in range(0, 11, 1):
# print(x)
# Jadval zarb
result... |
c2ee2574cfec20002dffafd8a5bc8f56b8b06381 | goragottsen/python-data-structures | /LinkedList/ll.py | 1,964 | 4.03125 | 4 | class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
... |
b7533f3e162ebae9888ee324398664875d142d75 | amberno1111/Data_Structure_and_Algorithm | /LeetCode/Python/Power_of_Three.py | 425 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# 给定一个整数,编写一个函数判断它是否是3的幂
# -------------------------------------------------------------------
import math
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
... |
ca61dcd177b393e04153b09873be709582412a83 | PacktPublishing/big-data-analytics | /Chapter 4/DataSourceJson.py | 662 | 3.515625 | 4 | # Copy input dataset(people.json) to HDFS and then get into PySpark Shell. To read json file, use format to specify the type of datasource.
df_json = spark.read.load("people.json", format="json")
df_json = spark.read.json("people.json")
df_json.printSchema()
df_json.show()
# To write data to another JSON fi... |
7d1521d75b16224384081722d8ce9f28adbba32c | Pallapupoojitha/guvi | /pooji6.py | 96 | 3.5625 | 4 | N=int(input())
if("n<0" or "n%1!=0"):
print("no")
else:
k=0
while(n!=0):
k=k+n
n=n-1
print("k")
|
a7be2bcd7e84109b50e169d37a42d113298d3f96 | nejads/aoc-2020 | /aoc1.py | 4,045 | 3.8125 | 4 | def getInputAsArray():
input = """1945
2004
1520
1753
1463
1976
1994
1830
1942
1784
1858
1841
1721
1480
1821
1584
978
1530
1278
1827
889
1922
1996
1992
1819
1847
2010
2002
210
1924
1482
1451
1867
1364
1578
1623
1117
1594
1476
1879
1797
... |
27a08e7e31b5d88e7dbde53f9f42d15aed74c02c | sanket-qp/codepath-interviewbit | /week4/bit_manipulation/reverse_bits.py | 566 | 3.84375 | 4 | """
https://www.interviewbit.com/problems/number-of-1-bits/
"""
def reverse_bits(n):
result = 0
counter = 32
while counter >= 1:
counter -= 1
right_most_bit = n & 1
print result, bin(result)
print n, bin(n)
result = (result << 1) + right_most_bit
n = n >> 1
... |
846deb83384e0dffdeefb76982fc2f16ed36f1f7 | tantakotan/PIKUMIN | /module/csv_process.py | 546 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import csv
def columns_of_index(arg1, arg2):
with open(arg1, 'r', encoding='utf-8_sig') as f:
tpl = csv.reader(f, delimiter=',')
tpl_list = []
index_list = next(tpl)
index_num = [i for i, x in enumerate(index_list) if x == arg2]
if len(index_num) >= ... |
1f4f0313c1a26503185fe3a916c8e15072ef7a89 | jmavis/CodingChallenges | /Python/CompressedSequence.py | 817 | 3.875 | 4 | import sys
def ReadFile(file):
""" Reads in and parses the lines of the given file."""
for line in file.readlines():
line = line.rstrip() #remove endline
numbers = line.split(' ');
currentNumber = numbers[0];
countOfCurrentNumber = 0;
for number in numbers:
if ... |
1db08839ef6ca99d746327ac2ede2deb253c6fae | sashakrasnov/datacamp | /14-interactive-data-visualization-with-bokeh/2-layouts-interactions-and-annotations/11-adding-a-hover-tooltip.py | 2,042 | 4.0625 | 4 | '''
Adding a hover tooltip
Working with the HoverTool is easy for data stored in a ColumnDataSource.
In this exercise, you will create a HoverTool object and display the country for each circle glyph in the figure that you created in the last exercise. This is done by assigning the tooltips keyword argument to a list... |
15e09951c7218d856379162f4e7e1515a016e3fc | Kushal997-das/Hackerrank | /Hackerrank_python/3.string/26.The Minion Game.py | 424 | 3.75 | 4 | def minion_game(string):
# your code goes here
sum1=0
sum2=0
vowel="AEIOU"
for i in range(len(s)):
if s[i] in vowel:
sum1=sum1+(len(s)-i)
else:
sum2=sum2+(len(s)-i)
if sum1>sum2:
print("Kevin",sum1)
elif sum2>sum1:
print("Stuart",sum2)... |
cce8e43602932adf5985e8eaa02e70b2dcaa2583 | jakehoare/leetcode | /python_1_to_1000/214_Shortest_Palindrome.py | 1,497 | 3.984375 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/shortest-palindrome/
# Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it.
# Find and return the shortest palindrome you can find by performing this transformation.
# Least number of characters ad... |
2519dae9444fa810582ef8f66da69286b94ab28f | zhenghaoyang/PythonCode | /ex19.py | 819 | 3.75 | 4 | # --coding: utf-8 --
#定义函数
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print "You have %d cheese!" %cheese_count
print "You have %d boxes of cracker!" %boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directl... |
5d9b8e4cc24ff766be67c1d0369539076b91ef5b | mwrouse/Python | /Design Exercises/die_roller.py | 392 | 3.765625 | 4 | """
Program: die_roller.py
Author: Michael Rouse
Date: 11/4/13
Description: Dice rolling function
"""
import random
def die_roller (sides, modifier=0):
""" Function to similater dice rolling """
# Generate random number between 1 and the sides of the dice
roll = random.randint(1, sides)
... |
72aeac11ea58d82179513b5c97dc8e392af3ef39 | pavananms/lp3thw | /ex5.py | 329 | 3.765625 | 4 |
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'blue'
teeth = 'white'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair}... |
47cdad3f51c6724a11cb435cd49e13ec4d02b7a3 | LiangZZZ123/algorithm_python | /1/02_linked_list.py | 6,022 | 4.03125 | 4 | """
LinkedList: addleft, addright, popleft o(1)
popright o(n), because must traverse to the second-last node
LinkedList是便于FIFO(addright, popleft)的o(1), 所以本身就是一个queue的最优实现
如果要做到LIFO的o(1),即stack的最优实现, 必须借助DoublyLinkedList.
因为LinkedList的popright 是o(n)
Array: addright, popright, o(1), when the assigned me... |
c4b45de3330b79ef221befcaa3811a4300f2f9bc | CCommandoApero/Javascript-Python | /MotLePlusLong.py | 198 | 3.53125 | 4 | texte = input ("Mets ta phrase wesh :")
mot_long = ""
mots = texte.split()
for mot in mots:
if len(mot) > len(mot_long):
mot_long = mot
print (mot_long)
|
6fd8cb0e737090e1c7d790193e4e975fd7ee7836 | nirvaychaudhary/Python-Assignmnet | /data types/question9.py | 228 | 4.40625 | 4 | # write a python program to change a given string to a new string
# where the first and last chars have been exchanged.
def exchange(str1):
swap = str1[-1:] + str1[1:-1] + str1[:1]
return swap
print(exchange("Hello")) |
c70243b6a1efa887c7908a60eabe0ae51d02d1c4 | Athithya6/MyCaptain-Python | /Task1.py | 120 | 4.125 | 4 | r=float(input("Enter the radius of the circle"));
print(r);
a=3.14*r*r;
print("Area of the circle is:");
print(a);
|
7d60df5b6e2db447b854a00549b04d99faebd757 | Wiinterfell/adventofcode2k19 | /day1.py | 196 | 3.640625 | 4 | import sys
total_fuel = 0
with open("input1.txt") as fp:
for line in fp:
fuel = int(line)
while (fuel > 0):
fuel = fuel / 3 - 2
if (fuel > 0):
total_fuel += fuel
print(total_fuel) |
b0b197832c7784f31bed8208e1b3127a116bc5e4 | redline-collab/Python-Basic-Programs | /Compound_Interest.py | 268 | 3.96875 | 4 | # To Finf Simple Intrest
print("Lets Find Compound Interest!")
p = int(input("Enter Principal Ammount:"))
r = float(input("Enter Rate of interest:"))
t = int(input("Time Interval of Interest in Terms of Year:"))
pi = p*(1+r/100)**t
print("Compound Interest is:",pi) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.