blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
959c2cbc231db6724ad9bb29ca5be19dea021cbc | gjtjdtn201/practice | /수업/stack2/미로.py | 808 | 3.515625 | 4 | import sys
sys.stdin = open("미로.txt", "r")
def safe(y, x):
return N > y >= 0 and N > x >= 0 and(Maze[y][x] == 0 or Maze[y][x] == 3)
def DFS(sty, stx):
global ans
if Maze[sty][stx] == 3:
ans = 1
return
visit.append((sty, stx))
for i in range(4):
Py = sty + dy[i]
Px ... |
4d3d6d0bbbf92446cf1a69dd5f7e2c42f043853f | syurskyi/Python_Topics | /021_module_collection/counter/_exercises/templates/counter_003_Finding the n most Common Elements_template.py | 1,873 | 3.859375 | 4 | # # Finding the n most Common Elements
# # Let's find the n most common words (by frequency) in a paragraph of text.
# # Words are considered delimited by white space or punctuation marks such as ., ,, !, etc - basically anything except
# # a character or a digit. This is actually quite difficult to do, so we'll use a ... |
e57cdc1ccc2f3a8a211c5bafec2cb96abaf8af1e | redpanda-ai/ctci | /solutions/animal_shelter.py | 2,104 | 3.828125 | 4 | """
Title:
Animal Shelter
Question:
An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals in the shelter, or they can select whether they would prefer a dog or a cat (and will receive t... |
3682e80cb780a03106473a4e8aba19de083d778c | Nguyen101/League-of-Legends-Data-Analysis | /mysklearn/myevaluation.py | 6,249 | 3.6875 | 4 | import mysklearn.myutils as myutils
import random
import math
def train_test_split(X, y, test_size=0.33, random_state=None, shuffle=True):
"""Split dataset into train and test sets (sublists) based on a test set size.
Args:
X(list of list of obj): The list of samples
The shape of X ... |
c2d8f3e7df9932067c67425ccc10bdc9e259628b | ljia2/leetcode.py | /solutions/math/233.Number.of.Digit.One.py | 397 | 3.890625 | 4 | class Solution(object):
def countDigitOne(self, n):
"""
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, ... |
68a9d33f8c4f0f71e887467f258c1f17fa343471 | jihoonog/Tim-The-Enchanter | /spellbook.py | 8,609 | 3.78125 | 4 | import pickle, os
from spell import *
class Spellbook:
def __init__(self, name):
self.name = name
self.spells = list()
def addSpell(self, spell):
self.spells.append(spell)
self.spells.sort(key=lambda k: k.name)
def removeSpell(self, spell):
try:
self.sp... |
8869e2e8b324fdcd308b9d003f0aa0c34398ee35 | S-Tim/saene | /saene/utils/copy_dict.py | 1,040 | 4.03125 | 4 | """ Utility to copy dictionaries that also have lists as values
Author: Tim Silhan
"""
import numpy as np
def copy_dict(original):
""" Copies the *original* dictionary
This function makes sure that lists and numpy arrays are copied as well
instead of only referencing the original list in the copy.
... |
cb23bbc23c62bddc3749522a5f79b4487b7bc59f | manhcuogntin4/Code_Gym | /cube_pile.py | 1,672 | 4 | 4 | '''There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then
.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible... |
c8e761c436ef53bd64163d0b515127d92d2fc72f | AdamsEatin/Data_Sci | /breakdown_per_country.py | 3,024 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Author: Adam Eaton - C00179859
This file generates a graph showing a breakdown of the different types of renewable energies used by each member
of the EU.
"""
import pandas as pd
import numpy as np
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
plotly.tools.set_cr... |
57c6ac48d70d5382e3a96e168f9d69d82debc15e | tenrenjun/python_experimental-task | /Experimental task/CH2_Task5.py | 840 | 3.984375 | 4 | # 新建list并输出其长度
classmates = ['Michael', 'Bob', 'Tracy']
print(len(classmates))
# 查看列表中第一个和第二个元素
print(classmates[0])
print(classmates[1])
# 添加元素
classmates.append('Adam')
print(classmates)
# 指定位置插入元素
classmates.insert(1, 'Jack')
print(classmates)
# 删除末尾元素
classmates.pop()
print(classmates)
# 删除指定位置元素
cl... |
ebfa5ed29b3df005b6f8533751ad3bebe88c0f43 | n-alegria/ProyectosPython | /Juegos_Python/Adivina el numero - facil/main.py | 2,011 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from random import randint
from exception_number import NumberException
def juego():
print("""
Bienvenido
Se le solicitará que ingrese un numero de tres digitos entre el 100 y 999 el cual será cotejado con un numero secreto generado automaticamente.
... |
d47f6548cbbec022548169d2556ad9e390056f8b | Kang-Hoon/Python_reviews | /190614_fin exam/1906_3.py | 376 | 3.734375 | 4 | # 스크립트 창입니다
import turtle
t = turtle.Turtle()
t.penup()
t.goto(100,100)
t.write("It's positive integer")
t.goto(100,0)
t.write("It's Zero")
t.goto(100,-100)
t.write("It's negative integer")
t.goto(0,0)
t.pendown()
i = turtle.textinput("","Enter integer : ")
j = int(i)
if j>0:
t.goto(100,100)
if (j==0):
t.g... |
1286a43a47ea69dc31f61408dcc8d0e1030b9abc | winonachen/2020-Jayden-AE401 | /成績.py | 227 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 11:28:58 2020
@author: user
"""
a=input("請輸入你的考試成績:")
a=float(a)
if a>59:
print("恭喜你~!有及格!")
else:
print("嗚~!沒及格!") |
d764b2b0ff06e08116824a16b54b23d6aa3f94b9 | zhaoxy92/leetcode | /918_maximum_sum_subarray.py | 782 | 3.59375 | 4 | def max_sum_noncircular_subarray(array):
ans = cur = array[0]
for n in array[1:]:
cur = n + max(cur, 0)
ans = max(ans, cur)
return ans
def maxSubarraySumCircular(A):
"""
:type A: List[int]
:rtype: int
"""
ans1 = max_sum_noncircular_subarray(A)
ans2 = sum(A) + max_s... |
83a640198eb4ebfab509ae6fc14b2ca9bf9c3936 | HarshaVardhan-Kaki/Hashing-2 | /longest_palindrome.py | 422 | 3.5625 | 4 | # O(N) TIME AND O(N) SPACE WHERE N IS LEN(S)
class Solution:
def longestPalindrome(self, s: str) -> int:
palindrome_len = 0
counts = set()
for char in s:
if char not in counts:
counts.add(char)
else:
palindrome_len += 2
... |
d6a8a7e1597ded9d8433d2757e17ed64159c5279 | jannuprathyusha/jannuprathyusha | /cspp1practicem3/m6/p3/digit_product.py | 134 | 3.578125 | 4 | N = int(input())
PRODUCT = 1
TEMP = 0
while N != 0:
TEMP = N%10
PRODUCT = PRODUCT*TEMP
N = N//10
print(PRODUCT)
|
243f03bb0f3a21d8d008ed4c1bbb862341fd7a1d | pranayreddy604/gitam-2019 | /28-06-2k19.py | 1,718 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
def test():
print("test() for function")
return
test()
# In[22]:
class Demo:
n=0
m=0
def test(self,n,m):
self.n=n
self.m=m
print("test() for the class and method",n+m)
return
obj=Demo()
obj.test(55,40)
# In[35]:
... |
d1cb3700ddecb7b563e04496b5372dde766e447b | saraht0607/phyton- | /evenloops.py | 48 | 3.609375 | 4 | #using while
i=2
while(i<=26):
print(i)
i=i+2 |
e64aa24b8697cc026b1079b06b09308bf55192d3 | kkemppi/TIE-courses | /Ohjelmointi 1/Ohjelmointi 1/alle 7. krs/teiskon_bussi.py | 579 | 3.796875 | 4 | def main():
lahtoajat = [630, 1015, 1415, 1620, 1720, 2000]
lahtoaika = int(input("Enter the time (as an integer): "))
ensimmainen = mika_eka(lahtoajat, lahtoaika)
print("The next buses leave:")
i = 1
monesko = ensimmainen
while i <= 3:
if monesko >= 6:
monesko = 0
... |
f3e30374970762c265f3a4b762b4a0bf76417f22 | eric496/leetcode.py | /tree/666.path_sum_IV.py | 1,615 | 4.03125 | 4 | """
If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.
For each integer in this list:
The hundreds digit represents the depth D of this node, 1 <= D <= 4.
The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The posit... |
2e34b0bb6dfc6f0db072ef96163d1079c679c4df | RoopakParashar/turtle-race-with-python | /TURTLEPROJECT.py | 1,077 | 3.78125 | 4 | from turtle import *
from random import randint
speed(20)
penup()
goto(-140,140)
for step in range(15):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
kirti= Turtle()
kirti.color('red')
kirti.shape('turtle')
kirti.p... |
5962f3f6aebeb00ab024833bcacb29fee86af064 | jimmy623/LeetCode | /Solutions/Simplify Path.py | 832 | 3.671875 | 4 | class Solution:
# @param path, a string
# @return a string
def simplifyPath(self, path):
folders = path.split("/")
result = []
for p in folders:
#print result,p
if p == "." or p == "":
continue
if p == "..":
if len(r... |
29a904cb6c9b0c37b24dbd960bfef3cd712136ce | svelezp/ST0245-008 | /Parcial_2/punto3_parcial2.py | 1,473 | 3.53125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def buildtree(inorder, preorder, instrt, inend):
if instrt > inend:
return None
Nodo = Node(preorder[buildtree.preIndex])
buildtree.preIndex += 1
if instrt == inend:... |
5781b03ab66ba69289f83bddd9748a7f8ad4a688 | makchamp/puzzle-search-algorithms | /src/node.py | 2,963 | 4.125 | 4 | from puzzle import Puzzle
class Node:
# this is a node in the tree on which we will apply a search algorithm
# this will be a static variable to store all the previously visited setups
# visited_setups = []
def __init__(self, puzzle: Puzzle, parent, arriving_move, move_cost, moved_tile, cost_to_reac... |
84d80c6c25ace281f635952375cc971ab27a5072 | longhao54/leetcode | /easy/263.py | 793 | 4.03125 | 4 | '''
编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例 1:
输入: 6
输出: true
解释: 6 = 2 × 3
'''
class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
# 下面这个方法测试用例42 就过不去
# if num < 0:
# num = -num
# return num % 6 ==0 or num %10 ... |
6f1090fbdbcf1992dc0e9ceed8b5449374de43b3 | stevenbrand99/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 525 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
0. My first square:
Write an empty class Square that defines a square:
You are not allowed to import any module
"""
class Square:
"""Square class - receive the size of an square"""
def __init__(self, size=0):
"""Init methos recive size attr ans pass it to... |
0a75816b4e91d17a766fb4ed7d76eeba501a56fc | JessicaJang/cracking | /Coursera/guess_the_number.py | 2,485 | 4.09375 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import math
import simplegui
secret_number = 0
limit = 0
count = 0
#indicate the range is up to 100 or 1000
flag = 0
# helper function to start and r... |
377bbfd815ff51578db8bfbc11c5b47473035b44 | bontu-fufa/competitive_programming-2019-20 | /day24/contains-duplicate-ii.py | 607 | 3.515625 | 4 | #https://leetcode.com/problems/contains-duplicate-ii
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
d = {}
for i in range(len(nums)):
... |
48d9aec213003c6301fb112f3d792deff66129f9 | doraemon1293/Leetcode | /archive/2249. Count Lattice Points Inside a Circle.py | 504 | 3.625 | 4 | from typing import List
class Solution:
def countLatticePoints(self, circles: List[List[int]]) -> int:
ans=set()
for x,y,r in circles:
for x0 in range(x-r,x+r+1):
for y0 in range(y-r,y+r+1):
if (x0-x)**2+(y0-y)**2<=r**2:
ans.add... |
d1a5856b1e2d5a90b7de5ea007a277ef940d6c0b | ww8007/Python | /Study/GUI/Text.py | 276 | 3.59375 | 4 | from tkinter import *
window = Tk()
t = Text(window, height = 5, width = 60)
t.pack()
t.insert(END, "텍ㅌ스트 위젯은 여러줄의 \n 텍스트를 표시할 수 있습니다.")
window.mainloop()
#텍스트는 html이나 css 스타일도 사용이 가능하다. |
ff2c98389e13ce2061601068c93999ff9f20a7a5 | OleksandrNikitenko/CodeSignal-Arcade | /ListForestEdge/IsSmooth.py | 1,229 | 4.21875 | 4 | """
We define the middle of the array arr as follows:
if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from
the beginning of the array and from its end;
if arr contains an even number of elements, its middle is the sum of the two elements who... |
11ae6090b834b1cabe02614fd290720330195dea | thehealer15/Freelance-work | /pdf/rotating_pdf.py | 655 | 3.625 | 4 | import PyPDF2 as p
# rotating pdf
location="file.pdf"
with open(location,'rb') as f:
pdf=p.PdfFileReader(location)
writer=p.PdfFileWriter()
# why writer?
# After rotating we need to save as pdf
page=pdf.getPage(0)
page.rotateClockwise(90)
# counterClockwise also there angle must be st... |
a4730135dc0515a8f46847780b4c8fd056664f39 | Matchinski/ImageQuizzer | /MongolianBirdTeacher.py | 9,336 | 3.5625 | 4 | import os
import random as rd
import tkinter as tk
from tkinter import font
from PIL import ImageTk, Image
# Clear the terminal at the start of each run
os.system('cls' if os.name == 'nt' else 'clear')
# Set the background image and the path to the picture folder
backgroundImageName = 'Background.png'
bi... |
803cd4156f07966baf3c15d955a73cc8b714b8b9 | aristeidismoustakas/Advanced-ML-techniques | /datasets/WineQualityDataset.py | 1,065 | 3.5 | 4 | import pandas as pd
from datasets.Dataset import Dataset
class WineQualityDataset(Dataset):
def __init__(self, data_file):
super(WineQualityDataset, self).__init__()
# Loading the 2 files with the red and the white wines.
red_wines = pd.read_csv((data_file + '-red.csv'), delimiter=';', h... |
43e755556cf3e08412a33f539e7905cb0f35e507 | nehakumari7/pythontutorial_ | /strings/palindrome_strings func.py | 426 | 3.953125 | 4 | if __name__=="__main__":
name="madam"
'''
x=name[::-1]
if x==name :
print("yes it is palindrome")
else :
print("no it is not palindrome")
'''
length=len(name)
print(length)
rev=""
i=length-1
while(i>=0):
rev=rev+name[i]
i=i-1
print(rev)
... |
f83ee57628f1d9e23fa193da42863d9cc3430f5c | ctOS-2019/Answer-to-exercises | /Zhejiang_University_Edition_Python Programming/Programming questions/T3.11.py | 812 | 4.03125 | 4 | '''
本题要求编写程序,读入5个字符串,按由小到大的顺序输出。
输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
输出格式:
按照以下格式输出排序后的结果:
After sorted:
每行一个字符串
输入样例:
red yellow blue green white
输出样例:
After sorted:
blue
green
red
white
yellow
'''
def com(a, b):
if a < b:
return True
else:
return False
list = []
f... |
f969b8b9863ae299037d92c933f7824b465d5ca3 | TonyNewbie/TicTacToe | /Tic-Tac-Toe/task/tictactoe/tictactoe.py | 2,812 | 3.703125 | 4 | # write your code here
def table_printer(table):
print('---------')
print(f'| {table[0][0]} {table[0][1]} {table[0][2]} |')
print(f'| {table[1][0]} {table[1][1]} {table[1][2]} |')
print(f'| {table[2][0]} {table[2][1]} {table[2][2]} |')
print('---------')
def check_table(table):
x_wins = ((tabl... |
e39b5337eb70061a7688fbd8c742d13f33d0ac24 | P4NK4J/Competitive_Coding | /practice problems/beginner/Easy_math.py | 580 | 3.59375 | 4 | def sumOfDigits(n):
sum = 0
while(n > 0):
sum += n % 10 # n%10 gives the digit at units place
n //= 10 # Integer division leads to loss of digit at unit's place, and shifts all digits by 1 place right.
return sum
t = int(input())
for k in range(t):
n = int(input())
arr = [i... |
0e1e460933a5ae4d20fc089a7f47c42bf055e152 | KYBee/DataStructure | /practice/dfs.py | 440 | 3.609375 | 4 | def dfs(graph, start, visited = set()):
if start not in visited:
visited.add(start)
print(start, end=" ")
nbr = graph[start] - visited
for v in nbr:
dfs(graph, v, visited)
mygraph = {
"A" : {"B", "C"},
"B" : {"A", "D"},
"C" : {"A", "D", "E"},
"D" : {"B",... |
c0c13d05aeedf02235bdb2dd8cdf8723745efe7e | cfee89/QualifyingOffer | /src/data/PlayerRecord.py | 585 | 3.5 | 4 | class PlayerRecord:
def __init__(self,inPlayerName,inSalary,inYear,inLeague):
self.playerName = inPlayerName
self.salary = inSalary
self.year = inYear
self.league = inLeague
def __str__(self):
return "Name: " + self.playerName + " Salary: " + str(self.salary)
def is... |
240b3c972aced7ae9bbbf2d77ddbc3bb4a58c02b | tugrazbac/web_science | /a1/scatter.py | 1,371 | 3.5 | 4 | #!/usr/bin/env python
# encoding: utf-8
import os
import sys
import json
import numpy
import networkx
import matplotlib.pylab as plt
def perform(graph):
''' Takes a networkx.Graph, calculates the degrees and clustering
coefficients for the given graph, calls 'plot' to generate a scatterplot
(degree vs. clusteri... |
09b08c50183e43278387ca93385d78fb5d261aef | 981377660LMT/algorithm-study | /11_动态规划/dp分类/有限状态dp/1824. 最少侧跳次数.py | 2,082 | 3.53125 | 4 | from functools import lru_cache
from typing import List
INF = int(1e20)
# 这只青蛙从点 0 处跑道 2 出发,并想到达点 n 处的 任一跑道 ,请你返回 最少侧跳次数 。
# 注意:点 0 处和点 n 处的任一跑道都不会有障碍。
# 1 <= n <= 1e5
# dp[i][j]表示第i点第j道最少的侧跳次数(一次侧跳可以跳多个格子)
class Solution:
def minSideJumps2(self, obstacles: List[int]) -> int:
"""AC
... |
ca13c468574004e1f68c80f6e14168bc38092157 | jinudaniel/Python-Projects | /Book_Store/book_store_frontend.py | 3,012 | 3.703125 | 4 | from tkinter import *
import book_store_backend
def get_selected_row(event):
global selected_tuple
if list1.curselection():
index = list1.curselection()[0] #returns index of selected element in tuple format so selecting the first element
selected_tuple = list1.get(index)
e1.delete(0, END)
e1.insert(END, sel... |
57d31ca3efe29523c304e958f744b1ab34afd5cf | taylorfuter/Tetris | /tetris.py | 8,714 | 3.5625 | 4 | # 15-112, Summer 2, Homework 4.2
######################################
# Full name: Taylor Futernick
# Andrew ID: tfuterni
# Section: C
######################################
####################################
# use the run function as-is
####################################
from tkinter import *
import random
def ... |
a50774bc2aea65fa994a93252b3c50f9e4cf60eb | RBabaev/Annoying-Fence | /RobertsSolution.py | 735 | 4.0625 | 4 | n = int(input())
maxLength = n // 2
#This portion sorts the boards by height.
boards = [int(s) for s in input().split()]
heights = set(boards)
lHeights = list(heights)
lHeights.sort()
#This portion assesses the possible heights.
possHeights = []
for height in lHeights:
for i in range(len(lHeights)):
if lHeights... |
cde62f98c13afd6ad02a93f7e13e40980d9a54c7 | sacrrie/reviewPractices | /CC150/Python solutions/5-0.py | 1,272 | 4.0625 | 4 | #bit manipulation practice file
#a simple bit manipulation function
'''
import bitstring
print(int('111001', 2))
def repeated_arithmetic_right_shift(base,time):
answer=base
for i in range(time):
answer=base>>1
return(answer)
a=repeated_arithmetic_right_shift(-75,1)
print(a)
def repeated_logical_ri... |
dc373038e9ba86473fd190f6ce1bc7122dd27db7 | Vampirskiy/Algoritms_python | /unit2/Task 7.py | 810 | 4.03125 | 4 | # Task 7
# Напишите программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2, где n - любое натуральное число.
# Ссылка на блоксхемму: https://drive.google.com/file/d/14vZjr7HoUfCmdr0BNCNs41PCJdkclAL2/view?usp=sharing
def m(n):
if n == 1:
ret... |
7250b0d22f23a19cc05ecdca3abb5590211a4291 | apecr/astwp-section-2 | /lists_tuples_sets.py | 491 | 3.703125 | 4 | my_variable = 'hello'
grades = [77, 80, 90, 95, 100]
grades_tuple = (77, 80, 90, 95, 100, 105, 107, 90)
set_grades = {77, 80, 90, 100, 100}
def average(grades):
return sum(grades) / len(grades)
set_grades.add(60)
set_grades.add(60)
# print(set_grades)
your_lottery_numbers = {1, 2, 3, 4, 5}
winning_number = {1... |
61b65618eb74fb06030834d2e812043acc40c5d5 | HenryCheng923/Henry_Cheng_PythonCode | /password-retry.py | 555 | 4 | 4 | #練習密碼判斷程式
#password = 'a123456'
#讓使用者重複輸入密碼
#最多輸入3次
#如果正確 就印出"登入成功!"
#如果不正確 就印出 "密碼錯誤! 還有__次機會!"
password = 'a123456'
count_pwds = 3 #三次機會
while count_pwds > 0:
count_pwds = count_pwds - 1
pwd = input('請輸入密碼: ')
if pwd == password:
print('登入成功!')
break
elif pwd != password and count_pwds > 0:
print("密碼錯誤!... |
20440fe476895e42c0459d5ceef6a12d7996a1e8 | penguin0416/my_repos | /2021136051_박선호_과제-06-2.py | 838 | 3.546875 | 4 | #실습과제06
import math #수학함수 불러오기
def fun_glb_distance(x1,x2,y1,y2): #함수 fun_distance 생성
print("첫번째 좌표는 (",round(x1,1), round(y1,1),") 이다.")
print("두번째 좌표는 (",round(x2,1), round(y2,1),") 이다.")
result = math.sqrt((... |
9fb0891693abffe94168010768110465f8cb1f40 | PengZiqiao/report_factory_3 | /utils.py | 676 | 3.859375 | 4 | from datetime import date
class Month:
def __init__(self):
self.month = date.today().month
self.year = date.today().year
def before(self, i):
"""i个月之前"""
if self.month - i > 0:
return self.year, self.month - i
elif self.month - (i - 12) > 0:
ret... |
8d41a9714ebb48ac1f641cd86f42876cc82b6469 | himanshu2922t/FSDP_2019 | /DAY-02/centered.py | 537 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 15:06:43 2019
@author: Himanshu Rathore
"""
number_list = input("Enter array of numbers space separated: ").split()
# sorting of numbers in another list
sorted_number_list = sorted(number_list)
# removing smallest and largest from sorted list
del sorted_number_list[0]... |
7ed3f5eddeb8f49f3cc8bffc9444e343165e60b4 | gladieschanggoodluck/CS5010_SemesterProject | /1_1116_FIFA_Normal_Plot.py | 12,128 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # FIFA visulization and statistical analysis
# In[54]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
get_ipython().run_line_magic('matplot... |
ce9b9f59aa0b90757b8f60e35becc4f4cd01c761 | clovery410/mycode | /python/chapter-1/discuss4-1.1.py | 428 | 4.0625 | 4 | #1.1 Print out a countdown using recursion.
def countdown(n):
"""
>>> countdown(3)
3
2
1
"""
if n <= 0:
return
print(n)
countdown(n - 1)
#1.2 Change countdown to countup instead.
def countup(n):
"""
>>> countup(3)
1
2
3
"""
if n <= 0:
retu... |
7d1fa29b488499995a74c8f0a50ba7e493761a7a | anjana996/luminarpython | /mockexam/wordcount.py | 199 | 3.578125 | 4 | file="hai hello hai hello"
words=file.split()
dict={}
for word in words:
if (word not in dict):
dict[word]=1
else:
dict[word]+=1
for k,v in dict.items():
print(k,",",v)
|
48489e987ae2730270aba07cc8b943282f65bb2f | nikolasvargas/python-adventures | /mini_games/playground.py | 1,251 | 3.65625 | 4 | """ main of main """
import riddle
import hangman
def main():
""" start select """
print("***************************************************", end="\n")
print("*********** Bem vindo ao salão de jogos! **********", end="\n")
print("***************************************************", end="\n")
... |
a74e5e89715c1f9d650a2e30051f638291b939cc | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/401-600/000437/000437.py | 2,128 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def pathSum(self, root, targetSum):
"""
:type root: TreeNode
:type t... |
3f64bed0bc77f15de807b3694b294240e6b3a93b | bmcclannahan/sort-testing | /sorts.py | 611 | 3.90625 | 4 |
def is_sorted(arr):
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
return False
return True
def swap(a, b, arr):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def insertion_sort(start, end, arr):
for i in range(start, end):
curr = i
while curr >= 1 and arr... |
c43b784c766fd9156c9a894282e4fcf509511a47 | W7297911/test | /python/firstPython/类属性_统计.py | 427 | 3.828125 | 4 | class Tool(object):
# 使用赋值语句定义类属性,记录所有工具对象
count = 0
def __init__(self, name):
self.name = name
# 让类属性的值+1
Tool.count += 1
# 1.创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("砍刀")
tool3 = Tool("钳子")
tool4 = Tool("榔头")
# print(Tool.count)
# print("工具对象总数:{}".format(tool1.count))
print("工具对象总数:{}".format(tool1.count)) |
244bb4f68578359a91df336efbeb253ae2ffebe0 | will-i-amv-books/Functional-Python-Programming | /CH3/ch03_ex3.py | 2,675 | 4.5 | 4 | #!/usr/bin/env python3
"""Functional Python Programming
Chapter 3, Example Set 4
"""
###########################################
# Imports
###########################################
import math
import itertools
from typing import Iterable, Iterator, Any
###########################################
# Generator expres... |
3c4fe8360ff25b984d1af3131aca1797ea18cf7f | josephcalver/CompleteDataStructuresAndAlgorithmsInPython | /ArraysAndLists/arrays.py | 1,599 | 4.375 | 4 | from array import array
# 1. Create an array and traverse
print("#1:")
my_array = array('i', [1, 2, 3, 4, 5])
print(my_array)
for i in my_array:
print(i)
# 2. Access individual element via index
print("#2:")
print(my_array[0])
# 3. Append a value to the array
print("#3:")
my_array.append(6)
print(my_ar... |
9ae57aabb32f6075c852791e12edcdc2f2ded907 | thrika/Gradient-Descent-from-Scratch | /Problem_2.py | 1,387 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import math
# In[ ]:
function = lambda x: np.sin(10*(math.pi)*x) + ((x-1)**4)
# In[ ]:
x = np.linspace(-0.5,2.5,500)
# In[ ]:
plt.plot(x, function(x))
#... |
030eba724fff9b8752c2c2bcf35bbcfee3d7bab4 | Dash275/herochest | /die_cast.py | 736 | 3.546875 | 4 | import random
import re
import itertools
def roll(n, x):
result = 0
for i in range(1, n + 1):
result += random.randrange(1, x + 1)
return result
def roll_expression(expression):
result = 0
expression = expression.replace(" ", "")
pieces = re.findall('\+?-?\d*d?\d+', expression)
for... |
edd13fb17ba91e07ada865333baa4b77b24cc3cc | IlshatVEVO/Data-Analys-Labs | /lab3/Task2_1.py | 203 | 3.671875 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 50, 0.01)
y = [i * 2.9 + 10 for i in x]
plt.plot(x, y, 'b')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Draw line')
plt.show() |
3d48062483273a58ccc26b9041dd4a6af677cfe5 | dkoh12/gamma | /Python/sort.py | 2,733 | 3.90625 | 4 | def binarySearch(lst, value, low, high):
if low > high:
return -1
mid = (low + high) // 2
if lst[mid] == value:
return mid
elif lst[mid] < value:
return binarySearch(lst, value, mid+1, high)
else:
return binarySearch(lst, value, low, mid)
def selectionSort(lst):
for i in range(len(lst)):
small = i
... |
cc574d42a17f2ae51d5691ee1aea78197dc1580a | Felipe-Ferreira-Lopes/programacao-orientada-a-objetos | /listas/lista-de-exercicio-03/questao3.py | 414 | 4.03125 | 4 | letra = str (input("Digite a letra desejada: "))
if letra == ("F"):
print("Feminino")
elif letra == ("M"):
print("Masculino")
'''A partir daqui eu fiz o restante das possibilidades apenas por diversão :), e para testar a linguagem identificando
letras maisculas e minusculas '''
elif letra ==("f"):
p... |
073bad8632066d50d21a80b3ee599727e7d60d98 | hanroy/Guess-the-Number | /guess-the-number.py | 398 | 3.8125 | 4 | from random import *
answer = raw_input("Do you wanna play [Y/N] : ")
guessnumber = randint(1, 15)
while (answer == "Y" or "y" or "yes"):
userguess = int(raw_input("Guess a number: "))
if userguess < guessnumber:
print ("Little Higher")
elif userguess > guessnumber:
print ("Little Lower")... |
509f1def0a896bc83ebf6bfa6b95ce05e94adfd4 | ho600-ltd/ho600-ltd-python-libraries | /ho600_ltd_libraries/utils/formats.py | 2,044 | 3.984375 | 4 | def customize_hex_from_integer(number, base='0123456789abcdef'):
""" convert integer to string in any base, example:
convert int(31) with binary-string(01) will be '11111'
convert int(31) with digit-string(0-9) will be '31'
convert int(31) with hex-string(0-9a-f) will be '1f'
convert... |
b4223446ccb2dc8d7e248ca50b84b44a60d802e7 | knshkp/hacktoberfest2021 | /Python/heapsort.py | 485 | 3.71875 | 4 | def heap(arr, n, i):
a = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
a = l
if r < n and arr[a] < arr[r]:
a = r
if a != i:
arr[i],arr[a] = arr[a],arr[i]
heap(arr, n, a)
def hS(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heap(arr, n, i)
for i in range(n-1, 0, -1):
arr[... |
b1c8fbe1c5c4375caac646244d322403d2cb1688 | MeXaHu3M/PythonTasks | /practice 1/task 04.py | 355 | 3.90625 | 4 | print("Обмен значениями с промежуточной переменной")
a = int(input())
b = int(input())
c = a
a = b
b = c
print("A =", a, "B =", b)
print("Обмен значениями без промежуточной переменной")
a = int(input())
b = int(input())
a = a + b
b = a - b
a = a - b
print("A =", a, "B =", b) |
08740496fb5aa5045df39fcca2873c1cef588de2 | MarioDeCrist/Python-Programs | /MadLibs_Lab.py | 2,412 | 3.890625 | 4 | #Madlibs Lab
#Mario DeCristofaro
#md2224
#9-11-17
#Section 1
print("Mad Libs Story please enter words accordingly: ")
print("=============================================\n")
#these are the adj's, nouns, and names that asks us for the input
first_name = input("Type a name ")
first_noun = input("Type a... |
a2eac8b9f6a884de20a41eb982a1c2096533e5d0 | amen619/python-practise | /Week-2/Operators/11-else-not-required.py | 151 | 3.9375 | 4 | def is_even(number):
if number % 2 == 0:
return True
return False # Only if the IF statement fails this will be executed.
is_even(20)
|
ceff2e666e5ed34ec4e7a53341332e4598d80d71 | JulCesWhat/Unscramble_Computer_Science_Problems | /Task4.py | 1,616 | 3.953125 | 4 | #!/usr/bin/env python3
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
def getCSVData():
texts = []
calls = []
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
... |
503ce68333579c7fb7f4d7ba86036da9ca8f940f | kbutler52/python_scripts | /williamHw/hw2.py | 231 | 3.890625 | 4 |
#05-19-2020
#Williams HW#2
first = 5
second = 2
print(first > second)#checks if statement
print(not(first > second))# chekcs ekse statement
if first > second:
print("5 is greater than 2")
else:
print("5 is less than 2")
|
68918f822db5babda0faeb501a0979447d27143d | misrapk/tkinter-Tutorials | /ClickEvents.py | 242 | 3.578125 | 4 | from tkinter import *
root = Tk()
def leftClick(event):
print("Left Press")
def RightClick(event):
print("Right Press")
frame = Frame(root, width = 300, height=300)
frame.bind("<Button-1>", leftClick)
frame.pack()
root.mainloop() |
a31bfe119af111ac9d549d78f9dfde0b3810daaa | Groookie/pythonBasicKnowledge | /015_01_func_demo.py | 6,635 | 3.671875 | 4 | #!/usr/bin/python3
# -*-coding:utf-8-*-
# author: https://blog.csdn.net/zhongqi2513
# ====================================================
# 内容描述: 函数操作相关
# ====================================================
print(ord("A")) # 把一个字符转换成unicode编码
print(chr(65)) # 把数字转换成一个字符
print(abs(-1)) # 求绝对值
print(type(3 + 4j)) ... |
9b92236383c5b2f9b48d3c8cff5f066683e996a5 | L1nwatch/Mac-Python-3.X | /Others/装饰器学习/learn_wrapper.py | 918 | 3.546875 | 4 | #!/bin/env python3
# -*- coding: utf-8 -*-
# version: Python3.X
"""
2017.02.15 想学习一下装饰器的知识, 参考资料:
http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
"""
__author__ = '__L1n__w@tch'
def wrapper(arg):
def _for_wrapper(func):
def _true_wrapper(*args, **kwargs):
print("[*] 这里的装饰器能够接... |
54169f69caab30c6669b74aded329c6c38320de3 | mrajalakshmim/python-programming | /amstrong no.py | 225 | 4.03125 | 4 | n=int(input("enter a number"))
sum=0
temp=numberwhile temp>0:
digit=temp%10
sum+=digit**3
temp//=10
if n==sum:
print(n,"is an Armstrong number")
else:
print(n,"is not an Armstrong number")
|
1927317a0a77e845258eb9bf63f6c24c8dd7642e | pedromxavier/euler | /src/euler0034.py | 447 | 3.53125 | 4 | ''' Project Euler 0034
====================
'''
import eulerlib as lib
import math
M = math.factorial(9)
def u(n: int):
'upper bound'
return (n / math.log10(n)) <= M
def find():
n = 10
s = set()
while u(n):
if n == sum(math.factorial(d) for d in lib.digits(n)):
s.add(n)
... |
e7e3293f72a26440106c435171f3a01d23e2ee1c | taalaybolotbekov/ch1pt2task10 | /task10.py | 874 | 4.21875 | 4 | f = 'In the first line, print the third character of this string'
print(f[3])
s = 'In the second line, print the second to last character of this string.'
print(s[1:-1])
t = 'In the third line, print the first five characters of this string.'
print(t[0:5])
f = 'In the fourth line, print all but the last two characters ... |
c1baa12b9c0a4b97c2ebc6636176d6fbdece9a35 | rishabhsinghvi/CS383-Artificial_Intelligence | /Assignment_2/agent.py | 318 | 3.90625 | 4 | from abc import ABC, abstractmethod
class Agent(ABC):
"""An abstract game-playing agent."""
@abstractmethod
def select_action(self, game, state):
"""
Choose a move given some game state.
The implementation of this method will be different for each agent!
"""
pass
|
af2171df4bd0fb98fba04d68bcb378b7ef258a0b | EpsilonHF/Leetcode | /Python/476.py | 620 | 4.03125 | 4 | """
Given a positive integer, output its complement number. The
complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a
32-bit signed integer.
You could assume no leading zero bit in the integer’s binary
representation.
Example 1:
Inpu... |
4ec60842cb8646734fa0702d7e2ba5f3eea62531 | kalasu-1999/MultipleErrors | /FindErrors.py | 3,259 | 4.0625 | 4 | # -*- coding: UTF-8 -*-
# 文件多行不同判断
def clean(line, num):
while num < line.__len__() and line[num].strip() == '':
num = num + 1
return num
def logic(c):
# 最后一行
if c.trueNum + 1 == c.trueLine.__len__() or c.falseNum + 1 == c.falseLine.__len__():
return False
# 中间行
else:
... |
471a83a86cb86406bc497ac198b09d2ac5d767a9 | Connor1996/Core-Python-Promgramming-Exercise | /Chapter11/11-10.py | 242 | 3.59375 | 4 | import string
def delspace(filename):
func = lambda string: string.strip()
with open(filename, 'r+') as f:
Is = map(func, f)
f.seek(0)
f.write(''.join(Is))
if __name__ == '__main__':
delspace('test.txt') |
117c4e710ed710632be1558d89f5e5f2d7db0b97 | Aminoragit/Mr.noobiest | /my1021_4_5.py | 687 | 4 | 4 | str1='python is'
str2=' good programming'
str3 = str1 + str2
#string 연산자 overloding 원래+는 사칙연산이라 숫자만 되는데 파이썬에서 내부에서.__add__가 써지는것임
str1.__add__(' ') #str 덧셈=__add__ 메서드
print(str3)
print('='*40) #=
print('len :', len(str1)) #문자열의 길이 length = len
mylist = [3,6,8,0]
print('list len : ' , len(mylist))
... |
7be1cecb563a8d6373e101b2e098d828bc3348c3 | MarkoNerandzic/FoodRecommendations | /FileIO.py | 3,465 | 3.578125 | 4 | #-------------------------------------------------------------------------------
# Name: FileIO - Class of FoodRecommendations
# Purpose: To gather the survey results from the .csv file and write out the
# user's inputs to the file.
#
# Author: Justin Moulton & Marko Nerandzic
#
# Created: ... |
b79374cf976930eacc42cf1d87adde3f7f1c8681 | tylerBrittain42/cse-111-project | /myComicList/my_comic_list.py | 33,537 | 3.671875 | 4 | import sqlite3
from sqlite3 import Error
def openConnection(_dbFile):
#print("++++++++++++++++++++++++++++++++++")
#print("Open database: ", _dbFile)
conn = None
try:
conn = sqlite3.connect(_dbFile)
print("Connection Success")
except Error as e:
print(e)
#print("+++++... |
3cc8ae521a848aa3ab7670262bc5abe6378c74ef | AdamZhouSE/pythonHomework | /Code/CodeRecords/2172/60604/267797.py | 1,543 | 3.90625 | 4 | def priority(z):
if z in ['×', '*', '/']:
return 2
elif z=='^':
return 3
elif z in ['+', '-']:
return 1
def in2post(expr):
stack = [] # 存储栈
post = [] # 后缀表达式存储
for z in expr:
if z not in ['×', '*', '/', '+', '-', '(', ')','^']: # 字符直接输出
post.append(... |
59d26e57c578e0f7ecd6919a33ae766d89203616 | seonhan427/python-study-unictre- | /2021.03.29/while_1.py | 225 | 3.96875 | 4 | i = 0
while i < 10:
print(i, end=" ")
i = i + 1
# 출력값과 변수값의 순서는 중요
# 대부분의 증감문들은 문장 제일 아래에 둔다
"""
for i range (10):
print(i, end=" ")
""" |
266199b9f3f663e58e9e207c6f0c5a0bee67b204 | ducang/python | /session8/crud.py | 724 | 4.03125 | 4 | lis = ['1','2','3']
print(lis)
while True:
action = input('enter action (C;R;U;D) or Exit:')
if action == 'C':
add = input('enter ur number:')
lis.append(add)
print('ur list here:',lis)
elif action == 'R':
if lis == []:
print('list has nothing inside')
els... |
86a32918c2d82a435042553c90529198f6dabc58 | MARGARITADO/Mision_04 | /Triangulos.py | 1,388 | 4.25 | 4 | #Autor: Martha Margarita Dorantes Cordero
#Identificar tipo de triángulo
def identificarTipo(l1, l2, l3) :
#Función que realiza la operación requerida para identificar el tipo de triángulo con las medidas recibidas.
#Si todos los lados son iguales es un equilátero.
#Si dos de los lados son iguales es un isó... |
e3c364cac5b7ba35ef8592ee5ab72444f09d4e26 | sandykramb/PythonBasicConcepts | /Second_counter.py | 420 | 3.6875 | 4 | segundos_str = input("Por favor, entre com o número de segundos que deseja converter:")
total_segs = int(segundos_str)
days = total_segs // 86400
segs_restantes = total_segs % 86400
horas = segs_restantes // 3600
segs_restantes2 = total_segs % 3600
minutos = segs_restantes2 // 60
segs_restantes_final = segs_restante... |
48d8316e46e0bc58d52f30ef051833845ce8cea3 | andresilmor/Python-Exercises | /Ficha N4/ex01.py | 541 | 4.0625 | 4 | #Desenvolver um programa que vá lendo do teclado números inteiros até que a
#soma desses números atinja ou ultrapasse um limite máximo indicado previamente
#pelo utilizador. O algoritmo deverá no final dizer quantos foram os valores
#digitados.
def soma2():
try:
num=int(input('Indique um número: '))... |
0df8c6d53c9011e0d4e90da899602acb148ec57b | RonanLeanardo11/Python-Lectures | /Lectures, Labs & Exams/Lecture Notes/Lect 5 - Classes and Definitions/lect5Classes.py | 1,142 | 4.4375 | 4 |
# Define class and attributes
class car:
make = "Unknown"
model = "Unknown"
engineCC = 1.2
# "Objects" or "Instances" of a class
Mercedes = car() # assign Mercedes object to car class
BMW = car() # assign BMW object to car class
Audi = car() # assign Audi object to car class
print(car) # prints <class '... |
db074e8eba6f955e20feba2b218e299f7351c7e2 | 011235813etc/QA_tests_stepik_course_homework | /chapter_2/lesson3_step6.py | 2,232 | 3.53125 | 4 | """
Задание: переход на новую вкладку
В этом задании после нажатия кнопки страница откроется в новой вкладке, нужно переключить
WebDriver на новую вкладку и решить в ней задачу.
Сценарий для реализации выглядит так:
- Открыть страницу http://suninjuly.github.io/redirect_accept.html
- Нажать на кнопку
- Пере... |
fef5c8706e2e297a4bbda5d3d3288b0e8cdebb76 | ppapuli/Portfolio | /Puzzles/ImportDecklist.py | 969 | 3.515625 | 4 | # This script will read a text file to clean up a decklist to import into Cockatrice
# Type the name of your text file that will be manipulated
#----------------------------------------------------------#
textfile = 'Marwyn.txt'
#----------------------------------------------------------#
# open the fi... |
991753395dc9e46d7e0e87080e125102a4bd1fda | chunchuvishnuvardhan/panagram | /p2.py | 329 | 3.921875 | 4 | import string
str=input("enter your string")
st=str.upper()
a=string.ascii_uppercase
answer=1
for i in a:
for j in st:
if i in st:
break
else:
answer=answer+1
break
if answer==2:
print("its not a pangram")
break
else:
print("its a ... |
40ea42f58988f63ede281ef3655e556ae3e94270 | logsdond4/Covid-Comorbidities | /Data Wrangle/data_filter_clean_analysis.py | 1,207 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Author: Dan Logsdon
Date: 10/11/2020
Description: This code analyzes the CDC's data related to Covid deaths and
comorbidities.
Limitations: The CDC did not provide record level data, which means that it is
impossible to do analysis by individual ICD10 code.
"""
#Package Imports
import ... |
a67d7302faf3a1f4377c08a7f1ad5a0d32669408 | williamboco21/pythonfundamentals | /FUNDPRO/temperature.py | 838 | 4.3125 | 4 | print(f'TEMPERATURE CONVERSION PROGRAM')
print(f'------------------------------\n')
print("Options:\n")
print(f'1. Convert Celsius to Fahrenheit\n'
f'2. Convert Fahrenheit to Celsius\n'
f'3. Exit Program\n')
choice = int(input("Enter your choice: "))
if choice == 1:
celsius = int(input("\nEnter temper... |
af1644c2a3f2b282f13575de10643fe7c4803ada | rarose67/Python-practice- | /Exercises/Ch3. Ex.py | 8,292 | 4.34375 | 4 | """ 1. Below is a short program that prompts the user to input the number of miles they are to drive on a given trip and converts their answer to kilometers, printing the result. However, it doesn’t work properly. Find and fix the error in the program.
miles = input("How many miles do you have to drive? ")
kilometers ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.