blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c31acba735310ace1d4f99c7715f4017d034b2ba | slamatik/codewars | /6 kyu/Find the missing letter.py | 380 | 3.828125 | 4 | from string import ascii_letters
def find_missing_letter(chars):
let = ascii_letters
p = 0
while let[p] != chars[0]:
p += 1
for i in range(len(chars)):
if chars[i] == let[p]:
p += 1
else:
return let[p]
# return p, let[p]
st = ["a","b","c","d","f"]... |
ddb51a40e3cbc49e856f6a9f95cf9637f39c372f | slamatik/codewars | /6 kyu/Unique in Order 6 kyu.py | 350 | 3.8125 | 4 | def unique_in_order(iterable):
if len(iterable) == 0:
return []
table = [iterable[0]]
for i in range(1, len(iterable)):
if iterable[i] != table[-1]:
table.append(iterable[i])
return table
print(unique_in_order('AAAABBBCCDAABBB'))
print(unique_in_order('ABBCcAD'))
print(uniq... |
aea0c94a63607d53c219cdcff663fd3456c2cdf8 | slamatik/codewars | /5 kyu/Compute the Largest Sum of all Contiguous Subsequences 5 kyu.py | 281 | 3.765625 | 4 | def largest_sum(arr):
if len(arr) == 0:
return 0
cache = [arr[0]]
for i in range(1, len(arr)):
cache.append(max(arr[i], cache[-1] + arr[i]))
return 0 if max(cache) < 0 else max(cache)
data = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(largest_sum(data)) |
adfb408d885e848cd1551331d8d6ba2ea3dfa10a | fanchunguang/python | /com/alrti/binary-search.py | 5,934 | 4.09375 | 4 | # !/usr/bin/env python
# !-*-coding:utf-8 -*-
# !@Author : fanchg
# !@Time : 2019/3/14
import unittest
class Solution:
def searchInsert(self, nums, target) -> int:
"""
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引
:param nums:
:param target:
:return:
"""
start, mid, end =... |
fc7ace8156f62d5b0388b7ad7052dfd64fa0e755 | ksu-is/Hangman_with_GUI_and_Difficulties | /testing.py | 6,853 | 3.71875 | 4 | from tkinter import *
import random
from tkinter import messagebox
from ISProject.Hangman_with_GUI_and_Difficulties.EasyWords import easy_list
from ISProject.Hangman_with_GUI_and_Difficulties.NormalWords import normal_list
from ISProject.Hangman_with_GUI_and_Difficulties.HardWords import hard_list
def get_difficulty... |
c3debb20ebe291fd2a4efda4c01951f64bd91817 | gany-c/DataStructures | /src/misc/MukanoolNerkaanal.py | 2,771 | 3.96875 | 4 | """
--------------------------------
Given 2 integers represented as 2 arrays of single digit integers,
add them together and output the result in the form of array of single digit integers.
For example:
Input: [3, 4, 5] and [9, 4] (represent 345 and 94)
Output: [4, 3, 9] (represents 439)
---------------------------... |
4b798d3491f597c4dec773b780243dace11b5958 | gany-c/DataStructures | /src/string/redditDictionary.py | 2,449 | 4.09375 | 4 | # import requests
# import mysql.connector
# import pandas as pd
# At Reddit, a big part of our job is to let our users find the best stuff in Reddit. To do this, we use a Search Engine, which lets us find Posts that match a query given by a user. For example, if you search for "meme", we want to be able to show all ... |
e465bf117aef5494bb2299f3f2aaa905fb619b52 | purple-phoenix/dailyprogrammer | /python_files/project_239_game_of_threes/game_of_threes.py | 1,346 | 4.25 | 4 | ##
# Do not name variables "input" as input is an existing variable in python:
# https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python
#
# By convention, internal functions should start with an underscore.
# https://stackoverflow.com/questions/11483366/protected-method-in-python
##
##
# @param o... |
fd29d21e8715829139f3b4ef11116c8cb85b8c69 | saotian/p1804 | /eryueyizhou/duotai.py | 312 | 3.59375 | 4 | class Duck(object):
def walk(self):
print("鸭子在走路")
def swim(self):
print("鸭子在游泳")
class People(object):
def walk(self):
print("老王在走路")
def swim(self):
print("老王在游泳")
def Func(obj):
obj.walk()
obj.swim()
duck = Duck()
ren = People()
Func(duck)
Func(ren)
|
5edc02fadd4b7bc1c910a97c0a5a9e2e3eacec09 | saotian/p1804 | /lei/people.py | 318 | 3.59375 | 4 | class PeopleYt(object):
def __init__(self):
self.__money = 0
def getmoney(self):
return self.__money
def setmoney(self,value):
self.__money = value
a = property(getmoney,setmoney)
class zhangsan(PeopleYt):
def __init__(self):
PeopleYt.__init__(self)
zs=zhangsan()
print(zs.a)
zs.a = 1000
print(zs.a)
|
a667dadc01bcbce1451bfaa6e1565ecf83116649 | saotian/p1804 | /eryueyizhou/xiaoming.py | 308 | 3.640625 | 4 | class People(object):
guoji = "china"
def __init__(eslf):
self.name = "小明"
def get_name(self):
return self.name
@classmethod
def get_guoji(cls):
return cls.guoji
def say_chinese(self):
print("中国话")
xiaoming = People()
print(People.guoji)
print(People.get-guoji)
People.say_chinese()
|
11d697fdccf31230f1a8fae44a79e59f330863d1 | saotian/p1804 | /05/6_ren人类.py | 344 | 3.828125 | 4 | class People(object):
def __init__(self,name,height,weight):
self.name = name
self.height = height
self.weight = weight
def introduce(self):
print("我的名字是%s,身高%s,体重%s"%(self.name,self.height,self.weight))
huahua = People("花花",180,130)
huahua.introduce()
caocao = People("草草",185,120)
caocao.introduce()
|
1a79515ce732ef169510986cbf42af807a06650d | JonTurner-Janrain/general_work | /record-generator/lib/random_date.py | 810 | 4.03125 | 4 | """return a date(time) string for the given the date-time format"""
import time
from random import randint
def random_date(date_format):
""" Return a random(ish) date for use as birthdays and the like. """
string = "{}-{}-{} {}:{}:{}".format(randint(1950, 2000),
str(rand... |
e8fa9fd7604523316bee7e9ba557dccbacb479de | robertocrw/python | /myCal.py | 2,548 | 3.953125 | 4 | '''Este codigo esta dividido em 4 fases'''
# 1.0 Definir as funções
# 2.0 Chamar os botões
# 3.0 Declarar as entradas
# 4.0 Declara as variaveis primeiron e segundon
# 4.1 Importar, declara o tk(), e finalizar o mainloop(), e definir as dimensões.
#4.1
from tkinter import * # importando as definiçoes tk
#4.1
myCal = T... |
cc58151fb96f524c85a647baf99c4bb2c3c7f09e | sheetla971/pycharm_newproject | /ter.py | 129 | 3.953125 | 4 | def check(a,b):
return a if a>b else b
a=input("first number:")
b=input("second number:")
a,b=int(a),int(b)
print(check(a,b)) |
0e12ca2f26cf00c1dd5a7be5e56c97903a3f29c5 | irenenikk/sentiment-analysis-comparison | /code/science_utils.py | 3,712 | 3.5 | 4 | from scipy.stats import binom
import numpy as np
import math
def calculate_p_value(N, k, q):
""" Calculates p-value using the binomial distribution. """
res = 0
for i in range(k+1):
res += binom.pmf(i, N, q)
return 2*res
def sign_test_p_value(plus, minus, null):
""" Calculates p-value for ... |
a897856eb5eb0b3b1786b20697825f2fd517f5e8 | ArtBelgorod/book | /city_functions.py | 245 | 3.578125 | 4 | def get_city_country(city,country,population = ""):
if population !="":
full_name = f"{city.title()},{country.title()} - population {population}!"
else:
full_name = f"{city.title()},{country.title()}"
return full_name |
18339a74d160d992d0e67c80e096dd00b247a40e | ArtBelgorod/book | /10_11_2.py | 401 | 3.65625 | 4 | import json
filename = "num.json"
try:
with open (filename) as f:
num = json.load(f)
except FileNotFoundError:
num = int(input("Введите Ваше любимое число - "))
filename = "num.json"
with open(filename, 'w') as f:
json.dump(num, f)
print("Мы Вас запомнили!")
else:
print(f"Ваш... |
40ea12e7a031f2ad3330a4b9947acb718de6d4bd | duyhieuvo/human-detection-and-tracking-using-Optical-Flow | /PC/GUI.py | 1,657 | 3.515625 | 4 | import tkFileDialog as filedialog
from Tkinter import *
from Display import *
import os
def browse_button():
# Allow user to select a directory and store it in global variable folder_path
global folder_path
filename = filedialog.askdirectory()
folder_path.set(filename)
#List all files in ... |
17255846c2d4f9c4e1a9a96040989ddbc8f06118 | yb170442627/YangBo | /Python_ex/ex5_1.py | 1,109 | 3.78125 | 4 | # -*- coding: utf-8 -*-
name = 'YangBo'
age = 35 # not a lie
height = 74 # inches : 英寸
weight = 180 # lbs (pounds) 磅
eyes = 'Bule'
teeth = 'White'
hair = 'Brown'
#%s,表示格化式一个对象为字符, 把 name代表的字符串放到%s的位置中
print "Let's talk about %s." % name
#%d,整数. 把 height 代表的整数放到 %d 的位置中
print "He's %d inches tall." % height
print "He'... |
40dcaf6d0f51e671ed643d3c49d2071ed65df207 | yb170442627/YangBo | /Python_ex/ex25_1.py | 339 | 4.34375 | 4 | # -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
words = "where are you come from?"
word = break_words(words)
print word
word1 = sort_words... |
a5341d137334ccca3977d0c4b85f17feeeaca78c | yb170442627/YangBo | /Python_ex/ex39.py | 457 | 4.125 | 4 | # -*- coding: utf-8 -*-
cities = {'SH': 'ShangHai', 'BJ': 'BeiJing','GZ': 'GanZhou'}
cities['GD'] = 'GuangDong'
cities['SD'] = 'ShanDong'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not Found."
cities['_find'] = find_city
while True:
print "State?(E... |
448f476ddbd8ec3582c3913c8926f3181dfb8cf7 | yb170442627/YangBo | /Python_ex/ex33_1.py | 831 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def append_num(num): # 定义了一个append_num(num)函数
i = 0 # 声明了一个常量 i
numbers = [] # 声明了一个空的列表 numbers = []
while i < num: # 执行while循环
print "At the top i is %d" % i
numbers.append(i) #调用列表的append方法,当i< num成立的时候,把i的值追加到numbers这个空的列表中
i = i ... |
31f0676f560bd845dc7ba12d65687ac682d08e4a | KaPiech/Various-programs-Python | /Kalkulator.py | 2,221 | 3.515625 | 4 | #Zadanie Kalkulator
import math
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def show_complex(self):
print("Wynik = ", self.r, " + ", self.i, "i")
def conjugate(self):
self.i = -self.i
def module(self):
return math.sqrt((self.r * self.r) + (self.i * self... |
ea1c75a52acd753cc978ed712c92e17b78f7085f | KaPiech/Various-programs-Python | /Pięciu_filozofów_deadlock.py | 2,485 | 3.59375 | 4 | #Zadanie Pięciu filozofów wersja z deadlockiem(kelner)
import time
import sys
import threading
class Fork(object):
def __init__(self, num):
self.number = num
self.user = -1
self.lock = threading.Condition(threading.Lock())
self.taken = False
def drop_fork(self, user):
w... |
0e86001c06f024369bebf201f384609e526b2799 | KaPiech/Various-programs-Python | /Liczby_zespolone.py | 733 | 3.5625 | 4 | #Zadanie Liczby zespolone
import math
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def show_complex(self):
print(self.r, " + ", self.i, "i")
def conjugate(self):
self.i = -self.i
def module(self):
return math.sqrt((self.r * self.r) + (self.i * self.i))
... |
b86bc57163990cb644d6449b1e70a5eb435325b4 | Green-octopus678/Computer-Science | /Need gelp.py | 2,090 | 4.1875 | 4 | import time
import random
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
score = 0
operator = 0
question = 0
#This part sets the variables for the question number, score and the operator
print('Welcome to my brilliant maths quiz\n')
time.sleep(1.5)
print()
prin... |
3d323188aa765039b86b3149a8c512990447ff66 | Joanna-O-Ben/ADM-HW1 | /Problem1/Collections/Piling Up!.py | 367 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
for t in range(int(input())):
input()
lst = [int(i) for i in input().split()]
min_list = lst.index(min(lst))
left = lst[:min_list]
right = lst[min_list+1:]
if left == sorted(left,reverse=True) and right == sorted(right):
... |
f59221aae91b469669e94313f89f4175022835ef | Joanna-O-Ben/ADM-HW1 | /Problem1/Strings/The Minion Game.py | 494 | 3.6875 | 4 | def minion_game(string):
# your code goes here
Stuart = 0
Kevin = 0
vowels = ["A", "E", "I", "O", "U"]
for l in range(len(string)):
if string[l] in vowels:
Kevin += len(string) - l
else:
Stuart += len(string) - l
if Kevin > Stuart:
print("Kevin "... |
e82281f0a4886f667fc25dc42b42b7dd785b6681 | Joanna-O-Ben/ADM-HW1 | /Problem1/Built-Ins/ginortS.py | 652 | 3.953125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
S = list(input())
# print(S, type(S))
LETTERS = []
low = []
up = []
DIGITS = []
odd = []
even = []
for c in S:
if c.isalpha():
LETTERS.append(c)
if c.isnumeric():
DIGITS.append(c)
# print(LETTERS, DIGITS)
for s in LETTERS:... |
23af6db1effffb122dc991a8f83d2ac6a60bdc05 | Fari98/GA_learning_Snake | /past_versions/Davide/past version/snake_game_neuralnetwork.py | 8,428 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
import pygame
import time
import random
import numpy as np
#DEFINIG 3 DISPLAY FUNCTIONS
def Your_score(score, yellow, score_font, dis):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def our_snake(dis,... |
6a2340a9996615d74e10bee8c872146e653e549e | gporceng/python-ordinal | /ordinals.py | 582 | 3.8125 | 4 | class OrdinalEngine:
def __init__(self):
pass
def ordinalize(self,x):
y=int(x)
if(x<11):
if(x==1):
return(str(x)+"st")
if(x==2):
return(str(x)+"nd")
if(x==3):
return(str(x)+"rd")
if(x>3):
return(str(x)+"th")
if(x>10 and x<20):
return(str(x)+"th")
#Find the e... |
a5f3fdde75ca1ba377ace30608a3da5012bb5937 | itspratham/Python-tutorial | /Python_Contents/Python_Loops/BreakContinue.py | 443 | 4.21875 | 4 | # User gives input "quit" "Continue" , "Inbvalid Option"
user_input = True
while user_input:
user_input = str(input("Enter the valid input:"))
if user_input == "quit":
print("You have entered break")
break
if user_input == "continue":
print("You habe entered continue")
conti... |
5732b9b78947a332125e21f441d20d73591a3f80 | itspratham/Python-tutorial | /Python_Contents/APAS/intersection_of_2_arrays.py | 181 | 3.703125 | 4 | def intersection(n1, n2):
l = []
for i in range(len(n1)):
if n1[i] in n2:
l.append(n1[i])
return l
print(intersection([4, 9, 5], [9, 4, 9, 8, 4]))
|
7563439f6f667bbe4c71a7256353dcf50de0ee8c | itspratham/Python-tutorial | /Python_Contents/data_structures/Stacks/stacks.py | 1,842 | 4.21875 | 4 | class Stack:
def __init__(self):
self.list = []
self.limit = int(input("Enter the limit of the stack: "))
def push(self):
if len(self.list) < self.limit:
x = input("Enter the element to be entered into the Stack: ")
self.list.append(x)
return f"{x} in... |
bd05b326c32c59a9e07132559e51435bf98c1aea | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern9.py | 131 | 3.515625 | 4 | g = 8
d = 9
for i in range(1, 10):
for j in range(i + g):
print(d, end=" ")
print(" ")
d = d - 1
g = g - 2
|
4c9b9f37153da03bba01f97011fe2619930726ea | itspratham/Python-tutorial | /Python_Contents/metaclass/eg4.py | 704 | 4.09375 | 4 | # the following variable would be set as the result of a runtime calculation:
x = input("Do you need the answer? (y/n): ")
if x == "y":
required = True
else:
required = False
def the_answer(self, *args):
return 42
class Philosopher1:
pass
if required:
Philosopher1.the_answer = the_answer
cla... |
2bdc343f4849c59a59823ce162851b6fb846c280 | itspratham/Python-tutorial | /Python_Contents/data_structures/Array_Rearrangement/2.py | 413 | 4.34375 | 4 | # Write a program to reverse an array or string
# Input : arr[] = {1, 2, 3}
# Output : arr[] = {3, 2, 1}
#
# Input : arr[] = {4, 5, 1, 2}
# Output : arr[] = {2, 1, 5, 4}
def arrae(arr):
l1 = []
n = len(arr)
# i=0
# while i<n:
# l1.append(arr[n-i-1])
# n = n-1
for i in range(n):
... |
c6ca7c13ca07e85f22cdc8a2114f4b82618dd03f | itspratham/Python-tutorial | /Python_Contents/OOP/SimpleInheritence/inheritence.py | 1,207 | 3.75 | 4 | class Human(object):
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Human):
def __init__(self, name, age, total, avg):
super().__init__(name, age)
self.total = total
self.avg = avg
def display(self):
print("N... |
5a9e775afdbb94c318be57ce4958b8b5ae55fc00 | itspratham/Python-tutorial | /Python_Contents/data_structures/Padma_Reddy/prg1.py | 2,774 | 3.96875 | 4 | # #Through Euclid's algorithm
# def gcd(m, n):
# while n != 0:
# r = m % n
# m = n
# n = r
#
# return m
#
#
# print(gcd(60, 200))
# Iterative approach
# def gcd(m,n):
# if n==0:
# return m
# return gcd(n, m%n)
#
# x = gcd(60,200)
# print(x)
# def gcd(m,n):
# while... |
04d31f088600732f14b74ad882fe4af4077f7ed5 | itspratham/Python-tutorial | /Python_Contents/File_Handling/file.py | 702 | 3.640625 | 4 | # x=open("hen.txt","r")
# #print(x.read(7))
# print(x.readlines())
# f = open("hen.txt", "r")
# for x in f:
# print(x)
# f = open("hen.txt", "a")
# f.write("Now the file has more content!")
# f.close()
# Assignment- Do it through loop
#
# f = open("hen.txt", "r")
# print(f.read())
# f = open("hen.txt", "w")
# f.w... |
7ad142d38fdf39eb2098d84804c80fe60d9331d8 | itspratham/Python-tutorial | /Python_Contents/Sample_Programs/Array_DS/arr.py | 18,391 | 4.15625 | 4 | # Write a Python program to find the first duplicate element
# in a given array of integers.
# Return -1 If there are no such elements.
#
# def prog(arr):
# for i in range(len(arr)-1):
# for j in range(1,len(arr)):
# if arr[i] == arr[j]:
# return arr[i]
#
# print(prog([4,3,4,5,2... |
aca6dd1cca7a053e1b6f9e7bc0408d50e3ddd372 | itspratham/Python-tutorial | /Python_Contents/data_structures/recursion/prg2.py | 2,776 | 3.625 | 4 | # Replace every array element with the product of every other element
# without using a division operator
# Input: {1, 2, 3, 4, 5}
# Output: {120, 60, 40, 30, 24}
#
# Input: {5, 3, 4, 2, 6, 8}
# Output: {1152, 1920, 1440, 2880, 960, 720}
# def multiply(arr1, arr2):
# sol = arr1 + arr2
# mul = 1
# for i in... |
57e8f174c09cd06a6a0bce3c31bfb878426dc887 | itspratham/Python-tutorial | /Python_Contents/APAS/recursion/prg1.py | 1,490 | 4.03125 | 4 | # Swap Nodes in Pairs
# Given a linked list, swap every two adjacent nodes and return its head.
# You must solve the problem without modifying the values in the list's nodes
# (i.e., only nodes themselves may be changed.)
# Example 1:
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
# Example 2:
#
# Input: head = []
# Ou... |
b8681e5d210cc1d5d5c36824ec627eaffc9b1db6 | itspratham/Python-tutorial | /Python_Contents/Pythonfunctions/simpleFunctions.py | 435 | 3.546875 | 4 | ## Function:
"""
def function_name(<varaibel1>,<varaibel1>):
statement1
statement2
return value
file.write()
"""
def minus(a, b):
print(a - b)
def add(a, b):
return a + b
print("The function returns {}".format(minus(12, 5)))
print("The function returns {}".format(add(12, 5)))
print("Callin... |
e0aa179b5acfc5514224e99d6a1a9eea7491c526 | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern20.py | 210 | 3.78125 | 4 | n = 5
for i in range(1, n + 1):
temp = i
for j in range(1, n + 1):
print(temp, end=" ")
temp = temp + 1
if temp >= n + 1:
temp = 1
print(" ")
temp = temp - 2
|
915c9204911082e9b78205172985f037b99b9f3a | itspratham/Python-tutorial | /Python_Contents/APAS/median_two_array.py | 1,619 | 3.78125 | 4 | # def median_of_two_sorted_array(a1,a2):
# final = sorted(a1+a2)
# if len(final)%2==1:
# return final[len(final)//2]
# else:
# d= final[(len(final)//2)-1] + final[(len(final)//2)]
# return d/2
#
# print(median_of_two_sorted_array([1,2,90754,98],[3,4.7574,86]))
# Input : arr[] = {... |
f7f08524e4dcc33fa16ba5d9d9216f0d2136c262 | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern10.py | 273 | 3.671875 | 4 | j = 0
count = 1
n = 5
for i in range(1, 6):
for k in range(i):
print(count, end=' ')
count = count + 1
temp = count
count = count - 2
for k in range(1, i):
print(count, end=' ')
count = count - 1
count = temp
print()
|
451d63d075056e056820a5582bd71cf98b60386c | itspratham/Python-tutorial | /Python_Contents/Caw Studios/prg1.py | 778 | 3.96875 | 4 | # Input: s = "leEeetcode" Output: "leetcode"
# Explanation: In the first step, either you choose i = 1 or i = 2,
# both will result "leEeetcode" to be reduced to "leetcode".
# Input: s = "abBAcC"
# Output: ""
# Explanation: We have many possible scenarios, and all lead to the same answer. For example:
# "abBAcC" --> "... |
2862b4d9c0d64e553e2a4c49ee80700025a6756b | itspratham/Python-tutorial | /Python_Contents/APAS/zigzag.py | 708 | 3.53125 | 4 | def convert(s, numRows):
if s is None:
return s
if numRows == 0:
return s
if numRows == 1:
return s
rstr = ""
for i in range(numRows):
if i == 0:
rstr += s[::numRows + (numRows - 2)]
elif i == numRows - 1:
rstr += s[i::numRows + (numRow... |
59fa0a1e50a49f472b1cc08f97e1707f6a86b85b | itspratham/Python-tutorial | /Python_Contents/problems/10.py | 280 | 3.96875 | 4 | """
Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
Click me to see the sample solution
"""
n = int(input("Sample value of n is: "))
print(f"The value of n+nn+nnn = {n + (n * n) + (n * n * n)}")
|
55c7cdd0b1907010883f3e07a1f68dfa48604140 | itspratham/Python-tutorial | /Python_Contents/Sample_Programs/linked_list.py | 5,078 | 4.09375 | 4 | # class Node:
# def __init__(self,data):
# self.data = data
# self.next = None
#
# class LinkedList:
# def __init__(self):
# self.head = None
#
# def append(self,data):
# if self.head is None:
# self.head = Node(data)
# return
# cur_node = self... |
1c92251342d8af5183a31dd0d3bcff67fca50a81 | itspratham/Python-tutorial | /Python_Contents/Python_Decision_Statements/IfElseif.py | 333 | 4.15625 | 4 | # Time 00 to 23
# Input the time from the user
tm = int(input("Enter the time:"))
if 6 < tm < 12:
print("Good Morning")
elif 12 < tm < 14:
print("Good Afternoon")
elif 14 < tm < 20:
print("Good Evening")
elif 20 < tm < 23:
print("Good Night")
elif tm < 6:
print("Early Morning")
else:
print("In... |
b12ba761572bb1ba3d56eb66fadf089b490e94a9 | Triple-L/Wartegg_test | /Test/T_python_fitline_最小二乘.py | 1,124 | 3.71875 | 4 | #python 最小二乘拟合直线
# -*- coding: utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 30, num=50)
y = 0.2*x+[np.random.random() for _ in range(50)]
if __name__ == '__main__':
plt.figure(figsize=(10, 5), facecolor='w')
plt.plot(x, y, 'ro', lw=2, markersize=6)
plt.grid(b=True, ls=':')
... |
ac328151d8868822f0f952fd1203b6cd00b0e097 | loicmidy/formation-python | /ressources data science/ensemble/conversions.py | 1,843 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
notesElevesMatières=pd.read_csv('C:/Users/loicm/ressources data science/ensemble/eleves.csv',sep="|",
dtype={'élève':str,
'moyenneMath':float,
'moyennePhysique':str... |
efcb316380076d0836d4f0f537df9d5aa94d8b66 | kuzxnia/algoritms | /brain_training/programming_challenges/euler/T006.py | 219 | 3.625 | 4 | def sum_square_difference():
def _squares_sum():
return sum([x**2 for x in range(1, 101)])
def _sum_square():
return sum([x for x in range(1, 101)])**2
return _sum_square() - _squares_sum() |
6ee7b86e0b5a838f7ac4657e5db72f47c8ff8e85 | kuzxnia/algoritms | /brain_training/programming_challenges/euler/T007.py | 365 | 3.796875 | 4 | import math
def ten_thousand_one_prime():
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
prime_amount = 1
number = 3
while prime_amount != 10001:
if is_prime(number):
prime_amount += ... |
c91b8d31cdd4da012183f9f84dae7f438a5e6dd2 | kuzxnia/algoritms | /brain_training/programming_challenges/src/T018/anagram.py | 126 | 3.875 | 4 | def is_anagram(word1, word2):
if len(word1) != len(word2):
return False
return sorted(word1) == sorted(word2) |
425c505c10a4b6020df0b4c65878b83aa39399d0 | kuzxnia/algoritms | /computer_science/algoritms/search/linearsearch.py | 160 | 3.78125 | 4 | # Big O complexity
# O(n)
def linearSearch(arg, arr):
for i in range(len(arr)):
if arr[i] == arg:
return i
else:
return -1
|
79f0af0443d62be98721a88646fa68b2fb4682cb | kobbyopoku/tic-tac-toe | /functions.py | 1,478 | 3.875 | 4 | students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase.append(student["name"].title())
return students_titlecase
def print_student_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_stude... |
1d0611e0addd37b212419b0323e1f5832d101b2f | omkarpoudel6/guicalculator | /calculator.py | 2,650 | 3.796875 | 4 | from tkinter import *
print("calculator")
def calculate(a):
try:
z=eval(a)
input.set(z)
except:
input.set("Error!!!")
root=Tk()
root.title("Calculator")
root.geometry("250x150")
root.resizable(0,0)
input=StringVar()
Entry(root,background="red",fg="black",font="TkFixedFont",textvariable=... |
d15ee695e1a24a6d25be60c26137a8d2caafd827 | slott56/building-skills-oo-design-book | /code/test_wheel.py | 892 | 3.6875 | 4 | """
Building Skills in Object-Oriented Design V4
Wheel Examples
"""
from unittest.mock import MagicMock, Mock
import pytest
from wheel_examples import Wheel, Wheel_RNG
def test_wheel_rng():
mock_rng = Mock(
choice=Mock(return_value="bin1")
)
bins = ["bin1", "bin2"]
wheel = Wheel_RNG(bins, mo... |
5e37e1e7d5c51fb873c637f2053884c508cbcdbe | slott56/building-skills-oo-design-book | /code/bin_examples.py | 1,592 | 3.6875 | 4 | """
Building Skills in Object-Oriented Design V4
"""
from typing import Iterable
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Outcome:
name: str
odds: int
class Bin1:
"""
>>> o1 = Outcome("This", 2)
>>> o2 = Outcome("That", 1)
>>> b1 = Bin1([o1, o2])
>>> len... |
9ff550bd05430e29373fd8774c982eeaac26436f | trilliwon/LeetCode | /easy/binary-tree-paths.py | 822 | 3.890625 | 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
... |
a47f3d24f79cca30c35d58f84aab2c930b7b0635 | trilliwon/LeetCode | /medium/add-two-numbers.py | 930 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
s = None
node... |
9c956501df5e5f6b8603da3f7b24e12bb0926c85 | trilliwon/LeetCode | /easy/base-7.py | 511 | 3.625 | 4 | class Solution:
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
answer = []
isNegativeNumber = num < 0
num = (-1)*num if isNegativeNumber else num
while num > 0:
answer... |
b3d7ecb6aaa236ca1e5ddf98f19ba07b11843d40 | trilliwon/LeetCode | /easy/symmetric-tree.py | 1,237 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
leftStack ... |
4945122a94e19bbeaf097b06ef92d616eeb40e49 | trilliwon/LeetCode | /easy/path-sum-iii.py | 1,249 | 3.8125 | 4 | import queue
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, sum):
stack = []
stack.append((root, root.val))
numOfPath = 0
... |
81c75f3f24f09d74f5f8ddca7584b7e4481833db | trilliwon/LeetCode | /medium/path-sum-ii.py | 1,118 | 3.59375 | 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 pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""... |
cb19f8de71ae92cae46b69d57803a64847891a9d | trilliwon/LeetCode | /easy/balanced-binary-tree.py | 1,408 | 3.75 | 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 depth(self, root):
if not root:
return 0
stack = []
stack.append((root, 1))
depthlist =... |
41d6bb00d8411fb8aa3dab8607c7ddd0919c6e3e | tushach/Python-projects | /encrypt.py | 359 | 3.828125 | 4 | alpha="abcdefghijklmnopqrstuvwxyz"
newmessage=''
msg=input("Enter your message: ")
key=int(input("Enter a key for your message: "))
for char in msg:
if char in alpha:
pos=alpha.find(char)
newpos=(pos+key)%26
newchar=alpha[newpos]
newmessage+=newchar
else:
newmessage+=char
print("The ... |
eaa4cb4848a01460f115a9dec5fe56ef329fc578 | Blu-Phoenix/Final_Calculator | /runme.py | 2,632 | 4.40625 | 4 | """
Program: Final_Calculator(Master).py
Developer: Michael Royer
Language: Python-3.x.x
Primum Diem: 12/2017
Modified: 03/28/2018
Description: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over.
Input: The user will be asked f... |
d0c49942872a33e70d8a35133578d09963c761d4 | Andrewlastrapes/car_calculator | /newcarcalc.py | 1,125 | 4.0625 | 4 |
def newcar():
input("How much is a new car going to cost you per month? Please hit enter to start")
p = int(input("Please enter total cost of car: "))
r = float(input("Please enter interest rate as a whole number(example: 15.6% = 15.6): National average is around 4.5%): "))
t = int(input("These payments would las... |
449219be2325b86c67ba461085f50b70fffbe537 | yujunjiex/20days-SuZhou | /day01/task05.py | 1,552 | 4.125 | 4 | # coding: UTF-8
"""
卡拉兹(Callatz)猜想:
对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。
这样一直反复砍下去,最后一定在某一步得到n=1。
卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,
结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1?
输入格式:每个测试输入包含... |
1aa2f192350934e720cb2546d7a7eebf9e09732e | un1xer/python-exercises | /zippy.py | 1,073 | 4.59375 | 5 | # Create a function named combo() that takes two iterables and returns a list of tuples.
# Each tuple should hold the first item in each list, then the second set, then the third,
# and so on. Assume the iterables will be the same length.
# combo(['swallow', 'snake', 'parrot'], 'abc')
# Output:
# [('swallow', 'a'), ('... |
93fd79478aa591de5d11976f78f7e6e856589cca | un1xer/python-exercises | /teachers.py | 1,763 | 4.0625 | 4 | # Create a function named most_classes that takes
# a dictionary of teachers and returns the teacher with the most classes.
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# ... |
b6c98e63330665bbf33d9952924ea921bc5e7c01 | un1xer/python-exercises | /data/file-test.py | 781 | 3.859375 | 4 | # read file countries.txt
f = open("countries.txt", "r")
countries = []
for line in f:
# removes newline at the end of each line from text file
line = line.strip()
# prints each line in countries.txt
print(line)
# creates list of countries
countries.append(line)
print (countries)
# loops thro... |
4c38fd6ace4910b56cd787280fe4b3de9d073ee6 | tshihui/pypaya | /introToPython/q2_15.py | 490 | 3.984375 | 4 | # 2.15
num1 = float(input('Please input first number: '))
num2 = float(input('Please input second number: '))
num3 = float(input('Please input third number: '))
min = num1
min2 = num2
min3 = num3
if (min < min2) & (min2 > min3):
min2 = num3
min3 = num2
if (min > min2) & (min > min3):
min3 = min
if (m... |
b7f4f3872363f50ad2649090dd3437614be8230d | tshihui/pypaya | /programmingQuestions/fibonacci.py | 756 | 4.25 | 4 | ###############
## Fibonacci ##
## 2/2/2019 ##
###############
def fib(n):
""" Fibonacci sequence """
if n == 1 :
return([0])
print('The first ', n, ' numbers of the Fibonacci sequence is : [0]')
elif n == 2:
return([0,1])
print('The first ', n, ' numbers of the Fibonacci se... |
6f5407397ab06b59760a4b8dff90f99adbb29ca9 | tshihui/pypaya | /pythonTutorial/tutorial7.py | 5,276 | 4.375 | 4 | if __name__ == '__main__':
print('formatting outputs with f or F')
year = 1000
event = 10
print(f'the number of {event} in the last {year} years')
print('another way to format output')
yes = 248952
no = 183095
percent = no/yes
print('{:-9} yes votes {:2.2%}'.format(yes, percent))
... |
63e96a978bb28a007211fd0d3a0529af8ac79b7a | tshihui/pypaya | /codility_practices/binaryGap.py | 2,716 | 3.65625 | 4 | #########################################################
#------- Solution to identify largest binary gap -------#
#########################################################
#-----------------------------------------#
#---------- Final Version ----------------#
#-----------------------------------------#
#----- Functi... |
d5688cef9797d4ab6a2f8c48a36bb813e317600f | goufix-archive/py-exercises | /exercicios/sequencial/18.py | 1,643 | 4.125 | 4 | import math
name = 'alifer'
# Faça um Programa para uma loja de tintas. O programa deverá pedir
# o tamanho em metros quadrados da área a ser pintada.
# Considere que a cobertura da tinta é de 1 litro para cada
# 6 metros quadrados e que a tinta é vendida em latas de 18 litros,
# que custam R$ 80,00 ou em galões de 3,6... |
eb9560d4677463b71c5b709a4f1f6013c0c26314 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/sistemaPython/main.py | 1,011 | 4.28125 | 4 | import funcionalidades #importa o modulo de funcionalidades que criamos
while True: #criamos um loop para o programa
print('#'*34) #fornecemos um menu de opcoes
print(">"*11,"BEM-VINDO","<"*11)
print("Escolha a operacao desejada")
print("[1] Cadastrar produto")
prin... |
2fba35593cff0e6f6397669b60e63d90ca9bc504 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo5/exercicio9.py | 779 | 3.890625 | 4 | lista = list(range(10)) #criar uma lista com 10 posicoes
for pos in lista: #para cada posicao na lista
lista[pos] = int(input("Insira um numero: ")) #entre com um inteiro e atribua a posicao
for i in range(10): # vamos contar de um a 10, i sera o contador
j = i+1 # j sera o contador para o numero vizi... |
da6fddd71439494fa40fa128eb958f8aee758809 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo3/exemplo19.py | 755 | 3.9375 | 4 |
#solicitamos o nome da disciplina
disciplina = input("Insira o nome da disciplina: ")
#solicitamos as notas de cada bimestre
nota1 = float(input("Insira a nota do 1 Bimestre: "))
nota2 = float(input("Insira a nota do 2 Bimestre: "))
nota3 = float(input("Insira a nota do 3 Bimestre: "))
nota4 = float(input("Insira a n... |
fc80005a87f4659595c0e83bef75e7c1e2c22cef | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo53.py | 451 | 4.1875 | 4 | def quadrado(numero): #a definicao de uma funcao e igual a de um procedimento
return numero**2 #usamos a instrucao return para retornar um valor
entrada = int(input("Insira um numero: ")) #pedimos um numero
quad = quadrado(entrada) #chamamos a funcao e guardamos o retorno em quad
print("O quadrado de %i e %i" %... |
e8677cd29a9cebe156ac92b710e3b845afe30e16 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo5/exemplo31.py | 338 | 3.984375 | 4 | lista = ["banana", "queijo", "trigo", "Azeite"] #lista inicial
print(len(lista)) #verifique o tamanho da lista
print(lista) #verifique os itens na lista
lista.append("cenoura") #adicione a cenoura no fim da lista
print(len(lista)) #verifique novamente o tamanho da lista
print(lista) #verifique novamente o... |
57ab37112b0079458b6764b8a553ae350ec67d85 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo52.py | 983 | 4.0625 | 4 | def soma(a, b): #definimos um procedimento para soma com dois parametros
print("O resultado e: ", a + b) #o procedimento informa a soma dos dois parametros
def subt(a, b): #tambem definimos um procedimento para subtracao
print("O resultado e: ", a - b) #que informa a subtracao entre os parametros
num1... |
da0d72971cfaa23536508e734299af13948a5411 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo54.py | 381 | 3.59375 | 4 | def formatar(nome, sobrenome): #definimos a funcao
formatado = nome + " " + sobrenome #processamento da funcao
return formatado.title() #retorno da funcao
meu_nome = "bruno" #string com nome
meu_sobrenome = "LUVIZotto CARLi" #string com sobrenome
nome_completo = formatar(meu_nome, meu_sobre... |
d4c50b61906ef9e3e776d857ee857da89cd107a8 | maxts0gt/pythoneveryday | /D18_Turtle_Projects/circle.py | 566 | 3.828125 | 4 | from turtle import Turtle, Screen, color, colormode
import random
turtle = Turtle()
screen = Screen()
turtle.shape('turtle')
turtle.color('black')
colormode(255)
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
color = (r, g, b)
r... |
c1af06d29e4b657caa6cc3b4dd156a4e712f4fea | maxts0gt/pythoneveryday | /D46_Spotify_Project/main.py | 2,206 | 3.6875 | 4 | import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pprint
pp = pprint.PrettyPrinter(indent=4)
CLIENT_ID = "YOUR CLIENT ID"
CLIENT_SECRET = "YOUR SECRET"
# 1. TODO Choose which year to select
which_date = input("Which year do you want to travel to? Ty... |
fed2a3c3fdf8ca62be24e4e351d6400c5acd1d61 | pns845/Dictionary_Practice | /exer_aug24.py | 231 | 3.703125 | 4 | db={'name':'Router1','IP':'1.1.1.1','username':'zframez','password':'zframez'}
print(db)
s=input("get data from user")
#print(db[s])
if s in db:
print("key is"+str(s))
print(db[s])
else:
db[s]='new value'
print(db)
|
96185701b42d39418c049884c2740c2fb3e2e938 | afakharany93/Numbers-game | /python3/cli_numbers_game.py | 1,411 | 3.546875 | 4 | from game_engine import NumGame
from help_string import help_string
help_string2 = help_string + """Method of input:\n
If you are guessing 12345 you will type 12345 and then you will press enter.\n
If you enter the character: e, the number will be revealed and you lose.\n
Press Enter to start\n
***********************... |
7553f4a04d4b684301ca8de86f83bd4c2f3bf3f0 | nishizumi-lab/sample | /python/basic/for/ex_obj.py | 184 | 4.03125 | 4 |
list = [1, 2, 3]
# list内の全要素が代入されるまで繰り返し
for x in list: # listの内容を1つずつ取り出してxに代入
print(x)# xを表示
print("End")
|
035992df7f2856f7fdbaa2ef068ab428086f3636 | nishizumi-lab/sample | /python/pandas/pivot_table.py | 524 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
def main():
# データフレームの初期化
df = pd.DataFrame({
'名前' : ['西住みほ', '秋山優花里', '武部沙織', '五十鈴華', '冷泉麻子'],
'身長' : [158, 157, 157, 163, 145]},
index = ['車長', '装填手', '通信手', '砲手', '操縦手']
)
# データ取り出し
df2 = pd.pivot_table(df, values='砲手', index=['車長', '装填手'],... |
77933b5cd45ab221fbd864bbeb69c8ab917dc5e9 | nishizumi-lab/sample | /python/sqlite/01_tutorial/05_select.py | 594 | 3.75 | 4 | # -*- coding: utf-8
import sqlite3
# データベース開く
db = sqlite3.connect("C:/github/sample/python/sqlite/00_sample_data/sarvant.db")
c = db.cursor()
# テーブル作成
c.execute('create table artoria (name text, atk int, hp int)')
# データ追加(レコード登録)
sql = 'insert into artoria (name, atk, hp) values (?,?,?)'
data = ('artoria',11221,151... |
a7323112d0ff3509ec5191486446755ae0c9be21 | nishizumi-lab/sample | /python/basic/file/csv/update.py | 712 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import csv
def read_csv(filename):
f = open(filename, "r")
csv_data = csv.reader(f)
list = [ e for e in csv_data]
f.close()
return list
def update_list2d(list, data):
for i in range(len(list)):
if list[i][0]==data[0]: list[i] = data
return list
def writ... |
2cb857d45ed8b9ef6f70e22707fb78611ca4c586 | nishizumi-lab/sample | /python/scikit/nn/sample01.py | 1,203 | 3.703125 | 4 | # -*- coding: utf-8
import numpy as np
# 活性化関数(ステップ関数)
def f(x):
x = np.array(x)
x[x>=0] = 1
x[x<0] = -1
return x
# 出力
def feed_forward(w, x):
return f(np.dot(w, x))
# 学習
def train(w, x, t, eps):
y = feed_forward(x, w)
# 出力と正解が異なれば重み更新
if(t != y):
w += eps * t * x
return w... |
7c8b0ac9e89b14cb5043edf4e109907bf708ddb1 | nishizumi-lab/sample | /python/csv/03_make_date_list/main.py | 1,078 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import csv
import datetime as dt
# 365日*24時間分の日付を取得
def get_dates():
date = dt.datetime(2017, 1, 1, 0, 0)
dates = []
for i in range(365*24):
dates.append(date.strftime('%Y-%m-%d %H:%M'))
date += dt.timedelta(hours=1)
return dates
# 2次元リストをCSVファイルに保存
def write_cs... |
cd5d71c17faa96e5ab16a62ec44d01c084f0a39d | nishizumi-lab/sample | /python/basic/for/in/list.py | 237 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def main():
# リストの初期化
names = ["宮内ひかげ", "富士宮このみ", "加賀山楓 "]
# 結果表示
for name in names:
print(name)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.