blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
324a7e8a74df370273742a33debd3f7315bc10c5 | Sun-Zhen/leetcode | /0101-0150/0122-BestTimeToBuyAndSellStock2/BestTimeToBuyAndSellStock2.py | 478 | 3.578125 | 4 | # -*- coding:utf-8 -*-
"""
@author: Alden
@email: sunzhenhy@gmail.com
@date: 2018/4/6
@version: 1.0.0.0
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
res = 0
for i in range(len(prices) - 1):
if price... |
68c2075e36b27c3c127d805437cb0b717218076d | yuyaxiong/interveiw_algorithm | /LeetCode/回溯算法/37.py | 3,558 | 3.6875 | 4 | from typing import List
# 37. 解数独
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.recur_solve(board)
return board
def recur_solve(self, board):
status = False
for ... |
60ec23d5bee4bc124c413184bb6726faf74f41f3 | Rutuja-haridas1996/Basic-python-problems | /max_product_dp.py | 715 | 3.84375 | 4 | def max_product_subarray(arr_length, arr):
dp = [arr[0]]
result = arr[0]
for i in range(1,arr_length):
if (arr[i] * dp[i - 1] > arr[i]):
dp.append(arr[i] * dp[i - 1])
else:
dp.append(arr[i])
if (dp[i] > result):
result = dp[i]
print("Maxim... |
f7748d00ba093c7129d261d4efbd1963d506a159 | BronzeEgo/PythonCourse | /copyme.py | 117 | 3.609375 | 4 | me = input("Say something ").lower()
while me != "stop copying me":
print(me)
me = input()
print('you win')
|
02a60d894b8780fbf4132ec1538789b357da30f3 | rodcruzh/AnalisisContratos | /cleaning/transformations.py | 3,041 | 3.546875 | 4 | import re
def cleanLugar(string):
"""
i.e: " Valle del Cauca : Cali"
=> {'departamento': "valle del cauca", "ciudad": "cali"}
"""
split_str = string.split(":")
if len(split_str)>1:
departamento = split_str[0]
ciudad = split_str[1]
if len(split_str)==1:
departamento = split_str[0]
ci... |
6ba66a6ba11f4619af66ffad50507ca93c5b8bba | Jongminfire/Baekjoon | /Python/1789 (수들의 합, 이분탐색).py | 299 | 3.671875 | 4 | n = int(input())
start = 0
end = n
ans = 0
def sum_all(n):
if n%2 == 0:
return (int((1+n)*(n/2)))
else:
return (int((1+n)*int(n/2)+(n+1)/2))
while start <= end :
mid = (start+end)//2
if sum_all(mid) > n:
end = mid -1
else:
ans = mid
start = mid + 1
print(ans)
|
9d53ecefa4f1574f6ff0a3601df960a3ca5f5377 | ekmartens/codefights | /removeK-linkedlist.py | 1,476 | 4.03125 | 4 | """
Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you'll be asked to do during an interview.
Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.
Example
For ... |
4dcefbfce469e2d9839a2983ae01c3ed332000c5 | shariful-cu/DataCamp | /dictloop00 | 950 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 2 02:02:44 2018
@author: Shariful
"""
# =============================================================================
# -*- Important message -*-
"""
Great! Notice that the order of the printouts doesn't correspond with the
order used when definin... |
3df2b255ffb0f49f5073211a1a5a6549d8f67133 | domicphp008/PyCursos | /AcumuladoresFaorialAula20.py | 148 | 3.640625 | 4 | '''
Acumuladores
Calcule o fatorial de dez
'''
i = 1
fat = 1
while i <= 10:
fat = fat * i
i = i + 1
print ("FaT(10) = %d" %fat)
|
4e709fc624b0fd02e931a7054b28a01250208e13 | jasonprogrammer/ham-radio-question-slides | /parse_questions.py | 4,072 | 3.671875 | 4 | import json
from string import Template
class Question():
def __init__(self, question_text, answer_lines, answer_letter):
self.question_text = question_text
self.answer_lines = answer_lines
self.answer_letter = answer_letter
self.correct_answers = self._get_correct_answers()
... |
964892e7c1697f89d7a32a36ea41dea153837378 | dacyzhan/python | /python_base/com/dacy/base/ListTupleTest.py | 3,503 | 4.3125 | 4 | # -*- coding:utf-8 -*-
import os
'''
List
Tuple
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
类似java 中的数组 下标从 0 开始 可以是负的 ,负的则按照倒数的来
list 中元素类型不受限制,可不一样。
classmates = ['Michael', 'Bob', 'Tracy']
Tuple
另一种有序列表叫元组:tuple。tuple和list非常类似,请注意,初始化格式不同,List 是 [],而 Tuple 是 ().
但是tuple一旦初始化就不能修改。
classmates = ('Micha... |
49ead4afa4ec979c11b0e25df8156236d0f253d3 | SandipSalunkhe007/Python | /Tutorials/tutorial31.py | 1,055 | 4.53125 | 5 | # __init__(), Constructor
# The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.In Python the __init__() method is called the constructor and is always called when an object is created.
# Syntax -
# def __init__(self):
# body of the co... |
7c8468691c078495aeb149845bbc7bc4adf32eb3 | Naereen/Introduction-au-Numerique-avec-Python-dpt-DEM-2020 | /Cours-4/Programmes-Python/M3-4.py | 264 | 3.625 | 4 | maliste = [2, 1, -5, 8, 7, 3, 4] # valeurs quelconques
i = 0
maxi = maliste[0] # on initialise le max à maliste[0]
while i < len(maliste):
if maliste[i] > maxi:
maxi = maliste[i]
i = i + 1
print("Le plus grand élément est :", maxi) # ici = 8
|
cc8f07a39de6c0412f9be6d890840548933fa283 | yinzaihecode/hongongpython | /venv/chap41-50/chap48.py | 860 | 3.546875 | 4 | # https://www.youtube.com/watch?v=PuGnDXwe7uo&list=PLBXuLgInP-5kr0PclHz1ubNZgESmliuB7&index=50
# getter setter
# https://www.youtube.com/watch?v=PuGnDXwe7uo&list=PLBXuLgInP-5kr0PclHz1ubNZgESmliuB7&index=50
# 기본적인 속성 : Attribute
# 변화를 준 속성 : property
# code refactoring >>>
# 선언
class Rect:
def __init__(self, widt... |
9b80c175bc414ccc73eb2962445fef7e99d00cec | umasp11/PythonLearning | /Class.py | 5,795 | 4.34375 | 4 | '''
#self parameter is a reference that the method belongs to the class
class calculator:
num=100 #Class variable
def add(self): #method
print('this is method')
ob=calculator() #Creating object for class to call method/variable
ob.add() ... |
ffdf5174a1d28d0a1390420a82859bd2df19504e | mansi135/LeetcodeProblems | /Arrays_and_Numbers/349-intersection-of-two-arrays.py | 783 | 3.78125 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
def intersection_alter(self, nums1, nums2):
"""
:type nums1: List[int]
... |
5f9b361bfffe8c40d3549660d625d6842cc7b739 | romanannaev/python | /STEPIK/complete_task/tandem.py | 710 | 3.765625 | 4 | # Вам дана последовательность строк.
# Выведите строки, содержащие слово, состоящее из двух одинаковых частей (тандемный повтор).
# Sample Input:
# blabla is a tandem repetition
# 123123 is good too
# go go
# aaa
# Sample Output:
# blabla is a tandem repetition
# 123123 is good too
import sys
import re
pattern = r'\... |
c2d54306e7b38139ce4352e174d6f800d5b84171 | maocalm/python | /use_python_webscrap/1.4.1.py | 1,266 | 3.65625 | 4 |
import urllib3
import urllib.request
import urllib.error
def download1(url):
"""Simple downloader"""
return urllib.request.urlopen(url).read()
print(download1('https://www.baidu.com'))
print('--------------------')
def download2(url):
print("downlaoding:" +url)
try :
html = urllib.reque... |
d8bac47ce54d8aa6335a70e19c50b469bba8296c | chaofan-zheng/tedu-python-demo | /month01/all_code/day05/exercise08.py | 375 | 4.0625 | 4 | """
练习:将下列英文语句按照单词进行翻转.
转换前:To have a government that is of people by people for people
转换后:people for people by people of is that government a have To
"""
message = "To have a government that is of people by people for people"
list_datas = message.split(" ")
message = " ".join(list_datas[::-1])
print(messa... |
17628fd381f01463e66f92a75218c45635957b12 | pontus/slasktest | /1/2.py | 411 | 3.578125 | 4 | #!/usr/bin/env python
from curses import window
window = []
old_ws = 0
count = 0
with open('input.txt') as f:
for line in f:
depth = int(line)
if (len(window) >= 3):
ws = sum(window[:3])
if ws > old_ws:
count += 1
old_ws = ws
if (len... |
6c978dcf5b63df14825d15b0b0ac2d7b8d7ea878 | ms-iot/python | /cpython/Doc/includes/sqlite3/collation_reverse.py | 484 | 3.859375 | 4 | import sqlite3
def collate_reverse(string1, string2):
if string1 == string2:
return 0
elif string1 < string2:
return 1
else:
return -1
con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)
cur = con.cursor()
cur.execute("create table test(x)")
cur.exec... |
0c5e592278d88d440caaa06b5603cb9217557d0e | umair3/pytorial | /basics/strings.py | 481 | 3.84375 | 4 | name = "umaiR anwar"
age = 31
print("Hello %s, age = %d" % (name, age))
print('Hello %s, age = %d' % (name, age))
data = ("Umair", 31)
print("Name = %s, Age = %d" % data)
print(len(name))
print(name.index('a'))
print(name.count('t')) # find occurrences
print(name.capitalize()) # capitalize fist letter, and other... |
6d4e4b5d8c15a64af73c183fa57f450a76541b09 | 1xdeadman/examples | /1_classes/8_classes.py | 581 | 4.125 | 4 | # abstract methods
# learning python, 5th edition, chapter 29
# https://www.python.org/dev/peps/pep-3119/S
# https://docs.python.org/3/library/abc.html
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@abstractmethod
def method(self):
print("method")
@classmethod
@abstractmeth... |
666d432fc797f08b5025ca79c6f64435f6b69d9d | LaurineMoes/programming1 | /les 8/pe8.6.py | 3,829 | 3.78125 | 4 | def menu():
print("\n1: Ik wil weten hoeveel kluizen nog vrij zijn")
print("2: Ik wil een nieuwe kluis")
print("3: Ik wil even iets uit mijn kluis halen ")
print("4: Ik geef mijn kluis terug")
print("5: Stoppen\n")
menukeuze = input("Kies een optie (1-5): ")
if menukeuze == "1":
aant... |
322d3653876eb6606589b6524240dc7d54012b95 | Fiona08/leetcode | /Python/121 BestTimeSellBuyI.py | 820 | 3.828125 | 4 | #121
# Time: O(n)
# Space: O(1)
# Say you have an array for which the ith element is
# the price of a given stock on day i.
# If you were only permitted to complete at most one transaction
# (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
#
# Example 1:
# Input: [... |
d9cf6de73623c6f4ce8d10dc7284b0aadbcc7ae8 | cooman-long/PassWord_Hacker | /Topics/Iterators/Word constructor/main.py | 146 | 3.65625 | 4 | words_1, words_2 = input(), input()
band_name = ''
for word_1, word_2 in zip(words_1, words_2):
band_name += word_1 + word_2
print(band_name)
|
5041f0454ab1e55c89134da35825e0024fccb6e4 | hanzhi713/thinkcs-python3-solutions | /Chapter 18/3-4 doris.py | 737 | 3.765625 | 4 | import turtle
Doris = turtle.Turtle()
Doris.speed(0)
Doris.hideturtle()
sc = turtle.Screen()
def Sierpinski(depth, step, size):
if step == 0:
for i in range(3):
Doris.forward(size)
Doris.left(120)
elif step == depth:
for i in ['red', 'blue', 'yellow']:
Dori... |
21c4e9b163501c417661f37c444bf0a4642c0748 | CStratton00/NumericalIntegrationProject | /NumericalIntegration.py | 7,743 | 4.09375 | 4 | """
Collin Stratton
CST-305
Topic 8 Project 8: Numerical Integration
Dr. Ricardo Citro
For this project, this is the coding section for part 1 where we are to graph the integrals of the functions
given throughout part 1 and output their values
Implementation approach:
- Research scipy integrals
- Developed functions ... |
8f1a4490ec2d11f9f29a955135b1cce5844533a3 | PedroSantana2/python-basico-solyd | /exercicios/aula_07.py | 508 | 3.953125 | 4 | '''
Escreva uma função que recebe um objeto de coleção e retorna o valor do maior número dentro dessa coleção
'''
def maior():
lista = []
var = True
print('Digite SAIR para ter as informações!')
while var:
numero = input('Digite um número: ')
if numero.upper() == 'SAIR':
va... |
108f86cd5fafcb760a916a4697608f1b67cced9e | AndrewLin-Umich/Project-Euler | /ex62.py | 523 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 27 02:02:28 2017
@author: andre
"""
def permute(x):
return ''.join(sorted(str(x)))
cubic_dict = {}
base_number = 345
found = False
num_of_permutations = 5
while not found:
k = permute(base_number**3)
if k not in cubic_dict:
cubic_dict[k] = [base_n... |
055a3206be132594d7e212610502925477436c83 | lucasdiogomartins/curso-em-video | /python/ex017_hypot.py | 283 | 3.875 | 4 | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
h = (co**2 + ca**2)**(1/2)
print('a hipotenusa vale {:.2f}'.format(h))
hip = hypot(co, ca)
print('hipotenusa calculada por .math: {:.2f}'.format(hip))
|
1d62eae6d772398939f6a2b6b774c360fb5e85d0 | buhuipao/LeetCode | /2017/link/reverse_linked_list_II.py | 1,159 | 4.1875 | 4 | # _*_ coding: utf-8 _*_
'''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
'''
class ListNode(object):
def __init__(se... |
d8ab67359e9d18ed2bdd06efb18a920cd592fadb | EmreTekinalp/PythonLibrary | /src/design_pattern/strategy_pattern.py | 2,886 | 4.4375 | 4 | """
@author: Emre Tekinalp
@contact: e.tekinalp@icloud.com
@since: May 28th 2016
@brief: Example of the strategy pattern.
Unit tests to be found under:
test/unit/test_strategy_pattern.py
"""
from abc import abstractmethod
class Language(object):
"""Language Base class."""
@abstractmethod
... |
6136f6dd9f59eca386db52a5983d78debbc41ea0 | Sweerna1/python | /classes_task.py | 2,283 | 4.1875 | 4 | from datetime import date
print("CLASSES TASK")
print("Welco to HR Pro 2019")
class Employee:
def __init__(self, name, age, salary, year):
self.name = name
self.age = age
self. salary = salary
self.year = year
def get_working_years(self): #--------------1
today ... |
31e51daf55e4931dd61ae29035e2064108881f7f | anastasiia-shevchenko/Python-3-course | /lab 10-11-12/my_class.py | 2,150 | 3.84375 | 4 | from abc import ABC, abstractmethod
class MenedgerFile(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
class SimpleIterator:
de... |
aada20e90316ba8ef62725c1082a1db7eafcb64b | innovatorved/BasicPython | /Python Programs/20.tuples.py | 331 | 4.0625 | 4 | #tuples :
#1. sequence of python objects like list
#2. we use parenthesis() instead of squire brackets[]
#3. unlike list tuples are immutable meaning thier value can't be changed
x=(1,2,3,'abhi',[2,3,'nidhi'])
print(x)
#4. we can change value of list stored in tuple
x[4].append('divya')
print(x)
x[4].insert(0,'ram'... |
2e0928f9c537b356ab8b12f42445090c8f2ef189 | NCRivera/Python-Crash-Course | /Chapter_3/3_2_greetings.py | 265 | 3.796875 | 4 | message = "Hey, how are you "
friends = ['Anna', 'Barbara', 'Cindy', 'David', 'Evelyn']
print(message + friends[0] + "?")
print(message + friends[1] + "?")
print(message + friends[2] + "?")
print(message + friends[3] + "?")
print(message + friends[4] + "?")
|
cc39d022c7ff6941ffc014321cec1fb85eb5a8e3 | Genyu-Song/LeetCode | /Algorithm/DynamicProgramming/ArithmeticSlices.py | 1,339 | 4.0625 | 4 | # -*- coding:UTF-8 -*-
'''
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2,... |
a9abb83f342d3211a49fa4466aa6509ec62eb7d1 | baubrun/HackerRank | /Missing_Numbers/Missing_Numbers.py | 1,156 | 4.25 | 4 | """
Numeros the Artist had two lists that were permutations of one another. He was very proud.
Unfortunately, while transporting them from one exhibition to another, some numbers were
lost out of the first list. Can you find the missing numbers?
Notes
If a number occurs multiple times in the lists, you must ensure... |
4d62c8fea2d2dfd719ccbeec9faa1470d1eb798c | IvanSerranoGit/Python-Django | /18_listas.py | 192 | 3.96875 | 4 | objetos = ['hola', 3, 4.5, True]
print(objetos)
objetos.append(False)
print(objetos)
objetos.pop(3)
print(objetos)
for elemento in objetos:
print(elemento)
objetos[ : : -1]
print(objetos) |
37e3d5619b647d5042b4f8b7a8f010e94147e986 | joshf93/MappingThePeaks | /python/utilities/calc_time.py | 1,311 | 3.5 | 4 | import datetime
import os
def process_file(filepath):
"""Processes a single file, extracting the time the submission took"""
times = []
day_names = ("Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat")
with open(filepath, 'r') as file:
for line in file:
if line[0:3] in day_names:
... |
219d2020314b81ddd979ad9f5def39d77d5f784f | gabriel-lepetitaimon/JuNNo | /lib/junno/j_utils/math.py | 5,984 | 3.53125 | 4 | from functools import reduce
import math
def prod(factor):
"""
Equivalent to sum(list) with multiplication.
Return the multiplication of all the elements in the list.
"""
return reduce(lambda x, y: x*y, factor, 1)
def quadratic_kappa(conf_matrix):
"""
Compute the kappa factor from a confu... |
6ecaac8393874b5b177e61b63d016d697b3e6fef | sakshisangwan/RandomPython | /ThinkPython/8strings/is_reverse.py | 242 | 4.03125 | 4 | def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2) - 1
while j >= 0:
if word1[i] != word2[j]:
return False
i = i + 1
j = j - 1
return True
x = is_reverse('hello', 'olleh')
print(x) |
d0ed9be19dcd2c1de7eaf3a16b547cf0b1008370 | lzlmike/ECS10 | /HW1/M2K.py | 179 | 3.9375 | 4 | def main():
Mile=eval(input("Please enter the distance in miles: "))
To_Kilometer=1.60934*Mile
print("%.2f miles is %.2f kilometers"%(Mile,To_Kilometer))
main()
|
5f86cb3e197534189f2ff8f9d0cb150c7e82c6a4 | CamilliCerutti/Python-exercicios | /Curso em Video/ex036.py | 699 | 4.125 | 4 | # APROVANDO EMPRÉSTIMO
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
casa = float(input('Valor da casa: R$'))
sal... |
82279a4608acf42ad2d2d42d1a0bf14fce776875 | KhaiTheTran/MYCode | /knightGrid.py | 6,994 | 4 | 4 | # -*- coding: cp1252 -*-
# Khai The Tran
# trank6@uw.edu
# Computer Science
# UW Seattle
# 11/27/2017
#Python 2.7
"""ExtraHop Programming Problem
Problem: Please write a function in Python that takes an 8x8 grid of letters and
a list of words and returns the longest word from the list (ignoring case) that
... |
ac8abafe0f1c50868e985bab8d6122958d68a614 | dylan-pham/Python-Challenges | /PC6.py | 515 | 3.609375 | 4 | import zipfile
comments = []
with zipfile.ZipFile("PC6.zip", "r") as z:
for name in z.namelist(): # iterating through files inside zip file
info = z.open(name).read() # looking at content inside each file
if "nothing" not in str(info): # checking if there are any files that stand out
... |
b9b3d7b805e64949e53f9eb3c508613cc426b767 | sbkaji/python-programs | /assignment/7.py | 697 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 00:13:09 2020
@author: Subarna Basnet
"""
"""7.write a program to print star patterns and alphabets pattern """
print("Print Alphabets pattern in python ")
lNumber = 6
asciiNumber = 65
for i in range(0, lNumber):
for j in range(0, i+1):
charact... |
d731f83178ee86085f54fd6ab00c837749c2311f | machenxing/my-algorithm-training | /python/q-series/Q8.4.py | 1,149 | 4.125 | 4 | '''
Power Set: Write a method to return all subsets of a set.
'''
def getSubsets(setz, index):
allSubsets = []
if len(setz) == index:
if [] not in allSubsets:
allSubsets.append([])
else:
allSubsets = getSubsets(setz, index + 1)
item = setz[index]
moreSubsets = ... |
7e284c960514c515fdda2592415ccf9e138d3b87 | brogan-avery/MyPortfolio-AndExamples | /Data Structures/OOP Basic Concepts/polymorphism/MeasurementsAveryDriver.py | 1,161 | 3.828125 | 4 | """
***************************************************************
* Title : Measurements
* Author: Brogan Avery
* Created : 2021-02-03
* Course: CIS 152 - Data Structure
* Version: 1.0
* OS: macOS Catalina
* IDE: PyCharm
* Copyright : This is my own original work based on specifications issued by the course instructo... |
c8491cc1a240b81e9875c1c595e0a5544015107b | andonyan/Python-Fundamentals | /data types and variables exercise/Elevator.py | 181 | 3.71875 | 4 | persons = int(input())
capacity = int(input())
courses = 0
if persons % capacity == 0:
courses = persons // capacity
else:
courses = persons // capacity + 1
print(courses) |
5dfe60feb7df1885b3ad4ac514a7ca172dc7e7f3 | erogers6264/tech | /making_change.py | 1,607 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Your quirky boss collects rare, old coins...
# They found out you're a programmer and asked you to solve something they've been wondering for a long time.
# Write a function that, given:
# an amount of money
# a list of coin denominations
# computes the number of ways... |
e18140569bf61f94ff8db96b1a72cd57b832f7ee | zhangke8/Applications | /Python/MW Scripts/remove duplicate items.py | 437 | 3.828125 | 4 | file = input("What file? ")
openFile = open(file)
print("Processing now, please wait")
removeDup = []
for line in openFile:
strip = line.strip()
if strip not in removeDup:
removeDup.append(strip)
openFile.close()
returnFile = input("return file? ")
ORFile = open(returnFile,"w")
for item i... |
a4e4bee16e8c57ce0f173f6cf474b2e6a269bd1d | kaja621/Python-Experiments | /Experiment_7.py | 380 | 4.03125 | 4 | """Given a non negative integer A, print all the pairs of integers(a,b) such that
a and b are positive integers
a<=b and
a^2 + b^2 = A
0 <= A
A<=1000"""
A=input("Enter a non negative integer")
s=int(A)
if s<=1000 and s>=0:
for b in range(s):
for a in range(s):
if a<=b:
c=a*a+b*b
... |
43a03d19056d0de6302ed8528c30761ab4ed1b2a | WilliamTrojniak/Year9DesignCS-PythonWT | /Unit 1 Schoolwork/GUIGridExample.py | 720 | 4.1875 | 4 | import tkinter as tk#tkinter is a module that holds code
#Root is variable holding information
#About the main window.
root = tk.Tk()
textOut = ""
ent = tk.Entry(root)
btn = tk.Button(root, text = "Press Me")
label = tk.Label(root, text = "...")
#Use grid geometry manager to pack widgets more controllably
ent.gri... |
2e0f92b967c1bf8177ae5b1aba112b26ac72873b | AchimGoral/DI_Bootcamp | /DI_Bootcamp/Week_5/Day_3/exercise_1.py | 3,725 | 4.03125 | 4 | # Exercise_1
print (abs.__doc__)
def abs(number):
"""Take the input value and return a positive number. A complex number will be returned as a positive number"""
pass
print("")
print (print.__doc__)
def print(input_value):
"""Prints out numbers, strings, dictionaries, lists by writing it in the Termin... |
aa4a554a0f52af933f97f715ab7d15a389fed2bb | rafal1996/CodeWars | /Your order, please.py | 1,361 | 3.90625 | 4 | # Your task is to sort a given string. Each word in the string will
# contain a single number. This number is the position the word should have in the result.
#
# Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
#
# If the input string is empty, return an empty string. The words in the input ... |
690d0129a0be9c93cf62218a51ded1aca753dac3 | dgilmore91/grepjuice | /data_treatment/bigrams.py | 298 | 3.625 | 4 | def generate_bigrams_list(sentence):
words_list = sentence.split(" ")
bigrams_list = []
for index, word in enumerate(words_list):
if index <= len(words_list) - 2:
bigram = [word, words_list[index + 1]]
bigrams_list.append(bigram)
return bigrams_list
|
19ffe5734ac92a9da3ccb028dba2cde7105ccf55 | John10mc/PythonPrograms | /Week7-Lab1/selection-sort-2.py | 218 | 3.5 | 4 | #!/usr/bin/env python
a = []
j = 0
end = 0
s = raw_input()
while s != "end":
a.append(int(s))
s = raw_input()
i = int(raw_input())
while i < len(a):
if a[i] < a[j]:
j = i
i = i + 1
print j
|
2b795c308478a9d3033d3b9db14927cc85a56853 | lofues/Data_Science | /01_numpy/05_ndarray_shape.py | 543 | 3.578125 | 4 | import numpy as np
a = np.arange(1,7)
print(a,a.shape)
# 视图变维 原数据改变视图改变,其实是一种引用
b = a.reshape(2,3)
print(b,b.shape)
a[2] = 100
print(a,b)
# 指定-1 自动计算行列个数
c = a.reshape(-1,2)
print(c)
# ravel 将原数组转换为行向量
d = a.ravel()
print(d)
a[1] = 999
print(a,b,c,d)
# 复制变维
e = a.flatten()
print('-------------')
print(e)
e.shape =... |
30028d17b2ed1c8f584da6cb43ddf002542b2065 | rbague5/formalizacion-del-problema-del-coloreado-de-grafos | /main.py | 1,625 | 3.625 | 4 | import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import to_agraph
# Function to assign colors to vertices of graph
def greedy_coloring(g):
# stores color assigned to each vertex
result = {}
# assign color to vertex one by one
for u in g.nodes():
# set to store color of adja... |
00d0d45658d163450525b671b3026391c816b514 | Akshay-s-raut/Python | /Fun/screen_pattern_counter/testing/screen_pattern_counter/test.py | 181 | 3.515625 | 4 | A = {1:(1,'A'),3:(0,'C'),2:(2,'B')}
# B = [(1,'A'),(3,'C'),(2,'Z')]
# print(sorted(A.values()))
# print(A)
# print(sorted(B))
def f(A):
A[1]=5
print(A)
f(A.copy())
print(A)
|
c5a6d95b2498720ce992bf168b45a467eaf9a199 | ViniciusDeep/Answers-URI-Online-Judge | /Answers/Python/1024.py | 1,244 | 3.78125 | 4 | # -*- coding: utf-8 -*-
#coding: utf-8
n = int(raw_input())
resultados = []
# transforma a string numa lista
def cria_lista(string):
stringlista = []
for i in range(len(string)):
stringlista.append(string[i])
return stringlista
# transforma os caracteres para +3 ascii
def tres_a_direita(string):
for i in ra... |
b6566631d3929fc5a763dfdc2495b6fb7aacb91b | u101022119/NTHU10220PHYS290000 | /student/101022105/drop_ball_height.py | 401 | 3.90625 | 4 | h=float(raw_input("Enter the initial height(m) you'd like it to be."))
t=float(raw_input("Enter the time interval(s) you'd like it to be."))
h2=h-4.9*t*t
if h2>0:
print 'At t seconds later, it will fall to the height of',h2,'above ground.'
if h2==0:
print 'At t seconds later, it just kisses the ground.'
else:
... |
a194757a8cb43976199571acc67d16aeacb7b231 | Gangadharbhuvan/31_Days_Leetcode_Challenge-December | /26.Decode_ways/26.Decode_ways.py | 1,261 | 3.875 | 4 | '''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Inpu... |
b90880a93103ff4aefe8c41de168946fcfa2a257 | AnanyaRao/Python | /tryp9.py | 227 | 4.21875 | 4 | def find_sum(num):
total=0;
while(num):
rem=num%10;
total=rem+total;
num//=10;
return total;
num=int(input("Enter a number:"))
sum1=find_sum(num)
print('The sum of number is',sum1) |
f4f3b0575c82a663f00ac7ad3bf5497b02ed3aa3 | Parizval/CodeChefCodes | /Python/Beginner/LCH15JAB.py | 260 | 3.734375 | 4 | for a in range(int(input())):
check = False;
string = input()
for i in string:
b = string.count(i)
if b == len(string) - b :
check = True
break
if check:
print("YES")
else:
print("NO") |
43a30623366776599bb17e9c65056ac8c42c245e | sixty-north/added-value | /source/added_value/invoke.py | 1,192 | 4 | 4 | from typing import Tuple
def parse_call(text: str) -> Tuple[str, str]:
"""Parse a string containing a reference to a Python attribute or invocation thereof.
Args:
text: The text to parse. e.g. "foo.bar.baz" or "foo.bar.baz(1, 2)"
Returns:
A tuple of the form (attribute, args) where attri... |
468c09ea03fc79630991ac10f7be895ee9d0c715 | RoadRunner11/CarRentalApp | /docs/src/socket_utils copy.py | 2,356 | 3.84375 | 4 | #!/usr/bin/env python3
# Documentation: https://docs.python.org/3/library/struct.html
import socket, json, struct, sys, os
# This method is used to send the json over socket
def sendJson(socket, object):
""" This method is used to send the json over socket
:param (object)object
"""
jsonString = json.du... |
d2e86b8ffbcc4f324d19479ad7eca62b166e33bb | Asunqingwen/LeetCode | /剑指offer/翻转单词顺序.py | 182 | 3.78125 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
strs = s.strip().split(' ')
strs.reverse()
return ' '.join([str_ for str_ in strs if str_ != ' '])
|
ce0337bd61eea0ae1364d99979f7d8b48b1e9ad7 | its-pikesh/Hangman_game_python | /hangmangame.py | 2,091 | 3.96875 | 4 | #python hangman game created on 17-07-19 by Pikesh for ASKNBID internship challange
import random
import string
wordlist=[] #empty list to collect words from text file
with open('words.txt') as file: #you can give your own list of words in a text file here
data=file.readlines()
for line in data:
... |
4c4236914c6f016a420bf77304f6b25c2ed5158c | ahmad-elkhawaldeh/ICS3U-Unit4-06-python | /rgb.py | 493 | 4.15625 | 4 | # !/usr/bin/env python3
# created by: Ahmad El-khawaldeh
# created on: Dec 2020
# this program is the "RGB code"
def main():
counter_number1 = 0
counter_number2 = 0
counter_number3 = 0
for counter_number1 in range(0, 256):
for counter_number2 in range(0, 256):
for counter_number3... |
e697beb5617d65fcd720a7e3e95d5e8ecb0e97e5 | R3tr093/Get-Started-Python3 | /Py/Bases/Variables.py | 1,278 | 4 | 4 | print (" Nous allons traiter des variables dans ce programme " )
print (" \n En python l'opérateur d'affection d'une valeur à une variable est = ")
print (" \n Donc pour déclarer une variable vous entrez le nom A, vous lui affectez une valeur = 4, A = 4 ")
print ( " \n Si on souhaite déclarer une valeur telle qu'u... |
74bc4bd83157888db9636d8d4939b92ce61811bc | James-Burgess/computerScience | /hyp/Python/hyp.py | 1,503 | 4.5 | 4 | #!/usr/bin/env python3
## before we get ahead of ourselves, lets look at how classes work:
class myClass(object):
# self.instance_variable = value #value specific to instance
# class_variable = value #value shared across all class instances
class_var = 10
def __init__(self, instance_var):
#i... |
d85ed0e113a22373e86c9190261e5eee7a849f60 | Kontowicz/Daily-coding-problem | /day_014.py | 302 | 3.734375 | 4 | # The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
import random
import math
inside = 0
for total in range(0, 1000):
tmp = math.hypot(random.random(), random.random())
if tmp < 1:
inside += 1
total += 1
print(4.0 * inside / total) |
cabb51a6020560e1a80fea35167b24c33b18303b | Ganeshbg/programs | /stack.py | 348 | 3.75 | 4 | class Stack:
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop(0)
def size(self):
return len(self.items)
s=Stack()
s.push(10)
s.push(20)
s.push(30)
print (s.pop())
print (s.p... |
d9bd03e6be142ead78aeaaa31cb9ff0948410d85 | MaxHenger/dse14-finding-venusian-volcanoes | /TrackAcceleratingOptimize.py | 18,928 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 6 23:03:22 2016
@author: MaxHenger
"""
import Atmosphere
import TrackAccelerating
import TrackCommon
import TrackBiasMap
import TrackAngleOfAttack
import TrackSettings
import numpy as np
import matplotlib.pyplot as plt
# OptimizeAccelerating is a piece of code that as... |
a198e8a56a906d02c4b66fb4f05ff683713d38fb | yagamiram/Leetcode_problems_in_python | /ugly_number.py | 920 | 4.3125 | 4 | import math
'''
This problem can be generalized to find all the prime factors of a number.
First step: In a while loop repeatedly divide the number by 2
Second step: After that the number would odd. From i - > 3 to the sqrt(n) increment by 2 (i+2 because to remain in odd all time)
find all the factors inside a while l... |
203a41ab575441bcc6b4d73f0b0223d18e9b6239 | sssouth/south | /判断字符串是否有效.py | 1,016 | 3.75 | 4 | strin=input("请输入只包括'(',')','[',']','{','}'的字符串:")
a_string=strin
if a_string.strip()=='':
print("%s是一个有效的字符串."%strin)
else:
if len(a_string)%2==1: #判断字符串的个数(奇数必无效)
print("%s是一个无效的字符串."%strin)
else:
for n in range(len(a_string)):
for i ... |
2d90fed207719a175e5bcec5ca66c332c5f959e2 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/09 LISTS BASICS - Дата 2-ри октомври, 1830 - 2130/05. Numbers Filter.py | 903 | 4.0625 | 4 | """
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#4
SUPyF2 Lists Basics Lab - 05. Numbers Filter
Problem:
You will receive a single number n. On the next n lines you will receive integers.
After that you will be given one of the following commands:
• even
• odd
•... |
51f4f6fa8168af3eeab536f610ff030b055e988c | tanacoto/week4-tsp | /solver_greedy_kmeans.py | 4,544 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
import math
import pprint
from common import print_solution, read_input, search_center
# データ加工・処理・分析ライブラリ
import numpy as np
import numpy.random as random
import scipy as sp
from pandas import Series, DataFrame
import pandas as pd
import math
# 可視化ライブラリ
import matplotlib.pyplot as ... |
eedeffb5ef5b8c2f0780f62fcf09be2d9dd536d9 | yurygnutov/hexlet | /solutions/count_smaller_elements_on_right_side.py | 435 | 3.640625 | 4 | __author__ = 'yury'
# For each element X of the given array, count how many elements to the right of X are smaller than X.
# The last value is always zero since there are no elements to the right of the last element.
# Example: [6,1,1,1,0,1,0] == solution([12,1,2,3,0,11,4])
def solution(sec):
result = []
for... |
3be72c84dbc9d194c40be1c3714e7b36273ef69e | Ryefalk/Project-Euler | /001 - Multiples of 3 and 5.py | 821 | 4.625 | 5 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def is_multiple (number, divisor):
"""
Checks if the number is a multiple of the divisor.
"""
if float(num... |
4fd65a252dcb715663dd35177b1a64ed27e512e6 | wandergram/datsci | /class5/pandas_homework_imdb.py | 5,644 | 4.03125 | 4 | '''
Pandas Homework with IMDB data
'''
'''
BASIC LEVEL
'''
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# imported to get rid of ascii encoding errors in movie names with special chars
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# read in 'imdb_1000.csv' and store it in a Da... |
6e0fba7c56216d7b2055df83251e32c3e1d48fca | appolimp/Education | /interview/test/dicts.py | 1,292 | 3.671875 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value # 1 символ от 'A' до 'Z'
from collections import defaultdict
set_nodes = defaultdict(list)
def calc_set(root):
k = {root.value}
size = 1
if root.left... |
927ca827a42ae35ef777d0f135139d72ae0b6924 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/ndxthr005/question4.py | 998 | 3.84375 | 4 | """thrianka naidoo
ndxthr005
assignment6, question4: program to sort marks and create diagram"""
marks = input("Enter a space-separated list of marks:\n")#input from user
marks_list = (marks.split(" ")) #splits string into a list
count1 =0 ... |
42d078ade056c6c284ae2ed539ab77604ca69011 | liangcyn/crazyeights | /crazy_eights.py | 2,978 | 4.03125 | 4 | import draw
import os
from game import Game
def crazy_eights():
startup_prompt()
def startup_prompt():
"""
Lists rules upon startup, prompts game.
"""
print()
draw.draw_centered('WELCOME TO CRAZY EIGHTS!', '-')
print('a quick rundown of the rules:')
print('\n\nGAMEPLAY:')
print('- each player is dealt fi... |
b66d94ba6bbdfc6c7af2bdf841a3cb3bbbd34890 | arnellja/PythonDataStructures | /BinaryRecursion/BinaryRecursion/BinaryRecursion.py | 491 | 3.78125 | 4 | lyst = [100,200, 300, 500, 500, 675, 800]
target = 675
def binary_search_recursion (lyst, target, low_point, high_point):
if (lyst[len(lyst)/2] > target):
return binary_search_recursion(lyst, target, low_point, len(lyst)/2)
elif (lyst[len(lyst)/2] < target):
return binary_search_recursio... |
331b58514b4b68474c19fc30c8a4d0251bb51619 | soulmatecm/iotadminapi | /apps/device/utils.py | 394 | 3.703125 | 4 | import random
def generate_random_string(length):
"""生成随机字符串
"""
raw = ''
range1 = range(58, 65) # between 0~9 and A~Z
range2 = range(91, 97) # between A~Z and a~z
i = 0
while i < length:
seed = random.randint(48, 122)
if seed in range1 or seed in range2:
cont... |
99be69355803d06a63d150839d819d17a72abf71 | hanksterhan/PasswordManager | /manager.py | 14,129 | 3.5 | 4 | #!/usr/bin/env python3
""" Command line interface for password manager
"""
import sys, getopt, random, string, os.path
import passwordmeter
from passlib.hash import pbkdf2_sha256
import pandas as pd
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
from Crypto.Util.strxor im... |
114ecd59c39552ae8a94d4aa7ab9d77e5d8ca2c2 | daniel-reich/turbo-robot | /ZuZn3E5auv2hDsc2X_15.py | 2,274 | 4.59375 | 5 | """
**SQL** is a great language on its own, but its functionality can be
empowered by **integrating** it into Python. For example, the `sqlite3`
library allows us to use Python **variables** in our databases, and to modify
tables during the runtime of a program.
_In previous challenges, you may have seen queries ... |
5f8616cd9fcf04f163d67fb528ff82492aedcb8a | alexovidiupopa/Fundamentals-of-Programming- | /A05-09/model/student.py | 1,598 | 4.15625 | 4 |
class Student(object):
'''
The class of an object of type Student
'''
def __init__(self, id,name, group,avgGrade = 0 ):
'''
student initalization. A student has an id (unique), a name, and a group, as specified in the requirements.
'''
self.__id = id
se... |
a44129f3a7ba67cc4d5796fd32f2021b1e0b8956 | tysonpaul89/django2-crud | /util/db.py | 851 | 3.546875 | 4 | def to_dict(cursor, result):
"""
Converts raw sql result which is a tuple into a dictionary
example:
from django.db import connection
from app.util.db import to_dict
sql = 'SELECT id, name FROM user'
cursor = connection.cursor()
result = cursor.execute(sql)
... |
077d146e753c81e9dba13748b54306fcdd9eb4b2 | Nikita-lys/Codewars | /6 kyu. Does my number look big in this?.py | 721 | 4.25 | 4 | # https://www.codewars.com/kata/does-my-number-look-big-in-this/
def narcissistic(n):
# return value == sum(int(x) ** len(str(value)) for x in str(value))
"""
A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number
of digits.
For example, tak... |
51cf9b1fdd55448a1b462dceda522cfd7fad6368 | poemusica/HackBright-whiteboarding | /CrackingCoding/crackingcoding.py | 2,245 | 3.765625 | 4 | # QUESTION 1
# Test if all chars in a string are unique.
# SOLUTION 1
def unique_dict(s):
d = {}
for char in s:
if d.get(char):
return False
d[char] = True
return True
# in this case, run-time is n^2
def unique(l):
for i in range(len(l)):
if l[i] in l[:i] or l[i] in l[i+1:]:
return False
return retur... |
c7807d6e29601abaa11e70ff208e8f40be220010 | GuillermoForero/competitive-programming | /CF-A/LightMoreLight.py | 324 | 3.5 | 4 | import math
import sys
while True:
bulbs = 0
try:
bulbs = int(sys.stdin.readline())
except EOFError:
pass
if bulbs == 0:
break
else:
square = math.floor(math.sqrt(bulbs))
if square * square == bulbs:
print('yes')
else:
print('... |
ce2664d85228974779b67dae735b430dd343d9a4 | eea76/python-misc-scripts | /easy list directory.py | 442 | 3.578125 | 4 | # sort -n "filepath" - This terminal command sorts the lines of a file numerically, smallest to largest
import os
outfile = open(r"/Users/elon/Desktop/files.txt", 'w', encoding='utf-8')
basepath = "/Users/elon/"
for dirpath, dirnames, filenames in os.walk(basepath):
for file in filenames:
fullpath = os.... |
7210fa022f8241c479f054cb7040139bc9eb4a81 | batbeerman/BOOK_DIRECTORY | /front.py | 5,686 | 3.59375 | 4 | from tkinter import *
import backend
def add_():
#Button for Adding Entry
backend.add(title_text.get(),
author_text.get(),
year_text.get(),
isbn_text.get())
listing.delete(0, END)
listing.insert(END,
(title_text.get(),
... |
426a46822c473da82570af7dddc7c65c6914ace1 | farukhpatel/Learning_Python | /First.py | 1,828 | 3.921875 | 4 | print("Hello python");
# casting in python
name=str("Farukh Patel")
roll_number=int(23)
percantage=float(7.78)
print("name "+name)
a_a="Farukh"
A="Farukh Patel"
print(a_a)
print(A)
# Assign multiple values
x,y=10,20
p1="Python is "
p2="Awesome"
p=p1+p2
print(p)
# p3=786
# p4="Awesome"
# p5=p3+p4
# print(p5) it gives ... |
da035d9c72b574c063a894f120ee4af5b7d55b77 | phttrang/MITx-6.00.1x | /Problem_Sets_2/Problem 1.py | 1,499 | 4.4375 | 4 | # Problem 1 - Paying Debt off in a Year
# (10/10 points)
# Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the
# credit card company each month.
# The following variables contain values as described below:
# balance - the outstanding ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.