blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fb93332121126c94a22c1ad2710399043c5fae43 | jessnswift/my_python_exercises | /class_inheritance/main.py | 414 | 4.09375 | 4 | # instantiate a new Dog and print out the results of making it speak
# Then...when youre done with making your Pet class
# 1.Create an instance of the Pet class and compose the Dog instance into it by adding the dog as a property of the new Pet
# 2.Add an owner by calling your pet's set_owner method (or whatever you ca... |
9641c0b2e43295223460960622901a50de4600bb | Darpan28/Python | /untitled/venv/MultilevelInhe.py | 1,540 | 3.734375 | 4 | class Product:
def __init__(self,name,brand,price):
self.name = name
self._brand = brand
self.__price = price
def __ShowProductDetails(self):
print(">>>>>",self.name,"<<<<<")
print("The Brand is:",self._brand)
print("The price is:",self.__price)
class Mobile(Pro... |
0e10fc539154a145d2d6d1329a93749dfdcaf774 | cjulliar/home | /python/learn/fichier1/package1/fonction1bis.py | 447 | 3.71875 | 4 | """Ce module contient une fonction multiplication"""
def table(nb, max=10):
"""Cette fonction affiche la table de multiplication
de 0 jusqu'à nb max (par defaut: 10)"""
i = 0
while i <= max:
print(i, "*", nb, "=", i * nb)
i += 1
# test de la fonction table
if __name__ == "__main__":
table(4)
# si name = mai... |
c69834a4e517a7056919a3d4da155b726627241b | dhruvghulati-zz/unsupervised-learning-workshop | /mnist_pca_knn.py | 1,826 | 3.703125 | 4 | from __future__ import print_function
from sklearn.datasets import fetch_mldata
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import numpy as np
# Download the MNIST digits dataset and store in the va... |
61f5ae21b969282a2aa4e6a707dcb2478c325d6c | Arashgs/python-object-oriented-programming-course | /chapter-2/getter.py | 601 | 3.703125 | 4 | class BankAccount:
def __init__(self, first_name, last_name, initial_balance):
self.first_name = first_name
self.last_name = last_name
self.balance = initial_balance
@property
def full_name(self):
return f'{self.first_name} {self.last_name}'
account_1 = BankAccount('Kate',... |
9b965e547c71db01eaa5d10f7356c0a2952f36a1 | Rider66code/PythonForEverybody | /bin/p3p_c2w5_final003.py | 1,366 | 4.46875 | 4 | #Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter, a string which represents one or more sentences, and calculates how many words in the string are considered negative words. Use the list, negative_words to determine what words will count as negative. The func... |
6e5e8b841f73b13573983f985f82f3f8c1e39beb | GirijaHarshith/InnovationWithPython_Girija | /Python-Project/Elevator.py | 2,822 | 3.71875 | 4 | from time import sleep
import pyttsx3
from gtts import gTTS
# Function to convert text to speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
print(command)
engine.runAndWait()
# Voice Converter - female version
voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE... |
7d0901f54d8ba9e8119be0ff147e7fcec805436f | JBustos22/Physics-and-Mathematical-Programs | /animations/Cradle.py | 1,296 | 4.03125 | 4 | """
This program simulates Newton's Cradle. Tow balls of equal radius are simulated and animated
to show harmonic motion with energy and momentum conservation. Two smaller balls are placed
on top of them to show the pivot for each pendulum.
Jorge Bustos
Feb 17, 2019
"""
from __future__ import division, print_function... |
7ae009ae148fa099e6b710b0aba4e27866ca2a82 | andreamandioDEV/iscte | /_scraping/bf_3_uc.py | 2,323 | 3.546875 | 4 | # Autor do ficheiro: André Amândio
# Nº aluno: 14900
# UC: Linguagens de Programação 2017/2018
# Ficheiro: bf_3_uc.py
# Ultima modificação: 01/02/2018
# Refs: http://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
import requests, json
from bs4 import BeautifulSoup
def restore_name(str):
return " ".join(... |
6c8e9219308a209c4f2507824f50552099376d98 | HebertFB/Exercicios-de-Python | /secao_5_exercicios/ex03.py | 192 | 4.03125 | 4 | # Ex03
import math
num = float(input('Digite um número real: '))
if num < 0:
print(f'\nO quadrado de {num} é {num ** 2}')
else:
print(f'\nA raiz de {num} é {math.sqrt(num):.2f}')
|
a9140c76b3aae997492a82f90c17b6280d50c221 | Rajveer3311/PYTHON | /sets.py | 553 | 4.125 | 4 | #create set ist method
sets={1,2,3,4,4.0,'raj'}
print(sets)
#list to set
# li=[1,2,3,4,3,"rajveer"]
# sets=set(li)
# print(sets)
# sets=list(set(li)) #set to list
# print(sets)
# add method
# sets.add(5)
# sets.add('singh')
# print(sets)
# delete or remove method
# sets.remove(7)
# print(sets)
#discard method
# se... |
1c69ca8eb690966c46da20ea947e54c50e16031b | dheeraj281/dataStructureProgrammes | /data_structure/strings.py | 792 | 4.09375 | 4 | #### reverse a string using recursion #####
def reverseWithRecursion(data):
size = len(data)
if size == 0:
return
print(data[size-1], end="")
reverseWithRecursion(data[0:size-1])
### reverse a string using stack ##########
class Stack:
def __init__(self):
self.item = []
... |
fbbf5b904f2df758cb0df76683d0a438d052db35 | Jingliwh/python3- | /pythonio.py | 3,039 | 3.5 | 4 | #python-IO学习
#open("路径","r/w")
#读写字符注意编码错误
#绝对路径与相对路径
#1读文件
#1.1文件打开
'''
f1=open("c:/Users/Administrator/Desktop/python_stydy/py3test/py3test.py","r")
str1=f1.read()
print(str1)
f1.close()
'''
#1.2打开文件捕获异常
'''
try:
f = open("py3test/py3test.py","r")
print(f.read())
except Exception as e:
p... |
e994ad4fc1aa12874506c8c3279807d9e5eb6884 | pwang867/LeetCode-Solutions-Python | /0670. Maximum Swap.py | 1,739 | 3.828125 | 4 | # time/space O(n), scan backwards, record the index of the pair to swap
class Solution2(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
s = list(str(num))
left, right = -1, -1 # (left, right) are the index of the pair to swap
max_... |
a6e419bd52c067ec4add6405cf8739f0d87593a5 | simplesmall/Python-FullStack | /Day0625/Day24_3主动调用其他类的成员.py | 1,429 | 3.84375 | 4 | #############################方法一######################
class Base():
def f1(self):
print('5个功能')
class Foo():
# class Foo(object): 这样写也可以调用到Base()里面的函数,跟自动调用以及这节涉及的东西没有关系
def f1(self):
print('3个功能')
# self不会自动传参
Base.f1(self)
# obj = Foo()
# obj.f1()
... |
94fa9e20600237d815201ca77511668a8429e5dd | hufslion8th/Python-Basic | /Assignment1/Minji-Choi/c-min-ji-hw.py | 756 | 3.984375 | 4 | #1
max_weight = 500
object1=float(input('첫번째 물건 무게: '))
object2=float(input('두번째 물건 무게: '))
current_weight = max_weight-(object2+object1)
print('첫번째 물건 무게:',object1,'두번째 물건 무게:',object2,'현재 엘레베이터의 허용무게는 ', current_weight,'kg 입니다')
#2
n = int(input())
for i in range(n):
print('■ '*n, end='\n')
#3
address = '용인시 처인구 ... |
ce9623c085d82a3d251343b63fbd0f58bce87199 | SehnazRefiye/Python-Data-Structure | /lab3.py | 274 | 3.921875 | 4 | #Write a short python function that takes a string s, representing a
#sentence and returns a copy of the string with all punctuation removed.
s = input("Please enter sentence: ")
x = ",:.;_-?*()[]'!/"
a = ""
for i in s:
if i not in x:
a = a + i
print(a)
|
9a49812810fcb6f40802f74afbadf09d8e2af7ee | ism-hub/cryptopals-crypto-challenges | /set1_5.py | 1,119 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Implement repeating-key XOR
Here is the opening stanza of an important work of the English language:
Burning 'em, if you ain't quick and nimbleI go crazy when\nI hear a cymbal
Encrypt it, under the key "ICE", using repeating-key XOR.
In repeating-key XOR, you'll sequentially apply each byt... |
eb10ae691ad6be372045aa3088a73d42765448b6 | EricaGuzman/PersonalProjects | /Python/conversion/KilometerConverson.py | 1,260 | 4.46875 | 4 | #Erica Guzman
#Lab 2
#This program calculates
#the number of miles traveled based on user input of kilometers traveled
#Define main
def main():
#Declare and initilaize float variables
#String userName
#Float Kilometers
#Float miles
#Float conversion = 0.621371
UserName = " "
Kilometers = miles = 0.0
... |
31a96cbaa1ee6548316c43887769bd3d5423a7f1 | adriansgrrx/Assignment-2-PLD-BSCOE-1-6 | /maxApplesAndChange.py | 281 | 4.0625 | 4 | yourMoney = int(input("Enter the amount of money you have: "))
applePrice = int(input("How much for an apple?: "))
maxApples = yourMoney // applePrice
yourChange = (yourMoney - maxApples * applePrice)
print(f"You can buy {maxApples} apples and your change is {yourChange} pesos") |
fac79c9b9f008743e5d0d6000bb88a5aa9339efa | timpark0807/self-taught-swe | /Algorithms/Leetcode/1324 - Print Words Vertically.py | 1,516 | 3.78125 | 4 | class Solution(object):
def printVertically(self, s):
"""
:type s: str
:rtype: List[str]
s = "HOW ARE YOU"
words = ['HOW', 'ARE', 'YOU']
^ ^ ^
['HAY', 'ORO', 'WEU' ]
['CONTE... |
69937625807a4506c0fec270b811849aa49920db | PWynter/LPTHW | /ex32.py | 1,047 | 4.625 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots,"]
change = [1, "pennies", 2, "dimes", 1, "quaters"]
# this kind of for loop goes through a list
for number in the_count:
# variable number is being assigned to each element of the_count
print(f"This is count {number}")
for fruit in fru... |
87c3d71c27b2af1609cbee3b0c6f385f4899f1b7 | PriyankaKhire/ProgrammingPracticePython | /Database Sharding/HelperFunctions/Database.py | 775 | 3.625 | 4 | import os.path
class Database(object):
def read(self, fileName):
output = ""
if not self.ifFile(fileName):
return output
file_object = open(fileName, "r")
for line in file_object:
output = output + line
file_object.close()
return ... |
0a63defc123bc6a4176e1be9e65acf1e6b2e081d | finddeniseonline/sea-c34-python.old | /students/MeganSlater/session06/static.py | 474 | 3.71875 | 4 | """ Question 1:
Can I use a static method to count the number of times
any particular class has been initiated?
"""
class Spam(object):
"""class counts number of times class was used.
Could add more features to this class if desired"""
numInstances = 0
def __init__(self):
Spam.numInstance... |
76ffa268fe760208943a46db3ee367aa56e67599 | brainaulia/dumbways | /2.py | 279 | 3.5 | 4 | # input: [19,22,3,28,26,17,18,4,28,0]
# output: [0,28,4,18,17,26,28,3,22,12]
def rev_array(lst):
rev=[]
for i in range(len(lst)-1,-1,-1):
rev.append(lst[i])
return rev
arr=[19,22,3,28,26,17,18,4,28,0]
print("input:",arr)
print("output:",rev_array(arr)) |
e2035a38d36064acedc8f4eac1a51b70cf24935f | liaison/LeetCode | /python/701_Insert_into_a_Binary_Search_Tree.py | 1,021 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
def dfs(node, value):
... |
85e8bc9c59ae5e0bd788a1f5bf45887a5536849f | hatamleh12/htu-ictc5-webapps-using-python | /W1/S2/ex0.py | 1,347 | 4.34375 | 4 | # Declaring a list
linux_distros = ['Debian', 'Ubuntu', 'Fedora',
'CentOS', 'OpenSUSE', 'Arch', 'Gentoo']
# Print the list
print("The list contains %s." % linux_distros)
print("The type of 'linux_distros' is '%s'." % type(linux_distros))
# Finding the length
print("The list contains %d elements." % l... |
3eaaec1d68c740b52537722c222f14855d87f0d3 | lxl0928/learning_python | /code/91_recommendations/quick_sort.py | 798 | 4.09375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: quick_sort.py
# author: Timilong
def quicksort(array):
less = []
greater = []
print("1: ", "array: ", array, "len(array): ", len(array))
if len(array) <= 1:
print("2: ", "array: ", array, "len(array): ", len(array))
return ar... |
712a5cbb6594ab223886264efb0f15a1e37634d7 | ouriblife/Game | /projectprototypeLatest (3).py | 10,525 | 4.03125 | 4 | #Trivia Game Sample Project by Fred Winters
#10 questions, predetermined order
#Topic - World History
import tkinter as tk #Label wraparound, wraplength=400 (ex), anchor = 'center'(ex)
import os
import sys
global runningscore,stage,questionset,photo
stage = 0
runningscore = 0
chancelevel = 0
count = 0
def initclue(): #... |
a69d60b06d67fa37adb95eb7a148677b2ffba31b | Aniket-Bhagat/Computing_tools_2 | /Q3.py | 937 | 3.953125 | 4 | print """------------------------------------------------------
| Extract Binary numbers only divisible by 5 |
------------------------------------------------------\n"""
def check(n):
binary=True
for i in str(n):
if i!='0' and i!='1':
binary=False
break
if binary==True:
if n%5==0 and n!=0:
retu... |
4214a11caff2b7a8e42955bb6cdb524ae639abc5 | Langzzx/OMOOC2py | /_src/om2py1w/1wex1/dialy_gui2.py | 528 | 3.890625 | 4 | # coding=utf-8
#exercise for Tkinter
import Tkinter as tk
from dialy import *
root = tk.Tk()
tk.Label(root, text="Hello world").pack()
var = tk.StringVar(value="Hi, please enter here:")
text_input = tk.Entry(root, textvar=var)
text_input.pack()
def update_text():
append_text(var.get())
text_output.config(text=ge... |
9cc542c3b8721d3c1a9eac830ed28b7c2caf0a5e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2433/60749/234323.py | 160 | 3.640625 | 4 | class Interval(object):
def _init_(self,s=0,e=0):
self.start=s
self.end=e
input=input()
lenint=len(input)
if lenint<2:
print(input)
|
8e7c6b38ef7805ac613ace50fe004123cd13e715 | Matias-Gutierrez/practica-con-python | /clase 2 semestre/clase 3/pangramas.py | 892 | 4.0625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# Nombre del Autor: Matías Gutierrez
# Bibliotecas importadas
# Definir funciones
def valPangramas(palabra):
letras = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","v","w","x","y","z"]
palabra = palabra.lower()
palabra = ... |
8976e8c7d285c9b60d3740abeb421e772e70c089 | visalakshi-annamalai/python_exercises | /problemset03/pbsiii5.py | 199 | 3.640625 | 4 | def avoids(str,forbidden):
for i in forbidden:
if i in str:
return False
else:
return True
str="rnbw"
forbidden=['a','e','i','o','u']
print avoids(str,forbidden)
|
5f0868392163cfd3a2063948710bc2292ddcbf52 | vonzhou/py-learn | /byte-python/chapter7/break.py | 216 | 3.984375 | 4 | #!/usr/bin/python
while True:
s = raw_input('Enter a string: ')
if ('quit'==s):
print 'The loop is exited.'
break;
print 'The len of your input is: ',len(s)
else:
print 'can you get here?'
print 'Done'
|
49c4b6116a513b47e3b585d44c593fed67fc7ef9 | angelusualle/algorithms | /cracking_the_coding_interview_qs/2.8/detect_loop.py | 891 | 3.953125 | 4 | class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
def detect_loop(linked_list):
slow = linked_list.head
fast = linked_list.head
while slow is not None and fast.next is not None:
s... |
e78b2b73c18e86d6eeedf1d23945a536cad57577 | martinbonneau/api-generator | /generator/functions.py | 878 | 3.90625 | 4 | from sys import exc_info
def replace_text(vars:dict, text:str):
for key, value in vars.items():
key = '$' + key + '$'
text = text.replace(key, value)
return text
#end replace(vars, text)
def replace_in_file(file, values):
try:
f = open(file, 'r')
f_content = f.read... |
c200b88edcb3ce8f6b752b9844bbdd85a22c7558 | bendanon/Riddles | /python/delete_node.py | 755 | 3.828125 | 4 | import unittest
"""
Delete a node from a singly-linked list, given only a variable pointing to that node..
"""
def delete_node(ptr):
if ptr.next is None:
raise Exception("Can't delete the last node!")
return
ptr.value = ptr.next.value
ptr.next = ptr.next.next
return False
class Li... |
d12dd5e22bfc0cee0279fe04122c392361663fb6 | gkdmssidhd/Python | /Python_day02/Day01Ex03.py | 917 | 3.859375 | 4 | from main import strr
user_name = input('성명 입력 >> ')
# input() 결과 형은 문자열이기 때문에
# 정수형으로 사용하기 위해서 정수형은 형변환 해줘야함.
#age = input("나이 입력 >> ")
#age = int(age)
age = int(input('나이 입력 >> '))
address = input('주소 입력 >> ')
str = """
성명 : {0}
나이 : {1}
주소 : {2}
""".format(user_name, age, address)
print(strr)
print('성명 : ' + use... |
db3d3082a22fab463748a6fdaf8aca03eceffa9c | psyvalvrave/Crime_Border_Rate | /crime_data.py | 3,829 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Names:Zhecheng Li
Program: Crime and Border project
Description: Extract data from wikipedia about cities
Calculate correlation between crime rate and distance to border
Last Modified: 02 Feb 2019
"""
from bs4 import BeautifulSoup
import urllib
import os
im... |
841f8fb53701708482047ee644bd59108ccb63c8 | ZainRaza14/gedcom_Agile | /userstories/sprint02_us/userStory16.py | 1,570 | 3.65625 | 4 | from ParserModule import parse_main
from utils import compare_date_to_todays_date,get_first_name
from print_main import printTables
'''
US16 Male last names All male members of a family should have the same last name
'''
def us16_male_last_names(file):
error_list = list()
#printTables(file)
'''
loop ov... |
13725bc5859e9eb572639a0ed7a93f60473901da | jrantunes/URIs-Python-3 | /URIs/URI1014.py | 397 | 3.8125 | 4 | #Consumption
#criar uma função para calcular o consumo medio de um automovel(distancia_percorrida / combustivel gasto)
def consumo(dp, cb):
res = dp / cb
print("{:.3f} km/l".format(res))
#ler a distancia percorrida(int)
dist = int(input())
#ler o combustivel gasto(float)
combs = float(input())
... |
4e0f0d2c9293e0882e023c23cb7d265664b0ed86 | Flor246/PythonFlor | /Modulo1/scripts/nombre.py | 71 | 3.671875 | 4 | nombre = input('Ingrese su nombre: ')
print('Hola {}!'.format(nombre)) |
ab0240ec05dd3939031569d1b95363c930d04804 | zacps/invis-encoder | /encoder.py | 1,793 | 4.1875 | 4 | #!/usr/bin/env python3
import gzip
import os
import sys
if len(sys.argv) != 3:
print("Expected two arguments, in file and out file")
sys.exit(1)
FILE = sys.argv[1]
OUT = sys.argv[2]
print('Opening file')
print(f'File length: {os.stat(FILE).st_size} bytes')
with open(FILE, encoding='utf8') as file... |
7276cff4b6d1d25fcec328169fd462561b7c829b | xiaohugogogo/python_study | /python_work/chapter_2/name_cases.py | 512 | 4.21875 | 4 | name = "Eric"
print("Hello " + name + ", would you like to learn some Python today?")
name = "zHAO yU Hu"
print(name.lower())
print(name.upper())
print(name.title())
sentence = 'Albert Einstein once said, "A person who never made a mistake never tried anything new."'
print(sentence)
famous_person = "Albert Einstein"... |
e37419585cf837002df1a9aa4a8a379082ac23f3 | FaderVader/CPH_AdvancedProg | /Dag07/bintree.py | 3,494 | 3.984375 | 4 | from collections import namedtuple
class BinTree:
"""
A binary tree.
>>> b = BinTree()
>>> b
BinTree(None)
>>> b[2] = "b"
>>> b[1] = "x"
>>> b[3] = "c"
>>> b[1] = "a"
>>> list(b)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> b.pprint()
- None
+ 1 = a
- Non... |
42c92e5875600612058a7d8a94a5aa1368c93e9e | alexander-jiang/RL2048 | /reinforcement_learning/experience_replay_utils.py | 4,399 | 3.5 | 4 | from collections import namedtuple
from typing import List
import numpy as np
BaseExperienceReplay = namedtuple(
"BaseExperienceReplay", ["state_tiles", "action", "successor_tiles", "reward"]
)
# action is encoded as an int in 0..3
ACTIONS = ["Up", "Down", "Left", "Right"]
class ExperienceReplay(BaseExperienceRe... |
a8cceb5cb380d26e5cecf192f65cd776a35ebe8e | govardhananprabhu/DS-task- | /longest palindrome with N digits.py | 1,293 | 4.15625 | 4 | """
Given a value n, find out the largest palindrome number which is product of two n digit numbers.
In des
First line contain integer N,denotes the range of digits.
Ot des
Print the palindrome.
2
9009
3
906609
Exp
From sample
9009 is the largest number which is product of two
2-digit numbers. 9... |
519981a7db5d32029a3efcdb9f915cee4077524d | monsterofhell/DSA-Python | /merge_sort.py | 814 | 3.875 | 4 | def merge_sort(a):
if(len(a) >1 ):
mid = (len(a))//2
part_one = merge_sort(a[0:mid])
part_two = merge_sort(a[mid:])
return merge(part_one,part_two)
return a
def merge(part_one,part_two):
final_list = []
len_one = len(part_one)
len_two = len(part_two)
ind_one = 0
... |
7e4b2f1a632d39c2b8227cc0a8321f4c61eb1775 | gauravcool/python-access-webdata | /ex_11_02.py | 197 | 3.59375 | 4 | fname = input("Enter file name: ")
if len(fname) < 2 : fname = 'mbox-short.txt'
handle = open(fname)
for line in handle:
line = line.rstrip()
if line.startswith('From'):
print(line) |
d6ec3f83772fa71bab1e0ffd2271980fceb16d70 | srinathalla/python | /algo/recursion/powerset.py | 507 | 3.90625 | 4 | #
# T.C : O(n*2^n) we have 2^n subsets created and at each subset creation we iterate through a list of size n for cloning
# S.C : O(n*2^n) we have 2^n subsets created and each subset can store a elements of size n.
#
#
#
def powerset(array):
subsets = [[]]
for x in array:
addElementToExistingSets(sub... |
6932f734e6614adde78ad8aad83307d1dfd79aed | faterazer/LeetCode | /2399. Check Distances Between Same Letters/Solution.py | 333 | 3.609375 | 4 | from typing import List
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
last = [0] * 26
for i, c in enumerate(s):
c = ord(c) - ord("a")
if last[c] and i - last[c] != distance[c]:
return False
last[c] = i + 1
... |
eb8862200dd6802189f233ec811af4f751b5a29f | lucifermorningstar1305/deeplearning | /NLP/brown.py | 3,566 | 3.625 | 4 | from nltk.corpus import brown
import operator
import re
class Brown():
def __init__(self):
pass
def remove_punctuation(self, sentence):
"""
--------------------------------------------
Description :
Funcion to remove punctuation from a sentence
Input :
... |
8fc23d51a49141c891d174c73be11063faa3289a | JinFree/cac.kias.re.kr-2017-3rd-day | /python_tutorial01/python_tutorial/basic/iteration.py | 249 | 4.25 | 4 | #!/usr/bin/env python
a = [ 'a', 'b', 'c', 'd', 'e' ]
for b in a:
print b
for i in range(len(a)):
print i, a[i]
a = { 'a': 1, 'b': 2, 'c': 3 }
for key in a:
print key, a[key]
for key, value in a.iteritems():
print key, value
|
ef3cf549c0f4d914b9fe24c4130dec9cffb5ddd0 | tuess/python | /others/基本/求最大值的顺序处理.py | 415 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
n=int(input("输入你有多少个数字要比较"))
max=float(input("输入一个数"))
for i in range(n-1):
i=float(input("输入一个数"))
if i>max:
max=i
print("最大值是:",max)
main()
##x1,x2,x3=eval(input("输入三个数字"))
##print("最大的是:",max(x1,x2x,x3))
##只有eval能同时多项赋值... |
17bca313d34e578c0992169925b4356f2bc5087a | amarshahaji/pythonprograms | /Assignment3/assignment3_2.py | 594 | 4.4375 | 4 | # 2.Write a program which accept N numbers from user and store it into List.
# Return Maximum number from that List.
# Input : Number of elements : 7
# Input Elements : 13 5 45 7 4 56 34
# Output : 56
import Assignment3Module as NumModal
size = int(input("how much number you want to enter "))
listofNumbers =... |
4f237b76624c0509d5d1dbb897032145d41658e9 | sabareesh123/pythonprogamming | /A6.py | 603 | 3.65625 | 4 | import sys, string, math
def IsIso(string1, string2):
W = len(string1)
n = len(string2)
if W != n:
return False
marked = [False] * 256
map = [-1] * 256
for J in range(n):
if map[ord(string1[J])] == -1:
if marked[ord(string2[J])] == True:
return False
... |
dd7e62a6b03cde077b782bf468ac1764c4822ecc | mondon11/leetcode | /0141hasCycle.py | 542 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
a = head
b = head
if not ... |
7d35cf4babe3ddc108f163fadae4deafddc683c7 | karloscalvillo18/Chapter_4 | /Backwards.py | 238 | 4.09375 | 4 | #Backwards.py
#By: Karlos Calvillo
#10/22/14
print("Hello! Lets type a word backwards for you.")
message=input("Type a word: ")
backward=""
counter=len(message)
while counter !=0:
backward+=message[counter-1]
counter-=1
print(backward)
|
0b2624a685615e6967f62ff1126bbeb49f66b563 | capric8416/leetcode | /algorithms/python3/palindrome_pairs.py | 771 | 4.125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e.
words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
E... |
b8b86b73970c461cb2544e16e31f2a0094274451 | tyree88/Object-Oriented-Programming | /PRACTICESORTING.py | 7,896 | 3.96875 | 4 | # File: sorting.py
# Description: Compares different sorting algorithms
# Student's Name: Charles Lybrand
# Student's UT EID: cbl652
# Course Name: CS 313E
# Unique Number: 51915
#
# Date Created: 04/07/2017
# Date Last Modified: 04/08/2017
################### GIVE CODE ###################
import random... |
2dd404a24a97541480000e106a29692324df8c90 | cikent/Python-Projects | /LPTHW/ex12-PromptingPeople-InputPrompts.py | 2,426 | 4.15625 | 4 | # prompt on-screen a question and save the value
age = input("How old are you? ")
# prompt on-screen a question and save the value
height = input(f"You're {age}? Nice. How tall are you? ")
# prompt on-screen a question and save the value
weight = input("How much do you weight? ")
# print to screen the results from t... |
d1ff162981c12e016ffb5e06372f0582c0f20c73 | bandiafatima/exo3.py | /exo2.py | 166 | 3.8125 | 4 | # pair ou impair
n = input (tapez la valeur n:")
n =int (n)
r = n % 2
-if (r=0) :
print ("le nombre n est pair")
-else :
print("le nombre n tapé est impair") |
f08be3cfadf06664f23ced5be7b9fe3f19448329 | Trietptm-on-Coding-Algorithms/ProjectEuler-2 | /4/palindrome.py | 853 | 3.75 | 4 | #############################
# Created By: Sean Moriarty #
# Created On:1/29/13 #
# Last Edit: 1/29/13 #
#############################
#Total of numbers multiplied and that number reversed
total = 0
totalBackwards = 0
#Variable for largest palindrome
largestPalindrome = 0
#For all numbers inbetween a ... |
ba01b8068e954f115f39d131c787cd7758f15635 | mattclarke/advent_of_code_20 | /day_15/day_15.py | 877 | 3.625 | 4 | PUZZLE_INPUT = "9,3,1,0,8,4"
# PUZZLE_INPUT = "0,3,6"
puzzle_input = [int(x) for x in PUZZLE_INPUT.split(",")]
print(puzzle_input)
turn = 0
record = {}
last = 0
for i in puzzle_input:
if turn == 0:
turn += 1
last = i
continue
# Put the previous value in to record
record[last] = t... |
f7194f8e1f742f05e4bf800bef8242aea0990509 | sivagopi204/python | /day 3-1.py | 500 | 4.1875 | 4 | #Write a program that declares and initializes a character variable.
#It prints true if the character corresponds to a digit i.e. one of 0, 1, 2, ..., 9; otherwise it prints false.
#Extend the program to check if it is an alphabet (i.e. one of a, b, ..., z or A, B, ..., Z) or a digit. Such characters are called alpha... |
f49f53e380001700c173022149fe060d07072026 | Prachithakur27/Python- | /dic.py | 542 | 4.34375 | 4 | dict = {};
print("Empty dictonary : ",dict);
#Dictionary holds key:value pair
dict = {1:'prachi',2:'manu',3:'gauri',4:'jayesh',5:'neha'};
print("Dictonary with some key:value pair : ",dict);
#Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
... |
076d72294177d8d771060dffa9a855d76b55e372 | Dylrak/CSNalarm | /main.py | 2,568 | 3.5625 | 4 | import RPi.GPIO as GPIO
import threading
import time
# constants
WINDOW_PORT = 13 # GPIO port for the 'window' (a.k.a. alarm initiation)
ALARM_PORT = 11 # port for alarm(s)
LOGIN_PORT = 15 # port for button to initiate login protocol
LOGIN_PASS = 'test' # password for login
TIME_PER_STEP = 10
MAX_STEPS = 100
cla... |
a412d099986f79f8a6dcc577bf60c57652cc2e01 | julianhasse/Python_course | /24_accesing_items.py | 558 | 4.28125 | 4 | letters = ["a", "b", "c", "d"]
print(letters[0])
letters[0] = "Julian"
for item in range(len(letters)):
print(letters[item])
# slicing a string
print(letters[0:3]) # returns 3 first items
print(letters[:3]) # zero is assumed
print(letters[0:]) # from first to the final item are returned
print(letters[:]) # ... |
41954adab4c6a36bcc67604d35adc9e5eeed62de | banga19/Personality-Guesser | /SecondPage.py | 594 | 3.796875 | 4 | from tkinter import *
HEIGHT = 450
WIDTH = 350
root = Tk()
frame2 = Frame(root, height=HEIGHT, width=WIDTH)
frame2.pack()
canvas2 = Canvas(root, height=HEIGHT, width=WIDTH, bg="#ffff99")
canvas2.pack()
L3 = Label(canvas2, bd=7, text="WHAT IS YOUR FAVORITE COLOR ?", )
L3.place(relx=0.5, rely=0.25, r... |
361193ccc4dcb92021f67c2ae7147acda2ce9d31 | christabella/code-busters | /pancakeflipper_linear.py | 1,221 | 3.984375 | 4 | #!/usr/bin/env python
'''The idea is that we can greedily determine whether a flip needs to be
made at each position in order for the pancakes to be happy.'''
import itertools
def all_combinations(l):
all_lengths = range(0, len(l)+1)
return itertools.chain.from_iterable(
itertools.combinations(l, i)
... |
e6616e98b6e1ed3afd73778acc750a89e95cb15d | SurakietArt/Programming.in.th | /03_Min Max.py | 139 | 3.5 | 4 | list = []
amount = int(input())
for i in range (1,amount+1):
num = int(input())
list.append(num)
print(min(list))
print(max(list)) |
881bbca0c9fb9de944545f45b9bfd4e27025cc9c | sagarnikam123/learnNPractice | /hackerRank/tracks/coreCS/algorithms/sorting/maximumSubarraySum.py | 2,305 | 3.84375 | 4 | # Maximum Subarray Sum
#######################################################################################################################
#
# We define the following:
# A subarray of an n-element array, A, is a contiguous subset of A's elements in the inclusive range from some
# index i to some inde... |
f5e8aad949f66be0727a8b4fad9f8e913b1566f5 | OnildoNeto/Aplica-oEscolaVers-o | /DDL.py | 3,032 | 3.78125 | 4 | import sqlite3
conn = sqlite3.connect('EscolaApp_versao2.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE tb_escola(
id_escola INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(45) NOT NULL,
FK_id_endereco INTEGER NOT NULL,
FK_id_campus INTEGER NOT NULL,
... |
3819d8be9271675530111bb3c4d6246ed166ea5f | deyukong/pycharm-practice | /practice/calculate prime.py | 673 | 4.0625 | 4 |
def countPrimes(n):
lst = list(range(4, n))
# print(lst)
nonprime = set()
if n in range(0, 3):
return 0
if n == 3:
return 1
for value in lst:
# print("the value is:",value)
i = 2
while i * i <= value:
# print("i is:",i)
if val... |
6df51a881da4331eac2441cfb5daa1534f41813b | odedf23232/Author-Verification-and-Determination-System | /document.py | 5,347 | 3.5 | 4 | import string
from typing import List, Tuple
from scipy import sparse
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import TfidfVectorizer
def _get_stop_words() -> List[str]:
"""
Loads stop words for using when transforming.
:return: list of stop words.
"""
# In "A Time... |
5e2dd354b7bbd8b1be5576aface1c16686d93910 | ddowns-afk/python | /exercise_8.py | 1,099 | 4.09375 | 4 | #quit = input('Type "enter" to quit: ')
#while quit != "enter":
# quit = input('Type "enter" to quit: ')
import sys
player_1 = input('Player 1 enter your name: ')
player_2 = input('Player 2 enter your name: ')
player_1_input = input(player_1 + ' choose rock, paper, or scissor: ')
player_2_input = input(player_2 + '... |
7247b8ca499ad0a0d436ca35c2ee07c3a3bdbec6 | BE-Project-Catastrophic-Forgetting/brain-inspired-replay | /models/fc/excitability_modules.py | 4,010 | 3.5 | 4 | import math
import torch
from torch import nn
from torch.nn.parameter import Parameter
def linearExcitability(input, weight, excitability=None, bias=None):
"""
Applies a linear transformation to the incoming data: :math:`y = c(xA^T) + b`.
Shape:
- input: :math:`(N, *, in\_features)`
... |
5f582c6451bf0284b243a1a7b7612f3991221289 | pivoda-madalina/word-counter | /main.py | 880 | 4.03125 | 4 | def word_counter(file_name):
"""This function counts the words from file! \
Return's word dictionary."""
word_dict = {}
with open(file_name) as f:
for line in f:
for chr in (",", "!"):
line = line.replace(chr, "")
for word in line.split():
... |
86c6c54ddb43e73e3fef652c6a81986d313286bf | zz-zhang/some_leetcode_question | /source code/151. Reverse Words in a String.py | 698 | 3.5625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
res1 = []
res2 = []
# print(words)
left, right = 0, len(words) - 1
while left <= right:
while len(words[left]) == 0 and left < right:
left += 1
while len(w... |
9c14cc2a5dffd4ff7b4ecb35bafa98086cf81194 | SupratimH/learning-data-science | /statistics/concepts/regressionAnalysis.py | 3,016 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 02 2018
@author: Supratim Haldar
"""
import math
import summaryStatistics as ss
from functools import reduce
""" Calculate Correlation Coefficient, r = 1/(n-1)*Sum(Z_X * Z_Y) """
def CorrCoeff(data_X, data_Y):
nX, nY = len(data_X), len(data_Y)
assert nX == nY and ... |
01c1d0b2074f85a066bae10cbdea096962c16b64 | Proffett/testsPY | /57.py | 56 | 3.546875 | 4 | str = input()
space = str.replace('@', '')
print(space)
|
5287a37129630dddb9ee0dccc6a9cc223584cfc5 | Aasthaengg/IBMdataset | /Python_codes/p03210/s600936103.py | 66 | 3.65625 | 4 | age = int(input())
print("YES") if age in (3,5,7) else print("NO") |
86e5da92b6fbcc9cba0147edd3b43d3fd4a5a391 | Schrodingfa/PY3_TRAINING | /day6/func_demo/ex13.py | 382 | 3.9375 | 4 | # Author:jxy
# day3 ex1 升级版
# 定义根据月份判断季节的方法
def season(month):
if month < 1 or month > 12:
return 'invalid parameter'
if month <= 3:
return 'spring'
if month <= 6:
return 'summer'
if month <= 9:
return 'autumn'
return 'winter'
m = int(input('please input a mouth:'))... |
5edce2bc9c3fde39962da9d16adfb5a28b747630 | ZhengZixiang/interview_algorithm_python | /jianzhi/09.斐波那契数列.py | 408 | 3.734375 | 4 | # 输入一个整数 n ,求斐波那契数列的第 n 项。
#
# 假定从0开始,第0项为0。(n<=39)
#
# 样例
# 输入整数 n=5
#
# 返回 5
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
... |
fed713acac0b749e6388f42b1626a66acabdb9df | jangwoni79/Programming-Python- | /VIII. 파일 처리/read_text_FILE.py | 267 | 3.625 | 4 | # f = open("file.txt","r")
#
# text = f.read()
# print(text)
#
# f.close()
f = open("file.txt", "r", encoding = "utf8") #r : read text
text0 = f.readline() # \n까지 읽기
print(text0)
text1 = f.readline()
print(text1)
text2 = f.readline()
print(text2)
f.close() |
637dddcecf8d94694ca72ef9b2e3c39c5290db06 | Alex-Au1/Matrix_Calculator | /string.py | 655 | 4.125 | 4 | from typing import Dict, List
# word_replace(str, word_dict) Replaces every instance of the
# keys from 'word_dict' that are found in 'str' with its
# corresponding value in 'word_dict'
def word_replace(str: str, word_dict: Dict[str, str]) -> str:
for w in word_dict:
replace_word = word_dict[w]
str = st... |
5f621cfcba22794060c52eb473ee25be8fd2026e | farh33n/building-restAPI-for-MLmodel-using-flask | /model.py | 378 | 3.640625 | 4 | from sklearn.linear_model import LinearRegression
class Model(object):
def __init__(self):
self.reg = LinearRegression()
def train(self, X, y):
"""Trains the regression model
"""
self.reg.fit(X, y)
def predict(self, X):
"""Returns the predicted value
"""
... |
41dcc07e49e88815684d4646620ae1ca50b19404 | gksheethalkumar/Python_Practice | /BSTree-prac.py | 971 | 3.9375 | 4 | class node():
def __init__(self,data = None):
self.data = data
self.rightval = None
self.leftval = None
def insert_tree(self,data = None):
newval = node(data)
if self.data:
if data < self.data:
if self.leftval is None:
se... |
acebab89ec3945473d19be6650d7ff40b08762bb | LPIX-11/ChessPyGame | /playChess.py | 9,003 | 3.546875 | 4 | # Importing pygame library for game environement building
import pygame
import os
from pygame.locals import *
# Importing the chess board
from board.chessBoard import Board
from board.move import Move
from ai.minimax import Minimax
# Initializing the environment
os.environ['SDL_VIDEO_CENTERED'] = '1' # You have to c... |
e8b8408bfa25e06286596c9d9457465f2d9479bf | Raghavendrajoshi45/python | /cel2fer.py | 173 | 4.09375 | 4 |
print("enter your num")
celsius = int(input())
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) |
38b386bb3c26567e1a9e0c82ae2dc857e9e7f5d2 | wanbibi/crawDemo | /interpy/4.1.py | 338 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
items = [2,4,5,6,7]
res = []
for i in items:
res.append(i*i)
print res
list1 = list(map(lambda x:x**x,items))
print list1
def jia(x):
return x+1
def jian(x):
return x-1
funcs = [jia,jian]
for i in range(1,5):
print i
value = map(lambda x:x+10, items)
... |
25e3d5239667030e4c8f95f23c355b96fb3440f1 | mrunmayichuri/reverse_engineering_little_fish | /fish_keygen.py | 499 | 3.671875 | 4 | #! /usr/bin/python
#Mrunmayi Churi
#Keygen for http://crackmes.de/users/vik3790/little_fish./
import sys
def generate_key(username):
C = 0
m = min(len(username),4)
for i in range (0, m):
C |= ord(username[i]) << (3 - i) * 8
C = (C*15 + 0xFF) & 0xFFFFFFFF
return "%X" %C
if __name__ == "__... |
33fe26368d6c12ce729f6256af2b670d971bdec6 | Somraz/Detect-ORF | /data_preprocessing.py | 1,641 | 3.59375 | 4 | #This code was used to pre-process textual features
import re
import csv
import os
import pandas as pd
from string import punctuation
from nltk import stem
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from ftfy import fix_text
stopwords = set(stopwords.words('english'))
stemm... |
1b26e38f72c8778b9645d8e26b3e89b0d1939f5d | maro199111/programming-fundamentals | /programming_lab/lab021019/anonimo5.py | 305 | 3.796875 | 4 | fl1 = float(input('Inserire il valore 1: '))
fl2 = float(input('Inserire il valore 2: '))
fl3 = float(input('Inserire il valore 3: '))
def x1x2(a,b,c):
x1 = -fl2 + ((fl2**2 - 4*fl1*fl3)**(1/2))/(2*a)
x2 = -fl2 - ((fl2**2 - 4*fl1*fl3)**(1/2))/(2*a)
return x1, x2
print(x1x2(fl1,fl2,fl3))
|
bfa12e0c452a9d4095c350de0095efbbf6003e83 | cassac/twitter_sentiment | /happiest_state.py | 2,028 | 3.828125 | 4 | """
ASSIGNMENT 1.5 FOR UOW COURSERA DATA SCI COURSE
SUMMARY: Calculates happiest state in continental
USA based on sentimental scores of tweets grouped
by states.
Run script:
python happiest_state.py AFINN-111.txt [tweets filename].txt
DATE: 2015/07/09
"""
import sys
import json
import re
from collections import d... |
e21741bb453c28884f83eec112ff854c788963d1 | ShiXianzheng/python-learning | /Built_in_Functions.py | 11,962 | 4.15625 | 4 | """
author: xzshi19
date: 2019.08.28
Aim: learn python's built-in functions
"""
# abs(x) --return the absolute value of a number; a complex number --> it's magnitude
# all(iterable) --return true if all elements of the iterable are true(or empty)
def all(iterable):
for element in iterable:
if n... |
42cbf660b2edacb5f21e818c32e725825e78bbc3 | mscwdesign/ppeprojetcs | /debuggando_com_pdb.py | 300 | 3.78125 | 4 | """
Debuggando com PDB
PDB -> Python Debugger
# Exemplo com PyCharm
def dividir(a, b):
try:
return int(a) / int(b)
except ValueError:
return ('Valor Incorreto')
except ZeroDivisionError:
return 'Não é possivel dividir por zero'
print(dividir(4, 7))
"""
|
7bd9650d367076410e57b118277d26612946b7b0 | Tech-at-DU/CS-1.0-Introduction-To-Programming | /T002-Working-with-Variables/assets/T2-CheckPlease.py | 852 | 4.28125 | 4 | # Check Please!
# Step 1: Assign the integer value 94102 to a variable named zip in the console.
# Step 2: Check the type of the variable zip by entering the line type(zip) in the console.
# Step 3: Assign the string value "San Francisco" to a variable named city. Remember to surround your string value with either s... |
2cc8e7e7918ec620a9969c1fa9f7df24e3605d28 | Hungs20/INT3117 | /phanhoach.py | 707 | 3.546875 | 4 | import unittest
def get_price(weight):
if weight > 0.0 and weight < 5.0:
return 5
elif weight >= 5.0 and weight < 10.0:
return 10
elif weight >= 10.0 and weight < 30.0:
return 15
else:
return "Không hợp lệ"
class TestMethods(unittest.TestCase):
def test1(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.