blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5af725b770a3330f78837f5dac0f56c43f9742a7 | Parth-Gandhi96/win_app_pa2 | /code_wine_predict.py | 4,921 | 3.53125 | 4 | import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
# check weather correctly imported or not
# print(pyspark.__version__)
# df = spark.sql("select 'spark' as hello ")
# df.show()
def loadDataFile(fileName):
df = (spark.read
.format("csv")
.options(... |
e56ac7b1c9a74370ed61483b83e053a16485bf4e | iWonder118/atcoder | /python/ABC086/B.py | 156 | 3.578125 | 4 | number = list(input().split())
int_number = int("".join(number))
for i in range(1,1000):
if i ** 2 == int_number:
print("Yes")
exit()
print("No")
|
583501fd9ae9134b2544d0bd5274c048da31098b | jdanray/leetcode | /movesToMakeZigzag.py | 1,142 | 3.53125 | 4 | # https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/
"""
The strategy is simple:
nums is a zigzag array if it satisfies either one of two conditions.
Say that a zigzag array can be either a zig array or a zag array.
So:
Try to transform nums into a zig array using only the necessary number of move... |
8b5da5a72f3004731d12610d0f311e629cdc76ca | SurajPatil314/Leetcode-problems | /DFS_canVisitAllRooms.py | 1,324 | 3.609375 | 4 | """
https://leetcode.com/problems/keys-and-rooms/
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have
some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] w... |
176801df18134b922109e60c600d0495416d3fdd | suavelad/Python_Mini_Projects | /msgCipher.py | 1,320 | 4.5 | 4 | #! usr/bin/python3
"""
This Program encrypts and decrypts messages
"""
import pyperclip
def Cipher():
try:
# mode ="encrypt" # or decrypt
mode = input("Do you want to \" encrypt \" or \" decrypt\" ? >>")
message=input("Insert the Message you want to {} >>".format(mode))
#en... |
4944d061a628348d34c40620d244d5557645cd3a | Mohali22/kalbonyan_elmarsos | /#1 Programming Foundations Fundamentals/3- variables and data types/chapter_summary.py | 2,507 | 4.625 | 5 | ##### Chapter Summary (variables and data types) #####
#----------------------------------------------------#
# What are the variables #
# ---------------------- #
# We use variables to save data in memory, to be used in our program
# The variable is created by typing the variable name, and then marks an equal, and th... |
0df5b12b3e929b12a504a6cac07d1362812a1232 | epsomsegura/evaluacion_software_centrado_usuario | /Kappa_De_Cohen/kappa.py | 1,101 | 3.5625 | 4 | """
Exp. educativa: Evaluación de sistemas interactivos
Ejercicio: Kappa de Cohen
Por: Epsom Enrique Segura Jaramillo
Detalles:
-Resultado obtenido: 0.185
"""
import sys, pandas, numpy
data_1 = pandas.read_csv(sys.argv[1], delimiter = ';')
# Coincidencias
ccb = 0
ccr = 0
ccm = 0
# Evaluador 1
ce1b = 0
ce1r = 0... |
120a74c811ec99f5afcae782716740cdda46a35c | kimseonjae/Python-basic | /practice01/01.py | 507 | 3.796875 | 4 | # 문제1. 키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요
while(True):
v = 0
a = input('숫자를 입력해주세요. ')
for i in a:
if (48 <= ord(i) and ord(i) <= 57):
v += ord(i)
else:
v = str(v)
if (type(v) == int):
if v % 3 == 0:
print('3의 배수 입니다')
elif v % 3 != 0:... |
51850fef3f97401438b3014f4548bd1633f9887b | deltahalo099/physics-251 | /classwork/while.py | 275 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 6 10:57:54 2020
@author: Ziron
"""
import numpy as np
from numpy import random
a = random.random(5)
b = np.random.random(10)
print(a)
print(b)
i = 0
while i < 10:
print(i)
i+=1
for i in range(5, 0, -1):
print(i)
|
af7eebe9095557fd1daec4968193103488dd21ff | Sakib1248/myappsample | /elif_example.py | 444 | 4.125 | 4 | name = 'Bob'
age = 3000
if name == 'Alice':
print('Hi Alice')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, granie.')
print('Hello world!')
print('What is your ... |
cf4d17c0a2c9df95c5e45b3fc8f87810db3da20a | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex093.py | 759 | 3.671875 | 4 | jogador = {}
lista = []
total = 0
jogador['Nome'] = input('Nome do jogador: ')
quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome'])))
for i in range(0, quantidade):
gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1)))
total += gol_quantidade
lista.append(gol_qu... |
1059def94d3ef7b77ccbab4fc2b1294f8f7d9d4a | stilyantanev/Programming101-v3 | /week4/1-Music-Library/song_test.py | 2,676 | 3.6875 | 4 | import unittest
from song import Song
class SongTest(unittest.TestCase):
def setUp(self):
self.test_song = Song("Rehab", "Rihanna", "Good Girl Gone Bad", "4:35")
def test_create_new_instance(self):
self.assertTrue(isinstance(self.test_song, Song))
def test_valid_members(self):
s... |
9ad49ad3b24aebc6964f03ab2f18a69df4707e65 | keryl/2017-04-02 | /month.py | 497 | 4.375 | 4 | def is_month(month):
# first check given month is string
if type(month) != str:
return "argument should be of type string"
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
# return True if given month is in months list
if month in months:
... |
dd675109aca17bec1830679f27fa7292ea8a4966 | gonzdeveloper/Python | /Ejemplos Poo y Algoritmos/problema_de_la_mochila.py | 643 | 3.609375 | 4 |
def mochila(tamano_mochila, pesos, valores, n):
if n == 0 or tamano_mochila == 0:
return 0
if pesos[n-1] > tamano_mochila:
return mochila(tamano_mochila, pesos, valores, n-1)
# el maximos de los valores con el esapacio disponible que tengo
return max(valores[n-1] + mochila(t... |
851b02041121e13e5caef371b210873848396727 | retzkek/projecteuler | /python/eu007.py | 1,204 | 3.75 | 4 | #!/usr/bin/python
# encoding: utf-8
"""
project euler (projecteuler.net) problem 7
solution by Kevin Retzke (retzkek@gmail.com), April 2009
"""
class primes:
def __init__(self, max):
self.numbers = range(2, max+1)
self.primes = []
def next(self):
"""
return next prime
""... |
e7aacd4c6f1b1d3fa6eb5f8c6a2ce8da6841e858 | yuliiasv/hackerRank | /emptyString.py | 626 | 3.65625 | 4 | #!/bin/python
import sys
def super_reduced_string(s):
changed = True
while changed:
i = 0
l =len(s)
changed = False
while i < l:
if i != l-1 and s[i] == s[i+1] :
if i == 0 :
s = s[i+2:]
else:
... |
2168464562e6502fedb22757948cc7465a6d377f | PawelKapusta/Python-University_Classes | /Lab5/rekurencja.py | 490 | 4.09375 | 4 | def factorial(n):
if n == 0 or n == 1:
return 1
else:
output = 1
for element in range(2,n+1):
output = output * element
return output;
def fibonacci(n):
if n == 0 or n == 1:
return n
else:
previous_number = 1; output = 1
for element in ran... |
d51168d8b011528a0eb1b9901824222d58825789 | Wxianpeng/Python_Exercise | /com/study/normal/work1.py | 1,376 | 4.0625 | 4 | # 1.print输出多个变量
# print("admin")
# name = "王"
# age = 20
# address = "山东"
# print("姓名是:%s,年龄是%d,地址是%s" % (name, age, age))
# 没有do - while switch
# if -else 嵌套
# age = 19
# if age > 18:
# print("我成年了")
# elif age > 30:
# print("我在 18-30岁之间")
# else:
# print("我为成年")
# 判断
# 去如果当前用户是男性的话 ,那么 就输入判断女性的要求
#... |
6e5086c9b19b7752cdae26f8daf699063367e174 | sameersaini/hackerank | /Trees/BstInsertion.py | 724 | 4.28125 | 4 | #Node is defined as
#self.left (the left child of the node)
#self.right (the right child of the node)
#self.info (the value of the node)
def insert(self, val):
#Enter you code here.
newNode = Node(val)
if self.root == None:
self.root = newNode
return
node = ... |
2e9c974f627ef8b34bbe0c78b765308dcb5f5459 | rudyuu/prograproyectos | /ascendente.py | 707 | 3.5 | 4 | import psycopg2
def calculo():
num1 = int(input("inicial "))
num2 = int(input("final "))
conexion = psycopg2.connect(host="localhost", database="tarea", user="postgres")
cursor1=conexion.cursor()
sql="insert into ascendente(inicio, final) values (%s,%s)"
if num1 < num2:
datos=(num1, num2)
cur... |
db508f76fb1874047351758fba5eb0a3291b5273 | sulaimaan26/getdaycalendar | /calendarlogic.py | 1,368 | 3.53125 | 4 | class GetCal:
@classmethod
def getdayvalue(cls, reminder):
lst = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
return lst[reminder]
@classmethod
def getmonthvalue(cls, actualmonth):
lst = [0, 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
return ls... |
1b4725f7946369811743b11b4ed24b90bf3f66ac | DonggyuLee92/solving | /2020 Nov/1109/6326/6326.py | 400 | 3.84375 | 4 | # num = int(input())
ans = 0
def factorial(num):
if (num>1):
return num * factorial(num-1)
else:
return 1
print(factorial(5))
# def factorial(n):
# if n == 1: # n이 1일 때
# return 1 # 1을 반환하고 재귀호출을 끝냄
# return n * factorial(n - 1) # n과 factorial 함수에 n - 1을 넣어서 반환된 값을 곱함
#
#
#... |
0491e4fa34c872c7992c97b78b76f505dea07348 | imabhishekkumar/GUVI-Sessions | /string.py | 464 | 3.828125 | 4 | class string:
def copy(self,inp):
return "".join(inp)
def rev(self,inp):
revInp=[]
l=len(inp)
last=l-1
for i in range(l):
revInp.append(inp[last])
last=last-1
return "".join(revInp)
class test:
inp= list(input("Enter... |
10cc2e950a49460bf2423440f1f6edbf5cdddcb3 | suryanjain14/prat | /foobar last.py | 242 | 3.546875 | 4 | import base64
encrypted = "CFIBDAINDxIaSREOU1IVCwQPHkZFThZXHBkeHAAJHwROTgsUVBABDQQLBwQNSR0UVBAUHw4cHhJO TgsUVBwcGhMLDggLAlQTX1VVGAIGAwQfC1xRHQFVWVtOTRQHAl5XGBAWXk1OTRMIDFNdBwZVWVtO TRIICFQTX1VVHw4BTUFTThZDGhtTXhw="
key = str.encode("suryanjain14")
decoded = base64.b64decode(encrypted)
decrypted = ""
for letter in ra... |
f156c1f58356548d2dfcb0c3f02fa2d22c0e2f80 | Tasari/University_things | /Bioinformatics-intro/Zestaw 2/Python/Zadanie4.py | 94 | 3.5 | 4 | print("Wprowadziles tekst posiadajacy "+ str(len(input("Podaj tekst\n").split())) + " wyrazy") |
89d3fbc0b8f1fc4889dcb8cdf50acfe2294529f4 | jamircse/Python-Database | /Python sqlite database/database.py | 716 | 3.6875 | 4 | '''
import sqlite3
conn = sqlite3.connect('database.db')
if(conn):
print("Opened database successfully");
cursor = conn.execute("SELECT *FROM user");
for row in cursor.fetchall():
print("ID = ", row[0])
print("NAME = ", row[1])
print("pass = ", row[2])
'''
from sqlite3 import connect
# Replace username wi... |
ca8c050b52febd08b7b9d48481765fe3cf082224 | cooks16/210CT | /Q6_Reverse.py | 236 | 3.9375 | 4 | def reverse(a):
b = ""
c = ""
for i in a:
if i != " ":
b += i
else:
c = b + " " + c
b = ""
c = b + " " + c
return c
print(reverse("This is awesome"))
|
553573a71ebbc15d14f2c81daed919574ccdf22c | AmanSingh1611/Sorting-Algos | /selectionsort.py | 265 | 3.78125 | 4 | def selection_sort(arr):
for i in range(0,len(arr)-1):
min_val = i
for j in range(i+1,len(arr)):
if arr[j]<arr[min_val]:
min_val=j
if min_val!=i:
arr[min_val],arr[i]=arr[i],arr[min_val]
arr=list(map(int,input().split()))
print(selection_sort(arr)) |
39ca36a2c4265df09230d520f75c9016a77ce6cf | amberhappy/-offer | /6-旋转数组的最小数字.py | 638 | 3.515625 | 4 | #把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
# 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
# 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
# NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
class Solution:
def miniNuberInRotateArray(self,rotateArray):
if len(rotateArray)==0:
return 0
ret = rotateArray[0]
fo... |
092c71dbe882bd7da7bb343b9a62468ae54b3923 | runda87/she_codes_python | /hello_world.py | 482 | 3.921875 | 4 | print("Hello, Anika!")
day = "Monday"
month = "June"
print(f"Today is: {day} and the month is:{month}")
# print (day)
# print (month)
# this is a comment / notes
run1_dist = 1400
print(run1_dist)
print(type(run1_dist))
run2_dist = 1800
total_distance = run1_dist + run2_dist
difference = run2_dist - run1_dist
print(... |
8296ec6ac2aab3360f6ce546562ba8364c6724f5 | QinmengLUAN/Daily_Python_Coding | /wk12_DP_numRollsToTarget_LC115.py | 1,641 | 4.09375 | 4 | """
1155. Number of Dice Rolls With Target Sum
Medium: DP, Recursion
Time complexity: O(d * f * target)
Space complexity: O(d * target)
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up ... |
b9ef90312083e70a3f72f5a2a9136a7d964a1c78 | LarisaOvchinnikova/Python | /1 - Python-2/13 - dict comprehension/from lesson.py | 865 | 3.671875 | 4 | print({i: i+2 for i in range(5)}) # {0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
arr = ['a', 'b', 'c']
dct = {el: i for i, el in enumerate(arr)}
print(dct) # {'a': 0, 'b': 1, 'c': 2}
square = {i: i**2 for i in range(1, 10)}
print(square)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
square = {i: i**2 for i... |
d7476d87016ea73e2f4e0591c6de4fca1a4843ab | morgan-lang/python | /week04/index-string-as-array.py | 731 | 4.09375 | 4 | import random
import time
word = input("type a word: ")
time.sleep(1)
print("The word you typed was", word, ".\n", "Now check this out. Cover the letter column with your hand and try to\n"
"determine the letter based on index position. Remember that positive\n"
... |
7ec90b98db4f484d3094f0fff7aa197bbf658dd6 | thijsvandamme/LearnPythonTheHardWay | /ex4.py | 966 | 4 | 4 | # assign 100 to the name cars
cars = 100
#assign a floating point to then name space_in_a_car
space_in_a_car = 4.0
#make variable drivers
drivers = 30
#make variable passengers
passengers = 90
#make a variable and fill it with a substraction of 2 other variables and their contents
cars_not_driven = cars - drivers
#give... |
0ce184f2ced4b583a00040bfc005edc0965e5131 | sfsharon/cpu_friend | /adi_py.py | 2,441 | 3.515625 | 4 | """
Calculate working point for CPU power usage Vs. temperature
23 Feb 2019
"""
class myDB :
"""
Wrapper class for database
"""
# Implementing a function table values :
# Key in self.db is the non-dependant variable x, and value is the function value f(x)
db = {1:20.3, 2:40.55, 3:89.02}
d... |
1e904a0e3869488371b198b107a0451fc011fc96 | Rajveer3311/PYTHON | /csv_file.py | 284 | 3.734375 | 4 | from csv import reader
with open("file.csv") as f:
csv_reader=reader(f)
next( csv_reader)
for i in csv_reader:
print(i)
# from csv import reader
# with open("file.csv") as f:
# csv_reader=f.readlines()
# for i in csv_reader:
# print(i,end='') |
86cb8d1daafa17cdb8296fa4335a284e00642bf2 | narayancseian/Programming-For-Everybody-Using-Python- | /assignment_7.2.py | 338 | 3.53125 | 4 | fname = input("Enter file name: ")
fhand = open(fname)
avg = 0
count = 0
for line in fhand:
if not line.startswith("X-DSPAM-Confidence:"):
continue
pos = line.find(" ")
val = line[pos:].rstrip()
val = float(val)
count = count + 1
avg = avg + val
print("Average spam confiden... |
e464674f721cbb5bca59e1f576660a494a955e66 | anirudhdahiya9/Open-data-projecy | /IIITSERC-ssad_2015_a3_group1-88a823ccd2d0/Akshat Tandon/201503001/person.py | 438 | 3.59375 | 4 | import item
class Person(item.Item):
"""
This class inherits from Item class and is the superclass of
Player,Donkey and Princess subclasses
"""
def __init__(self,x,y,width,height,image_path):
""" Constructor of Person class"""
super(Person,self).__init__(x,y,width,height,image_path)
def get_position... |
4c3c48c06f7c998da63387b6b92e716d34dc65d7 | open-covid19/covid19-api | /covid19_countries/utils.py | 950 | 3.828125 | 4 | from typing import Dict, Union, List
from stringcase import camelcase as camel
from stringcase import lowercase as lower
from stringcase import snakecase as snake
import re
def recursive_camel_case(obj):
if isinstance(obj, dict):
return _handle_dict(obj)
elif isinstance(obj, list):
... |
38e46b041f0cdf56198d0ee99b9c8afd6d04e48e | Darshan110801/Heap-Management-Simulator | /BT19CSE070_CPL_ASSIGN3_CODE.py | 9,547 | 3.5625 | 4 | from tkinter import *
#globals
mem_size = 64
#Linked list utilities
class free_node:
def __init__(self,tag,size):
self.tag = tag
self.size = size
self.next = None
self.prev = None
#initially whole memory is free
free_head = free_node(0,mem_size)
def delete_node(itr):
global fre... |
93586e72faabf0da7f5f5d72261bd4e314b9f1cf | vishaldhateria/100daysofcode | /18-August-2020/arraytranspose.py | 423 | 3.75 | 4 | # my_array = numpy.array([[1,2,3],
# [4,5,6]])
# print numpy.transpose(my_array)
# #Output
# [[1 4]
# [2 5]
# [3 6]]
# my_array = numpy.array([[1,2,3],
# [4,5,6]])
# print my_array.flatten()
# #Output
# [1 2 3 4 5 6]
n, m = map(int, input().split())
array = numpy.ar... |
faf090a9485afb50c4cf7e5dbd26101110ec56f3 | LOG-INFO/PythonStudy | /6_python_programming/2_plus_multiples_of_3_and_5.py | 214 | 3.96875 | 4 | def plus_multiples_of_3_and_5(limit):
result = 0
i = 1
while i <= limit:
if (i % 3) or (i % 5):
result += i
i += 1
return result
print(plus_multiples_of_3_and_5(1000))
|
4d0bd8daba8bcfa8d99c524941c297d0321e13f6 | Mixser/mega_project | /numbers/prime_factorize.py | 614 | 3.71875 | 4 | from math import sqrt
cached_prime = {1: False, 2: True}
def is_prime(num):
if num in cached_prime:
return cached_prime[num]
for delimiter in xrange(2, int(sqrt(num)) + 1):
if num % delimiter == 0:
cached_prime[num] = False
return False
cached_prime[num] = False
... |
e31fb5aaf11e6df6110787757b5224ba51c55cd3 | wsldwo/Python | /LeetCode/leetcode#083.py | 1,893 | 3.640625 | 4 | class Solution:
'''
执行结果:通过
执行用时:56 ms, 在所有 Python3 提交中击败了20.24%的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了53.66%的用户
力扣这耗时是不是乱填的啊!!!
'''
def deleteDuplicates(self, head: ListNode) -> ListNode:
#此题可以不创建Dummy节点,因为首节点不必删除
#仍然使用快慢指针
if not head or not head.next:
retu... |
776d5a92536510026b5727a10975d304007bac95 | neeraj-somani/Python_Algos | /Leetcode-Arrays-101/MergeSortedArray.py | 1,212 | 3.921875 | 4 | '''
Definition - from question itself
https://leetcode.com/explore/learn/card/fun-with-arrays/525/inserting-items-into-an-array/3253/
Data
- input - two sorted integer array
- ouput - one fully sorted array
- edge cases -
- assumption - these assumptions provided in question itself
-- The number of elem... |
22d86ec85d4eb48d13aaf652d4e4a7820c7a605c | ZordoC/the-self-taught-programmer-August-2019 | /Chapter 22 - Algorithms/Count_Characthers.py | 417 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 01:01:50 2019
Count Characthers Occurences
@author: zordo
"""
def count_characters(string):
count_dict = {}
for c in string:
if c in count_dict:
count_dict[c] += 1
else:
co... |
e7b3bd6ed2590418889aaec301a75ddadec592a4 | gauravdaunde/training-assignments | /99Problems/Arithmetic Problems/P31.py | 478 | 4.28125 | 4 | '''
Determine whether a given integer number is prime.
Example:
* (is-prime 7)
T
'''
#checking number is prime or not
def isPrime(number):
#checking given number is divisible by any number from 2 to number itself
for num in range(2,number):
if number == 1 or number % num ==0 and number != num: #if s... |
f7513fd03e3fd017b6aba51d2c8729c65b2e574e | xuedong/leet-code | /Problems/Algorithms/2215. Find the Difference of Two Arrays/find_difference_arrays.py | 287 | 3.59375 | 4 | #!/usr/bin/env python3
from typing import List
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
ans = []
ans.append(list(set(nums1) - set(nums2)))
ans.append(list(set(nums2) - set(nums1)))
return ans
|
b08e62bd8a50a684db543d849d183fc409bc4283 | MrKagabond/Random_Maze_Generation_Application | /src/Main.py | 2,793 | 4.1875 | 4 | from src.Tile import Tile
from src.MazeGenerator import MazeGenerator
import pygame
# global variables
TILES = -1 # will change upon user input
TILE_CAP = 50 # MAX number of tiles is capped at 50, REMOVE at your own RISK
SHOW_SOLUTION = False # will change upon user input
def maze_init():
padding_w = WIDTH - ... |
c6680253b152298f6ac67284e7de7bc9b26853b6 | CernatMonicaRoxana/py-labs | /lab1-old/ex2.py | 746 | 3.78125 | 4 | def spiral(matrix):
size = len(matrix)
res = ''.join(matrix[0])
res += ''.join([matrix[i][size-1] for i in range(1, size)])
res += ''.join(matrix[size-1][-2::-1])
res += ''.join([matrix[i][0] for i in range(size-2, 0, -1)])
if size > 2:
res += spiral([matrix[i][1:size-1] for i in range(... |
040ec508a77009b158f59a5d8e7e460fad3234be | mbadheka/python_practice_code | /7.py | 216 | 3.6875 | 4 | name = input("enter your name : ")
i=0
temp_var = ""
while i<=len(name)-1:
if name[i] not in temp_var:
temp_var = temp_var+name[i]
print(f"{name[i]} is {name.count(name[i])}")
i=i+1
|
0a18d7bcb3b373696bde7ba8c90fda4299377114 | zhou-jia-ming/leetcode-py | /problem_2.py | 1,006 | 3.578125 | 4 | # coding:utf-8
# Created at: 2020-01-04
# Created by: Jiaming
# 题目:两数相加
# https://leetcode-cn.com/problems/add-two-numbers/submissions/
# 执行用时 :68 ms, 在所有 Python3 提交中击败了94.10%的用户
# 内存消耗 :12.6 MB, 在所有 Python3 提交中击败了99.59%的用户
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
se... |
8e57ea71c112666a8106371f50a5dd9be800c440 | p3ngwen/open-notes | /Intro to CS with Python/src/solutions/answer1205.py | 237 | 3.671875 | 4 | numbers = 101 * [True]
numbers[1] = False
for i in range( 1, len( numbers ) ):
if not numbers[i]:
continue
print( i, end=" " )
j = 2
while j*i < len( numbers ):
numbers[j*i] = False
j += 1 |
ef98d3376815fa52c98a6ec97516d4524c902335 | Charity10/zuri_tasks | /atm.py | 3,469 | 3.703125 | 4 | import random
database = {
445694103: ['mercy', 'umoh', '0990', 'umi', 'iku', 800 ]
}
balance = [700, 800, 600, 1000, 200000]
def init():
isValidOptionSelected = False
print('Welcome to Lemo Bank!!!')
while isValidOptionSelected == False:
haveacct = int(input('Do you have an account with us? ... |
c6da1bb5526ae352201e50b5df914bb14d9ddf55 | stephanieeechang/PythonGameProg | /PyCharmProj/Cipher.py | 1,461 | 4.3125 | 4 | def get_alphabet():
'''
this function returns the alphabet in a list
:return: list
'''
alphabet = [chr(i) for i in range(97,123)]
return alphabet
def cipher_alphabet(key='alext'):
'''
create cipher alphabets with the key provided
:param key: string
:return cipher_d: dictionary
... |
905a39922faf36e249ce9cbc7b5f126b45d363e1 | JeahaOh/Python_Study | /Do_It_Jump_To_Python/1_Basic/02_Type/03_List/02_IndexingAndSlicingOfList.py | 1,050 | 3.578125 | 4 | # coding: utf- 8
'''
리스트의 인덱싱과 슬라이싱
리스트도 문자열처럼 인덱싱과 슬라이싱이 가능함.
'''
# 리스트의 인덱싱
print('-' * 10 + '리스트의 인덱싱' + '-' * 10)
a = [1, 2, 3]
print(a)
print( a[0] )
print( a[0] + a[2] )
# 음수 index는 뒤에서부터 센다.
print( a[-1] )
# 리스트 안의 리스트
print('-' * 10 + '리스트안의 리스트' + '-' * 10)
a = [1, 4, 8, ['Fuck', 'Python']]
print( a[0] )
pr... |
550b090bb85e5829e5d89e919bebc0ee8d4641a5 | jellive/pythonstudy | /Chap02. Python basic - Struct/02-2. String.py | 4,543 | 4.15625 | 4 | # 문자열 자료형
a = "Life is too short, You need Python"
b = "a"
c = "123"
# 문자열을 만드는 네 가지 방법
# 1. 큰따옴표로 양 쪽 둘러싸기
"Hello world"
# 2. 작은따옴표로 양 쪽 둘러싸기
'Python is fun'
# 3. 큰따옴표 3개를 연속으로 써서 양 쪽 둘러싸기
"""Life is too short, You need python"""
# 4. 작은따옴표 3개를 연속으로 써서 양 쪽 둘러싸기
'''Life is too short, You need python'''
# 문자열 안에 따옴표를 ... |
3298a037efc6fc5ca5251b59d5472d39d79d8e83 | jpedrodias/MicroPython | /examples/01-2 Button MicroPython.py | 470 | 3.796875 | 4 | from machine import Pin
from time import sleep
D4 = 2 # to connect to the button
D3 = 0 # to connect to the button
D2 = 4 # to connect to the green led
D1 = 5 # to connect to the red led
# OutPut
green = Pin( D2, Pin.OUT )
red = Pin( D1, Pin.OUT )
# Input
btn1 = Pin(D3, Pin.IN)
last_value = 1
whil... |
ef1ef58ab6d2c89ac8d4e208497d8662e9f53a0c | creaputer/HumanInterfaceTopCoders | /JK/0_FriendsScore/FriendsScore_py/main.py | 1,483 | 3.65625 | 4 | def highestScore(friends):
FRIEND = "Y"
relationship = []
iMe = 0
for me in friends:
relationship.append(set([]))
iYou = 0
for you in me:
if you == FRIEND:
relationship[iMe].add(iYou)
iYourFriend = 0
for yourFriend in... |
fdf420e9e18f5d4f6b9ecffa53cb5dab703df071 | Fredmty/estudos-pythonicos | /dicionarios.py | 2,171 | 3.8125 | 4 | """
noutras lingugens de programação, os dicionaríos são conhecidos como mapas.
dicionários são coleções do tipo chave/valor
dicionáios são representados por {}
obs: sobre dicionários:
--chave e valor são separados por : "chave" : "valor"
-- tanto chave e valor podem ser de qualquer tipo de dado
-- podemos mistur... |
475636a5d1f8d1d567d37a7301718692dd93cae1 | 20190314511/python | /samples/magicSqure/ms_demo.py | 606 | 3.75 | 4 | def print_ms(ms):
n = len(ms)
for i in range(n):
linesum = 0
for j in range(n):
linesum+=ms[i][j]
print("{:3d}".format(ms[i][j]), end=" ")
print(" {}".format(linesum) )
def ms_odd(ms):
n = len(ms)
x=0
y=int(n/2)
for i in range(1, n*n+1):
... |
f81d6562204f075f8706a634a859d76a8e7ea3df | AleByron/AleByron-The-Python-Workbook-second-edition | /Chap-3/ex77.py | 239 | 3.640625 | 4 | x = 1
y = 11
print(' ',end='')
for a in range(x,y):
print("%4d" % a, end="")
print('\n')
for b in range(x, y):
print("%4d" % b, end="")
for c in range(x, y):
print("%4d" % (b * c), end="")
print('\n') |
1dd93f711b60a7bcef8f8845d10eee2797e425d0 | iammohit07/Python-Programs | /exception.py | 281 | 3.96875 | 4 | try:
num1,num2 = input('enter values to divide '),input('enter values to divide ')
print(int(num1)//int(num2))
except ZeroDivisionError:
print('cannot divide with zero ')
except TypeError:
print('invalid value')
except ValueError:
print('invalid value') |
a86c5dc6ef17d4c55dff2d172d2bd2a14a8b1499 | joshuafernandes1996/Image-to-GrayScale-in-Python | /grayscale.py | 726 | 3.625 | 4 | import cv2 #importing openCV library
import matplotlib.pyplot as plt #importing a function from mpl
import tkinter as tk #GUI help from tkinter for filedialog to select files in windows
from tkinter import filedialog
name=input("Name?")
root=tk.Tk()
root.withdraw() #to avoid root windows of tkinter
path=fi... |
0d5a8498bbbc800d025e50f45ce389b0eda78887 | bala4rtraining/python_programming | /python-programming-workshop/HomeWorkProblems/9.Collection-of-Words.py | 398 | 4.125 | 4 |
# Read a collection of words entered by the user. display
# each word entered by the user only once, in the same order
# that the words are entered. use a list
newset = set()
for count in range(5):
word = input("Give a word")
newset.add(word)
print(newset)
newlist= []
for count in range(5):
word = inpu... |
cbe796596de2bd27f81c505aa77052726e54597b | Accitri/PythonModule1 | /(3) 29.11.2017/Class work/Converting between celsius and fahrenheit.py | 1,130 | 4.46875 | 4 |
import turtle
#defining a function
def celsiusToFahrenheit():
myInput = int(input("Enter a temperature in celsius: "))
tempInFahrenheit = int((((myInput + 32)/5)*9))
print(myInput,"degrees celsius, equals", tempInFahrenheit, "degrees fahrenheit.")
def fahrenheitToCelsius():
myInput = int(input("Enter... |
99978fae9dda14a39113f5028fa93cb9697dacff | ftconan/python3 | /python_tricks/class_oop/copy_demo.py | 1,374 | 4.15625 | 4 | """
@author: magician
@date: 2019/11/22
@file: copy_demo.py
"""
import copy
class Point:
"""
Point
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({0}, {1})'.format(self.x, self.y)
class Rectangle:
"""
Rectangle
... |
a165b18eb472e378b46c723fd8e51a2a0494aa80 | chuanfanyoudong/algorithm | /leetcode/List/MajorityElement.py | 814 | 3.8125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: zkjiang
@description:
@site: https://www.github.com/chuanfanyoudong
@software: PyCharm
@file: MajorityElement.py
@time: 2019/4/30 8:41
"""
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
... |
408239806a64e001f8587c8331e77fcde6abe289 | anthonywww/CSIS-9 | /codingBat2.py | 992 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: codingBat2.py
# Anthony Waldsmith
# 07/24/2016
# Python Version 3.4
# Description: Extra Credit
# Optional import for versions of python <= 2
from __future__ import print_function
def cigar_party(cigars, is_weekend):
if cigars < 40:
return False
... |
7ba73215012d4c6730f60ae65ef0785e84a98416 | AEaker/python-challenge | /PyBank/main.py | 2,339 | 3.921875 | 4 | import os
import csv
filepath = "Resources","budget_data.csv"
with open(filepath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
#Total $ holder
NetTotal = 0
#previousrow to calculate change between months
previous = 0
#Greatest Increas... |
f088a18d464928e497891cae873a0815853ed483 | suresh-boddu/algo_ds | /ds/trees/remove_single_child_nodes.py | 1,075 | 4 | 4 | from ds.trees.tree import Node
from ds.trees.tree import Tree
def remove_single_child_nodes(node):
"""
Method to remove the nodes with single child (replace the current node with the single child so that its parent points to its single child)
"""
if not node:
return None
if node.left and... |
52dce1801819cc329565861d5341a4e81c1fc854 | abdazmi/turtles_crossing_the_road-game-project | /car_manager.py | 998 | 3.953125 | 4 | from turtle import Turtle
from random import Random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 5
class CarManager:
def __init__(self):
self.Cars = []
self.X = 6
def create_car(self):
easy_mode = Random().randint(1, sel... |
bb0d02266ec430c1de020513454bc51b487d6f39 | Yasaswi08/MLP-and-Linear-Classifiers-from-Scratch | /Perceptron.py | 1,984 | 4.5 | 4 | """Perceptron model."""
import numpy as np
class Perceptron:
def __init__(self, n_class: int, lr: float, epochs: int):
"""Initialize a new classifier.
Parameters:
n_class: the number of classes
lr: the learning rate
epochs: the number of epochs to train for
... |
87afc42aa43c11c600e6d884e6e4afc206ac1b70 | xiaojinghu/Leetcode | /Leetcode0138_Hash.py | 1,096 | 3.546875 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
# build a... |
e2d5776393680e35a95d883486091f00958d029d | eessm01/100-days-of-code | /data_structures_algorithms/C-1_20_suffle.py | 1,151 | 4.46875 | 4 | """This program is a solution for:
Python’s random module includes a function shuffle(data) that accepts a list of elements and
randomly reorders the elements so that each possible order occurs with equal probability.
The random module includes a more basic function randint(a, b) that returns a uniformly ... |
8b2e2fe73f8c9fe4715c4f1c5659e2f7e968af0f | DonghyunSung-MS/Algorithms_study | /Programmers/level2/프린터.py | 560 | 3.734375 | 4 | from collections import deque
def solution(priorities, location):
deq = deque(priorities)
current_max = max(deq)
index = 0
n = 0
while True:
tmp = deq.popleft()
if tmp==current_max:
n+=1
current_max = max(deq) if deq else -1
if location == 0:
... |
8787e80895c3ce6af390e9a31776ad5ff90a234c | RCoon/CodingBat | /Python/Logic_1/date_fashion.py | 791 | 4.21875 | 4 | # You and your date are trying to get a table at a restaurant. The parameter
# "you" is the stylishness of your clothes, in the range 0..10, and "date" is
# the stylishness of your date's clothes. The result getting the table is
# encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very
# stylish, 8 ... |
3c40c2b5ac6a9591c5b050855340457e6b7b1b9f | Mr-QinJiaSheng/python2021 | /python2021课程源码/8.5 内置模块datetime.py | 420 | 3.53125 | 4 | #内置模块datetime
import datetime
#获取当前的日期时间
now=datetime.datetime.now()
print(type(now))
#获取一个指定时间
d1=datetime.datetime(2018,2,13,5,23,45)
print(d1)
#日期转字符串
s1=d1.strftime("%Y年-%m月-%d日 %H:%M:%S")
print(s1)
#字符串转日期(格式一定要一致)
s2="2018/02/13 05:23:45"
d2=datetime.datetime.strptime(s2,"%Y/%m/%d %H:%M:%S")
print(d2,type(d2... |
5643b345f2cbaee5ab90c8abc804e90b95f967ff | zhouzi9412/Python-Crash-Course | /第七章/7-2.py | 139 | 4.0625 | 4 | number = input("How many people?: ")
number = int(number)
if number >= 8:
print("no more seat.")
else:
print("we have some seats.") |
31da9e68bebba21ec01fefb6608734fd18c0c28b | gwqw/LessonsSolution | /stepik/Algorithms/04_GreedyAlgo/05_Huffman_code_reader.py | 571 | 3.65625 | 4 | """
Input
1 1 <- different letters, code size
a: 0 <- code table
0 <- code to decrypt
"""
if __name__ == "__main__":
# input parser
k, l = input().split()
k, l = int(k), int(l)
decode_table = {}
for i in range(k):
w = input().split(':')
decode_table... |
c15dc12b48fe4e8028c544a7c7f759456cca5de2 | Manjeetkapil/tkinter-python | /entry_form.py | 510 | 4.09375 | 4 | from tkinter import *
root = Tk()
e = Entry(root,width=50,bg="blue",fg="white",borderwidth=5)
e.pack()
e.insert(0,"xx")
'''
e = form input same as html
e.get() to get value inside the form currently we calling button from myclick() funtion
e.insert(0,"put default text inside form")
'''
def myClick():
hello = "hello ... |
4ecf0fff52c91894ffbfded047c30fea1082a8a8 | manojuppala/sorting-algorithm-visualizer | /heapsort.py | 1,593 | 3.703125 | 4 | import time
swap=0
compare=0
complexity='O(nlog(n))'
def heapify(data, n, i,drawData,timeTick,changetext):
global swap
global compare
global complexity
# Find largest among root and children
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and data[i] < data[l]:
largest = l
... |
bd0d1362e0e6b6765e9268f370174360dd1e63b1 | babiswas/Tree | /test23.py | 1,530 | 4.09375 | 4 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def inorder(self):
if self:
if self.left:
self.left.inorder()
print(self.value)
if self.right:
self.right.inorder()
def is_Mirro... |
161a8d48a812499daa42f880848f107c31e688f0 | serputko/Recursive_algorythms_tasks | /dict_parsing.py | 213 | 3.875 | 4 | chain = {'A': 'start', 'B': 'A', 'end': 'B', '-': 'end'}
def parse_chain(key):
if chain[key] == 'start':
return 'start'
return parse_chain(chain[key]) + ' ' + chain[key]
print(parse_chain('-'))
|
8e7a9b1ff5f2a3ebbf2156b7be8851659b39784a | egene-huang/python-learn | /test-all/filter.py | 853 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
## 这是一个过滤器, 根据规则过滤掉符合规则的元素, 这都是高阶函数的产物
## 同样接受两个参数,第一个为规则函数,第二为一个序列, 然后根据规则函数返回值来判断是否保留该元素 ,该规则函数一次作用到序列每个元素上
## 注意: 提供的规则函数是含有一个参数的 否则会提示参数个数不匹配, 定义为0个参数,但是filter却传递了一个参数给fun
# TypeError: fun() takes 0 positional arguments but 1 was given
def fun(n):
# return True... |
3748eb0d40fb925b86875d7f238b732c75fdee35 | liu1073811240/Programming-exercises | /end.py | 151 | 3.734375 | 4 | # 定义函数,求两数之和
def t1():
for i in range(5):
print(i)
return # 结束整个函数
print("函数结束")
t1() |
41addb8d5a8a943ac10b3484be76934b5abded69 | alexdebolt/Pokemon-Battler | /trainerClass.py | 2,428 | 3.953125 | 4 | from pokemon import Pokemon
# class to create trainers
class Trainer:
# constructor method
def __init__(self, name, pokemon_list, potions=1):
self.name = name
self.pokemons = pokemon_list
self.potions = potions
self.current_pokemon = 0
def __repr__(self):
print("... |
95ad950e083059e926a58ec4bb809a2d0d335984 | NeonedOne/Basic-Python | /Second Lab (2)/test.py | 1,960 | 3.5625 | 4 | # Алексей Головлев, группа БСБО-07-19
#folder_path, cell
is_allowed = True
cell_check = True
check = ""
permitted_folders = []
for _ in range(int(input())):
folder_path_permitted = input()
if "." not in folder_path_permitted.split("/")[-1]:
folder_path_permitted += "/*"
permitted_folders.append(fo... |
9ba86bb16d923254b18e8888dc760c2fbd2e61da | JBielan/leetcode-py-js | /python/max_profit.py | 499 | 3.734375 | 4 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy_price, profit = float('inf'), 0 # set buy_price and profit to the highest and lowest possible options
for price in prices:
if price < buy_price: buy_price = price # in case you find the lowest price, set it as buy_price
if price - buy... |
c06c3882b81000703455d99f052def8fccb118b6 | tahniyat-nisar/if_else | /enter city to know famous site.py | 218 | 4 | 4 | city=input("enter name of the city:")
if city=="mumbai":
print("gate way of india")
elif city=="delhi":
print("red fort")
elif city=="hyderabad":
print('charminar')
elif city=="agra":
print("taj mahal") |
b65ca66877d465a41d3c192398279d53dad17ff4 | soft-rain/AlgorithmBasic-Inflearn | /2.6QuickSort.py | 761 | 4.0625 | 4 | def quickSort(S, low, high):
if (high > low):
pivotpoint = partition(S, low, high)
quickSort(S, low, pivotpoint - 1)
print(S)
print(pivotpoint)
quickSort(S, pivotpoint + 1, high)
print(S)
print(pivotpoint)
def partition(S,low,high):
pivotitem=S[low]
j... |
20f9b4b81c50b8eefa4fa5190285cdf647698164 | Pawan459/infytq-pf-day9 | /easy/Problem_12.py | 886 | 4.15625 | 4 | # Write a python function to generate
# and return the list of all possible sentences created from the given lists of Subject, Verb and Object.
# Note: The sentence should contain only one subject, verb and object each.
# Sample Input Expected Output
# subjects=["I", "You"]
# verbs=["Play", "Love"]
# objects=["Hockey... |
0070a92ed85d6ed8aa55deeb9ec8a574934e07b0 | Liambass/Python-challenges-exercises-and-tutorials | /Tutorials/adder.py | 458 | 4.21875 | 4 | # Open a new window and type the following:
# number1 = float(input("Please enter the first number: "))
# number2 = float(input("Please enter the second number: "))
# answer = number1 + number2
# print(number1, "+", number2, "=", answer)
# What does this program do?
number1 = float(input("Please enter the first numb... |
3c495192798aa7afc37d5e8f172d18fe0044f2a1 | jakeolenick/Orchestra | /converter.py | 566 | 3.59375 | 4 | def convert(n):
notes = [" ", 'C', 'd', 'D', 'e', 'E', 'F', 'g', 'G', 'a', 'A', 'b', 'B', 'C1', 'd1', 'D1']
#print len (notes)
keys = ["-", 'a', 'w' , 's' , 'e', 'd', 'f', 't' , 'g' , 'y', 'h', 'u', 'j', 'k', 'o', 'l']
#print len (keys)
return keys [notes.index (n)]
def score (s):
r... |
24be1039f10217a5a3d62d6197523b5a40850bfc | kkmonlee/Programming-Contests | /HackerRank/Implementation/FindDigits.py | 168 | 3.84375 | 4 | def findDigits(n):
count = 0
digits = str(n)
for digit in digits:
if digit != '0' and n % int(digit) == 0:
count += 1
return count |
fea6e6dac4524528563ea7950a29c8770afd668d | BluDobson/PythonPrograms | /PythonPrograms/Programs/fnp.py | 190 | 3.890625 | 4 | def add_calc(number1, number2):
answer = number1 + number2
return answer
added_number = add_calc(int(input("Enter a number: ")), int(input("Enter a number: ")))
print(added_number) |
514a5d0bccd1f6c9800078e330f34a027635192e | isalu18/Stuff | /Python/basic/while_for.py | 287 | 3.71875 | 4 | numero = 12345678
c = 0
while numero >= 1:
numero /= 10
c += 1
else:
print("El numero es menor a 1: ", c, numero)
titulo = "Curso de Python 3"
for letra in titulo:
if letra == "P":
#break termina con el for
continue #se salta la letra
print(letra) |
da2cbc7e01f6360407e757a9d889b56d946260f8 | vesssz/Fundamentals | /FINAL_EXAM_EX/01.09.08.2019.g0.Followers.py | 900 | 3.578125 | 4 | line = input()
all_users = {}
while line != "Log out":
data = line.split(":")
command = data[0]
username = data[1]
if command == "New follower":
if username not in all_users.keys():
all_users[username] = 0
elif command == "Like":
count = int(data[2])
all_users.se... |
ba5b06172125a21afb9124bec6cb44d1aaac9180 | OllieRees/ProjectEuler | /Sum of Primes.py | 823 | 4 | 4 | import math
#check if n is prime
def isPrime(n):
if (n == 1):
return False
for fact in range(2, math.floor(math.sqrt(n)) + 1):
if(n % fact == 0):
return False
return True
def primeSieve(list):
for e in list:
if(e != 2 and e % 2 == 0):
list.remove(e)
... |
e9e21d508f5c92719515ee6bb02ea4878e6d2c33 | Veronicahwambui/pythonClass | /car.py | 389 | 3.75 | 4 | class Car:
def __init__(self,make,color,model,speed) :
self.make=make
self.color=color
self.model=model
self.speed=speed
def park(self):
return f"my car is called {self.make}, it is {self.color} . {self.model} is its model and it runs at a {self.speed} spee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.