blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
40d62cb23cb8341c4e219c1df9206640ba150a06 | dmnsn7/projecteuler | /13/138.py | 225 | 3.5 | 4 | #!/usr/bin/env python3
import sys
def main():
a, b, ans = 38, 17, 0
for _ in range(12):
ans += b
a, b = a * 9 + b * 20, a * 4 + b * 9
print(ans)
if __name__ == "__main__":
sys.exit(main())
|
44ea12790778062af23981786ec8361e4590393b | luisavitoria/introducao-curso-basico-python | /code/COH-PIAH.py | 4,833 | 4 | 4 | import re
def main():
ass_cp = le_assinatura()
textos = le_textos()
infectado = avalia_textos(textos, ass_cp)
print("O autor do texto",infectado,"está infectado com COH-PIAH")
def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comp... |
65155a9bdd9bcd761474807ff12ea9fb768b9129 | huang-jingwei/Coding-Interview-Guide | /chap3/04.二叉树的序列化和反序列化/04_serialize_deserialize.py | 2,506 | 3.6875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
# 层次序列的序列化
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
846c62af64e4e09357792e41fa4ba2fb6376ec63 | bainco/bainco.github.io | /course-files/lectures/lecture21-old/01_dictionary.py | 542 | 4.15625 | 4 | #example:
eng2sp = {
'one': 'uno',
'two': 'dos',
'three': 'tres',
'four': 'cuatro',
'five': 'cinco',
'six': 'seis',
'seven': 'siete',
'eight': 'ocho',
'nine': 'nueve',
'ten': 'diez'
}
# things you can do with dictionaries...
print(eng2sp)
print(eng2sp.keys())
print(eng... |
763ee1d2b4f979b52d5d88aa758f4a6eea394d37 | JulseJiang/leetcode | /lc322_凑零钱.py | 710 | 3.5 | 4 | # # Title : dynamic_programming.py
# # Created by: julse@qq.com
# # Created on: 2021/7/4 22:25
# # des : 零钱凑整 -- 超时
class Solution:
def coinChange(self, coins,amount):
coins = coins
dp = [float('inf')]*(amount+1)
dp[0] = 0
for coin in coins:
for x in range(coin,amou... |
d17d0dda2c81ef51d7acd8ae53b85a2a54ed8b8a | brittany-morris/Bootcamp-Python-and-Bash-Scripts | /python fullstackVM/birthday_party.py | 656 | 3.8125 | 4 | #!usr/bin/env python3
#use sys to get argument from command line (file to open)
import sys
file_name = sys.argv[1]
# open that file
with open(file_name, 'r') as f:
# initialize a counter dictionary
counter_dictionary = {}
# loop through the lines
for line in f:
name = line.strip()
# if name is not in dictiona... |
0c6b5ba7094684367fdd2668419b7b6c9375f2a1 | daniel-reich/ubiquitous-fiesta | /79tuQhjqs8fT7zKCY_17.py | 725 | 3.78125 | 4 |
def postfix(expression):
tokens = expression.split()
stack = []
ops = ['+', '-', '*', '/']
while len(tokens) > 0:
token = tokens.pop(0)
if token in ops:
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
e... |
307dd1f0d51d11c919433b3b736839846ba4d37d | raymondberg/devstart | /projects/game_store.py | 1,544 | 4.09375 | 4 | class Game:
def __init__(self, name, cost):
self.name = name
self.cost = cost
class VideoGameStore():
def __init__(self, starting_items):
self.shelves = starting_items
def buy_item(self, item):
self.shelves.append(item)
def list_items(self):
for item in self.sh... |
4f7180c6caac5b956eeabac1db83e61205adc3f6 | SouzaCadu/guppe | /Secao_07_Colecoes/07_33_tuplas.py | 2,528 | 4.65625 | 5 | """
Tuplas (tuples)
As tuplas são representadas por parênteses, são imutáveis toda a operação em uma
tupla gera uma nova tupla
Tuplas são definidas por vírgula e não por parênteses
print(type(()))
# Representações de uma tupla
tupla1 = (1, 2, 3, 4, 5, 6)
print(tupla1)
print(type(tupla1))
tupla2 = 1, 2, 3, 4, 5, 6... |
7e6af3d55b8ae4759c846b897546f871fd2e2866 | Stormy110/Digital-Crafts-Classes | /Programming101/condition_exercises.py | 309 | 3.75 | 4 | print(1 == 3)
print(4 <= 4)
print("a" == "a")
print(10 > 11)
print("b" > "c")
my_number = 25
print(my_number > 75)
print(my_number < 45)
print(my_number == 26)
name = "Ian"
if name == "Ian":
print("YES these strings are the same!")
if name != "George":
print("NO These strings are different!")
|
d7d018731efc965ec2a657d50c9fb97449ab819f | sepehr-ahmadi/maktab52_python | /hw4/inheritance.py | 1,277 | 3.8125 | 4 | class A:
def do_job(self,*args):
if len(args)>1:
if args[-1]!='e':
print('I am walking ...')
else:
print('I am walking ...')
class Z:
def do_job(self, *args):
if str(args[0]).isnumeric():
print(f'I am counting from 1 to {args[0]}: {... |
5904c63cd705f3d724452e9020caa355e4c83853 | SENOMOY/Stock_Analysis-Recommendation | /prediction/LinearRegression_Prediction.py | 1,527 | 3.875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
def linearRegressionPrediction(company_ticker,company):
data = pd.read_csv("data/stock_prices/"+company_ticker... |
0191cf40bca08a9e3a5cf76db52f524fda9f69aa | Leo-Malay/Python-Data-Structure | /Sorting.py | 1,037 | 3.96875 | 4 | #
# Implemented: Sorting Algorithms
# Author: Malay Bhavsar
# Date: 15-04-2021
# Version: 1.0
#
class Sorting:
def __init__(self, arr):
self.arr = arr
self.length = len(arr)
def bubbleSort(self):
arr = [x for x in self.arr]
isSorted = False
while isSorted == Fa... |
c9b832a9c25ee104b3e00dc534329a6c589fa16f | felipeescallon/programming_fundamentals_py | /Semana_3_2/2_introduccion_vectores/ejemplo_vector.py | 1,170 | 3.8125 | 4 | """
Ahora asumamos que queremos hacer un censo para Antioquia y sus 10 municipios (dato no verificado). En este caso, volvemos a tener las siguientes planillas:
- Identificador del municipio al que pertenece la casa
- Número de personas
Los códigos son:
1. Medellín
2. Envigado
3. ...
125. Zaragoza
No podemos u... |
857e1d8e5f5bca25aeff84f7c56809c2d38e8caa | pavanmaradia/Python202103 | /sessions/session_08.py | 1,936 | 4.25 | 4 | """
Data Structure
set
array
Conditional Statement
if
if else
if elif else
nested if
Assignment:
1) find the union from 3 sets
2) find the difference from 3 sets
3) find the maximum number from 5 variables
4) take input from user and if input is 'a' then print 'apple' like wise ... |
e27e505b242abbc44118e208376585d51e5d259e | cmjagtap/Algorithms_and_DS | /strings/countSubstrOcc.py | 230 | 4.09375 | 4 | def countSubsrt(string,substr):
if not string or substr:
return
else:
count=0
for x in range(len(string)-len(substr)+1):
if string[x:x+len(substr)]==substr:
count+=1
return count
print countSubsrt("ABCDCDC","CDC") |
ccdf0397c45f1e6bd51d18c3467b728cfc343d49 | hansuho113/AlgorithmStudy_SwUniv | /Our Codes/programmers/level2/다리를 지나는 트럭/Kyungjin/cross_the_bridge.py | 891 | 3.75 | 4 | # Programmers level2 - 다리를 지나는 트럭
import collections
def solution(bridge_length, weight, truck_weights):
bridge = collections.deque()
current_weight = 0
step = 0
for _ in range(bridge_length):
bridge.append(0)
for truck_weight in truck_weights:
while True:
current_we... |
a14032433b48d0cd4931d49df293b8979481bddc | ck-unifr/leetcode | /design/460-lfu-cache.py | 2,993 | 4 | 4 | """
https://leetcode.com/problems/lfu-cache/
460. LFU Cache
Design and implement a data structure for Least Frequently Used (LFU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache,
otherwise return -1.
put(ke... |
f3947da4927fee98e710a7a0fe418848ed762d4b | EKYoonD/gitCodes | /brown_yellow_box_20211104.py | 332 | 3.609375 | 4 | def solution(brown, yellow):
volume = brown + yellow
xy = [0, 0]
for x in range(1, volume):
if volume % x == 0 and x <= int(volume / x) and (x-2)*(volume/x-2)==yellow:
xy[0] = int(volume / x)
xy[1] = x
return xy
print(solution(10, 2))
print(solution(24, 24))
print(solu... |
dc5c81ae21c98ca202b03312ef139f303723cd32 | hackettccp/CIS106 | /SourceCode/Module10/checkbutton_demo_2.py | 2,984 | 3.984375 | 4 | #Imports the tkinter module
import tkinter
#Imports the tkinter.messagebox module
import tkinter.messagebox
#Main Function
def main() :
#Creates the window
test_window = tkinter.Tk()
#Sets the window's title
test_window.wm_title("My Window")
#Creates two frames that belong to test_window
upper_frame = tkinter.F... |
7557ffcccf641b53f7bfa004e07842df57ed3962 | h4m5t/algorithm | /007快速排序2.py | 723 | 3.953125 | 4 | '''
Author: h4m5t
Date: 2021-01-19 14:58:10
LastEditTime: 2021-01-19 15:29:13
'''
#归位函数
def partition(li,left,right):
tmp=li[left]
#从右找一个,再从左找一个,向中间逼近
while left<right:
while left<right and li[right]>=tmp:
right-=1
li[left]=li[right]
while left<right and li[left]<=tmp:
... |
3035803256f920a0088560b171a625ca255de0a1 | albertomartinezcaballero/laboratorio | /laboratorio.py | 1,211 | 3.75 | 4 | class Producto():
def __init__(self, nombre, precio):
self.nombre = nombre
self.precio = precio
def get_info(self):
return [self.nombre, self.precio]
class Medicamento(Producto):
def __init__(self, nombre, precio, compuesto, porcentaje):
super().__init__(nombre, precio)
... |
c2bb3ed43965af0d1fb95ad7fd4f1aec7d4c021b | Pranavtechie/Class-XII-Projects | /Section B/Group - 9 (67,50)/Source Code/guest.py | 943 | 3.5625 | 4 | import src
from os import system
def guest_menu():
print("\n----- GUEST MENU -----\n")
print("Press (1) to see the cars table")
print("Press (2) to see the bikes table")
print("Press (3) to return to main menu")
print("Press (4) to exit the program")
def guest_main(name):
system('cls')
p... |
975a796b3176358a5c8727c4df66dfb14cbd2535 | b1ueskydragon/PythonGround | /ap_programming/treeSearoh_queue01.py | 779 | 3.6875 | 4 | """
BFS
"""
from queue import Queue
def treeSearoh(given, target):
"""
O(2^n)
"""
queue = Queue()
i = 0
curr_sum = 0 # sum til current
res_sum = curr_sum # candidate
size = len(given)
queue.put(curr_sum)
while not queue.empty():
curr_sum = queue.get()
# vari... |
adad70effd7c5e05f52641425c66a749dedf1c70 | jalayrupera/opencvBasics | /1.Reading the picture from the computer/face.py | 257 | 3.5 | 4 | import numpy as np
import cv2
img = cv2.imread('Messi-jugada.jpg',cv2.IMREAD_GRAYSCALE) //CONVERTS THE COLOR OF THE PICTURE INTO THE GRAY
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.imwrite('rey.jpeg',fh) //TO SAVE THE PICTURE
cv2.destroyAllWindows()
|
abce2633585b354a2afc28372b22eadefe10d53f | nimishn2021/Day3 | /ex1.py | 1,341 | 4.25 | 4 | # Write python function to find the powers of numbers. Each item in the Array must take the next element in the
# array as it pow and return.
# If any number is left-behind without next number, then it shall take the min number in the array as its pow.
# The max pow that can be taken is 5. If there is any item in th... |
822bab8f3452fe1f0ef7d9437725873007242e76 | Ayushjain7890/Python | /Palindrome.py | 224 | 4.03125 | 4 | n=int(input("Enter number: "))
r=0
x=n
print("Given number",n)
while n>0:
d=n%10
r=r*10 +d
n=n//10
if x==r:
print("It is a Palindrome number",x)
else:
print("It is NOT a palindrome number",x)
|
3d9c5e0fd1c246f5aeb1c212504da04a4471bc04 | nandanabhishek/LeetCode | /problems/268. Missing Number/sol.py | 847 | 3.90625 | 4 | # Approach-1 : General and Best Approach- By using XOR operation
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# using XOR operation
res = 0
for i in range(1, len(nums)+1):
res = res ^ i
for num in nums:
res... |
34243997186e9ef072eb64135074eda7d57b6025 | harikishangrandhe/FST-M1 | /Python/Activities/Activity4.py | 1,448 | 4.3125 | 4 | print("This is a Rock Paper Scissor game.Players can enter Rock or Paper or Scissor. ")
continuegame="yes"
while(continuegame=="yes"):
Player1=input("Player 1: Enter your option ").lower()
Player2=input("Player 2: Enter your option ").lower()
if Player1=="rock":
if Player2=="paper":
... |
1eebec1d6f5aee0ce4fbb7720edb862638bdb301 | JamKingJK/AdventOfCode2019 | /day_1/part_1/main.py | 307 | 3.765625 | 4 | import math
with open('input.txt', 'r') as input_file:
lines = input_file.readlines()
total_required_fuel = 0
for line in lines:
module_mass = int(line)
required_fuel = math.floor(module_mass / 3) - 2
total_required_fuel += required_fuel
print(total_required_fuel)
|
9616c09231771a1241798796f7dc9fae97038e23 | R-obins/PyStudys | /Base/Operators.py | 2,917 | 3.921875 | 4 | #######运算符#######
# 算术运算符
# + - * / % **(幂次,a**b为 a的b次方) //(取整数)
a=2
b=4
print(a**b) #2的4次方
c=20
d=3
print(c//d) #20除3的结果整数
# 比较运算符
# == != > < >= <= (python2中<>表示不等于)
print(c!=d)
# 赋值运算符
# = += -= *= /= %= **= //=
c*=a # c=c*a
# 位运算符 把数字看作二进制来进行计算
'''
& 按位与运算符:参与运算的两个值如果两个相应位都为1,则该位的结果... |
0f30c619d1e38938507e031b869112b90a9456f4 | lucho19jose/EjercicioCincit2020 | /ejercicio.py | 530 | 3.5625 | 4 | #
tam = int(input('ingrese:'))
A = []#se almacena a
B = []#lista temporal que nos permite join
C = []#lista principal
Dic = {}# se guarda el indice del C y el valor de C
#ingresando valores
for i in range(tam):
b = 0
B.clear()
A.append(int(input('ingrese a: ')))
b = str(input('ingrese b:'))
for j in range(A[i... |
ca8c0c9f7567015dcba9aa3cde5e94b74b9aa77e | rayhanaziai/Practice_problems | /str_compression.py | 777 | 4.09375 | 4 | """Implement a method to perform basic string compression using the counts of repeated characters. e.g. the stinrg aabcccccaaa would become a2b1c5a3. If the "compresed" string would not become smaller than the original string, your method should return the original string"""
def str_compression(s):
result_lst = []... |
349ea4b683dd8c7d48381b337669c9f917351329 | HedwigMueller1337/EpicGameWTF | /dice.py | 642 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 15 21:22:29 2017
@author: kram
"""
import random
class dice():
# sides: list of sides
def __init__(self, sides = [], weights = []):
self.sides = sides
self.weights = weights
# add sides to dice
def extend(self, newSides):
... |
720eb8fe521ecd332253821323387efb1f94c153 | araschermer/python-code | /LeetCode/first-last-position.py | 1,140 | 4.125 | 4 | # Runtime: 80 ms, faster than 90.25% of Python3 online submissions for Find First and Last Position of Element in
# Sorted Array.
# Memory Usage: 15.3 MB, less than 82.68% of Python3 online submissions for Find First and Last
# Position of Element in Sorted Array.
def search_range(nums, target):
"""Given an array o... |
a5785e1b22a58a5efb6c003e65dee8d29371595e | alexisbedoya/SimulacionDigital | /generadorMMM.py | 1,526 | 3.796875 | 4 | def generarMC():
while True:
try:
seed=int(input("Ingrese la semilla: "))
if len(str(seed)) > 3:
break
except ValueError:
print("OPCIÓN INVÁLIDA!!....")
while True:
try:
num=int(input("Cuántos números aleatorios desea?: "))
break
... |
4912fa88231b64237973289f0240ba063629568e | Dexels/app-tools | /apptools/entity/io.py | 1,012 | 3.5625 | 4 | import os, io
class IndentedWriter(object):
def __init__(self, path: os.PathLike, indent: int = 0):
self.path = path
self.indent = indent
self.indentation = " " * indent
def __enter__(self):
if self.path is not None:
self.fp = open(self.path, "w")
else:
... |
2cf682ce489e3b2e27a37ec8d54c1c8d5e2a40c0 | KordingLab/fmri-iv | /code/stats_util.py | 1,918 | 3.578125 | 4 | import numpy as np
def calc_dist_matrix(multidim_data, norm_ord=2):
"""
Find the pairwise distances between multidimensional points.
Input multidim_data should be N x D (N observations, D dimensions)
Distance is defined by an L2 norm by default, or specify norm_ord parameter as in np.norm
"""
... |
ecc98b4fa0822c0f18ce0aa454b98a5a1d079fb6 | z727354123/pyCharmTest | /2017/9_Sep/21/13-list count.py | 386 | 3.953125 | 4 | listA = [1]
listB = [1, 2, 3, 4, listA]
listC = [1]
listB *= 3
print(listB)
print(listB[9] == listA)
print(listB[4] is listA)
print(listB[9] is listA)
print(listB[9] is listC)
print('-------------------------')
print(listB.count(listA))
print(listB.count(listC))
print(listB.index(listC, 5))
print(listB.index(listC, 5,... |
e6557810b9bea6aa561a5cc2e985089f5be89811 | artheadsweden/New_Courses_2020 | /Python_Fundamentals/04_Variables_And_Data_Types/05 Strings Bytes and ByeArrays/04 String Operations/10 encode.py | 261 | 3.671875 | 4 | def main():
# unicode string
string = 'pythôn!'
# print string
print('The string is:', string)
# default encoding to utf-8
string_utf = string.encode()
# print result
print(string_utf)
if __name__ == '__main__':
main() |
45cc1a516680f6487b7c2890f262d2b7ffa37f6c | LungTel/zero_AIkoza | /args_and_return.py | 152 | 3.546875 | 4 | a = 7
b = 3
def add1(c, d):
e = c + d
print e
add1(a, b)
def add2(c, d):
e = c + d
return e
f = add2(a, b)
print f
|
9d8fc7d56eee9c89f314050228371cf3b5ba23ab | fabriciofk/entra21 | /URI/uri_1011.py | 98 | 3.5625 | 4 | pi = 3.14159
raio = float(input())
volume = (4/3) * pi * raio ** 3
print(f"VOLUME = {volume:.3f}") |
1b19128f5ae86f3678af1eb11ac08cf56921d2e8 | rishulike/project | /G1.py | 507 | 3.546875 | 4 | #G
st=""
for r in range(7):
for c in range(0,7):
if ((c==0 and r!=0 and r!=6)or (r==0 and c!=0 and c!=1 and c!=4 and c!=5 and c!=6)or(c==2 and r!=1 and r!=2 and r!=3 and r!=4 and r!=5)
or(r==3 and c!=1 and c!=2 and c!=6)or(r==6 and c!=0 and c!=3 and c!=4 and c!=5 and c!=6)or
(r==5... |
fec17d3bfe611d9447dbb9f0d559a566f934aa37 | GonzaloFerradas/my_files_py | /break_continue.py | 452 | 3.890625 | 4 | #Ejemplo para break
print("while con la sentencia break \n")
contador = 0
while contador < 10:
contador+=1
if contador == 5:
break
print("Valor actual de la variable: ", contador)
#Ejemplo para continue
print("while con la sentencia continue \n")
contador = 0
while contador ... |
b92413c27b1a497eb5c1025fb7ce2731f119122b | sylvialilyli/csc148 | /music player/make_some_noise.py | 25,617 | 3.78125 | 4 | """CSC148 Assignment 1 - Making Music
=== CSC148 Summer 2019 ===
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains classes that describe sound waves, instruments that play
these sounds and a function that plays multiple instruments simultaneously.
As discussed in th... |
3775efb1092a5431e7f53abe98c73db01b73a5fe | karbekk/Python_Data_Structures | /Interview/DSA/LinkedList/recursive_reverse.py | 362 | 3.59375 | 4 | def rec_reverse(self):
if self.head is None:
return None
self.rec_reverse_util(self.head, None)
def rec_reverse_util(self,current,prev):
if current is None:
self.head = prev
current.nextnode = prev
return
next = current.nextnode
current.nextnode = pre... |
b099db6d308880460580bdc4f94cf58c220060da | laodajiade/seleniumTest | /seleniumWebdriver/mySeleniumTest01.py | 912 | 3.8125 | 4 | # 1、用selenium打开Firefox/chrome浏览器
# 2、打开一个页面链接
# 3、定位页面元素进行内容搜索
from selenium import webdriver
from time import sleep
class myTest:
#打开浏览器
driver = webdriver.Chrome()
def __init__(self):
baiduUrl = 'https://www.baidu.com/'
self.baiduUrl = baiduUrl
#打开链接
def openUrl(self):
se... |
1b20473a3e846f49e78e9cdd191ab4d84fa16592 | Jamiil92/Machine-Learning-by-Andrew-Ng | /examples/example1.py | 2,586 | 3.953125 | 4 | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from plot_learning_curve import plot_learning_curve
#Loading our data
# Download the data from the folder data in the repository an... |
6339a5ffbdc77c9639b72f0678fa8b2883d2b1ec | pcaff321/Dijkstra-Algorithm-Extended-For-Road-Maps | /Edge.py | 1,666 | 4.3125 | 4 | class Edge:
""" An edge in a graph.
Implemented with an order, so can be used for directed or undirected
graphs. Methods are provided for both. It is the job of the Graph class
to handle them as directed or undirected.
"""
def __init__(self, v, w, element):
""" Cre... |
d57dec86d4c443d88bab322b0b030c30aa0c16ea | rakesh08061994/Raka-Python-Code-1 | /indianRailway.py | 1,048 | 3.71875 | 4 | class Indian_Railway:
total_seats = 100
file = "main.txt"
with open(file,"w") as open_file:
append_file = open_file.write(str(total_seats))
print("completed")
def __init__(self, name, seat):
self.name = name
self.seat = seat
def book_T... |
bb7284846cfb758cd27db51133a5060e08eeef2b | ebmm01/ppc-2019-1 | /contest5/exC.py | 331 | 3.6875 | 4 | str = input()
hello = ['h','e','l','l','o']
str = str.lower()
str_lst = list(str)
while True:
try:
if str_lst[0] == hello[0]:
str_lst.pop(0)
hello.pop(0)
else:
str_lst.pop(0)
except IndexError:
break
if len(hello) == 0:
print("YES")
else:
p... |
b244a447c64bff13fe645c221f9ab55d59b411d4 | skybohannon/python | /w3resource/string/12.py | 396 | 4.15625 | 4 | # 12. Write a Python program to count the occurrences of each word in a given sentence.
def count_occurances(str):
wordcount = {}
words = str.split()
for word in words:
if word in wordcount:
wordcount[word] += 1
else:
wordcount[word] = 1
return wordcount
pri... |
97f5e7f142660628ea29bc26d801801d0b7e727f | danilocamus/curso-em-video-python | /aula 21/desafio 104.py | 754 | 3.875 | 4 | def leiaInt(msg):
ok = False # começa com valor falso ate digitar um numero valido inteiro
valor = 0
while True:
n1 = str(input(msg)) # variavel n recebe da variavel msg um valor no formato string
if n1.isnumeric(): # se o valor da variavel n for um numero
valor = int(n1) #... |
b9bd0fc0a0efaaff503fa66b90085c9a6d79693d | HaliaBlyzniuk/Python_labs | /lab_02.2.py | 574 | 3.859375 | 4 | error = "You've entered incorrect value. Try one more time:"
x = float(input("Enter x : "))
e = float(input("Enter e > 0: "))
while e < 0:
print (error)
e = float(input("Enter e > 0: "))
old_a = x
a = (2*old_a) + ((16+x)/(4+abs(old_a**3)))
n = 2
while abs(a - old_a) >= e and n <= 100:
old_a = a
... |
9699daa3bb16c55aea0e1b7fd038a0468aadac47 | czfyy/Think-Python-2ed | /ThinkPython_Exercise8.3.py | 809 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 19:48:53 2019
@author: czfyy
"""
fruit = 'banana'
'''
正序:(第一项是0)
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
倒序:(倒数最后一项用-1表示)
index = -1
while index >= 0 - len(fruit):
letter = fru... |
fb33cafd1431ded48875ab7e21a4427caf7dc458 | kgreenfield3/Intro_Media_Computation | /HW/hw03.py | 989 | 4 | 4 | #Kyrsten Greenfield
#kgreenfield@gatech.edu
#I worked on the homework assignment alone, using only this semester's course materials
#Problem 1:
def pizza(nameList):
for name in range(len(nameList)):
print nameList[name] + " " + "wants pizza!"
#Problem 2:
def sleep(napTime, alarm):
hourList = range(napTime, a... |
a3aa6f85d46da3772a698f93e07b9c648d23a109 | SagnikDev/Infytq-Programme-Codes | /Binary Search/traversal.py | 713 | 4.0625 | 4 | # Python program to print postorder
# traversal from preorder and
# inorder traversals
def printpostorder(inorder, preorder, n):
if preorder[0] in inorder:
root = inorder.index(preorder[0])
if root != 0: # left subtree exists
printpostorder(inorder[:root],
preorder[1:root + 1],
len(inorder[:... |
bc1f4e179f15efc5e312eac1d100a8ec92d38232 | Rashid3601/day-2---python---codenation | /day 2.py | 2,589 | 4.3125 | 4 | #learning about variables and making them
my_name = "Rashid"
my_age = 26
Learner = True
print(my_name)
fav_drink = "hot chocolate"
print(fav_drink)
print("my faviorate drink is", fav_drink)
name = "Rashid"
fav_drink ="hot chocolate"
print("{} faviorate drink is {}".format(name,fav_drink))
print(f"{name} fav... |
8738c46b10b4ea5204c98f678acc340c47ed0381 | jjh42/oldalgo | /mincut/mincut.py | 2,988 | 3.59375 | 4 | """Calculate the minimum cut of a graph."""
from random import randint
import copy
class Graph():
"""Representation of a graph. Vertices are represented as a dictionary,
edges as a list."""
def __init__(self, file=None):
self.v = {}
self.e = []
if file == None:
file = o... |
f8f1f61c898b2d5d17ad9cf750d1e6457f7f7717 | ceuity/algorithm | /leetcode/039.py | 702 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 01:59:59 2021
"""
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
def dfs(csum, index, path):
if csum < 0:
return
... |
99e45ba012cbf33b7146b735c15a7d2be5c1f99d | dom-0/python | /PyFlow/6.4ifchallenge.py | 345 | 4.0625 | 4 | name = input("Enter your name: ")
age = int(input("Enter your age, {0} ".format(name)))
if 18 < age < 31:
print("Welcome {0}, you are in".format(name))
elif age <= 18:
print("Please come back after {0} year(s), {1}".format(19 - age, name))
else:
print("Sorry {0}, but you should have tried {1} years earlier... |
f9f8d699d5e695f03132688f82e69d93a1b7f7d8 | ZacThePaul/PyGame-calc | /atts.py | 1,806 | 3.796875 | 4 | import pygame as p
p.font.init()
x = 'Pygame Tutorial!'
small_font = p.font.Font("freesansbold.ttf", 20)
white = (255, 255, 255)
black = (0, 0, 0)
class Button:
def __init__(self, length, width, xposition, yposition, color, surface):
self.length = length
self.width = width
... |
e9391f591a825718ca969387d03d40cc8d576f16 | karetz/Python_work | /Py2 HW5.py | 956 | 3.9375 | 4 | """
# Kareen Sade id: 304924327
# Curse: Python
HW 5
"""
##4##
#function that compute the sum of numbers from 1 to n.
def sum(n):
if n>1 or n==1:
x =n + sum(n-1)
return x
else:
# print()
return 0
print(sum(57))
#1653
#%%
##5##
#function that compute snd returns the sum of ... |
91f3c6e00f46c8a7d55d355cb6321c2021d741b2 | 3riccc/newML | /grow.py | 1,837 | 3.5 | 4 | #encoding:utf-8
# 填充结构
import fillStructure as fs
# 文件操作
import operator
# 生成结构
import generateStructure as gs
# 即将被填充的数组
arr = []
# 读取文件并填充到数组中
f = open("testDigits/1_1.txt");
for line in f.readlines():
# 去掉末尾的换行符
line = line.strip("\n").strip("\r")
# 每一行的数组
row = []
for letter in line:
row.append(letter)
arr... |
78a96f665e3fe78167fa806f0163916d089b1c04 | ayellowdog/python | /pythonlearn/求最大公约数.py | 169 | 3.796875 | 4 | """Լ"""
def max(a,b):
if a<b:
a,b=b,a #a is the max
while b!=0:
tem=a%b
a=b
b=tem
return a
|
31c02ae839075aabc445814ad10ca28af56d5bd9 | taoxianfeng/design_patterns | /proxy_pattern/force_proxy.py | 3,539 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
module name:force proxy design pattern
module description:
强制代理模式对外暴露的接口仅是真实用户类,由真实用户指定代理用户
Authors: taoxianfeng(taoxianfeng2012@163.com)
Date: 2020/08/09
游戏物理编程模拟场景:
玩家A:name: Tony passwd:123
玩家B:name: Alice passwd:456
玩家A指定王家B做代理
"""
from abc import ABC, abstrac... |
d3e7d68f66df030354b91cf5efddcbd120b7a21d | eddiehou2/HackerRank | /Algorithms/Strings/pangrams.py | 333 | 3.5625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
s = sys.stdin.readline()
alpha = []
for i in xrange(26):
alpha.append(0)
s = s.lower()
for i in xrange(len(s)):
if s[i].isalpha():
alpha[ord(s[i]) - ord('a')] = 1
if min(alpha) == 0:
print "not pangram"
else:
pri... |
5df3961dccd7db5906efe13a34abd4c58a76a9f4 | egdw/image_print | /index.py | 1,203 | 3.515625 | 4 | from PIL import Image, ImageDraw, ImageFont, ImageFilter
# 二值化生成法
image_file = Image.open("/Users/hdy/Downloads/test/demo.jpg") # open colour image
image_file = image_file.convert('L') # convert image to black and white
threshold = 80
table = []
for i in range(256):
if i < threshold:
table.append(0)
... |
475592b1ec77b8957c9a9151b888df54705fb8c9 | rameshrvr/HackerRank | /Algorithms/Implementaion/append_and_delete.py | 1,427 | 4.1875 | 4 |
def get_matching_substring(string1, string2):
"""
Method to get the matching substring from the two given string
Args:
string1: string1
string2: string2
Return:
Matching sub string
"""
matching_string = []
for a, b in zip(string1, string2):
if a == b:
... |
e59503cf597531fd9c2db778c7abb25760ce1817 | vanxkr/learning | /learnPython/qiepian.py | 367 | 3.859375 | 4 | # -*- coding: utf-8 -*-
#切片
l = ['a', 'b', 'c']
#0-n
print(l[0:3])
#0开始 可以省略
print(l[:3])
#倒数切片
print(l[-2:])
print(l[-2:-1])
#0-99
LL = list(range(100))
print(LL)
print(LL[:10])
print(LL[-10:])
print(LL[10:20])
#前10个数 每两个数取一个
print(LL[:10:2])
#所有的数每5个取一个
print(LL[::5])
|
f348c4336260a5d6280a1c4f5841605330607e0e | UG-SEP/NeoAlgo | /Python/math/euler_totient_function.py | 1,030 | 3.9375 | 4 | ''' python program for Euler's Totient Function '''
def euler_totient(num):
''' Takes in a variable num and return the number of coprimes of n '''
arr=[]
for count in range(num + 1):
arr.append(count)
for count in range(2, num + 1):
'''if this condition is satisfied then we are re... |
a6da2062585d75edf9643bdac2f9df4619211327 | vijaypatha/python_sandbox | /numpie_mani.py | 2,173 | 4.375 | 4 | '''
pretty simple:
1) Create a array
2) Manipylate the arary: Accessing, deleting, inserting, slicing etc
'''
#!/usr/bin/env python
# coding: utf-8
# In[10]:
import numpy as np
#Step 1: Create a array
x = np.arange(5,55,5).reshape(2,5)
print("Array X is:")
print(x)
print("Attrubute of Array X is:")
print("# of ... |
9702e5f172a2937a3151afc744f98b8afcad6e5b | Aasthaengg/IBMdataset | /Python_codes/p03399/s589653405.py | 195 | 3.6875 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
if (a>=b):
if (c>=d):
print(b+d)
else:
print(b+c)
else:
if (c>=d):
print(a+d)
else:
print(a+c)
|
99da58a08906dc985b1cb3fa254420424a3f5445 | rafaelblira/python-progressivo | /exibir_label.py | 477 | 3.984375 | 4 | import tkinter
class MinhaGUI:
def __init__(self):
# Criando a janela principal
self.main_window = tkinter.Tk()
# Criando um Label com o texto 'Curso Python Progressivo'
self.texto = tkinter.Label(self.main_window, text='Curso Python Progressivo! ' )
# Chamando o metodo ... |
e6a763c20be237c4d21610a3e98dff71f0af8e2d | robertdigital/ML_Finance_Codes | /RL/dqMM/examples/random_generator.py | 551 | 3.734375 | 4 | """
In this example we show how a random generator is coded.
All generators inherit from the DataGenerator class
The class yields tuple (bid_price,ask_price)
"""
import numpy as np
from tgym.core import DataGenerator
class RandomGenerator(DataGenerator):
@staticmethod
def _generator(ba_spread=0):
whil... |
8f1d6a4263a16444f998831fb51609ddb71da4f7 | mangalagb/Leetcode | /Medium/MeetingScheduler.py | 2,972 | 3.828125 | 4 | # Given the availability time slots arrays slots1 and slots2 of two
# people and a meeting duration duration, return the earliest time
# slot that works for both of them and is of duration duration.
#
# If there is no common time slot that satisfies the requirements,
# return an empty array.
#
# The format of a time sl... |
5099213eee6d7d9ed0ee3658a9d74a51080e1fe8 | sankar-vs/Python-and-MySQL | /Data Structures/Tuple/8_Remove_item.py | 293 | 4.21875 | 4 | '''
@Author: Sankar
@Date: 2021-04-11 09:33:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-11 09:36:09
@Title : Tuple_Python-8
'''
'''
Write a Python program to remove an item from a tuple.
'''
tuple = ("Heyya", False, 3.2, 1)
print(tuple)
tuple = tuple[:1] + tuple[2:]
print(tuple) |
166de180d9e9a677349296f206fac7827d319126 | RuzimovJavlonbek/qudrat-abduraximovning-kitobidagi-masalalarni-pythonda-ishlanishi | /if30/if_21.py | 228 | 3.90625 | 4 | a = float(input("A butun Sonni kiriting: X = "))
b = float(input("B butun Sonni kiriting: Y = "))
if a==0 and b==0:
print("0")
elif b==0 and a!=0:
print("1")
elif a==0 and b!=0:
print("2")
else:
print("3")
input()
|
975e5ae1fb8516ff98ed9b56dfa34a94ed2e6306 | ranga/python-exercises | /FunctionalProgramming.py | 3,800 | 4.5 | 4 | """
Chapter 3: Functional Programming
"""
def power(x,n):
"""
Mathematically we can define power of a number in terms of its smaller power.
Computes the result of x raised to the power of n.
>>> power(2, 3)
8
>>> power(3, 2)
9
>>> power(3,0)
1
"""
if n == 0:
return 1... |
8334491e0d807a6b0ce04080c20df12a5ccf2c99 | EarthChen/LeetCode_Record | /easy/search_insert_position.py | 905 | 4.125 | 4 | # Given a sorted array and a target value,
# return the index if the target is found.
# If not, return the index where it would be if it were inserted in order.
#
# You may assume no duplicates in the array.
# Here are few examples.
# [1,3,5,6], 5 → 2
# [1,3,5,6], 2 → 1
# [1,3,5,6], 7 → 4
# [1,3,5,6], 0 → 0
class ... |
498c1faa3bf23afbb8a9ac434aeda22d1bd571be | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/181/51397/submittedfiles/testes.py | 287 | 3.890625 | 4 | n=int(input('digite n:'))
x1=int(input('digite x1:'))
x2=int(input('digite x2:'))
y1=int(input('digite y1:'))
y2=int(input('digite y2:'))
if (x1<=(n/2) and x2>(n/2)) or (x2<=(n/2) and x1>(n/2)) or (y1<=(n/2) and y2>(n/2)) or (y2<=(n/2) and y1>(n/2)):
print('S')
else:
print('N')
|
652c2c865ce6f1ccbbd26bc3b33796ea8b4febf7 | jascals/homework | /py27/p31.py | 592 | 3.5625 | 4 | # -*- coding:utf-8 -*-
# author cherie
# jascal@163.com
# jascal.net
# Next Permutation
class Solution(object):
def nextPermutation(self, nums):
if len(nums)<=1:
return
for i in range(len(nums)-2,-1,-1):
if nums[i]<nums[i+1]:
for k in range(len(nums)-1,i,-1... |
fd4ce7c851b4badcfe6182025b4e9fc80762c63f | ramprasadtx/SimplePrograms | /relegation_battle.py | 1,122 | 3.65625 | 4 | #Find the 3 teams that will be relegated with points
team_info = { 'Arsenal':56,
'Aston Villa':35,
'Bournemouth ':34,
'Brighton & Hove Albion':41,
'Burnley':54,
'Chelsea':64,
'Crystal Palace':43,
'Everton':49,
... |
e9219608a294994a7a6a5c6e095495b0cfcba043 | developer-md/language-translator | /translator.py | 1,172 | 3.703125 | 4 | from tkinter import *
from translate import Translator
def trans():
translator=Translator(from_lang=lan1.get(),to_lang=lan2.get())
translation=translator.translate(var.get())
var1.set(translation)
root=Tk()
root.title("Translator")
mf=Frame(root)
mf.grid(column=0,row=0, sticky=(N,W,E,S))
m... |
364280b4e6f06e7e8f46588dc739912d2ba02510 | sbashar/python | /src/hackerrank/challenges/py_if_else.py | 592 | 4.15625 | 4 | """
Solution for Hackerrank problem: https://www.hackerrank.com/challenges/py-if-else/problem
"""
def is_wierd(number):
"""
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and g... |
38cb6cdaea8f574c9274612114f3b3b2724719ca | davidpvilaca/prog1 | /roteiros/roteiro 7/rot7ex6.py | 1,531 | 3.75 | 4 | # DAVID VILAÇA
# ROTEIRO 7 - EXERCICIO 5
def f_ordena(lista):
#variaveis locias
i = 0; aux = 0; trocas = 0;
lenl = 0
#processamento
lenl = len(lista)
trocas = 1
while trocas != 0:
trocas = 0
for i in range(lenl-1):
if lista[i] > lista[(i+1)]:
aux = lista[i]
lista[i] = lista[(i+1)]
lista[(i... |
baf66e09ceb0e164f351234c2c8326ebd48b3903 | PavanTatikonda/Python | /Print_List_of_Even_Numbers.py | 476 | 4.1875 | 4 | # INPUT NUMBER OF EVEN NUMBERS
def print_error_messages(): # function to print error message if user enters a negative number
print("Invalid number, please enter a Non-negative number!")
exit()
n = int(input()) # user input
if n < 0:
print_error_messages()
result = ''.join(str(i)+"\n" f... |
28ae76c8ec845122d6d56525d4658dc4e19c7f4e | DantesMindless/task10 | /task10.py | 3,564 | 3.8125 | 4 |
#task1
class Person():
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def talk(self):
print ('Hey, my fullname is ' + pers.firstname, pers.lastname, 'and i am ' + pers.age + ' years old')
... |
f914174b9c6095e5118c1558dc34f9099954a7f4 | rickmaru85/cursoemvideo | /exercicios/ex006.py | 164 | 4.09375 | 4 | from math import sqrt
valor = int(input('Digite um numero:'))
print('O dobro é {}, o triplo é {} e a raiz quadrada é {}'.format(valor*2,valor*3,sqrt(valor)))
|
e82eee924826326eb706e74f034279079418a156 | CiaraG98/CompLingProject | /analyse_complexity.py | 924 | 3.5 | 4 | """
@author Ciara Gilsenan
@version 20/04/2021
Inferential Statistics Analysis on the data
"""
import pandas as pd
import numpy as np
# read in excel sheets with linguistic complexity scores
df1 = pd.read_excel('Political - Linguistic Complexity Measurements.xls')
df2 = pd.read_excel('Comedy_Culture - Linguistic Compl... |
4651bd016056e50a98afeeb8e19cc447ac8b9e20 | barmi/CodingClub_python | /LV1/SourceCode/Chapter5/ourEtchaSketch.py | 1,808 | 3.75 | 4 | # ourEtchASketch 응용 어플리케이션
from tkinter import *
##### 변수 설정:
canvas_height=400
canvas_width=600
canvas_colour="black"
p1_x=canvas_width * (2 / 3)
p1_y=canvas_height
p1_colour='red'
p2_x=canvas_width / 3
p2_y=canvas_height
p2_colour='green'
line_width=5
line_length=5
##### 함수들:
# 사용자 콘트롤
def move(player, x, y):
... |
3e95aac46838c396fb2039801f556b1b8905cc9a | swcarpentry/2012-11-scripps | /example_parsing/parse.py | 3,171 | 3.84375 | 4 | #! /usr/bin/env python
import sys
# Open the file
try:
input = open(sys.argv[1], 'r')
new_file = sys.argv[2]
except:
print "The input requires two arguments, an input file and an output file"
sys.exit(2)
# Read in each line of the file
lines = file.readlines(input)
# Create empty dictionaries
energy... |
a14a587460c1742308c6c25535ec02215b6125ea | nextdesusu/Learn-Python | /SICP/examples/Interval.py | 2,099 | 3.578125 | 4 | class Interval:
def __init__(self, lb, ub):
self.lower_bound = lb
self.upper_bound = ub
def __str__(self):
return "[{}|{}]".format(self.lower_bound, self.upper_bound)
def make_center_width(c, w):
return Interval(c - w, c + w)
def center(i):
return... |
c253c3e5bd07ae9ad8f6f67406a01a2423e701ef | cfeola/SI206 | /madlibhw3.py | 1,836 | 4 | 4 | # Using text2 from the nltk book corpa, create your own version of the
# MadLib program.
# Requirements:
# 1) Only use the first 150 tokens
# 2) Pick 5 parts of speech to prompt for, including nouns
# 3) Replace nouns 15% of the time, everything else 10%
# Deliverables:
# 1) Print the orginal text (150 tokens)
# 1)... |
39dd62971b093c5d888ac27fd9e4f3004abb78d2 | petermatyi/coursera | /grep.py | 236 | 3.828125 | 4 | import re
rExp = raw_input("Enter a regular expression: ")
fh = open("mbox.txt")
count = 0
for line in fh :
line = line.rstrip()
count = count + len(re.findall(rExp, line))
print "mbox.txt had", count, "lines that matched", rExp |
5ec5c2276af1bcbd96499f8500eab74e4b099cd4 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/etwum/lesson03/slicing.py | 4,789 | 4.0625 | 4 |
def exchange_first_last(seq):
# exchanges the first/last items in a sequence then copies the new sequence into a new string, list or tuple
# performs this part of the if statement if the sequence is of type string
if type(seq) is str:
y = seq[-1] + seq[1:-1] + seq[0]
new_string = y
... |
4a5911536109d19a30e34c978c741f108407e99e | VladaPlys/amis_python | /km73/Plys_Vladyslava/4/task12.py | 156 | 3.703125 | 4 | n = int(input("n="))
m = int(input("m="))
k = int(input("k="))
if (n%2==0 or m%2==0) & k<n*m & (k%n==0 or k%m==0):
print("YES")
else:
print("NO")
|
9fa4d78eba071a185918762ca82c5b5b5c62f74f | PawelGilecki/python | /fibonacci.py | 410 | 4.03125 | 4 | value = int(input("podaj ile liczb z ciagu pokazac: "))
x = 0
y = 1
def fibonacci_list(n):
if value == 0:
fibonacci = [0]
if value == 1:
fibonacci = [0, 1]
if value > 1:
fibonacci = [0, 1]
for i in range(2, value):
fibonacci.append(fibonacci[i-1]+fibo... |
8233723a6c47a30b74d2ccbd5321c6a322642a0b | kunhwiko/algo | /6-others/sliding_windows.py | 694 | 3.75 | 4 | # Sliding Window "slides a window" of size k through an array from left to right
# Example 1
# Find the max sum of a size k subarray
def max_subarray(nums, k):
curr = best = sum(nums[:k])
for i in range(1, len(nums)-k+1):
curr -= nums[i-1]
curr += nums[i+k-1]
best = max(best, curr)
... |
b632ea1dcb4ee15071d5e497d8e00e746ed19af5 | moodycam/MARS-5470-4470 | /Harrison/Lectures/Lec 3.1.1 control1.py | 1,660 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# make a function that finds the mean of a list
# add the elements to gether
# divide by the number
# x is my list
def mean1(x):
return sum(x)/len(x)
#%%
mylist = [2, 5, 16, 8]
mean1(mylist)
#%%
# try somethin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.