blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dd1ab026e6a6ef01f05685a1d7527d45174859ad | jc486487/Assignment_1 | /songs_list.py | 7,634 | 4.375 | 4 | """Name: Sherin Sarah Varghese
Date: 20 April 2018
Brief program details: This program tracks the song file- songs.csv,
the user wishes to learn and songs they have learned.
It also allows the user to add songs to the file indicating
the title, art... |
bd12b15525f046c666930b62e4e548a9e569c18e | RobertSimion/SPN_encryption_and_decryption | /main.py | 1,940 | 3.609375 | 4 | import SPN
import random
def main():
# Getting clear-text from console ,consists in 4 bytes.
clearText = input("Enter cleartext made of 4 bytes:").split()
# Transforming it in a list of 4 bytes.
clearText = SPN.prepareClearText(clearText)
print("The clear-text is:",clearText)
# We have ind... |
4675094b0f6f4147c46c32617b6140560eec04ae | zerohk/python | /10_10count_the.py | 449 | 3.71875 | 4 | # -*- coding: GBK -*
def read_file(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Բļ" + filename + "ڣ"
print(msg)
else:
num = contents.lower().count("the")
print("ļ" + filename + "Уthe " +... |
cff49db583f1a259ae6a639d30a1bf1c0430fd7c | leiurus17/tp_python | /functions/function_var_length_args.py | 423 | 4.25 | 4 | #Function definition is here
def printinfo(arg1, *vartuple):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var + 1
return
# Now you can call printinfo function
first = 10
print first
printinfo(first)
second = (10, 20, 30, ... |
4c4979d1c1aa9d6a67e287ce292e6c4fe261dcec | zhangruochi/leetcode | /CXY_01_05/Solution.py | 1,456 | 3.71875 | 4 | """
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
示例 2:
输入:
first = "pales"
second = "pal"
输出: False
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/one-away-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def oneEd... |
cbb2f2430afec075b6de53d7a53975dde82a6e9d | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 4/Lista de Exercícios Adicionais 3/Adicional3Exercicio1-primalidade.py | 706 | 4.40625 | 4 | '''
Curso de Introdução à Ciência da Computação com Python Parte 1
Exercício Adicional 1
Escreva um programa que receba um número inteiro positivo na entrada e verifique se é primo. Se o número for primo, imprima "primo". Caso contrário, imprima "não primo".
Exemplos:
Digite um numero inteiro: 13
primo
Digite um n... |
62380439edcf4799d49dd471d65013bf7b7e86d2 | jnsong/Leetcode | /26. Remove Duplicates from Sorted Array.py | 239 | 3.578125 | 4 |
def removeDuplicates(nums):
if len(nums)==0:
return 0
s = 0
for j in range(1,len(nums)):
if nums[s]!=nums[j]:
s+=1
nums[s] = nums[j]
return s+1
result = removeDuplicates([1,1,2])
|
7a267e01f371947a1614dc34704e44d7dfe167b9 | vivek-gour/Python-Design-Patterns | /Patterns/Behavioral/memento.py | 1,249 | 3.5625 | 4 | __author__ = 'Vivek Gour'
__copyright__ = 'Copyright 2018, Vivek Gour'
__version__ = '1.0.0'
__maintainer__ = 'Vivek Gour'
__email__ = 'Viv30ek@gmail.com'
__status__ = 'Learning'
class Memento:
def __init__(self, file, content):
self.file = file
self.content = content
class FileWriterUtil:
d... |
ce2421a85ec76764c622c3353ae1a689f4185d8a | mariasilviamorlino/python_practice | /w3resource/integers_romans.py | 1,448 | 4 | 4 | """
from https://www.w3resource.com/python-exercises/class-exercises/
'write a Python class to convert an integer to a roman numeral'
strategy (integer to roman): left-pad the given integer (<3999) so it has 4 digits
transform every digit into its roman number equivalent"""
def left_pad(num):
num = str(num)
... |
34cfa198e488cb143351955d706d8a2e5c4666fa | hexycat/advent-of-code | /2022/python/11/main.py | 5,229 | 3.953125 | 4 | """Day 11: https://adventofcode.com/2022/day/11"""
from typing import Callable
class Monkey:
def __init__(
self,
items: list[int],
operation: Callable[[int], int],
test: Callable[[int], int],
divisor: int = 1,
) -> None:
self.items = items
self.operatio... |
33f5c7938cc8b0b3f1de8f10474adbf35220ba55 | ANASinfad/LP-python-Polygons | /polygons.py | 14,600 | 3.6875 | 4 | import math
from decimal import Decimal
from PIL import Image, ImageDraw
class ConvexPolygon:
# Constructora por defecto.
def __init__(self):
self.vertices = []
self.color = [0, 0, 0]
# Funcion Para imprimir los vértices del polígono
def printPolygon(self):
n = len(self.vert... |
81e5fbead11e13e118d165217e03276cdabfb341 | roger6blog/LeetCode | /SourceCode/Python/Problem/00219.Contains Duplicate II.py | 1,076 | 3.65625 | 4 | '''
Level: Easy Tag: [Array]
Given an integer array nums and an integer k,
return true if there are two distinct indices i and j in the array such that
nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Examp... |
62ab7c3a23cd760df76e84d3caadd34e90b451f7 | upasanapradhan/IW-Python-Assignment | /IW-PythonAssignment/22.py | 231 | 3.921875 | 4 | def remove_duplicates(my_list):
result = []
for i in my_list:
if i not in result:
result.append(i)
return result
list1 = [1, 2, 3, 4, 2, 1, 10, 15, 4, 10]
print(remove_duplicates(list1)) |
ba9442e4570a4c21b4add889048256a4a3ebe63d | Dombrauskas/Resources | /Python/Geradores/yield01.py | 875 | 4.5 | 4 | """
"
" Maurício Freire
" Geradores são funções que retornam um objeto por vez, de forma a ser possível
" iterá-los. Usar yield no lugar de return faz com que o método returne sem que
" ele seja encerrado.
" Generators are functions that return an object per time, thus it is possible
" to iterate them. Using ... |
93f070cc548d5f4f7dea8e1f1eb629350e4d76f4 | shivamnegi1705/Competitive-Programming | /Codeforces/Educational Round 102/B. String LCM.py | 333 | 3.921875 | 4 | # Question Link:- https://codeforces.com/contest/1473/problem/B
from math import gcd
def lcm(x,y):
return (x*y)//gcd(x,y)
for _ in range(int(input())):
a = input()
n = len(a)
b = input()
m = len(b)
l = lcm(n,m)
t1 = l//n
t2 = l//m
if a*t1 == b*t2:
print(a*t1)
else:
... |
a0a775b98ef711307e06580302ec834ed31d34e1 | wduan1025/python-intro | /lecture7/search_demo.py | 167 | 3.53125 | 4 | import re
s = "My name is John,I'm a software_engineer with 4.5 yrs exp,\nI have 112 projects on www.github.com"
pattern = r"I'm"
m = re.search(pattern, s)
print(m) |
cd4069b94c2ce3c78416412d4a70bec65da47735 | feliciahsieh/holbertonschool-webstack_basics | /0x01-python_basics/102-infinite_add.py | 411 | 3.640625 | 4 | #!/usr/bin/python3
""" 102-infinite_add.py - adds infinite-sized integers together """
import sys
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
if len(sys.argv) < 2:
print("0")
elif len(sys.argv) == 2:
print(sys.argv[1])
else:
sum = 0
... |
861850f7810812f12ce821c0687d62a38125dcab | AP-MI-2021/lab-2-ZarnescuBogdan | /main.py | 2,092 | 3.78125 | 4 | import math
def get_leap_years(start: int, end: int) -> list[int]:
list = []
for i in range(start, end + 1):
if i % 4 == 0:
list.append(i)
return list
def test_get_leap_years():
assert get_leap_years(2000, 2008) == [2000, 2004, 2008]
assert get_leap_years(2000, 2009) == [2000, ... |
dff3c4bb5cedf4954e42c6434e3a50afaf89e377 | sahana-s16/File-structures-mini-project-on-indexing | /add.py | 853 | 3.578125 | 4 | import indexingg
def add1():
ID1=input("Enter ID: \n")
with open(r"C:\Users\Aishu\Desktop\FS\NewCSv.csv", 'r') as myfile:
if ID1 in myfile.read():
print("Primary key already present!!")
else:
#name1=input("Enter ID: \n")
age1=input("Enter Casenumber:... |
6ef91a3e6c75d787b869bda2b92b3689774ce09a | AbhinavPelapudi/coding_challenges | /missingnums.py | 654 | 4.125 | 4 | def missing_number(lst, max_num):
"""Find the missing number in a list
Example::
>>> missing_number([2, 1, 4, 3, 6, 5, 7, 10, 9], 10)
8
"""
sorted_set = sorted(lst)
if sorted_set[0] != 1:
return 1
if sorted_set[-1] != max_num:
return max_num
missing_num = None
idx = 0
while idx < len(sorted_set) -... |
11a84809ac9c3479f9fb4aab5b95bab17e12bc17 | group4BCS1/BCS-2021 | /src/Chapter3/exercise2.py | 364 | 3.96875 | 4 | # Determining the pay using try and except
try:
hours = int(input("Enter Hours: \n "))
rate = int(input("Enter Rate: \n "))
if hours > 40 :
hours = hours - 40
pay = 40 * 10
pay = pay + ((hours * rate) * 1.5)
print(pay)
else:
pay = hours * rate
print(pay)
... |
6dc073ce027fd41249b1e313b9d11ad1f436e90d | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 09/capitulo 09/capitulo 09/exercicio-09-03.py | 2,063 | 4.25 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpres... |
a2e324bc31236c5363021e78b6605c4982d1b29c | PythonCHB/PythonIntroClass | /week-09/code/timing.py | 734 | 4.15625 | 4 | #!/usr/bin/env python
"""
timing example
"""
def primes_stupid(N):
"""
a really simple way to compute the first N prime numbers
"""
primes = [2]
i = 3
while len(primes) < N:
for j in range(2, i/2): # the "/2" is an optimization -- no point in checking even numbers
if not i ... |
9f51e668e9c5cafcda05c7175bc6a77942ceda8d | taariksiers/udemy-complete-python-bootcamp | /Lectures/Section3_Lecture15.py | 711 | 4.28125 | 4 | print("String Indexes")
print("---------------")
mystring = "Hello World"
print("Original: " + mystring)
print("Indices 0:" + mystring[0] + " | 6:" + mystring[6] + " | 9:" + mystring[9] + " | -3:" + mystring[-3])
print("\nString Slicing")
print("---------------")
mystring = "abcdefghijk"
# start index, stop index, ... |
5b0af1246b41298a3ccaaddb4c136001c747654b | lilitkhamalyan/loops | /loops.py | 296 | 4 | 4 | i = 0
# Get the number from the user
number = int(input("Enter a number from 1 to 20: "))
# Number should be [1, 20]
while not number in range (1, 21):
number = int(input("Error! Enter a number from 1 to 20: "))
# i < number, print i^2
while (i < number):
print(i ** 2)
i = i + 1
|
d4eff84cf57706405b20ca64395eb96f9e28e42b | hadismhd/PythonExercise | /Day1/greeting.py | 347 | 4.03125 | 4 | # Set the variable called greeting to some greeting, e.g. "hello".
# Set the variable called name to some name, e.g. "Heisenberg".
# Then set the variable called greet_name that that concatenates greeting , name , and a space " " between them.
greeting = "Hello"
name = "Hadis"
greet_name = (greeting + " " + nam... |
9bc9df29c1f08aff1deecd159f2f287c8fc8d2ca | subham73/fcc-P-Q-A | /CH-06.py | 470 | 4.3125 | 4 | #Exercise 5:
#Take the following Python code that stores a string:
#str = 'X-DSPAM-Confidence:0.8475'
#Use find and string slicing to extract the portion of the string after the
#colon character and then use the float function to convert the extracted
#string into a floating point number
##############
#solution:-
s... |
2e149ed04060ee1c9f3f9e3cba20c23a267faa0f | kanisan007/testgame_kanisan007 | /kiekie.py | 1,473 | 3.5 | 4 | def printsquaresstatus(squarestatus: list):
squareinfo = []
for i in range(9):
if squarestatus[i] == 0:
squareinfo.append(' ')
elif squarestatus[i] == 1:
squareinfo.append('〇')
elif squarestatus[i] == 2:
squareinfo.append('×')
else:
... |
2e31f289de983664d0788d14960d9ed73a8b5e71 | RetamalVictor/Data_Structures_and_algorithms | /Array_based_sequences/arrays_based.py | 2,072 | 3.71875 | 4 |
class Dynamic_Array():
def __init__(self):
self._number_of_items = 0
self._data = [None]
def __len__(self):
return self._number_of_items
def is_valid_index(self, index):
if not 0 <= index < self._number_of_items:
raise IndexError
def __getitem__(self, in... |
1225ff6ddddc54a2879954c65c562d89c5e1bcfd | Pedromoisescamacho/python-mega-course | /lesson 1-5/ageplus50.py | 482 | 4.125 | 4 | #this is the way that we integrate user input into a function
#creating the function
def age_plus_50():
while True:
try:
age = int(input("please enter a age: "))
if 0 < age <= 150:
print(age + 50)
break
else:
print("please e... |
b955651e8321c877eff492ea6d546ee0211f99a6 | briworkman/Graphs | /projects/ancestor/ancestor.py | 2,355 | 3.78125 | 4 | # class Stack():
# def __init__(self):
# self.stack = []
# def push(self, value):
# self.stack.append(value)
# def pop(self):
# if self.size() > 0:
# return self.stack.pop()
# else:
# return None
# def size(self):
# return len(self.stack... |
e1d775146fbf51104f8467794eb09da75b298b36 | jlaframboise/Calculator | /Calc10.py | 8,813 | 4.0625 | 4 | #Calculator10.py
#Jacob Laframboise March 6, 2017
#A calculator which can take an expression involving addition, subtraction, multiplication, division, exponents, and brackets with positive and negative numbers
#Code to quickly run program with a constant input instead of getting user input
#input1='(-17)+(44/6*1... |
009f18767ac8789ff537b98f0795114f7e98504c | srlm89/portfolio | /python/meta-circular-lisp/meta_circular_lisp/parser.py | 2,311 | 3.53125 | 4 | def atom(token):
try: return int(token)
except ValueError:
try: return float(token)
except ValueError:
return str(token)
def tokenize(line):
pairs = 0
opens = []
line = line.strip()
tokens = line.replace('(', ' ( ').replace(')', ' ) ').split()
for i in range(len... |
2d5752f02d782c75f66e30531185a83690448cae | danielhac/python_practice_epi | /string/is_planindromic.py | 543 | 4.03125 | 4 | # A palindromic string is one which reads the same when it is reversed.
# Checks if string is palindromic
# s[~i] is s[-(i + 1)], which is the the opposite elem as s[i]
# all(): returns true if all is true
def is_palindromic(s):
return all(s[i] == s[~i] for i in range(len(s) // 2))
# Longer version, but same as... |
2286187b77335399bc0304c4312898b404d809bc | akonon/pbhw | /06/hw5_solution.py | 959 | 4 | 4 | # -*- coding: utf-8 -*-
class Person(object):
"""Represents an entry in a contact list"""
def __init__(self, surname, first_name, birth_date, nickname=None):
from datetime import datetime
self.surname = surname
self.first_name = first_name
self.birth_date = datetime.strptime(b... |
9ed57079e1b9196f62dedde9b64564c04ddf4d17 | MadSkittles/leetcode | /23.py | 811 | 3.75 | 4 | from common import ListNode
class Solution:
def mergeKLists(self, lists):
head = tail = None
while True:
min_, index = float('inf'), -1
for i, p in enumerate(lists):
if p and p.val < min_:
index, min_ = i, p.val
if index < 0:
... |
649a1d32b5ea68f68e86a1edc2dac9f67282fcb7 | vivekm56/CodeSnippets | /Object-Oriented/Class-Static-Methods/oop.py | 1,601 | 3.78125 | 4 | class Employee:
numOfEmployees = 0
raiseAmount = 1.04
def __init__(self, firstName, lastName, salary):
self.firstName = firstName
self.lastName = lastName
self.salary = salary
self.mailId = (firstName + lastName + '@company.com').lower()
Employee.num... |
16d8d80f2cf806246e52845ff052f643569ebd15 | pdhhiep/Computation_using_Python | /fem1d_heat_explicit/basis_function.py | 1,564 | 3.859375 | 4 | #! /usr/bin/env python
def basis_function ( index, element, node_x, point_x ):
#*****************************************************************************80
#
## BASIS_FUNCTION evaluates a basis function.
#
# Discussion:
#
# Piecewise linear basis functions are used.
#
# Basis functions are associated with ... |
80e78ca00e83ed75247aa1817143b351fbf0b527 | BauerJustin/Elements-of-Programming-Interviews-in-Python | /Ch.7 Linked Lists/7.4 Overlap/overlap.py | 735 | 3.9375 | 4 | #code
def is_overlap(L1, L2):
temp = []
while L1:
temp.append(L1)
L1 = L1.next
while L2:
if L2 in temp:
return L2
L2 = L2.next
return None
# Linked list classes and base code
class ListNode:
def __init__(self,data=0,next_node=None):
self.data = da... |
46b3cf3016b30bcc4e3d8c0a0ff1b11930d64b96 | IEEE-CS-TXST/checkers | /checkers.py | 3,250 | 3.765625 | 4 |
class Board:
def __init__(self):
#initialize 2d array populated by 'None' in all fields
self.board = [[None for i in range(8)] for j in range(8)]
#spots where red pieces start
self.startRed = [(0,1), (0,3), (0,5), (0,7), (1,0),
(1,2), (1,4), (1,6), (2,1), (2,3) , (2,5) , (2,7)]
#spots where black piece... |
180f7b619063edfaf300c214f3788d0d724725ee | aitiwa/pythonTraining | /m3_3_whileBreakTest_001.py | 989 | 3.890625 | 4 | print("Section001 알고리즘-1에서 100까지중 입력받은 수까지 합계")
print("m3_3_whileLoopIfBreakTest_001.py")
print()
print("1. count, sum, limit 변수 선언과 초기화: ")
print(" count = 0 ")
print(" sum = 0 ")
count = 0
sum = 0
print("2. 사용자로부터 limit 변수의 input값을 받는다.")
print(' limit = int(input("어디까지 더할까요? :"))')
limit = int(input(" ... |
61b252d3fa9e86a83230b3e371f1b8a8df686065 | Jenychen1996/Basic-Python-FishC.com | /Living_example/Narcissus.py | 754 | 3.8125 | 4 | # -*- coding:utf-8 -*-
def Narcissus1():
'小甲鱼方法'
for each in range(100, 1000):
temp = each
sum = 0
while temp:
# 第一次sum = 0 + 个位数 ** 3 ; temp = 除个位数
# 第二次sum = 个位数 ** 3 + 十位数 ** 3 ; temp = 百位数
# 第三次sum = 个位数 ** 3 + 十位数 ** 3 + 百位数 ** 3 ; temp
... |
732052be15e3b19cd6593a91ae40ee331890385d | murali-kotakonda/PythonProgs | /PythonBasics1/functions/Ex3.py | 431 | 3.796875 | 4 | """
write a function that performs sum of two nums.
"""
def sum(x,y):
res = x+y
print("sum = ", res)
#call the function
sum(10,20)
sum(80,20)
sum(180,220)
sum(12.1313,131313.2424)
n1 = 90
n2= 30
sum(n1,n2)
"""
local variable:
variable created inside the function
global variable:
variable cre... |
68fbf8108a9879a7119844ab8af0f42cf0209d26 | sgenduso/python-practice | /src/datetime_methods.py | 418 | 3.65625 | 4 | # import datetime library
from datetime import datetime
now = datetime.now()
print now # 2016-04-25 18:27:59.145463
print now.year # 2016
print now.month # 4
print now.day # 25
print '%s/%s/%s' % (now.month, now.day, now.year) # 4/25/2016
print '%s:%s:%s' % (now.hour, now.minute, now.second) # 18:27:59
print '%s/%s/%s ... |
521e2470eaf8e33dd3bc12d59df06569dfc1cc61 | colephalen/SP_2019_210A_classroom | /students/GKim/lesson04/mailroom2.py | 6,185 | 3.5 | 4 | #!/usr/bin/env python
from textwrap import dedent
import sys, os
main_donors = [
{"name": "Luke Skywalker", "donations": [100.25, 200.55, 50]},
{"name": "Han Solo", "donations": [100.80, 50.99, 600]},
{"name": "Yoda", "donations": [1000.01, 50, 600.55, 200.47]},
{"name": "Ben... |
7e10f9f91560ebcc5ab920e9f0eb4f84dc3cf9cb | ankitk2109/LeetCode | /12. AddTwoNumbers(linkedlist).py | 1,804 | 3.65625 | 4 | #Problem Statement available at: https://leetcode.com/problems/add-two-numbers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def createNode(self, val, current, carry):
if(val>9):
r = val % 10... |
df7fc5374c7df10b93058a0b39736ee5ee127687 | St3h/Exercicios-Python | /Semana4/fatorial.py | 160 | 3.90625 | 4 | num = int(input('Digite o valor de n: '))
multiplier = 1
result = 1
while multiplier <= num:
result = result * multiplier
multiplier += 1
print(result) |
68b2acf05cbba703ca1ae9534442f658eca4c4ef | wanghaoListening/python-study-demo | /day-exe/day07-8.py | 949 | 4 | 4 | """
子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override)。通过方法重写我们可以让父类的同
一个行为在子类中拥有不同的实现版本,当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,这个就是多态(poly-morphism)。
"""
from abc import ABCMeta,abstractmethod
class Pet(object,metaclass=ABCMeta):
def __init__(self,nickname):
self._nickname = nickname
@abstractmetho... |
83655259168152059dba174b75ea8f6f61ae7260 | preetgur/python | /Oop9.py | 1,580 | 4.09375 | 4 | # super() and overriding
# class varible is override by "instance varible "
class A:
classvar1 = "I am a class variable in class A"
def __init__(self):
self.var1 ="I am inside class A's constructor"
self.special ="This is special instance variable used with the help of super().__init__"
... |
4fac2c14a49b47449fc69dc9a007050e73c005c6 | htg30599/SS1 | /HW/w3/bubble_sort.py | 331 | 3.59375 | 4 | def bubbleSort(nlist):
for passnum in range(len(nlist) - 1, 0, -1):
for i in range(passnum):
if nlist[i] > nlist[i + 1]:
temp = nlist[i]
nlist[i] = nlist[i + 1]
nlist[i + 1] = temp
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
bubbleSort(nlist)
pr... |
f515ad7fa11571f9bff156893b4a7a0d9b442d2e | syurskyi/Algorithms_and_Data_Structure | /Python for Data Structures Algorithms/src/12 Array Sequences/Array Sequences Interview Questions/PRACTICE/Largest Continuous Sum .py | 1,180 | 3.953125 | 4 | # %%
'''
# Largest Continuous Sum
## Problem
Given an array of integers (positive and negative) find the largest continuous sum.
## Solution
Fill out your solution below:
'''
# %%
def large_cont_sum(arr):
if len(arr) == 0:
return 0
max_num = sum = arr[0]# max=sum=arr[0] bug: TypeError: 'int' objec... |
d3f93cde28a6d571a4553bf8134c77286a03c180 | skk4/python_study | /src/network/ex40submit_get.py | 983 | 3.515625 | 4 | '''
Created on 2017.7.21
@author: Administrator
'''
import sys, urllib2, urllib
def addgetdata(url, data):
'''Adds data to url. Data should be a list or tuple consisting of 2-item
lists or tuples of the form :(key, value)
Items that have no key should key set to None.
A given... |
f8550fa835a9b68cef0b12cface5dd6694791230 | hlywp8/PythonDemo | /dataStructure.py | 702 | 3.59375 | 4 | shoplist=['mango','banana','apple']
for i in shoplist:
print(i,end=',')
shoplist.append('rice')
shoplist.sort()
print(shoplist)
del shoplist[0]
print(shoplist)
zoo=('wolf','elephant','penguin')
new_zoo=('monkey','dolphin',zoo)
print('%s is last'%new_zoo[2][2])
ab={'tom':'tom1','jerry':'jerry1','lily':'lily1'}
ab[... |
fb8809bbb36ae61f46a3bf30c25e67da1c7e7666 | shesan/Python-Projects | /CodingQuestions/1021.py | 507 | 3.65625 | 4 | # 1021. Remove Outermost Parentheses
class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
pos = 0
result = ""
for c in S:
if c == ")":
pos -= 1
if pos:
... |
9b18821a8179f08cd68549de348b22bc7be87e07 | st2013hk/pylab | /chatbot/chat1.py | 1,190 | 3.609375 | 4 | from chatterbot import ChatBot
chatbot = ChatBot("hellochatbot")
# from chatterbot.trainers import ListTrainer
# conversation = [
# "Hello",
# "Hi there!",
# "How are you doing?",
# "I'm doing great.",
# "That is good to hear",
# "Thank you.",
# "You're welcome."
# ]
#
# chatbot.set_trainer... |
1189038656cea30682826e72d6e33cf5c7f31718 | uu64/project-euler | /problem035.py | 840 | 3.5625 | 4 | #!/usr/bin/env python3
def sieve(limit):
is_prime = [True for _ in range(limit)]
# primes = []
is_prime[0] = is_prime[1] = False
for i in range(2, len(is_prime)):
if is_prime[i]:
# primes.append(i)
for j in range(i*2, len(is_prime), i):
is_prime[j] = Fal... |
d911232e91dc886d7f33f07e3ab2d1b73cd9c76a | eterne92/COMP9021 | /assignment/assignment_1/quiz_4.py | 3,317 | 3.828125 | 4 | from random import randint
import sys
poker2dice = {
'Ace':0,'King':1,'Queen':2,'Jack':3,'10':4,'9':5
}
dice2poker = ['Ace','King','Queen','Jack','10','9']
def check_hand(dices):
check = [0] * 6
for dice in dices:
check[dice] += 1
if max(check) == 5:
return 'Five of a kind'
elif m... |
c08eedbb71547315df10e2b27a17e2083dbf728a | cosmicTabulator/python_code | /Graham - Week 3 HW.py | 1,043 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 30 11:03:54 2016
@author: Graham Cooke
"""
#Website to be anaylyzed
website = "example.site.domain/main/home"
#stores the location of the most recently found slash
#-1 is a placholder to indicate that no slash has been found
slash = -1
#main loop
#sets the range of inde... |
973995e9258f0053c96a8ec8447a4cf8a65d5d9c | vemanand/pythonprograms | /general/sets1.py | 738 | 4.3125 | 4 | '''
Sample program to demonstrate different SET operations
Python offers a datatype called set whose elements must be unique. Set must be declared using curly/flower brackets
It can be used to perform different set operations like union, intersection, difference and symmetric difference.
'''
# define two sample sets
S... |
d59acab76690ed543c5d9a775f3621c5433fca08 | namratarane20/python | /algorithm/insertionword.py | 510 | 4.21875 | 4 | #this program is used to load the file and read the values and perform insertion sorting of the values
from data import main
try:
file = open('wordlist','r') # opening the file
str_ = file.read() # read the text and storing in object
split_array = str... |
68d5535267725c58a26271957f4569859c93a968 | Danieltech99/CS-222-Final-Project | /helpers/fiedler.py | 2,116 | 3.625 | 4 | import numpy as np
# return the Fiedler value to show strong connection of the array
def fiedler(adj_mat):
'''
Return the fiedler value, the second smallest
eigenvalue of the Laplacian.
Done by constructing a degree matrix from the
adjacency matrix and calculating the Laplacian
and its eigenva... |
2b5a05626c732d22186e1e45d69cfbce8138af15 | citatricahayas/Cita-Tri-Cahaya-Sakti_I0320020_Aditya-Mahendra_Tugas4 | /I0320020_exercise4.1.py | 253 | 3.75 | 4 | x = 28
y = 2
#Output x+y = 30
print("x+y = ", x+y)
#Output x-y = 26
print("x-y = ", x-y)
#Output x*y = 56
print("x*y = ", x*y)
#Output x/y = 14
print("x/y = ", x/y)
#Output x//y = 14
print("x//y = ", x//y)
#Output x**y = 784
print("x**y = ", x**y) |
da3f5536bf1f9d127019ccb1835ca41ad4a1fc90 | zarbod/Python-labs | /fourth.py | 101 | 4.25 | 4 | radius = float(input("Enter radius: "))
print("Area of the Circle is: " + str(3.14*radius*radius)) |
eb09354142758498019b15b7b8dca5c217cb8b72 | BorjaCuevas/PuzzleSolver | /Core/piece.py | 369 | 3.53125 | 4 | """ Piece class """
class Piece:
def __init__(self, key, sideA, sideB, sideC, sideD):
self.key = key
self.sideA = sideA
self.sideB = sideB
self.sideC = sideC
self.sideD = sideD
def rotate(self):
"""
Rotate the piece to make easy to look for restriction... |
9acb21fdedec85175de70604ea0de7f5b0c23cc9 | narennandi/interview-cake | /sorting_searching_logarithms.py | 1,242 | 3.96875 | 4 | def binary_search(nums, target):
low = 0
high = len(nums) -1
while low <= high:
mid = (high + low) // 2
if nums[mid] == target:
return mid
elif target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return "Target no... |
bee39ef20702db94f7bb22922067051ed702fccc | BAFurtado/Python4ABMIpea2019 | /for_loop.py | 198 | 4.0625 | 4 |
# for i in 'hello':
# print(i)
#
# for i in range(5):
# # print(i)
#
# a = 'hi, my name is Bernardo'
# for i in a.split(' '):
# print('pa' + i)
for i in range(5):
print(i.upper()) |
3f2d5148f6c94b76897b654959805ab382364def | zefaradi/Coding-Challenges-from-codewars.com | /Human Readable Time.py | 790 | 4.03125 | 4 | # Human Readable Time
# Description:
# Write a function, which takes a non-negative integer (seconds) as input and
# returns the time in a human-readable format (HH:MM:SS)
# HH = hours, padded to 2 digits, range: 00 - 99
# MM = minutes, padded to 2 digits, range: 00 - 59
# SS = seconds, padded to 2 digits, ra... |
b8eab53f165858c45015f5103bfc6af109e8f43a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2662/60898/317192.py | 359 | 3.765625 | 4 | def intToBi(x):
temp=""
while(x>1):
temp=str(x%2)+temp
x=x//2
temp=str(x)+temp
return temp
t=eval(input())
for i in range(0,t):
x=eval(input())
str1=intToBi(x)
cnt=0
for j in range(0,len(str1)):
if str1[j]=='1':
cnt+=1
if(cnt%2!=0):
print(... |
2b3985a018d793cc3c12022250313a8904d8d9f7 | alinbabu2010/Python-programs | /calculator.py | 770 | 3.734375 | 4 | import math
def add():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a+b
print("Sum is {}").format(c)
def sub():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a-b
print("Difference is {}").format(c)
def pro():
a,b=map(int,raw_input("Enter the two numbers... |
f829ac02ab839a3e48575e60b4bae0b6ae5342fa | ChinaChenp/Knowledge | /learncode/python/tuple.py | 229 | 3.53125 | 4 | dimensions = (200, 50, 200, 300, 412)
for dimension in dimensions:
print(dimension)
dimensions = (1, 2, 5, 1, 7, 8)
print(dimensions)
#可以是不同类型
tuples = ("a", 1, 5, "fdjs", "9", 6)
for v in tuples:
print(v) |
df3e432546842bd21ad5206438785d9d7d6a857a | ProgmanZ/Modul-15.5-Tasks--HW- | /Task-07.py | 1,179 | 3.65625 | 4 | # Задача 7. Контейнеры
def weight_input(dialog):
while True:
print(dialog, end='')
weight_container = int(input())
if 200 >= weight_container > 0:
break
else:
print("Ошибка. Вес контейнера не может превышать 200 кг.")
return weight_container
def search_... |
38d5fee05736012c35f4ea576bb94a32186b5ebd | aaronrambhajan/sunshine-list-analyzer | /main.py | 1,653 | 3.90625 | 4 | import functions
print('This program calculates the average salary increase of all UofT \
employees on the Sunshine List who were employed between two given years, \
ranging 2006 to 2016. The Sunshine List includes public sector employees \
with salaries in excess of $100k.')
answer = 'yes'
while answer.lower() == '... |
576ed152dc496c6c604581873157a17e518f6d40 | ridvanaltun/project-euler-solutions | /040/040.py | 790 | 3.859375 | 4 | """
While döngüsü kurup kontrol ifadesi koyabilirdim ancak her seferinde
kontrol ifadesi programı ~2 kat yavaşlatacaktır.
Bu yüzden aşağıdaki hesabı yaptım.
(9 * 1) + (99 * 2) + (999 * 3) +
(9999 * 4) + (99999 * 5) + (76135 * 6) = 1000005
Yani döngü toplamda 9 + 99 + 999 + 9999 + 99999 + 76135 kez döndüğünde
1000005... |
cc65c69b2cabb47eaef5079fa600dd6e2ed00b47 | Iftakharpy/Data-Structures-Algorithms | /section 10 implementaion_of_Binary_Tree_with_Node.py | 1,738 | 3.890625 | 4 | class Node:
def __init__(self,value):
self.value = value
self.high = None
self.low = None
def __repr__(self):
return f'[value:{self.value},\nhigh:{self.high},low:{self.low}]'
class Binary_Tree:
def __init__(self,value=None):
if value==None:
self.root = N... |
7c5b7266b8cbc35f27dd7ef69f98624a9e7b23a2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3985/codes/1592_2425.py | 67 | 3.546875 | 4 | a= float(input())
b= float(input())
c= a/b
print(round(c,3),"km/l") |
66a47167c2401ff04917df9ba595062b587a6643 | kih1024/codingStudy | /(삼성,시뮬)주사위굴리기.py | 1,350 | 3.546875 | 4 | def move(li):
temp = li[-1]
li[1:] = li[0:3]
li[0] = temp
def rotate(d):
# 오른쪽으로 돌릴때
if d == 0:
li = [dice[0], dice[2], dice[5], dice[3]]
move(li)
dice[0], dice[2], dice[5], dice[3] = [i for i in li]
# 왼쪽으로 돌릴때
elif d == 1:
li = [dice[0], dice[3], dice[5], d... |
81ce564bb048503047157725590a9fa8fcd75ce2 | j2sdk408/misc | /mooc/algorithms_II/graph_process.py | 1,146 | 3.90625 | 4 | """
implementation of graph algorithms
"""
from graph import Graph
class GraphProcess(object):
"""class for graph processing"""
@staticmethod
def degree(G, v):
"""compute the degree of v"""
return len(G.adj(v))
@staticmethod
def max_degree(G):
"""compute maximum degree"... |
99bc910a9d1b6ed412b05b73da75f01af01ec92c | baloooo/coding_practice | /top_k_frequent.py | 1,261 | 4.03125 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
'''
class ... |
4a94e296f7ffce5292df94946a0f6605f779e5ac | wkddngus5/data-structure-python | /sorting/bubble-sort/index.py | 2,373 | 4.65625 | 5 | import unittest
# Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an array with n number of elements.
# Bubble Sort compares all the element one by one and sort them based on their values.
# If the given array has to be sorted in ascending order,
# then bubble sor... |
844e7f340d023a46706da4b951bc531fb5c4ec80 | Alf0nso/NN-Games | /NN/nn_tic_tac_toe.py | 1,533 | 3.921875 | 4 | # Training of Tic tac toe
#
# @Author: Afonso Rafael & Renata
#
# Train the neural network on
# tic tac toe games and observe how it
# performs!
import neural_net as nn
import numpy as np
import utils as ut
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.met... |
56037bd446e10089f8fb2ffb7b804c0dde08599c | Hamza-Ejaz/Python | /Assignment 3/max_no._of_list.py | 80 | 3.5 | 4 | list1 = [9,7,6,4,16,29,13,20,43,36,11,52,47,19,]
list1.sort()
print(list1[-1]) |
140d1ece0346562e78b8c5aab70004f94da21316 | Dorrro/PythonPlayground | /PythonPlayground/zaj2/4.py | 620 | 3.78125 | 4 | import random
words = ["jeden", "dwa", "dom", "test"]
word = random.choice(words)
step = 1
guess = ""
print("W słowie znajduje się " + str(len(word)) + " liter")
while step <= 5 and guess != word:
letter = input("Podaj literę, która może istnieć w słowie: ")
if len(letter) != 1:
print("Litera ma ty... |
6e352f8b76bc17768bbc6227fc03cbe594cd7f22 | marlonsd/FerrIA-Robots | /player.py | 10,950 | 3.65625 | 4 | """
Based on Paul Vincent Craven code
http://simpson.edu/author/pcraven-2/
"""
import pygame, abc, sys
import numpy as np
from objects import Base, Mine, Wall
# Colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
RED = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
YELLOW =... |
eff5f158a3bf7b335b257b2322f1b1f94b4bb2d4 | amarschn/VOT_2014_Tracking_Challenge | /utilities.py | 2,333 | 3.640625 | 4 | #!/usr/bin/env python
"""
Utilities
===========
This module contains multiple utility functions:
get_jpeg => will load jpeg images and return them as an array.
plot_pixel_position => will plot pixel location given an array.
rect_resize => will resize a rectangle given an array of points.
"""
import cv2
import os
im... |
4f4aefd5d67caec1e912f9fb806a282114e74335 | Sk0uF/Algorithms | /py_algo/arrays_strings/string_manipulation/terrible_chandu.py | 579 | 3.671875 | 4 | """
Codemonk link: https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/terrible-chandu/
Reverse the given string.
Input - Output:
The first contains the number of test cases.
Each of the next T lines contains a single string S.
Sample in... |
7cc059a69d5719d3909cf0d98f98e5e6d07d5d3d | namanj401/A-Z-ML | /Regression/Polynomial Regression/polynomial regression.py | 884 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset= pd.read_csv('Regression\Polynomial Regression\Position_Salaries.csv')
X=dataset.iloc[:,1:-1].values
y=dataset.iloc[:,-1].values
from sklearn.linear_model import LinearRegression
lin_reg=LinearRegression()
lin_reg.fit(X,y)
from sklearn.pr... |
6a4603a0cbf46fec268bcb2f6b25fb6577ae7296 | Escartin85/scriptsPy | /calculation_marks_university/final_average_RISK.py | 1,154 | 3.609375 | 4 |
def conversionLetterToScore(subMark_letter):
if (subMark_letter == "F3"): return 0
if (subMark_letter == "F2"): return 23
if (subMark_letter == "F1"): return 37
if (subMark_letter == "D"): return 43
if (subMark_letter == "D+"): return 47
if (subMark_letter == "C"): return 53
if (subMark_let... |
80b24bada743deccd58825714e1cda753547eb0d | Sriram-Reddyy/Leetcode_solutions | /787.Cheapest Flights Within K Stops.py | 1,307 | 3.578125 | 4 | """
787. Cheapest Flights Within K Stops
Medium
There are n cities connected by m flights. Each flight starts from city u
and arrives at v with a price w. Now given all the cities and flights, together
with starting city src and the destination dst, your task is to find the cheapest
price from src to dst with up ... |
8544cabefdb473d9b80b5db7ff68d041652a0cf4 | wlsdhr477/OpenCollegePythonWebProject | /OC_1112/whlieroof.py | 898 | 3.703125 | 4 | sum=0
n=0
while n<11:
sum=sum+n
n=n+1
print(sum)
print(n)
#break 여기까지 처리하겠다./continue이번 처리는 Skip하고 그 다음 처리 반복
n=0
while n<10:
n = n + 1
if n==3:
continue
print("현재 n은" + str(n) + "입니다.")
if n==5:
break
print("현재 n은 " + str(n) + "입니다.")
#List Comprehension
#특정 List에 대한 조작을... |
c589edbbd471915928918ae3b7aaa4d27a2028e4 | PCA1610/Smartninja | /Uebung07/variables.py | 316 | 3.921875 | 4 | a = int(input("Gib eine Zahl ein: "))
b = int(input("Gib eine zweite Zahl ein: "))
o = input("Choose your opperator: + - / *: ")
c = True
if o == "+":
if c:
print(a + b)
elif o == "-":
print(a - b)
elif o == "/":
print(a / b)
elif o == "*":
print(a * b)
else:
print("Falscher Operator") |
c9d619c34324b198ef83213af5585eb361f93fbb | gauraviitp/python-programs | /Threading.py | 502 | 3.640625 | 4 | import threading
# Below code simulates printing in tandem.
#
semA = threading.Semaphore()
semB = threading.Semaphore()
semB.acquire()
def fooA():
count = 20
while count >= 0:
semA.acquire()
print('A')
semB.release()
count -= 1
def fooB():
count = 20
while count >... |
fde879c8ff95b2a3890e0a4d6b75bdae24620bf8 | GuilleCulebras/X-Serv-13.6-Calculadora | /calc.py | 609 | 3.59375 | 4 | #!/usr/bin/python3
import sys
NUM_VALORES= 4 #constantes definirlas con mayusculas
if len(sys.argv) != NUM_VALORES:
sys.exit("Usage: python3 calc.py operacion operando1 operando2")
funcion= sys.argv[1]
try:
op1 = float(sys.argv[2])
op2 = float(sys.argv[3])
except ValueError:
sys.exit("Los operandos han de ser f... |
fd75f53549a2753003423152a4d4d9cfd92eb4b6 | taraszubachyk/homework | /Task2.py | 438 | 4.3125 | 4 | #Task2
#Output question “What is your name?“, “How old are you?“, Where do you live?“.
# Read the answer of user and output next information: “Hello, (answer(name))“, “Your age is (answer(age))“, “You live in (answer(city))“
name = input("What is your name: ")
age = int(input("How old are you: "))
location =input("... |
1bff468db3cc6e58e79b2cbe70f7c6fce9bf66d3 | hyc121110/LeetCodeProblems | /String/lengthOfLongestSubstring.py | 832 | 3.984375 | 4 | '''
Given a string, find the length of the longest substring without repeating characters.
'''
def lengthOfLongestSubstring(s):
# 2 pointers: pointer scan from left to right, pointer record first
# character
if len(s) == 0: return 0
# stores index of char's first occurence
dict = {}
start... |
7381be9f357956721ce144b1d311532dc4b50dbe | Mishakaveli1994/Python_Fundamentals_Jan | /Lists_Basic_Excercises/1_Invert_Values.py | 320 | 3.734375 | 4 | number = input()
number_sep = number.split(' ')
for i in range(len(number_sep)):
if int(number_sep[i]) < 0:
number_sep[i] = abs(int(number_sep[i]))
elif int(number_sep[i]) > 0:
number_sep[i] = int(number_sep[i]) * -1
elif int(number_sep[i]) == 0:
number_sep[i] = 0
print(number_sep)
|
5262e7f48d3f369d974226932fb92a68d73c0b98 | Ozyman/LearnPython | /5/lesson5-reading.py | 1,522 | 4.40625 | 4 | # Read this code, and try to understand what will happen when you run it, then run the code and see if you were correct.
# If you didn't predict it correctly, review the code to identify your misunderstanding.
correct_guess = 42
guess = input("Guess a number between 1 and 100: ")
# The input() function always return... |
eb2bed84b6577dae54c07a2fedb6eadf0e3939e3 | Diniz-G/Minicurso_Python | /minicurso_python/strings2.py | 499 | 3.9375 | 4 | a = "Gabriel"
b = "Diniz"
concat = a + " " + b + "\n"
print(concat)
print(concat.lower())
print(concat.upper())
print(concat.strip()) #remove o "\n"
#######################################
my_string = "O rato roeu a roupa..."
my_list = my_string.split() #separa em strings a cada " "
#ou passa-se como argumento em qua... |
667a78368e07842ecd89fa33e8ad8501b8e7f3b0 | Usherwood/usherwood_ds | /usherwood_ds/tools/topic_wordclouds.py | 2,692 | 3.9375 | 4 | #!/usr/bin/env python
"""Creating wordclouds for pandas series of text records"""
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
__author__ = "Peter J Usherwood"
__python_version__ = "3.5"
class Visualizer:
"""
Creates a class to wrap around WordCloud
"""
def _... |
17a966127b416fa167c405a5740c843a4f804c80 | Matt41531/Chuck_A_Luck_Dice_Game | /program3.py | 7,474 | 4.0625 | 4 | from graphics import *
from random import *
def draw_dice(x,y,dienum,win):
'''
Purpose: draw a dice image on the screen at the location given, using
the corresponding gif file
Pre-conditions: (int) x and y of location, (int) number of the die,
(GraphWin) graphics window
Post-conditio... |
01f143333a0157925a9dd77a4029cbf3fc68838c | yaoguoliang92/demo | /WebContent/python/xiao-jia-yu/20han-shu-quanju-bianliang.py | 382 | 3.59375 | 4 | def func():
global count #变为全局
count =10
print(10)
def fun1():
print('func1')
def fun2():
print('func2')
fun2()
fun1()
#fun2访问不到
#----------------
#闭包
def FunX(x):
def FunY(y):
return x*y
return FunY
print(FunX(8)(5))
def func1():
x=5
def func2():
nonlocal x #用list[]也可以
x*=x
return x
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.