blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0af3653311c847886fabcd93f91c4a4353733300 | lidianxiang/leetcode_in_python | /数组/661-图片平滑器.py | 1,228 | 3.515625 | 4 | """
包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。
示例 1:
输入:
[[1,1,1],
[1,0,1],
[1,1,1]]
输出:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
解释:
对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
对于点 (1,... |
4c9f75b9474a3428d0649e25dc167eb8f48f45af | souravnandi42sn/GUVIstar | /printHello.py | 107 | 3.59375 | 4 | try:
n=int(input())
i=0
while(n>i):
print("Hello")
n=n-1
except:
print("")
|
f94f6711243482e07934c2a3411ece8aa406ed6a | Duncanhlc/Python-homework | /Hobbies.py | 223 | 3.953125 | 4 | hobbies = " "
for i in range(3):
s = input("請輸入你的小愛好(最多三個,按Q或q結束):")
if s.upper() == "Q":
break
hobbies += s + " "
print("你的小愛好是:"+hobbies) |
6974ab656c729df195a6e9fc23b2a9a9f7a45223 | QMHTMY/DataStructurePy | /sort/quickSort.py | 1,033 | 4 | 4 | #!/usr/bin/python3
"""快速排序
选择中枢点做交换
"""
def quickSort(alist):
quickSortHelper(alist, 0, len(alist) - 1)
def quickSortHelper(alist, first, last):
if first < last:
splitPoint = partition(alist, first, last)
quickSortHelper(alist, first, splitPoint-1)
quickSortHelper(alist, splitPoint+1, ... |
5a979244e3343ba1948d79ca9c7f62c02ad9a73a | ardicsobutay/phys48y | /Assignment 1/Homework 1/hw1_huseyinanilgunduz.py | 152 | 3.890625 | 4 |
s = raw_input('Please enter a string:')
count= 0
for i in range(len(s)):
if s[i] == "o":
count+=i
print "Sum of indices is" ,count |
2d4d3ea17c8dda42cc77e1bc13d69a218735b9a7 | francois-drielsma/pi0_reco | /pi0/cluster/cone_clusterer.py | 8,324 | 3.671875 | 4 | import numpy as np
from pi0.directions.estimator import *
class _Angle:
"""
Angle and slope are dependent attributes, so we define a descriptor.
This way slope and angle are properly linked, i.e., changing one of them
will change the value of another consistently.
"""
def __get__(self, instance... |
65a65154845e47d49393d7c834df0daef2bfb5f5 | manhduc07/CTDL-GT | /BT7.py | 928 | 3.671875 | 4 | class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next
self.prev = prev
self.data = data
def push(self, new_data):
new_node = Node(data = new_data)
new_node.next = self.head
new_node.pre... |
1578ec41af3ade4a594d1bd36d288096ff1b1565 | Aasthaengg/IBMdataset | /Python_codes/p03045/s649721457.py | 1,178 | 3.78125 | 4 | import sys
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
# 0-indexed
class UnionFind:
N=0
parent=None
size=None
def __init__(self,N):
self.N=N
self.parent=[i for i in range(self.N)]
self.size=[1]*self.N
def root(self,x):
while x!=self.parent[x]:
self... |
0be822e67ed98eba20b12def2d97ec965ac8e4d2 | sloniewski/programing-challenges | /19.Count_words_in_a_string/python/2.7_python.py | 242 | 4.0625 | 4 | import re
text = raw_input('Please type some text: ')
match = re.findall('[a-zA-Z]+', text)
letters = 0
for i in range(len(match)):
letters = letters + len(match[i])
print ('Letters:' + str(letters))
print ('Words: ' + str(len(match)))
|
3a37ce3f74bb72b8a7b911c9cb782d4b20040042 | willcanniford/python-notes | /rating_systems/elo.py | 1,556 | 3.59375 | 4 | import pandas as pd
import numpy as np
# Constants for the Elo rating system
K = 32 # The K-factor, which controls the sensitivity of the ratings to the results
INITIAL_RATING = 1500 # The initial rating for each team
# Create a sample dataset of results
results = pd.DataFrame({
'team_a': ['A', 'B', 'C', 'A', 'C'... |
cd94f7bfe3d33e5b1cfa31fd1ec696136c5ba152 | Konohayui/LeetCode | /123. Best Time to Buy and Sell Stock III.py | 582 | 3.515625 | 4 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
first_buy = -prices[0]
first_sold = -float("inf")
second_buy = -float("inf")
second_sold = -float("inf")
for price in prices[1:]:
first_buy... |
05f0e30fa9e2cffb3f3ee09589c2817df44ba548 | TaeLim777/PythonLearningGames | /pong.py | 3,534 | 4.34375 | 4 | #A pong game in Python
import turtle
wn = turtle.Screen() #creating window
wn.title("Pong")
wn.bgcolor("blue")
wn.setup(width=800,height=600)
wn.tracer(0) #stops window from updating which speed up our game a bit
#score
score_a=0
score_b=0
#Paddle A
paddle_a = turtle.Turtle() #turtle object. module name.class nam... |
f4b81b4fd0fd040e35599a468a78f56829fc173c | mayank25awasthi/portfolio | /Data_Structure_Python/Trees/Binary_Heap/Binary_Min_Heap_Array_Implementation.py | 2,569 | 3.703125 | 4 | class MinHeap():
""" Min Heap:-Node values will always be lees than the left and right child """
def __init__(self):
#Creating a Array to push heap values
self.heap_list=[None]
def push_element(self,value):
self.heap_list.append(value)
#Getting right child from postion 2x
def get_left_child(self,index):
... |
a1749213d2976543291e93e0af07cb5f33e95713 | nandorhegyi/Simple-Python-Games-and-Starter-Projects | /Flappy_Bird/pipe.py | 1,937 | 3.671875 | 4 | import pygame
from pygame.sprite import Sprite
class PipeDown(Sprite):
"""A class to represent the downward facing pipes from the game."""
def __init__(self, fb_game):
"""Initialize the pipes and set their starting position."""
super().__init__()
self.screen = fb_game.screen
... |
88e5b04670a8cb049dd3f2b9c095df4a25a7ee11 | DMamrenko/Kattis-Problems | /soft_passwords.py | 611 | 4.03125 | 4 | #Soft Passwords: Kattis
numbers = '0123456789'
def reverseCase(string):
result = ''
for letter in string:
if letter in numbers:
result += letter
elif letter not in numbers and letter == letter.upper():
result += letter.lower()
else:
result ... |
9bd8eb975ee70112f3388f1779c926202afeca77 | rohan-khurana/Algorithms | /LeetCode_Monthly_Challenge/June/Python3/Week_2/is_subsequence.py | 458 | 3.8125 | 4 | /*
PROBLEM:
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
*/
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i=j=... |
3dffb091e276c0997ff6b2683c586737be29adb3 | vpatov/ProjectEuler | /python/projecteuler/complete/01-50/p028.py | 818 | 3.84375 | 4 | """
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a... |
99a507cc1b21120520c66253937e79341cf8d1c7 | HKKKD/leetcode | /88merge.py | 357 | 3.765625 | 4 | def merge(nums1, m, nums2, n):
i, j, k = m-1, n-1, m+n-1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
k -= 1
i -= 1
else:
nums1[k] = nums2[j]
k -= 1
j -= 1
while i >= 0:
nums1[k] = nums1[i]
k -= 1
i -= 1
while j >= 0:
nums1[k] = nums2[j]
k -= 1
j -= 1
retur... |
90f757753b525c513868752e7d5315cd99236ea5 | rishabhranawat/challenge | /leetcode/ll/reverse_ll.py | 762 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
head = head
... |
108365643b8d6104f88779a9319589b68b91ecf5 | Aurora-yuan/Leetcode_Python3 | /0414 第三大的数/0414 第三大的数.py | 759 | 3.890625 | 4 | #label: array difficulty: easy
"""
解题思路:
1.时间复杂度必须是O(n),那么sort()方法不能使用(sort()时间复杂度为O(nlogn))。
2.去掉重复元素,可以使用集合(set),将列表转化为集合
3.删除最大和次大的元素,可以使用remove()
"""
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#将列表转化为集合
nums =... |
84f4ed972b53c280c14edacfc520589202e82cac | a625687551/Leetcode | /Leetcode/27. Remove Element.py | 302 | 3.515625 | 4 | # !/usr/bin/env python
# coding:utf-8
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while val in nums:
nums.remove(val)
return nums
if __name__ == '__main__':
main() |
f8724a98a228da412b79b2a15603919769bedacb | michaelmdrs/polemic-hackaton-2 | /desafio5.py | 275 | 3.84375 | 4 | """
Desafio 5 - Verificar password
"""
import random
from time import sleep
password = input('Digite uma senha: ')
if len(password) < 6:
print('Senha, FRACA!')
elif len(password) >= 6 and len(password) <= 12:
print('Senha, MÉDIA!')
else:
print('Senha, FORTE!') |
7d16219b85bf7ebe8b227c2755c0640217982a08 | zhaolijian/suanfa | /jingdong/JD1.py | 1,130 | 3.53125 | 4 | # 年终奖
# 小东所在公司要发年终奖,而小东恰好获得了最高福利,他要在公司年会上参与一个抽奖游戏,游戏在一个6*6的棋盘上进行,
# 上面放着36个价值不等的礼物,每个小的棋盘上面放置着一个礼物,他需要从左上角开始游戏,每次只能向下或者向右移动一步,
# 到达右下角停止,一路上的格子里的礼物小东都能拿到,请设计一个算法使小东拿到价值最高的礼物。
# 给定一个6*6的矩阵board,其中每个元素为对应格子的礼物价值,左上角为[0,0],请返回能获得的最大价值,
# 保证每个礼物价值大于100小于1000。
class Bonus:
def getMost(self, board):
dp = [[0 for... |
8801dcd936cfeaf027dd094945c4be18d7830bac | rui725/rui-portf | /practices/python/p4.py | 618 | 4.03125 | 4 | import re
email = raw_input()
if(re.search('^[a-zA-Z][a-zA-Z0-9\_]*\@[a-zA-Z]+[a-zA-Z0-9]*\.com',email)):
print 'Valid Email Address'
else:
print 'Invalid Email Address'
if not email[0].isalpha():
print 'email address always starts with a letter'
print 'sugguest using a'+email
elif '@' not in email:
print 'm... |
33c139e5af2302d759bf355eb22e33f776adca0a | lnewman909/Module-5 | /listy_lo.py | 1,428 | 4.3125 | 4 | if __name__ == "__main__":
# Create a list named food with two elements 'rice' and 'beans'.
food = ['rice', 'beans']
print(food)
# Append the string 'broccoli' to food using .append().
food.append('broccoli')
print(food)
# Add the strings 'bread' and 'pizza' to food using .extend().
ad... |
81fbf8c4a2c5f6640667904d2b8cedfd2a55d950 | czs108/LeetCode-Solutions | /Hard/76. Minimum Window Substring/solution (1).py | 2,280 | 3.515625 | 4 | # 76. Minimum Window Substring
# Runtime: 128 ms, faster than 38.98% of Python3 online submissions for Minimum Window Substring.
# Memory Usage: 14.9 MB, less than 63.43% of Python3 online submissions for Minimum Window Substring.
from collections import Counter
import math
class Solution:
def minWindow(self, ... |
044692b3d53237e1c7b3c57070411e61c4cd1d65 | Genodan/my_files | /calculator.py | 623 | 3.53125 | 4 | from colorama import init
from colorama import Fore, Back, Style
# use Colorama to make Termcolor work on Windows too
init()
print(Back.GREEN)
print(Fore.BLACK)
what = input("What function? (+, -, *, /): ")
print(Back.CYAN)
a = float(input("Insert first number: "))
b = float(input("Insert second numb... |
fdf06b8dd2aefefefc9134b11810cf0c47c4e54b | johnny-tamanaha/Basketball-Shooting-by-Distance | /shooting_scrape.py | 7,853 | 3.71875 | 4 | '''Scrape individual shooting efficiency data from basketball-reference.com'''
import numpy as np
import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup, Comment
def scrape_players(letters):
'''Scrape player names that begin with a given set of letters.
Arguments:
1. le... |
465524f060d913503b53d49b9752d89d78e930ba | Jivaldo-Cruz/Trabalho-da-Intep-2-Estrutura-de-Decis-o | /15_desafio.py | 653 | 4.03125 | 4 | __autor__ = "Jivaldo Da Cruz"
import math
def equacao():
a = float(input("Informe o número que coresponde o A: "))
if(a == 0):
return False
b = float(input("Informe o número que coresponde o B: "))
c = float(input("Informe o número que coresponde o C: "))
delta = (b**2) - 4 * a * c
pr... |
bb57def87fa49c110fe9fbec08e4c0e23adcbe3e | frekkanzer2/PythonTests | /Exercises/coroutineRangeOfResponsability.py | 2,170 | 3.578125 | 4 | from FunctionsModules.Decorators import coroutine
@coroutine
def handler_one(successor=None):
while True:
request = (yield)
if 1 <= request <= 10:
print("Gestito da ConcreteHandlerOne, richiesta {}".format(request))
elif successor is not None:
successor.send(request... |
62314dad8fe78467d56e7605ad8ad91c0d35bea1 | tariqpathan/cs61a | /hw02/hw02-tests.py | 824 | 4.1875 | 4 | from operator import add, mul, sub
square = lambda x: x * x
identity = lambda x: x
triple = lambda x: 3 * x
increment = lambda x: x + 1
def product(n, f):
"""Return the product of the first n terms in a sequence.
n -- a positive integer
f -- a function that takes one argument to produce the term
>... |
e364b416e4ce64b3ebe1c4cec7d7d0d44d4c21c3 | dalerxli/pyodex | /odex/partition.py | 1,606 | 3.671875 | 4 |
def _try_partition(a, k, maxheight):
"""Partition an array into k bins
:param a: array of values to partition. must be sorted descending
:param k: number of bins to partition the values
:param maxheight: maximum bin height
"""
n = len(a)
bins = [[] for ii in range(k)]
sums = [... |
53d3d2ec76833a4d17b5d6665ec82b7df3d8a91a | lilyli007/AE597 | /multiClassLinear.py | 3,057 | 3.84375 | 4 | import mglearn
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.svm import LinearSVC
import numpy as np
X, y = make_blobs(random_state=42)
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.legend(["Class 0", "Class 1", "Class 2"])
''... |
171463369fa14766d4d4c00f222f79b88cf68241 | yasssshhhhhh/DataStructuresAndAlgo | /Linkedlists/RemoveLoop.py | 534 | 3.953125 | 4 | def removeLoop(self, head):
low = head
high = head
while low and high and high.next:
low = low.next
high = high.next.next
if low == high:
break
if low == head:
while high.next is not low:
high = high.ne... |
653ed2bb3c4833348fac4acc291283b3f9a026ed | suhassrivats/Data-Structures-And-Algorithms-Implementation | /Problems/Leetcode/143_ReorderList.py | 1,533 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
Time Complexity:
... |
a5bddf21712b1906da5474d98081227e40ffdfb8 | badillosoft/python-b | /pyb.py | 346 | 3.640625 | 4 | import turtle
def linspace(a, b, n):
d = (b - a) / (n - 1.)
x = []
for i in range(0, n):
x.append(a + i * d)
return x
def draw_points(points, ex, ey, ox, oy):
turtle.penup()
for x, y in points:
turtle.goto(x * ex + ox, y * ey + oy)
turtle.pendown()
turtle.penup... |
224b9788886106609001a4a1ba6867cadbd8b579 | unixpickle/CursorDancePartyHacks | /cursorinfo.py | 2,073 | 3.703125 | 4 | import json
class CursorInfo:
""" A class which represents a cursor description on cursor dance party. """
def __init__(self, x, y, angle, scale, cursor, rotations):
self.x, self.y, self.scale = x, y, scale
self.angle = angle
self.cursor, self.rotations = cursor, rotations
@staticm... |
0d04bc4e3256ea9da5c771270b1f6dec6b659a36 | dilarakkl/sentiment_analysis | /findNegatedContext.py | 2,703 | 3.59375 | 4 | '''
This script finds the negated context in the tweets.
In output file, each tweet represented in a single line:
if tweet doesn't have negation there is an empty line.
if there is negation, "C S1 E1 S2 E2 ... Sn En" is found in the corresponding line
where C is the number of negated context
S1 is the... |
e4d8b247dee5b9622a6aaaf98e36ece60ceddc23 | Fabhi/Project-Euler | /2 - Even Fibonacci Number.py | 818 | 3.65625 | 4 | # Problem 2 - Even Fibonacci Number
# https://projecteuler.net/problem=2
# Note: Only "Even-Valued" terms are needed.
def brute(x):
Fn_2, Fn_1 = 1, 1
total = 0
while True:
Fn = Fn_2 + Fn_1
if Fn >= x:
break
if Fn%2 == 0:
total += Fn
Fn_2, Fn_1 = Fn_1... |
864cfd04a045885f3b91892b3a3be431394062ff | Divisekara/Python-Codes-First-sem | /PA2/PA2 2013/PA2-9/pa2-9-2013.py | 1,135 | 3.640625 | 4 | def getText():
try:
FileOpen=open("FileIn.txt","r")
L=map(int,FileOpen.read().split())
except IOError:
print "File Not found"
pass
except ValueError:
print "Enter numerical integers only."
pass
else:
M=L[0]
N=L[1]
if n... |
a39ebe3fb488ee6e0326c78a4345c0f0371393cd | ecotom/girls_who_code | /contactList.py | 1,884 | 4.25 | 4 | ##myDict = {}
myDict = {}
addContact = True
while addContact == True:
print("Would you like to add a contact to your contact list?(y/n)")
answer = input().lower()
if (answer == 'y'):
print ("What is the name?")
Contact = input().lower()
print("Would you like to a... |
c169acb7bed8d490e2de518421bbea5debcb80c2 | ZachNich/py_student_exercises | /reports.py | 4,711 | 3.703125 | 4 | import sqlite3;
class Student():
def __init__(self, first, last, handle, cohort):
self.first_name = first
self.last_name = last
self.slack = handle
self.cohort = cohort
def __repr__(self):
return (f'{self.first_name} {self.last_name} is in {self.cohort}')
class Instru... |
7449d577d016d85391bebad16964ecd90b15cfab | or-katz/WorldOfGames | /GuessGame.py | 1,635 | 4.125 | 4 | from random import randint
# generate random number between 1 and level of difficulty
def generate_number(num1):
return randint(1, num1)
# get guess from user according to level of difficulty
def get_guess_from_user(num2):
# show the user the range of numbers
def select(select_question, min_n... |
9fc8ed758aa5e15ac16c20a80fe2dc6416008969 | cybelewang/leetcode-python | /code326PowerOfThree.py | 382 | 4.25 | 4 | """
326 Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
"""
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and... |
c25bcdcddd6d3d741777666a9b348e4e38b84507 | ahlag/Data-Structures-and-Algorithms-Specialization | /Algorithmic Toolbox/Week4/Program3.py | 272 | 3.5625 | 4 | # python3
import collections
def solve(n, a):
a.sort()
print(" ".join([str(i) for i in a]))
if __name__ == '__main__':
n = int(input())
a = [int(i) for i in input().split()]
solve(n, a)
|
0663d1d7d7acbb13aa4050ac4a8c3dc64b2f8f36 | Rushi-Bhatt/Self-Study | /python_codes/DesignPatterns/iterator.py | 846 | 4.375 | 4 | """ The iterator pattern allows a client to have sequential access to the elements of an aggregate object without exposing its
underlying structure. An iterator isolates access and traversal features from an aggregate object. It also provides an interface
for accessing the elements of an aggregate object. An iterato... |
1c5ceae325c41b64e9ac0ffa5f0450e8be286d0c | VardgesDavtyan19931208/classworks | /game.py | 940 | 3.859375 | 4 | #import random
#hidden_number = random.randint(1,100)
#user_guess = 0
#while not user_guess == hidden_number:
# user_guess = int(input("Guess a number: "))
# if user_guess > hidden_number:
# print("Too high!")
# elif user_guess < hidden_number:
# print("Too low!")
# else:
# print("Thats right")
#for i in rang... |
98ff16bea37d7249e6e030039b461a0bb475635a | Akg093kumar/kindofnumber | /factorial.py | 309 | 4.1875 | 4 | #Python program to find the factorial of a number provided by the user.
n=int(input("Number="))
def facto(n):
if(n<0):
print("Please insert an positive integer and Try again!!!")
elif((n==0)|(n==1)):
return 1
else:
return facto(n-1)*n
print(n,"! = ",facto(n)) |
c983ad535ebe5b57bfb70fb889ac25b45c60c6d6 | zuqqhi2/my-leetcode-answers | /122-Best-Time-to-Buy-and-Sell-Stock-II.py | 792 | 3.609375 | 4 | # Algorithm: Backtrack
class Solution:
def maxProfit(self, prices) -> int:
if len(prices) <= 0:
return 0
max_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
max_profit += prices[i] - prices[i - 1]
return max_profit
... |
66e7a8007b5ca39cb91fa70ff80d82c86ef98acc | CSC1-1101-TTh9-S21/ps10 | /part2.py | 2,998 | 4.375 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
def bubblesort(mylist):
comparisons = 0
# You have to go through the list n times.
for i in range(len(mylist)):
# Each time through the list, it might turn out
# to be sorted already. You can tell it's sorted
# if th... |
aefad76c9ac5bb30bd1ea83fc34d6c8955ded75c | cforsythe/Steganography | /unhideTextInImage.py | 2,932 | 3.890625 | 4 | from PIL import Image
import functions
def decryptImage(imagepath):
#Opens image with hidden text
imageWithText = Image.open(imagepath)
pixel = imageWithText.load()
width, height = imageWithText.size
#An text file for the hidden text is created here
outputfile = open('hiddenText.txt', 'w')
#This loop grabs ev... |
9fc4399997e86d7afbcced5a7af253a45dfff76a | whitneygriffith/Introduction-to-Com-Sci-Labs | /get_location_path.py | 2,335 | 4.34375 | 4 | '''
Problem 2: Get location path
Download the starter files locations.py and get_location_path.py (link here). locations.py containns a dictionary of geographical location pairs (e.g. city and state, state and country, country and continent, etc). Open that file and make sure you understand how the dictionary is struct... |
d5f5f065bf728433b705ac959730471dcf1df8f8 | jmirazee/qbb2019-answers | /20190913/IMPROVE_2/calc_velvet_2.py | 1,082 | 3.875 | 4 | #!/usr/bin/env python3
import sys
from fasta import FASTAReader
reader = FASTAReader(open(sys.argv[1]))
sequence_list = []
for ident, sequence in reader:
sequence_list.append(sequence)
sequence_list = sorted(sequence_list, reverse = True, key = len)
#print(len(sequence_list)) #123 is number of contigs
#calculate ... |
f83044eb758692224588dc1e6f10aab5ca139411 | 240302975/study_to_dead | /并发编程/02多线程/10 定时器.py | 1,103 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time :2020/2/11 13:27
# 定时器
from threading import Timer
def task(name):
print('hello %s' % name)
t = Timer(2, task, args=('egon',))
t.start()
from threading import Timer
import random
class Code:
def __init__(self):
self.make_cache() # 先拿到验证码
... |
2c0e70f7906144c4609967b3aaa59f62011927c2 | Margarita-Sergienko/codewars-python | /7 kyu/Bug Squish.py | 551 | 3.765625 | 4 | # 7 kyu
# Bug Squish!
# https://www.codewars.com/kata/5a21f943c5e284d4340000cb
# Take debugging to a whole new level:
# Given a string, remove every single bug.
# This means you must remove all instances of the word 'bug' from within a given string, unless the word is plural ('bugs').
# For example, given 'obugobugobuo... |
5721325bbc263c03d2ef39628723cc826db05028 | DhanushaRamesh/CodeKata | /sumdigit.py | 155 | 3.53125 | 4 | class sumit:
def ofdigit(self,n):
count=0
while(n>0):
dig=n%10
count+=dig
n=n//10
print(count)
n=int(input())
call=sumit()
call.ofdigit(n)
|
4d5383d139a83203ec3b90c6ec1bb71c889d035f | wanga0104/learn | /homework/usename.py | 217 | 3.84375 | 4 | username = input('请输入用户名:')
password = input('请输入您的密码:')
if username == str('andy')and password == str('123456'):
print('登陆成功!')
else:
print('用户名密码错误') |
47f355861f4fdbf6970f47717d7e2b2a4f5a4fc2 | shivang98/Templates | /DecoratorsTemplate.py | 848 | 3.75 | 4 | import functools
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func():
print("I'm inside decorator")
func()
print("After function executes")
return function_that_runs_func
@my_decorator
def my_function1():
print("Hello World")
# my_function()
def decor... |
0333e3085beccda2371c326613aac3f8e76f4e88 | mccornet/project_euler_2014 | /problem_061.py | 2,355 | 3.6875 | 4 | def tria_fun(n): return (n*(n+1))//2
def squa_fun(n): return n**2
def pent_fun(n): return (n*(3*n-1))//2
def hexa_fun(n): return n*(2*n-1)
def hept_fun(n): return (n*(5*n-3))//2
def octa_fun(n): return n*(3*n-2)
def init_data(set_in):
functions = [tria_fun, squa_fun, pent_fun, hexa_fun, hept_fun, octa_fun]
f... |
a80e0f0e1b5e7b57bb32013888264278dd3c9b86 | LeonardoRoig/TrinketPythonBYU | /Area Calculator With Function.py | 1,814 | 3.96875 | 4 | import math
# Add your code here
# TODO -> Add welcome function here
def displayWelcome():
print "Welcome to the Area Calculator!"
print "-" * 50
# TODO -> Add circle area function here
def calcAreaCircle(radius):
area = math.pi * radius ** 2
return area
# TODO -> Add circle perimeter function here
def cal... |
af1781aeae2d71bf6a34159742e3bb8c14a0cd52 | segatomo/STEP | /hw4/wiki.py | 2,593 | 3.546875 | 4 | # coding: utf-8
import math
import read_txt
def find_name(name):
"""
探したい単語がpages.txtのなかにあったらそのidを返す関数
name: 探したい単語(str)
"""
data = read_txt.read_names('wikipedia_links/pages.txt')
for d in data:
if d['name'] == name:
print('Find %s!' % name, end='')
print('The i... |
5039d19e808604d4dac58e55f7a44e2171fc59d5 | kbcmdba/pcc | /ch4/ex4-8.py | 64 | 3.625 | 4 | numbers = range(1, 11)
for number in numbers:
print(number**3)
|
14dce46286c9f10b92553448642517d768a5ce43 | cnsnyder/pyqver | /pyqver/pyqverbase.py | 3,990 | 3.671875 | 4 |
import sys
# Base globals
_min_version = (0, 0)
_printer = None
def uniq(a):
"""
Removes duplicates from a list. Elements are ordered by the original
order of their first occurrences.
In terms of Python 2.4 and later, this is equivalent to list(set(a)).
"""
if len(a) == 0:
return []... |
fa6568264e525bee4e608efbc376b6d88b587559 | ambrosy-eric/100-days-python | /beginner/day-10/main.py | 925 | 4.09375 | 4 | from utils.tools import operations, add_numbers, subtract_numbers, divide_numbers, multiply_numbers
from utils.art import logo
def main():
print(logo)
n1 = float(input('Enter a number\n'))
for operation in operations:
print(operation)
more_math = True
while more_math:
func = input('... |
7376de79db9e253316d9af2495246675544b04bf | praveen-datasci/ML | /DataTransformation.py | 6,673 | 3.53125 | 4 |
# Data Preparation for Machine Learning | Data Transformation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
np.set_printoptions(precision = 3) #round off decimal values
df_diabetes_cleaned
#using cleaned df from DataCleaning.py
df_diabetes_cleaned.isnull().sum() #no missing val... |
2081eb3c197d51ec93cdb498d97fb6e82754fa32 | CastriDani/fundamento-de-programaci-n- | /FUNCIONES/PRODUCTO_CUADRADO.py | 422 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 08:53:24 2021
@author: santi
"""
def cuadrado():
x = int(input('Ingrese un número: '))
cuadrado = x*x
print(f'El cuadrado de {x} es {cuadrado}')
def producto():
n1 = int(input('Ingrese un número: '))
n2 = int(input('Ingrese un número: ... |
8afd8748b32e050c7709e0a6851dfaae9bf1a856 | brightcode-k/python_homework | /Laboratory3/lab3task1.py | 1,112 | 3.8125 | 4 | """
Заміна вибраного символа на інший
"""
import re
def int_validator(text):
n = input(text)
while not bool(re.match(r'^\d+$', n)):
n = input(text)
return int(n)
def string_validator(text):
string = input(text)
while bool(re.match(r'^\s*$', string)):
string = input(text)
... |
4cd342d92a311bebddcf11c79dbbbfa1bf68ecae | babushkian/jet_socium | /soc_time.py | 7,250 | 4.0625 | 4 | """
Модуль, определяющий формат даты а так же параметры времени по которому живет социум живет.
А так же всякие сложение-вычитание дат, вычисление периодов времени
"""
from __future__ import annotations
from typing import Union
class Date:
MONTHS_IN_YEAR =4
DAYS_IN_MONTH = 1
DAYS_IN_YEAR = MONTHS_IN_YEAR ... |
741ed867fec5920aa6cd7ca67663949dd3273dbf | cvillarr123/TradingBOTCVI | /Python trading bot/src/statistic.py | 2,576 | 4.09375 | 4 | def sumatorio(lista_valores):
"""Función que dada una lista de valores calcula el sumatorio
Args:
lista_valores (list): Lista con los valores
Returns:
int-float: Valor del sumatorio
"""
acumulador = 0
for valor in lista_valores:
acumulador += valor
return acumulador... |
0878689f231df531ad0ea5e3f47d41e68b163675 | surya3217/Machine_learning | /Linear_Regression/Foodtruck.py | 2,361 | 4.40625 | 4 | """
Code Challenge
Problem Statement:
Suppose you are the CEO of a restaurant franchise and are considering
different cities for opening a new outlet.
The chain already has food-trucks in various cities and you have data for profits
and populations from the cities.
You would like to ... |
45bee0b25d14e8c14b99159aaae110abd3d1ab43 | goyal-aman/codeforces | /Vanya and Cubes.py | 237 | 3.609375 | 4 | n = int(input())
i = 1
total_cube = 0
while total_cube <= n:
total_cube += (i*(i+1))//2
i+=1
print(i-2)
# n = int(input())
# temp = 2
# while n>=sum(range(1,temp)):
#
# n -= sum(range(1,temp))
# temp +=1
# print(temp-2)
|
cf4a0dbc776528314c7c706588ee7b9569a0a169 | patelyash9775/Basic-python | /Sorting in list.py | 226 | 3.71875 | 4 | names = ['Earth','Air','Fire','Water']
names.sort()
print(names)
names.sort(reverse=True)
print(names)
names.sort(key=len)
print(names)
names.sort(key=len,reverse=True)
print(names)
names.pop()
print(names) |
7a95cc33b2e48647252d474e57131de1c2730327 | YorkFish/learning_notes | /Python3/MorvanZhou/Tkinter/Tkinter_11.py | 1,109 | 3.578125 | 4 | #!/usr/bin/env python3
# coding:utf-8
import tkinter as tk
from tkinter import messagebox
window = tk.Tk() # 窗口 object
window.title("my window") # 标题
window.geometry("300x200") # 窗口大小
def hit_me():
# tk.messagebox.showinfo(title="Hi", message="hahaha") # 信息符号,伴随声音 1
... |
a48fade51afaea2e2aab88ec022c016f6568a6f8 | scottespich/HPM573S18_Espich_HW1 | /Question1.py | 275 | 3.765625 | 4 |
x=17
print('setting x =', x)
# interger
y1 = x
print(type(y1))
# float
y2 = float(x)
print(type(y2))
# string
y3 = str(x)
print(type(y3))
# Boolean, '23 > 18'
y4 = bool(x > 18)
print(type(y4))
print(y4)
text = 'The value of x is',(y1)
print (text)
|
d227e4461f42c3d940c284b01f20458cfa4f9298 | morganhowell95/TheFundamentalGrowthPlan | /Data Structures & Algorithms/Queues & Stacks/ArrayImplOfQueue.py | 1,085 | 4.1875 | 4 | #The queue is a First In First Out (FIFO) data structure
#As with stack, the implementation of a queue with an array in Python is trivial due to Python's list support
#Please refer to the solution in Java for a more comprehensive understanding
class Queue:
def __init__(self):
self.q = []
def enqueue(self, d):
s... |
0b18d23bed5f14c1ad891fc2efcfa252d38e2a7e | nowacki69/Python | /edx/Artists&Revenue.py | 520 | 3.671875 | 4 | def sort_artists(listOfTuples):
all_artists = []
revenue = []
for items in listOfTuples:
index = 0
for info in items:
if index == 0:
all_artists.append(info)
else:
revenue.append(info)
index += 1
all_artists.sort()
... |
fe9df6622bf7b1d22b37fbf06224c9e37edec7ca | nestor22/pythonMegaCurse | /exercise1.py | 360 | 3.953125 | 4 | def convertCelsiusToFahremheit(degress):
f = degress * 9/5 +32
return f
try:
celsius = float(input("plis input the celsius degress: "))
if celsius <= -273.15:
print("thas is imposible")
else:
print ("fharenheis is: " + str(convertCelsiusToFahremheit(celsius)))
except:
print("eror... |
fe0be390c19b228b5a84b7ecce23a89e35b9827e | michaellevot/python | /ngrammer.py | 1,587 | 3.84375 | 4 | #!/usr/bin/python
# Prints ngrams \t frequencies for text input.
# Syntax: ngrammer.py -f TEXT_FILE -n MINIMUM_NUMBER -x MAXIMUM_NUMBER
import argparse,sys
from collections import Counter
def main():
# Creates arguments "-f" for input file, "-n" for minimum ngram length, "-x" for max mgram length
parser... |
16aab6d4c4813d39be19a38b4206b977a53e33bf | joy1954islam/ddad-internship-joy1954islam | /Answer No 03.py | 554 | 3.921875 | 4 | def isPalRec(st, s, e):
if (s == e):
return True
if (st[s] != st[e]):
return False
if (s < e + 1):
return isPalRec(st, s + 1, e - 1)
return True
def isPalindrome(st):
n = len(st)
if (n == 0):
return True
return isPalRec(st, 0, n - 1);
... |
2bd83bf388f171aafbd4f7fa3c0628d4c484d8fc | antoniott15/ProblemSolving | /python/BeautifulDays/beautifulDays.py | 221 | 3.640625 | 4 | def beautifulDays(i, j, k):
count = 0
for elements in range(i,j+1):
if (elements-int(str(elements)[::-1]))%k == 0:
count+=1
return count
i = 13
j = 45
k = 3
print(beautifulDays(i, j, k)) |
61673c4e7a6d9c66ad4496bd772b02dbc676b4e2 | TreyMcGarity/PythonPractice | /Python-Practice/hash-practice_1.py | 1,963 | 4.15625 | 4 | """
Given a package with a weight limit "limit" and a list "weights" of item weights,
implement a function "get_indices_of_item_weights" that finds two items whose sum
of weights equals the weight limit "limit". Your function will return a tuple of
integers that has the following form:
(zero, one)
where each... |
ffd863d3852abda137df814332565cb9bd801059 | marylt/python | /lab8.py | 1,063 | 4.4375 | 4 |
# libraries to be imported
import sqlite3
import csv
# opening csv file and creating reader with encoding + delimiter
data = open('books.csv', 'r', encoding = 'utf-8')
reader = csv.reader(data, delimiter=',')
# defining connection memory and cursor
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
... |
49c04a656893979b1d3e70bc469ff9e456aa0426 | wendelsilva/Python | /exercicios/exe026.py | 448 | 4.03125 | 4 | frase = input("digite uma frase: ")
minusculo = frase.lower() # transforma a informação recebida toda para minusculo
espaco = minusculo.strip() # remove os espaços contidos antes da informação
contar = espaco.count('a') # conta a quantidade de 'a' na palavra
buscar = espaco.find('a') # encontra a posição da primeira le... |
2ca161b37fbbcb3838b0f18804bae3e23a173f3b | rehabiftikhar93/web-development | /car game.py | 698 | 4.03125 | 4 | command=""
started=False
while True:
command=input('> ').lower()
if command=='start':
if started:
print("car is already started")
else:
started=True
print("car started")
elif command=='stop':
if not started:
... |
eb8ade1876dce9b04dc0a5503e6e6ff54b19eb79 | AnderX003/Algorithms-with-Python | /algorithms_09.py | 1,601 | 3.59375 | 4 | def start(s, f):
graph = [
[False, True, False, True, False, False, False, False, False],
[True, False, False, True, False, True, False, False, False],
[False, False, False, False, True, True, False, False, False],
[True, True, False, False, True, False, True, True, False],
[... |
50ecc9c50ae090f182ca59cea629d041affd4858 | arthurdysart/LeetCode | /0367_valid_perfect_square/python_source.py | 1,725 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Leetcode - Valid Perfect Square
https://leetcode.com/problems/valid-perfect-square
Created on Fri Nov 23 20:18:24 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
import sys
# FUNCTION DEFINITIONS
class Solution:
"""
Binary search for target element.
... |
cf2e30652c45256dcc21dbef53b5d9cd051ac3ca | measylite/measyPython | /fileManipulation/write2file.py | 392 | 3.90625 | 4 | #
# Miguel Soria
#
#Read and Write files using built in Python file methods
def main():
# Open a file for writing, create it if it doesn't exist => +
# f = open("textfile.txt", "w+") # write
f = open("textfile.txt", "a+") # append
# Lets write something
for i in range(20):
f.write("This is my line number %... |
593a285e8f5d6f2258bb8149e6fded5cf8d75ae8 | Damanpreet/Algorithms | /leetcode/LinkedList/p206-ReverseLL.py | 778 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# recursive solution
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def rec(node, prev):
if node:
nextnode=node.next... |
f09f520a49f8d86161f5667970f9a9a542db9055 | Amanda-Wakefield/Projects | /treehouse/tuples1.py | 481 | 3.6875 | 4 | # combo(['swallow', 'snake', 'parrot'], 'abc')
# Output:
# [('swallow', 'a'), ('snake', 'b'), ('parrot', 'c')]
# If you use list.append(), you'll want to pass it a tuple of new values.
# Using enumerate() here can save you a variable or two.
def combo(it1, it2):
it2 = list(it2)
my_list = []
for num, animal... |
36c58088a332b28343ce725359a78057eec066f1 | MBoaretto25/study-decorators | /decorators.py | 2,633 | 3.71875 | 4 | """
File to save decorators for study purposes
@author: Marco Boaretto
from: https://realpython.com/primer-on-python-decorators/#functions
"""
import functools
import time
## Old examples
# def do_twice(func):
# def wrapper:
# func()
# func()
# return wrapper
#
# def do_twice_with_args(func):
... |
8e19fcdbc72aebfcd22c4957b79b6f2fa73ea52b | ArtySem/ForGB | /exercise1.py | 396 | 4.03125 | 4 | number1 = 15
number2 = 3
#pr_number = str(number)
print(number1)
action = input('Выберите арифметическое действие +, -, / или *: ')
if action == '+':
print(str(number1 + number2))
if action == '-':
print(str(number1 - number2))
if action == '/':
print(str(number1 / number2))
if action == '*... |
477d034a2a68345f507a9e9c69e300e217ae98e6 | tomyoo/wine-info-microservice | /compendium/clib/utils/iters.py | 4,543 | 3.796875 | 4 | from itertools import groupby
from itertools import izip_longest, cycle, islice
def first(iterable):
"""Returns the first element of an iterable or None if it is empty"""
try:
return next(iter(iterable))
except StopIteration:
return None
def last(iterable):
"""Returns the first eleme... |
96d26c44d7634cda7a7fe85516809cd0cf677ea8 | daehyun1023/Algorithm | /python/kakao/2021/5월채용인턴십/test1.py | 459 | 3.546875 | 4 | def solution(s):
answer = 0
return answer
s = "one4seveneight"
dic = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', }
st = ''
answer = ''
for char in s:
if char in '0123456789':
answer += char
st ... |
02f3be076f09577d18185e8e308f59014939f8d8 | villemarchant/Koulu | /broken_reader.py | 1,577 | 3.640625 | 4 | from io import StringIO
class BrokenReader(StringIO):
'''
This class is used to artificially create problems. :)
The class will take a normal Reader object and serve
all data read from that Reader until a given breaking
point is reached. At this point the read method will throw
an OSExcep... |
6fe2ac2779bb1bfd401f91c64d39c19a252ac8b7 | chsasank/design-patterns | /facade/main.py | 2,007 | 3.84375 | 4 | class Scanner:
"""Takes in a stream of characters and produces stream of tokens."""
def __init__(self, stream):
self._input_stream = stream
def scan(self):
"""Tokenize the input."""
return self._input_stream.split()
class Parser:
"""Uses ProgramNodeBulder to construct parse tr... |
5e50ab31644f8ac08f7db96d46b16e79f9ae3eb1 | tommahs/HU_Prog | /Les4/4_1.py | 541 | 3.859375 | 4 | def convert(celcius):
fahrenheid = ((celcius*1.8)+32)
return fahrenheid
def table(Celsius):
for i in Celsius:
if i >-30 and i < 40:
return i
a= -100
b = 100
print(' F C')
def table(a,b):
loop = 1
while loop == 1:
for i in (range(a, b)):
if i >= -3... |
cfa7c43af515b74ef821e57afb53a6096753cd61 | NickATC/GUI_design | /17.2 extract_Spinbox.py | 669 | 3.734375 | 4 | # Simple GUI with:
# Label
# Spinbox with 5 options
# Button
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.title("My Personal Title")
window.geometry("300x200")
window.resizable(0,0)
window.wm_iconbitmap("images/ok.ico")
#Label to guide user:
label1 = ttk.Label(win... |
8471c3ff84aa7e5858514ea9c6d464f66fb45d0e | papapalapa/project-euler-python | /003 - Largest prime factor/main.test.py | 1,139 | 3.53125 | 4 | import unittest
from main import Problem3
class Problem3Test(unittest.TestCase):
def testPrimeNumbersList_10(self):
primeList = Problem3(0).primeNumbersList(10)
self.assertEqual(primeList, [2, 3, 5, 7])
def testPrimeNumbersList_20(self):
primeList = Problem3(0).primeNumbersList(20)
... |
01c39d3c4fca021a6d6b65cacc1843dcb85cc30c | samhithaaaa/Array-1 | /productexceptnumber.py | 457 | 3.515625 | 4 | class Solution:
def productExceptSelf(self, nums):
if not nums:
return [0]
result = []
product = 1
result.append(1)
for i in range(1,len(nums)):
result.append(product * nums[i-1])
product = result[-1]
product = 1
... |
e8a28ff60acf3c120b7a5726b6711aa2fbfa9aba | Jagrmi-C/jagrmitest | /codility.com/TimeComplexity/permMissingElem.py | 422 | 3.59375 | 4 | def solution(a):
if len(a) == 0:
return 1
elif len(a) == 1:
if a[0] == 1:
return 2
else:
return 1
else:
a.sort()
for i in range(len(a)):
if a[i] != i+1:
return i+1
return len(a)+1
a = [2, 3, 1, 5]
print(so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.