blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5d3d761609204bfc419fbd225c42f3ac8d6db3ce | doriachen/Shop-poc | /my_test_proj/map.py | 830 | 3.953125 | 4 | #some fake code for our project!
import numpy
#example code from prof paine
def inc(x):
return x + 1
#searchbar method that should only accept strings in search bar
def searchbar():
searchvalue = input("Search:\n")
if isinstance(searchvalue, str)
return searchvalue
else:
print("Please ... |
a09667406a44765143bafd7e73aa35e0c0cfae10 | illusionist99/Python_BootCamp_42 | /module04/ex00/FileLoader.py | 880 | 4.125 | 4 | from pandas import DataFrame, read_csv
class FileLoader:
@staticmethod
def load(path):
"""
takes as an argument the file path of the dataset to load,
displays a message specifying the dimensions of
the dataset (e.g. 340 x 500) and returns the dataset
loaded as a pandas.D... |
9ec41523e3bff269e3c608d4abc4d9f6c3606d6e | pbhereandnow/schoolpracticals | /Class 12/q15/q15.py | 1,204 | 3.75 | 4 | """
Dhruv Jain
XII-D
Question 15
"""
f = open("myfile.txt", "r")
d = {}
words = 0
for i in f.readlines():
for j in i.split():
if j.lower() in d:
d[j.lower()] += 1
else:
d[j.lower()] = 1
for i in d.values():
words += i
print("Total number ... |
f8dfdebc61288fd21d1e9a97816209644b8aaaa6 | lgreco/Algorithms | /Graphs/MaximumFlow.py | 3,388 | 3.9375 | 4 | import collections
class Graph(object):
"""Instantiates a graph object based on an adjacency matrix supplied
in the form of a list of lists."""
def __init__(self, adjacency_matrix):
self.graph = adjacency_matrix # residual graph
self.row = len(adjacency_matrix)
def bfs(self, s, t, pa... |
8e1193fa658b9c5451b57e6e4f3bd159a0e74ff7 | Goldlizard2/BinarySearch | /student_files/binary_module.py | 2,631 | 3.640625 | 4 |
import tools
# uncomment the next line if you want to make some Name objects
from classes import Name
import time
start_time = time.time()
"""two comparison Binary search developed by Okoko Anainga 22/08/2020"""
def binary_result_finder(tested, quarantined):
""" The tested list contains (nhi, Name, result) tup... |
6f01d302ac3084d4030cbfe72270181c193e07a6 | nerdjerry/python-programming | /library/tree/Tree.py | 1,611 | 4.0625 | 4 | from TreeNode import TreeNode
class Tree(object):
def __init__(self):
self.root = None
def insert(self,value):
if self.root == None:
self.root = TreeNode(value)
else:
self.root.insert(value)
def traverseInOrder(self):
if self.root != None:
... |
56bf8a174f89705f378ea946104c217530c87da5 | wjohnsson/adventofcode | /2015/05/day05.py | 2,290 | 4.0625 | 4 | def main():
input_lines = open("input").read().splitlines()
nice_part1, nice_part2 = 0, 0
for s in input_lines:
# Part 1
if at_least_three_vowels(s) and \
one_letter_twice(s) and \
not has_disallowed_substrings(s):
nice_part1 += 1
# Part 2
if... |
0145dc4ebd16d28609194fe226ba0d1e20118f0d | FridayAlgorithm/juhee_study | /BOJ/PRIORITY_QUEUE/11279.py | 1,619 | 3.984375 | 4 | #-*- encoding: utf-8 -*-
"""최대 힙"""
import sys
def insert(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 1:
if heap[i//2] < heap[i] : # 부모가 자식보다 작다면 교체
heap[i], heap[i//2] = heap[i//2], heap[i] # swap
i = i // 2
else:
break
def remove(heap):
... |
a747d701e3f7049d5b5c2175a3fd5aa41b1d8a8a | nikitamarchenko/checkio | /dot-separated-numbers.py | 539 | 3.6875 | 4 | __author__ = 'nmarchenko'
# http://www.checkio.org/mission/task/info/dot-separated-numbers/python-27/
def checkio(data):
def f(data):
if data.isdigit():
return "{:,}".format(int(data)).replace(',', '.')
return data
return ' '.join(map(f, data.split(' ')))
checkio('123456') == ... |
7198f03e3c021e0851771c07581acc319280a472 | daelsaid/python_utils_and_functions | /extract_csv_into_dict_fxn.py | 392 | 3.703125 | 4 | import csv
def extract_data_from_csv_into_dict(csv_file_to_extract):
dict_name=[]
with open(csv_file_to_extract, 'U') as file:
input_csv_lines=csv.reader(file)
input_csv_lines=map(list, zip(*input_csv_lines))
dict_name =csv_file_to_extract.split('.')[0]+'_dict'
new_dict = dict((... |
81966c0d86f93d1f53c3813667dc6d69f5be73b9 | artkpv/code-dojo | /hackerrank.com/challenges/sherlock-and-anagrams/problem.py | 695 | 3.75 | 4 | #!python3
"""
https://www.hackerrank.com/challenges/sherlock-and-anagrams
Anagram - rearranged letters
ss - consequentive letters from s
1 <= |ss| < n
s: 2..100
q: 1..10
Anagrams - ?
1) BF. For 1..n-1, all ss, count all pairs. anagrams = pairs*(pairs-1)/2. T: O(n^3*q), ~10^7. S: O(n^2)
"""
qu... |
89bec5eda3ad231ce4dd9c0bfd71a8aece743b8e | tomato3391/algorithm | /[hard] reverse-nodes-in-k-group.py | 1,460 | 3.84375 | 4 | # Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
# Note:
# Only constant extra ... |
aa1aa0ee179dfd2ae29c8ba1f140b6b5e9334e44 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/ex086.py | 911 | 4.34375 | 4 | # Ex: 086 - Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores
# lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta.
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 086
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
matriz = [[], [], []]
f... |
7355e4f3108da5d6acc2f738d55305ba4fbf3e5c | darakian/ciphers | /ciphers.py | 3,076 | 3.78125 | 4 | #!/usr/bin/python3
import array
import string
#Taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
... |
46ac1c1a9e964eaa71fcca71721f1634cba46d33 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/atbash-cipher/34be9ef6170549d39ba97554a019eb8b.py | 456 | 3.9375 | 4 | alphabet = '0123456789abcdefghijklmnopqrstuvwxyz9876543210'
mapping = {a: b for a, b in zip(alphabet, alphabet[::-1])}
def decode(ciphertext):
return ''.join(mapping[letter] for letter in ciphertext if letter in alphabet)
def encode(plaintext):
plaintext = [letter for letter in plaintext.lower() if letter in... |
6929cb859ca96d5dabd8455820d852a3890bcd24 | ceeblet/OST_PythonCertificationTrack | /Python1/python1Homework/three_param.py | 259 | 3.921875 | 4 | #!/usr/local/bin/python3
""" three_param.py """
def my_func(a, b="b was not entered", c="c was not entered"):
args = [a, b, c]
for arg in args:
print(arg)
my_func("test")
my_func("test", "Test")
my_func("test", "Test", "TEST")
print(my_func) |
01f33d095ba093104149a7020ce6f41d6d1d022a | inducer/pudb | /debug_me.py | 1,061 | 3.578125 | 4 | from collections import namedtuple
Color = namedtuple('Color', ['red', 'green', 'blue', 'alpha'])
class MyClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
self._b = [b]
mc = MyClass(15, MyClass(12, None))
from pudb import set_trace; set_trace()
def simple_func(x):
x ... |
5e4df9d421e850db6331be59a6fa97dbdc7476b9 | edenriquez/past-challenges | /morning-training/odd-position.py | 258 | 3.796875 | 4 |
def odd_position(x):
odd = []
for index,position in enumerate(x):
if(index % 2 == 1):
odd.append(position)
return odd
a = [1,2,3,4,4,4,6567,67878,7,564,5,4,2,346,5,76,1,1,3,2,3,4,4,4,6567,67878,7,564,5,4,2,346,5,76,1,1,3,34]
print odd_position(a) |
f796e30b4a781091e0f09b771431a5f986e19b72 | frankieliu/problems | /leetcode/python/825/original/825.friends-of-appropriate-ages.0.py | 1,384 | 3.65625 | 4 | #
# @lc app=leetcode id=825 lang=python3
#
# [825] Friends Of Appropriate Ages
#
# https://leetcode.com/problems/friends-of-appropriate-ages/description/
#
# algorithms
# Medium (34.72%)
# Total Accepted: 12.5K
# Total Submissions: 36.1K
# Testcase Example: '[16,16]'
#
# Some people will make friend requests. The l... |
9b7893d7cada69d932ae3903ba895146b4496ebc | pforderique/Python-Scripts | /Coding_Practice/Libraries/OpenCV/haar_cascading.py | 753 | 3.640625 | 4 | # HAAR CASCASE METHOD:
# feature based machine learning
# uses pretrained images of labeled poitives and negatives
# runs through thousands of classifiers in a cascaded manner
# Use cases: detecting faces
import numpy as np
import cv2
img = cv2.imread("Detection/assets/faces.jpg")
gray = cv2.cvtColor(img, cv2.COLOR... |
bc59b0954c719dc04874953905ff4502ad160754 | josemorenodf/ejerciciospython | /Ejercicios Métodos Diccionarios/MetodoSetDefault.py | 472 | 3.90625 | 4 | # Devuelve el valor de la clave si ya existe y, en caso contrario, le asigna el valor que se pasa como segundo argumento. Si no se especifica este segundo argumento, por defecto es None.
d = {'uno': 1, 'dos': 2}
print(d.setdefault('uno', 1.0)) # Devuelve el valor de la clave si ya existe.
d.setdefault('tres', 3) # Inc... |
9a5792f417b5242df918e8d70e25559cd0655b7b | Demon000/uni | /fp/lab4/utils.py | 984 | 3.828125 | 4 | import json
def is_valid_unsigned(value, min_=None, max_=None):
'''
Checks if the passed value is a valid int.
Args:
min_ (int, optional): The minimum which the passed value is allowed to be.
min_ (int, optional): The maximum which the passed value is allowed to be.
'''
if type(val... |
f97825fd5e64e68cf21ea7f70aa61edea26db8ce | go0g/turtle_crossing | /traffic_control.py | 1,374 | 3.546875 | 4 | from turtle import Turtle
import random
CAR_COLORS = ['green', 'yellow', 'blue', 'purple']
START_POSITION = 300
END_POSITION = -320
class TrafficControl:
def __init__(self):
self.cars = []
self.tick_counter = 0
self.add_cars()
def add_cars(self):
for _ in range(random.randint... |
7cec2ed6926a1de77c62f309b3dfd752341e71bd | jolleyjames/Advent-of-Code-2020 | /day24.py | 2,451 | 3.625 | 4 | '''
Advent of Code 2020, Day 24.
James Jolley, jim.jolley [at] gmail.com
'''
def hex_tile_pos(s):
'''
Return the (x,y) position of a hexagonal tile from a reference.
'''
pos = [0,0]
while len(s) > 0:
if s[0] in 'ew':
pos[0] += (2 if s[0] == 'e' else -2)
s = s[1:]
... |
6c2e3ad87df363e636d3b73f4631f65f2dfaba6c | daniel-reich/ubiquitous-fiesta | /tNRvtHKZxvqPRnAeF_8.py | 167 | 3.578125 | 4 |
def digit_occurrences(start, end, digit):
c = 0
for i in range(start, end+1):
i = str(i)
for j in i:
if str(digit) == j:
c += 1
return c
|
dbace6d1ec084a923661b695558271f1ea8e03e1 | zeewii/zeng_2018 | /面对对象编程方法-路由登录功能实例/login_control.py | 2,272 | 3.546875 | 4 | #coding:utf-8
#作者:尹霞
#描述:登陆控制层代码,包括登陆的页面元素的获取和设置,其继承子类publicControl功能
from public_control import PublicControl
class LoginControl(PublicControl):
def __init__(self,driver,username=None,password=None):
PublicControl.__init__(self,driver)
self.username = username
self.password =password
#... |
4b0f66ff09f33f7afe27796e5202b8a6d3fbeb76 | lslee714/tinker | /tinker/practice.py | 740 | 3.578125 | 4 | class Solution:
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
if not matrix or len(matrix) == 1:
return
initial_len = len(matrix)
added = 0
for col in range(len(matrix)):
print("matrix so far... |
3389a21e0ad2244a6dcca9c54e5f6625f4308c67 | pktolstov/Lesson_5 | /task_3.py | 873 | 3.90625 | 4 | """
3. Создать текстовый файл (не программно),
построчно записать фамилии сотрудников и величину их окладов (не менее 10 строк).
Определить, кто из сотрудников имеет оклад менее 20 тыс.,
вывести фамилии этих сотрудников.
Выполнить подсчет средней величины дохода сотрудников.
"""
with open('task_3_staff_salary') as my_f... |
fc28cf9605ddac96a21db9fe1b752bf86704eba0 | salihzain/go-shell | /test.py | 90 | 3.90625 | 4 | while True:
print("enter your name please")
name = input()
print("hi ", name)
|
3823041a4e2d9c5cdc2fc955fb451cee84d456ca | vd265/Group_Project_Calculator | /src/project/helper.py | 1,434 | 3.71875 | 4 | import functools
class Helper():
@staticmethod
def validateNumberInput(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
counter = 0
containStringInput = False
for item in args:
if counter >= 1:
if type(item) not i... |
3b8fefb0edd434e21aed805d58040c90713af800 | shloknatarajan/TwitterFollowProject | /cleanfilter.py | 1,105 | 3.828125 | 4 | def remove_duplicates():
# Remove Duplicates
lines_seen = set()
noduplicates = []
for line in open("TextFiles/filteredprelim.txt", "r"):
if line.strip() not in lines_seen: # not a duplicate
noduplicates.append(line.strip())
lines_seen.add(line.strip())
print("Removed ... |
4d6273db53203628d22c9db6c66e50c2e2d2d379 | manjory/start_test | /interview_practice/intersection_three_sortedarray.py | 892 | 4 | 4 | import time
# Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
# # Output: [1,5]
# # Explanation: Only 1 and 5 appeared in the three arrays.
# using set
# using 3 for loops
def arraysIntersection_set(arr1, arr2, arr3):
t = time.monotonic_ns()
a2=set(arr2)
a3=set(arr3)
a=[]
for i... |
3373c7daf8446ee6599aba5cb3f80ca9a31d7674 | nishikaverma/Python_progs | /remove_max_min().py | 277 | 4.09375 | 4 | def remove_max_min(list1):
mylist=[x for x in list1 if x!=min(list1) and x!=max(list1)]
return mylist
list1=list(input("enter a sequence of num."))
print("the original list is",list1)
print("list after removing the max and min values is")
print(remove_max_min(list1))
|
6420f6293af47e504d25bbc22ad96e244d529515 | mchobby/esp8266-upy | /is31fl/examples/test_blink.py | 1,134 | 3.671875 | 4 | # Make a blinking arrow
#
from machine import I2C
import is31fl3731 as is31f
i2c = I2C(2) # Y9=scl, Y10=sda or Pyboard-Uno-R3 (I2C over pin 13)
# initialize display using Feather CharlieWing LED 15 x 7
display = is31f.CharlieWing(i2c)
# class Matrix: Adafruit 16x9 Charlieplexed
# class CharlieBonnet : Adafruit 16x8 ... |
ae8cd4f61870d97bc59716e0ee93fc861e6f6673 | cjshaw1976/treehouse-python-techdegree-project-02 | /ship.py | 953 | 3.890625 | 4 | import constants
class Ship():
"""Defines the ship. A ship has:
a model (Name): For reference
a position list (list of tupples): To show the positions of the ship
a hits list (list of strings): To show where the ship has been hit
"""
def __init__(self, model, position_list):
self.mode... |
5b969ec3e668c3e654b03746b76fc6f894de8ac0 | omri-sokol/TKINTER_Project | /dropdown_menus.py | 499 | 3.53125 | 4 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("Title")
root.iconbitmap("icon.png")
root.geometry("400x400")
# Drop Down Boxes
def show():
label = Label(root, text=clicked.get()).pack()
options = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
]
clicked... |
6f2308461fe664db8d1cbbd3e6e1e98b88ad0db3 | sarthakbansalgit/basic-python- | /queue.py | 975 | 3.921875 | 4 | a = []
def enqueue(a,val):
a.append(val)
if len(a) == 1:
front = rear = 0
else:
rear = (len(a)-1)
def dequeue(a):
if len(a) == 0:
print("bruh kuch ni h vha")
else:
s = a.pop()
print("the element deleted was",s)
if len(a) == 0:
front = rear = None
de... |
2bf29910dd65f5a4439550dbecf5e49a57d0f0c5 | subashinie/my_captain_assignment2 | /pyramid.py | 303 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 22 12:24:41 2021
@author: suba
"""
def fullPyramid():
for i in range(5):
for s in range(5, i+1, -1):
print(end=" ")
for j in range(i + 1):
print(end="* ")
print()
fullPyramid()
|
b7c2173fd9dddc92a355c8e55cb830b1203cec4f | xumaxie/pycharm_file-1 | /Algorithma and Data Structures/图解算法数据结构/07剑指offer35复杂链表的复制.py | 1,383 | 3.734375 | 4 | #@Time : 2021/11/414:30
#@Author : xujian
# 1.
# 请实现 copyRandomList 函数,复制一个复杂链表。
# 在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,
# 还有一个 random 指针指向链表中的任意节点或者 null。
#我的思路是每次复制一个遍历
#但是不足的地方就是需要在循环外面对复制的新链表头结点单独处理
class Node:
def __init__(self, x, next: 'Node' = None, random: 'Node' = No... |
12d919bf4dd832689cdb10a5cfa57790524f21d7 | jhomola/python-washu-2014 | /day2/clock_jh.py | 1,025 | 3.8125 | 4 | class Clock():
def __init__(self, hours, minutes=0):
self.hours = hours
self.minutes1 = hours*60
self.minutes2 = minutes
@classmethod
def at(cls, hours, minutes=0):
return cls(hours, minutes)
def __str__(self):
return "%02d:%02d" % (self.hours, self.minutes2)
def __add__(self, other):
time = se... |
762436ae7763f9ad7d436326ace88d1e18dc2757 | infinite-Joy/programming-languages | /python-projects/algo_and_ds/power_set.py | 943 | 3.90625 | 4 | """
https://leetcode.com/problems/subsets/
since this is finding the power set we cannot come less than 2n.
but we dont need to store all the output. we can just store the combination
we can store we are picking the item or not in the form of the combination
so basically for each combination,. find the set bits and the... |
9338e87e005b8134837b505d335f3b490717c467 | TanzinaRahman/PythonCode24 | /PythonProgram24.py | 151 | 4.0625 | 4 | # Vowel ; a , e , i , o , u
ch = 'b'
if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u':
print("Vowel")
else:
print("Consonant")
|
d99482d7083d5ef0d11802859ae3566030749d01 | mvkumar14/Sprint-Challenge--Data-Structures-Python | /names/names.py | 3,274 | 3.5 | 4 | import time
from lru_cache import LRUCache
print("\n\nMVP:")
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the... |
e1c793c06968ec13af3177f7eb7ae8402a58a3fb | ws18503469313/python_learnng | /python/condition_language.py | 345 | 4.1875 | 4 |
cars = ['audi', 'bmw', 'toyota']
for car in cars :
if car == 'bmw':
print(car.upper())
else:
print(car.title())
print( 1 ==2 and 2 ==2)
print('audi' in cars)
print('bmw' not in cars)
safe = True
unsafe = False
age = 14
print(age)
if(age < 2):
print("baby")
elif(age > 2 and age < 14):
print("children"... |
03dbfba3fdef2bbe5a7f9d3b169e1be463b87abe | BrettMcGregor/w3resource | /list65.py | 564 | 4.5625 | 5 | # Write a Python program to access dictionary keys element by index.
# First, create a list of dictionaries
def list_of_dicts():
colours = ["red", "orange", "yellow", "green", "blue"]
dicts_list = []
for i in range(len(colours)):
dicts_list.append({i + 1: colours[i]})
return dicts_list
# li... |
2ad1ff26f2bac8467b94a82484f283ee2aa7b8ab | theassyrian/Competitive_Programming | /Stack_Queue/Interleave.py | 978 | 4.21875 | 4 | '''
The problem was asked by Google
Given a stack of N elements, interleave the first half of it with the second half
but reversed, using one and only one other queue. This should be done in-place.
You can only push and pop from stack, enqueue and dequeue from queue.
Ex: [1,2,3,4,5] -> [1,5,2,4,3]
Ex: [1,2,3,4] -> [... |
a92376f8ca2f0011f41e7df8875d648b912fda49 | stormpat/Problems | /euler/python/1.py | 401 | 3.734375 | 4 | problem = '''Find the sum of all the multiples of 3 or 5 below 1000. \n'''
# With nested func
def w_nested(limit):
def criteria(n):
return n % 3 == 0 or n % 5 == 0
return sum(list(filter(criteria, range(1, limit))))
# With lambda
def w_lambda(limit):
return sum(list(filter(lambda n: n % 3 == 0 or n % 5 == 0... |
55f73261d76952adb770ddeaaa35c3815ab6408e | Kargina/stepic_python_intro | /3/3_6_2.py | 761 | 3.5625 | 4 | class Matrix:
MAX_SIZE = 1000
def __init__(self, max_size=None):
self.size = max_size
if max_size is None:
self._matrix = [None]
else:
self._matrix = [[None] * max_size] * max_size
def __str__(self):
if self._matrix == [None]:
return("N... |
2bd17143b8e53af2d0e5c7d35ccd299957894eb0 | abigailStev/learn_python_the_hard_way | /ex12.py | 223 | 3.765625 | 4 | age = raw_input("\nHow old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "\nSo you're %r years old, %r inches tall, and %r pounds heavy.\n" % (age, height, weight) |
f8d88972fc7770224540bf44d194d8a305594183 | Brandixitor/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-pascal_triangle.py | 549 | 3.8125 | 4 | #!/usr/bin/python3
"""
eturns a list of lists of integers
representing the Pascal’s triangle of n
"""
def pascal_triangle(n):
"""
eturns a list of lists of integers
representing the Pascal’s triangle of n
"""
if n <= 0:
return []
res = []
l = []
for x in range(n):
row =... |
5734ba952b4f47c0f6e5e32459ae33ff5fa583e3 | BruceHi/leetcode | /month8-21/isFlipedString.py | 792 | 3.578125 | 4 | # 面试题 01.09. 字符串轮转
class Solution:
# def isFlipedString(self, s1: str, s2: str) -> bool:
# if len(s1) != len(s2):
# return False
# if not s1:
# return True
# for i in range(len(s1)):
# if s1[i:] + s1[:i] == s2:
# return True
# retur... |
4fcc4db4ca4926c5827276e540f8bcc06aca0545 | grg909/LCtrip | /Letian2020/OA2.py | 764 | 3.78125 | 4 | # -*- coding: UTF-8 -*-
# @Date : 2020/1/21
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
解题报告:https://www.1point3acres.com/bbs/thread-564350-1-1.html
LintCode.982
"""
class Solution:
"""
@param A: an array
@return: the number of arithmetic slices in... |
826be1d879d13c9cdd2c5623b164a69d11a95ca4 | matthewyingtao/Penguin-Adventure-Tkinter | /main.py | 30,677 | 3.828125 | 4 | from tkinter import *
from tkinter.scrolledtext import *
from tkinter import ttk
import random
import sys
root = Tk()
# root.iconbitmap(default="Penguin.ico")
root.wm_title("Penguin Adventure")
# manages invalid inputs
def invalid_input():
gstate.consecutive_invalid += 1
if gstate.consecutive_invalid < 3:
... |
5dc94d65ddd0dba1eb41b242a6924d8f32b69313 | aliabbas1987/python-practice | /practice/functions/evenoddlamda.py | 62 | 3.578125 | 4 | f=lambda x: "Yes" if(x%2==0) else "No"
print(f(2))
print(f(3)) |
d49c9a0dbe92b35f268c6c7d2744fea08dbd2df5 | zhaolijian/suanfa | /swordToOffer/20.py | 1,559 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
# 用于存放对应栈元素所在位置及之前元素最小值
self.assist = []
def push(self, node):
if len(self.assist) == 0 or node < self.assist[-1]:
self.assist.append(node)
else:
self.assist.append(self.mi... |
c1a2d1615449b8c2db450a546030d1394caafcb1 | 1miaocat/Exercise5 | /3.py | 367 | 3.9375 | 4 | def findvalue(mydict,val):
for i in mydict.items():
# for j in val:
if val == i[1]:
print(i)
v = 2
d = {'a' : 1, 'b': 2, 'c': 2, 'd': 4}
findvalue(d,v)
def findvalue(mydict, val):
mylist =[]
for key in mydict.keys():
if val == mydict[key]:
... |
2c83776f9f1e9a8d50f1ad171a6b0a3be3788b46 | zhengshiyu/cocostools | /python/class.py | 413 | 3.640625 | 4 | class zhengshiyu(object):
def __init__(self, arg):
super(zhengshiyu, self).__init__()
self.name = arg
print "init"
def getName(self):
print self.name
person = zhengshiyu("zhengshiyu")
person.getName()
class wangbeibei(zhengshiyu):
"""docstring for ClassName"""
def __init__(self, arg):
super(zheng... |
5c2e7bdcc5b42c3f412687b99c8e035ba51ed13f | erochal247/Clase-Poo-ejercicios | /ejercicio_14.py | 1,174 | 3.65625 | 4 | class ordenar:
def __init__(self, lista):
self.lista=lista
def burbuja(self):
for i in range(len(self.lista)):
for j in range (i+1,len(self.lista)):
if self.lista[i] > self.lista[j]:
aux=self.listä[i]
self.lista[i]=self... |
80d74a9536a8792518ba14a85b1d827976393757 | arshad-taj/Python | /Mosh/Largest_Num_In_List.py | 217 | 4.15625 | 4 | numbers = [5, 54, 88, 63, 7]
largest_num = numbers[0]
for i in range(len(numbers)):
if numbers[i] > largest_num:
largest_num = numbers[i]
print(f'Largers num is : {largest_num}')
num = numbers
print(num) |
2d868bc5b7720626efffcec39cf9227e4e93a1b8 | jostbr/INF4331-Projects | /assignment3/rpn.py | 8,949 | 3.71875 | 4 |
import sys
import math
class ReversedPolishNotationCalc:
"""Class that contains attributes and methods for handling
a calculator session using reversed polish notation"""
def __init__(self, command_line_input = None):
"""Constructor function for class that defines attributes (that are mainly used in process_user... |
be093ba4665a73a0da18d860e3a75a95c029abbe | debesh26360/Python-Programs | /traffic light function.py | 654 | 4 | 4 | import time
def countdown(n):
for i in range(n,0,-1):
print(i)
time.sleep(1) #starts from 10 then 10-1 i.e 9, then 8, then 7....
def trafficlight():
color='red'
if(color=='red'):
print('color is red. stop')
color='green'
countdown(10)
... |
0adcbb43303b661534e3ff7dc663cf8080a96eda | ljdongysu/LeetCode | /931/minFallingPathSum.py | 640 | 3.734375 | 4 |
def minLength(squareList):
if len(squareList) == 1:
return squareList[0][0]
for i in range(1,len(squareList)):
for j in range(len(squareList[0])):
temp = squareList[i - 1][ j]
if j > 0:
temp = min(temp,squareList[i][j-1])
if j < len(squareLi... |
93ba8ef73acfa216eb569cdd3d9090992de55c3d | Karnak123/maznet | /fizzbuzz.py | 1,483 | 3.828125 | 4 | """
FizzBuzz is the following problem:
For each of numbers 1 to 100:
* if the number is divisible by 3, print "fizz"
* if the number is divisible by 3, print "buzz"
* if the number is divisible by 15, print "fizzbuzz"
* otherwise, print the number
The following program gives more or less correct results after 10000 e... |
a7e8ce62a9d8ef2fe98ebad50dba6cfaf6d5104b | ivanchau1001/D002-2019 | /L2/Q1_ivanchau.py | 375 | 4.15625 | 4 | n = int(input(' Enter an integer\n'))
prime = True
x = 3
if (n/2) % 2 == 0:
prime = False
elif n % 5 == 0:
prime = False
elif n % x == 0:
prime = False
elif n % 10 == 0:
prime = False
elif n < 0:
prime = False
else:
prime = True
if prime == False:
print (" Not a pri... |
8bf334e014cca1617a2e360a492f4690b49cadbe | jimdoran-26/SuperBowlBox | /box_creator.py | 2,991 | 4.03125 | 4 | import random
from random import sample, shuffle
import sys
###FUNCTIONS TO MAKE PRINTING OF FINAL TABLE EASIER
#Print top row of the final table row
def print_top_row():
final=''
for i in range(10):
final+= ' | ' + str(random_a[i])
return final
#Print a single row of final table with na... |
8d9acdec69fd343966700092e0792838ea670090 | biddutSR/simple-calculator-python | /calculator.py | 287 | 4.125 | 4 | n1 = int(input("enter any number: "))
b = input("enter +,-,*,/ operator: ")
n2 =int(input("enter number: "))
if b=='+':
print(n1+n2)
elif b=='-':
print(n1-n2)
elif b=='*':
print(n1*n2)
elif b=='/':
print(n1/n2)
else:
print("error! please check again!!!!") |
3d9f8ea1d9787dd510da3d3cffc0335181986047 | LaurineMoes/programming1 | /les 8/pe8.3.py | 392 | 3.5625 | 4 | invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
def getallen(tellen):
list = (sorted(map(int, tellen.split("-"))))
print ("Gesorteerde list van ints: {}\nGrootste getal: {} en Kleinste getal:"
" {}\nAantal getallen: {} en Som van de getallen: {}\nGemiddelde: {}".format(list, max(list)
, min(l... |
01082f641405794eefe3dc99e7f00dfb26e004b9 | LakshmikanthRavi/guvi-lux | /neareven.py | 57 | 3.53125 | 4 | j=int(input())
if j%2!=0:
print(j-1)
else:
print(j)
|
bb7764a99ad619eebd1c8beb4293630ef6c517bf | surya-lights/Python_Cracks | /Loop iterations.py | 363 | 4 | 4 | # For loop
nums = [0, 1, 2, 3, 4]
for num in nums:
print(nums)
# To break loop iteration
nums_1 = [5, 6, 7, 8, 9]
for nums_1 in nums_1:
print(nums_1)
if nums_1 == 4:
print('Found')
breakpoint()
print(nums_1)
# Continue Statement and to skip Iteration
for val in "string":
if val == "i":
... |
f5c7e608e5a0d8093437782896e103f4e0d05ab4 | BtLutz/ProjectEuler | /Problem2/Problem2.py | 296 | 3.515625 | 4 | sum = 2
firstTerm = 1
secondTerm = 2
thirdTerm = 0
while thirdTerm < 4000000:
thirdTerm = firstTerm + secondTerm
firstTerm = secondTerm
print "%s | %s | %s " % (firstTerm,secondTerm,thirdTerm)
secondTerm = thirdTerm
if thirdTerm % 2 == 0:
sum += thirdTerm
print sum
|
f52a205c2efae7f23d1dba49a2082ce2feefaa36 | Nasimuleshan/ms-editor | /demanding.py | 1,037 | 3.578125 | 4 | import docx
with open('test.txt', 'r') as file :
filedata = file.read()
print (filedata)
print (type(filedata))
li = list(filedata.split(" "))
print('enter value')
a=int(input())
new = ""
for x in li:
if '[' in x:
if '.' in x or ',' in x:
x = x.replace("... |
68063cfad40327c8d99845bfb09fae46f5dc03ad | seiichiinoue/procon | /atcoder/abc012/b.py | 172 | 3.53125 | 4 | n = int(input())
h = 0
m = 0
s = 0
while n >= 3600:
n -= 3600
h += 1
while n >= 60:
n -= 60
m += 1
s += int(n)
print("{:0>2}:{:0>2}:{:0>2}".format(h, m, s)) |
b6eb2cd8fb39022cd8ab52870408d088e77d14c8 | bptfreitas/Project-Euler | /problema9.py | 558 | 4 | 4 | #A Pythagorean triplet is a set of three natural numbers, a b c, for which,
#a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
af=bf=cf=0
Found=False
for a in range(3,1000):
for b in range(1,a):
i... |
9c32d0df55a4ff2dc948f8d44b170de5926cb411 | oibe/bittorrent | /pieces.py | 2,906 | 3.75 | 4 | import math
import hashlib
from bitstring import BitArray
BLOCK_SIZE = 2**14
class Piece(object):
"""
Holds all the information about the piece of a file. Holds the hash of that
piece as well, which is given by the tracker.
The Piece class also tracks what blocks are avialable to download.
Th... |
b8b4c2b64cc6908898e146ebb0e7eeb51628a62a | JovanXin/numbguess | /numbguess.py | 623 | 3.65625 | 4 | #setting variables
min = 1
max = 1000
steps = 0
#importing math for math.ceil function
import math
#loops the program
while True:
bestGuess = math.ceil((min + max - 1) / 2)
userGuess = ""
while userGuess != ("y", "l", "h"):#"y" or userGuess != "l" or userGuess != "y":
userGuess = input("is "+str(bestGuess)+" ... |
3327dfc9a93ada2d6396945e4db11ca8e508816d | florentrkt/exercism | /python/atbash-cipher/atbash_cipher.py | 552 | 3.71875 | 4 | import string
def encode(plain_text):
a=[string.ascii_lowercase[::-1][string.ascii_lowercase.index(x)]
if x.isalpha() else x for x in plain_text.lower() if x.isalnum()]
x=0
s=''
while x<len(a) :
s+=''.join(a[x:x+5])
s+=' '
x+=5
return s[:len(s)-1]
def decode(ciphered_text):
b=[string.ascii_lowerca... |
243f9ef62e1ab5266987ad5584d05babbbe1bca9 | bunnymonster/personal-code-bits | /python/learningExercises/ControlFlowIfStatements.py | 177 | 4.3125 | 4 | x = int(input("Please enter an integer"))
if x < 0:
print("You entered a negative")
elif x == 0:
print("You entered 0")
else:
print("You entered a positive number")
|
90232549c0f22ca40ea13e4e3426373f08e1e807 | gabriellaec/desoft-analise-exercicios | /backup/user_098/ch16_2020_03_02_18_50_15_258989.py | 134 | 3.875 | 4 | valor = float(input("Qual o valor da conta?"))
valor_final = 1.10*valor
print("Valor da conta com 10%: R$ {0}" .format(valor_final)) |
81ec68e6502422ef9d3dc9fd67bd976d83fcef36 | zstarling131227/1905 | /month05/code/pandas/day08/demo09_merge.py | 1,095 | 3.734375 | 4 | """
demo09_merge.py 合并
"""
import pandas as pd
left = pd.DataFrame({
'student_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'student_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung', 'Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'class_id': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4]})
right = pd.DataFrame(
{'class_id': [... |
22da6d07fa0db788a1dbfa9ca7552dc544a3074b | MikeBeautfarmer/Homework_9 | /schleife.py | 477 | 4.09375 | 4 | import random
secret = random.randint(1, 30)
guess = 0
i = 3
for x in range(i):
try:
guess = int(input("Guess the secret number (between 1 and 30): "))
except ValueError:
print("Please type in a number")
continue
if guess == secret:
print("Yeah!")
break
elif gu... |
68c0beb388c72d4674e0e3eff3a61c9f6a8a8056 | viig99/Pylgos | /sorting_algos.py | 1,558 | 3.90625 | 4 | def mergeSort(a):
if len(a) <= 1:
return a
a1 = a[:len(a)/2]
a2 = a[len(a)/2:]
a1 = mergeSort(a1)
a2 = mergeSort(a2)
return merge(a1,a2)
def merge(a, b):
c = []
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
... |
26dbaba26ec971449b37e1f49300937d007f33cc | evelyn-0912000/INFDEV02-1_0912000 | /Assignment 6/Assignment_6.py | 3,303 | 4.0625 | 4 | import sys
import math
#def dimensions(shapeName, dim):
# try:
# length
try:
dim = int(raw_input("What is the length you wish the squares and the full rectangular triangle to have?\n> "))
except ValueError:
print("You need to put in an integer.")
sys.exit("Error occured, program aborted.")
# F... |
d2d5e3c01aed6c9535d63e19f4e308b33df416c2 | BBode11/CIT228 | /Lesson4/Chapter_09/user_class.py | 2,227 | 3.9375 | 4 | print("\t\t***---------- Exercise 9-3 ----------***")
class User:
def __init__(self, first_name, last_name, username, password, email):
self.first_name=first_name
self.last_name=last_name
self.username=username
self.password=password
self.email=email
def describe_user(se... |
61c8dcfbd52887c812dd6399f35ad1dac2983b8c | phamhieu04/ss11 | /ss11/PART3.py | 681 | 3.71875 | 4 | dict={
'HP' : 20,
'DELL': 50,
'MACBOOK': 12,
'ASUS': 30,
}
# Hiện ra số lương MACBOOK có trong kho
print("so may macbook la:",dict['MACBOOK'])
# Tính tổng số máy, bao gồm tất cả các loại hãng có trong kho
sum=dict['HP']+dict['ASUS']+dict['MACBOOK']+dict['DELL']
print("tong so may la:",su... |
8eb4deb4684aafd3f8a1da6f0ac726c45c3756b1 | HeithRobbins/python_notes | /morning exercise/morning_exercises.py | 288 | 3.671875 | 4 | my_list = [1, 2, 3]
my_second_list = [my_list, ['a', 'b'], ['c', 'd', ['found me']]]
print(my_second_list[0])
print(my_second_list[0] [1])
print(my_second_list[1] [0])
print(my_second_list[2][2])
print(my_second_list[2][2][0])
my_second_list.append('banana')
print(my_second_list) |
a4599b6ca6fc1aa97e90606445675540e9d443cb | AbdelrhmanKhater/CNIT124 | /Chapter3/scan.py | 279 | 3.53125 | 4 | #!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target = raw_input("Target: ")
port = int(raw_input("Port: "))
if s.connect_ex((target, port)):
print("Port " + str(port) + " is closed")
else:
print("Port " + str(port) + " is open")
|
38aaa4ce02ab230639336ac3c64f3bf574252c03 | cloudaice/stackview | /stack.py | 4,062 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import cmd
import sys
class stack:
def __init__(self):
self.lists=[]
def put(self,value):
self.lists.append(value)
def get(self):
lenth = len(self.lists)
if lenth:
print self.lists[lenth-1]
del self.lists[lenth-1]
else... |
d5c5481694ef303e6aa05bf6dd3792e14c320bd2 | srikanthpragada/PYTHON_21_SEP_2020 | /demo/ds/password.py | 345 | 4.21875 | 4 |
pwd = input("Enter password :")
upper = digit = special = False
special_chars = '@#_&*'
for ch in pwd:
if ch.isupper():
upper = True
elif ch.isdigit():
digit = True
elif ch in special_chars:
special = True
if upper and digit and special:
print("Valid Password")
else:
prin... |
57f6ee338cf63de8d88687c5dd1f89676424a161 | kaypee90/gRpc_pb2 | /calculator.py | 123 | 3.5625 | 4 |
def square_root(number):
return number * number
def addition(value_one, value_two):
return value_one + value_two
|
764e787d08b83b2440489c82825ee64c931d80d6 | MandipSh/TestNew | /test/G1.py | 392 | 3.671875 | 4 | #!/usr/bin/python
import random
import sys
letters = [chr(ord('a')+i) for i in range(26)]
def generate_name():
name = ""
for i in range(9):
name = name + random.choice(letters)
return "Testing_Mark[" + name + "]";
def main():
generate_name();
# print command line arguments
#for arg in... |
1bf0f6b23ff68cea62a4204f1efccfc153a408e9 | samech-git/Scripts | /Plot/plot_2dmap.py | 4,808 | 3.53125 | 4 | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to plot 2D maps. The maps are named after the input files but
with a "png"-extension.
Example:
plot_2dmap.py -f grid_dhh_low.dat grid_dhh_upp.dat
plot_2dmap.py -f grid_dhh_low.dat grid_dhh_upp.dat --ylabel "Y [nm]" --xlabel "X [nm]" --extent 0 1... |
455a7b39e9809837b92ab4cbf472758a5ed00eb1 | loribard/challenges | /hackerrankspiesrevised.py | 1,292 | 3.71875 | 4 | from random import shuffle
def spies(N):
""" makes sure all there are no two spies in any row or column and no three
spies in any 45 or 135 degree line"""
lista = range(1,N+1)
shuffle(lista)
print lista
count = 1
while count > 0:
count = 0
for i in range(N-2):
... |
b690744b55a0086633b3f7f3deebf9ce576bfb37 | berk245/algorithms-and-data-structures | /1-Time_Complexity/4-quadratic_time.py | 783 | 4.09375 | 4 | def quadratic_time(arr):
counter = 0
for val in arr:
for val in arr:
counter += 1
print(counter)
arr = [1, 2, 3, 4, 5]
quadratic_time(arr)
'''
Quadratic Time Complexity refers to the cases in which the execution time of an algorithm is proportional to the squared size of the input da... |
ac14dd30f3693fb90d8c552a3c2ebb923cb4fed7 | tianwei1992/python_practice | /4-my-1.py | 726 | 4.125 | 4 | #4-my-1.py
#3ways to create a dictory
#1 way
dic1={'A':1,'B':2,'C':3}
dic2=dict([('A',1),('B',2),('C',3)])
dic3=dict(A=1,B=2,C=2)
print('dic1:',dic1,'\n')
print('dic2:',dic2,'\n')
print('dic3:',dic3,'\n')
#basic operation
print('len[dic1]:',len(dic1),'\n')
print("'A' in dic1",'A' in dic1,'\n')
print("dic1['A'] :"... |
6a25fcdcf35289253e56969d8bf52a7245bf8e03 | fish-ball/Codeforces | /0343B.py | 145 | 3.65625 | 4 | l = []
for c in input():
if len(l) > 0 and l[-1] == c:
l.pop()
else:
l.append(c)
print('Yes' if len(l) == 0 else 'No')
|
39f7df3c607e9eca578c99b6eb4c5be9fec62bcf | IvanDavais/Python | /Python_Loop/wf_02_formatVariable.py | 440 | 4.0625 | 4 | """"
student_no = int(input("please input your student ID number: "))
print("My student number is %06d" %student_no )
price = float(input("please enter the price of apple: "))
weight = float(input("please enter the weight of apple: "))
money = price * weight
print("The price of apple is %.2f /kg, and you want to buy %.... |
813b34903e5f3ee77820d5f996575d4777884df1 | prem17101996/CodeChef | /Turbo Sort.py | 135 | 3.71875 | 4 | t=int(input())
lst=[]
for i in range(t):
numbers=int(input())
lst.append(numbers)
lst.sort()
for item in lst:
print(item) |
72f543e47404679584e11b982fe44b8fd06a9ff3 | yunhacho/SelfStudy | /Algorithm/BOJ/BOJ_1920_수찾기.py | 548 | 3.859375 | 4 | from sys import stdin
def Does_Number_Exist_in_Sequence(N: int) -> bool:
left, right = 0, len(sequence)-1
while left <= right:
mid=(left+right)//2
if sequence[mid]==N: return True
elif sequence[mid]>N: right=mid-1
else: left=mid+1
return False
if __name__=="... |
a26f1c8c985437cda738f34b42ebe71a76326fa5 | Aasthaengg/IBMdataset | /Python_codes/p03631/s991556835.py | 156 | 3.765625 | 4 | def main():
number = input()
r_number = number[::-1]
if int(number) == int(r_number):
print("Yes")
else:
print("No")
main() |
d0349ed6c4f58608c6322114a0024b8aca5e880a | abhi-laksh/Python | /new.py | 360 | 3.515625 | 4 | #,--- DATE : June 07, 2019 | 15:24:39
#--- --- By Abhishek Soni
#--- About (also write in below variable):
about=''
print('About :' + about)
import time
a = list(range(1,100000))
def rot(arr):
n = len(a)
k = n//2
f = 0
while k>0:
arr[f] ,arr[n-1] = arr[n-1] ,arr[f]
n-=1
f+=1
k-=1
st = time.time()
rot(a)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.