blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd07971c3ebea63ba60990fb68c53dc34710c94e | STELMASHENKO/SQLtasks | /Company Python/sql18.py | 550 | 3.546875 | 4 | import csv
with open('companyProduct.csv') as productCSV:
products = csv.reader(productCSV, delimiter=',')
Prod = {}
for product in products:
Prod[product[2]] = product[1]
del Prod['model']
print(Prod)
with open('companyPrinter.csv') as printerCSV:
printers = csv.reader(printerCSV, delimit... |
927271f95d3d2f6ba3a0026079e1937dd6bafc7b | duongvutuanminh/functional_programming | /musicplayer PYTHON/musicplayer.py | 2,081 | 4.03125 | 4 | """
Author: Duong Vu Tuan Minh
Application: Music player
Date: 7/5/2020
"""
#Creating a defined music player
# from playsound import playsound
class Track:
def __init__ (self,number,track_title, author, location):
self.number = number
self.track_title = track_title
self.author = author
... |
9aa4faa1229301a72d43e8f90d7d20e4edd5f374 | SenayYakut/Python-Coding-Challanges | /reverse.py | 526 | 4.4375 | 4 | '''
Write a function named reverse_string that has a string named word as a parameter. The function should return word in reverse.
'''
# Write your reverse_string function here:
def reverse_string(word):
reversed = ""
for i in range(len(word), ):
reversed += word[-i-1]
return reversed
# Uncomment these f... |
5b500dd41da4389f8a215d29fa96f0b581839cac | green-fox-academy/nandormatyas | /week-04/day-03/nandi_work.py | 1,326 | 3.84375 | 4 | class Apple():
def get_apple(self, string_input):
return string_input
class Summa():
def sum_numbers(self, numbers):
summa = 0
for number in numbers:
summa += number
return summa
class Anagram():
def anagram(self, one_string, two_string):
one_string = ... |
e9e85d18792bf3175a691fdb3cff116435a645ef | JinzhuoYang/hogwarts | /class_pritice/class_pritice1.py | 682 | 3.65625 | 4 | class person:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def set_att(self,value):
self.value = value
def eat(self):
print(f" name : {self.name}, age : {self.age}, gender : {self.gender} i'm eat")
def drink(self):
... |
5893d0cc3aab0e96f8a5fe3d78ef878e6d24c637 | harshvijaythakkar/Training | /text wrap.py | 415 | 3.921875 | 4 | def wrap(string, max_width):
start = 0
end = max_width
ans = ""
while end<=len(string):
l = ""
l = string[start:end]
ans=ans+l+"\n"
#print(ans)
start = end
end += max_width
if end > len(string):
ans=ans+string[start:len(string)]
return str(... |
6c075f0d5107d08cff43f1c0e0b9ef1511f1168f | Deviloxide/Dynamic-Python-Programming | /1.2 Indirect Recursion.py | 295 | 3.65625 | 4 | def func1(string, n):
if n > 0:
print(string, "called func1 with n =", n)
func2("func1", n - 1)
def func2(string, n):
if n > 0:
print(string, "called func2 with n =", n)
func1("func2", n - 2)
def main():
func1("main", 7)
main()
|
3d54fdcee1439318515ac50b46c311700003f3cf | rogeriosilva-ifpi/ifpi_ads_algoritmos_2020 | /algoritmos_fabio01_parte02/f1_p2_q3_semanas_dias.py | 258 | 3.71875 | 4 | # Leia um número inteiro de dias, calcule e escreva quantas semanas e quantos dias ele corresponde.
dias = int(input('Quantidade de dias: '))
s = dias // 7
d = dias % 7
print('{} dias correspondem a {} semana(s) {} dias(s)'. format(dias, s, d))
|
9d9fc3f3eea56f9f5ba3b72f89b5850cd2131a1f | ck-unifr/breadth-first-search | /breadth-first-search.py | 1,581 | 3.953125 | 4 | # sample tree implemented as a dictionary
tree = {'A': ['B', 'C', 'E'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B', 'H', 'I'],
'E': ['B'],
'F': ['C'],
'G': ['C'],
'H': ['D'],
'I': ['D'],
}
"""
A
/ | \
B ... |
9bfbaf3ef616e537d0f0b53b13884501a988e735 | jackfan108/GameProgramming | /2014/test.py | 470 | 3.546875 | 4 | from math import *
from lib import *
board = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
board = addrandomnumber(board,2)
board[1][2] = 16
board[2][3] = 128
board[0][1] = 1024
printboard(board)
#board has been initiated with two tiles
if (True):
move = raw_input("Please choose where to go(\"w,a,s,d\"): ")
if move == ... |
54ea9c4981783af9cf533f61e24b1f8a98197215 | LEECHHE/acmicpc | /solved/2562.py | 161 | 3.625 | 4 | cur_max = -1;
index = -1;
for i in range( 0, 9 ) :
cur = max( input(), cur_max )
if cur_max < cur :
cur_max = cur
index = i + 1
print cur_max
print index |
6717de65dadead7a5e97e829f4cfd266e911f1ce | saberly/qiyuezaixian | /thread/thread_func.py | 460 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 23 16:16:48 2017
@author: ice-fire
"""
import threading
def thread_func(x):
print("%d\n" %(x * 100))
threads = []
for i in range(6):
threads.append(threading.Thread(target=thread_func, args=(100,)))
for thread in threads:
thread.start(... |
5c0929786782c5ee9c1ee9235b7708a85a414cbb | saber-030/Python-Codes | /Histogram_Normal.py | 994 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 22:08:38 2020
@author: neel
"""
"""
Program to view 3 normal distribution in the same plot,
using matplotlib, numpy, scipy and math libraries,
view label, style and legend
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
#... |
d66a4e497aeb1f8ff1faba8a966d9cecc24bdc87 | N-Shilpa/python | /rock_paper_scissors.py | 1,201 | 4.15625 | 4 | p1=input("enter your name")
p2=input("enter your name")
print("you want to play the game?")
player1=input("%s enter your choice yes or no" %p1)
player2=input("%s enter your choice yes or no" %p2)
while(player1 and player2)=="yes":
player1=input("%s choose your option in the following :\n1.rock \n2.paper \n3.scissor... |
10edfba38b13849d436cb9245ca9d0739f0be3e4 | wavetogether/wave_algorithm_challenge | /2020/2020-03/04/joy.py | 858 | 3.515625 | 4 | class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
b = len(nums) -1
f = 0
i = 0
while i <= b:
if i != b and nums[i] == 2 and nums[b] == 2:
... |
67a8b069ca4f898e787e047042ed3f611be38231 | Oleksandr-Korol/My_Python3_lab | /HomeWork1.py | 228 | 3.875 | 4 | number = input ("Введіть Ваш вік >>> ")
number = int (number)
if number < 16 :
print ("Привіт;")
elif number < 30 :
print ("Вітання;")
else:
number > 30
print ("Добрий день.")
|
3329278f0bc2948e769c41d5f7a2a42508eb21eb | allenmattp/automate | /ch15/encryptPDF.py | 445 | 3.921875 | 4 | #! python3
# Add encryption to a PDF doc
import PyPDF2
password = input("Select a password: ")
pdfFile = open("meetingminutes.pdf", "rb")
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWrite... |
cca8899424ce75a39f93a620b67625367f30e564 | bogdan-stv/2PEP21 | /C03_collections/app_1.py | 695 | 3.703125 | 4 | from collections import UserString, Counter
class InformationGetter(UserString):
def information(self):
my_data = Counter(self.split())
for key in my_data.keys():
if len(key) <= 3:
my_data[key] = 0
print(my_data)
sum = 0
for value in m... |
604df8cd3843ceda63be8c4a7de19eb31f088611 | sbeetsma/TeamV1A1 | /mongo_to_pg.py | 7,704 | 3.5625 | 4 | import PostgresDAO
import MongodbDAO
def retrieve_from_dict(dict: dict, key):
"""Tries to retrieve a value from a dictionairy with a certain key, and catches the KeyError if it doesn't exist.
Args:
dict: the dictionairy to retrieve the value from.
key: the key associated with the desired data... |
ad25c74b791217c989b1095c532fbb069d6d6860 | chenlei65368/algorithm004-05 | /Week 1/第一周练习题.py | 6,253 | 3.5625 | 4 | # 26. 删除排序数组中的重复项
# 使用双指针-->快慢指针
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = 0
for j in range(1,len(nums)):
if nums[j] != nums[i]:
nums[i] = nums[j]
i+=1
return i + 1
# 189. 旋转数组
class Solution:
def... |
9e55bcf02c3d10841fee311f2a6ae9253b227f91 | Kanres-GH/Pokolenie-Python-Stepik | /Мини проекты/Шифр Цезаря.py | 632 | 3.90625 | 4 | def caesar(alphabet):
text = input("Text: ")
shift = ii("Shift: ")
def get_char(char, alphabet_, shift_):
if char.isalpha():
i = 0
if char.isupper():
i = 1
return alphabet_[i][(alphabet_[i].index(char) + shift_) % len(alphabet_[0])]
return char
... |
04e66e72ff02b5f720df6f792f548dfa506c542d | poojataksande9211/python_data | /python_tutorial/excercise_10_enumerate_function/any_and_all_func.py | 707 | 4.28125 | 4 | #any and all function
#write a program to check all eve no or not(by using all function)
# numbers1=[2,4,6,8,10]
# numbers2=[1,3,5,7,9]
# even_no=[]
# for num in numbers1:
# if num%2==0:
# even_no.append(True)
# print(even_no)
#-------------------------------
# even_no1=[]
# for num in numbers1:
# even_... |
b34d652dec480dd486be6c21ce15603b3e3bf90b | Oushesh/Fast-GRE-py | /GRE_Essay_001.py | 4,687 | 3.609375 | 4 | '''
GRE Essay.py
##Reference https://www.youtube.com/watch?v=mhzlaHXHaK4
### Reference to original https://www.gregmat.com/
Choosing a thesis:
mostly agree: body1, body2, body 3
'''
'''
Introduction:
The following appeared in a letter to the editor of a journal on
environmental issues.
"Over the past year, the Crus... |
48452b8e0a8629aa948fca46c745f27bde1c036d | AndrewAct/DataCamp_Python | /Statistical Thinking in Python (II)/Parameter Estimation by Optimization/Fertility_Data.py | 353 | 3.75 | 4 | # 5/16/2020
# Plot the illiteracy rate versus fertility
_ = plt.plot(illiteracy, fertility, marker ='.', linestyle ='none')
# Set the margins and label axes
plt.margins(0.02)
_ = plt.xlabel('percent illiterate')
_ = plt.ylabel('fertility')
# Show the plot
plt.show()
# Show the Pearson correlation coefficient
print(p... |
28f452c07b6b98f408ab29727e6fdd8d1e120b6f | Learning-and-Intelligent-Systems/lis_pr2_pkg | /scripts/simple_ros_examples/echo.py | 2,001 | 3.59375 | 4 | #!/usr/bin/env python
"""
This program recieves an image from a rostopic and converts it
to a cv2 image. Then, it immediately converts it back to a
ros message of type sensor_msgs/Image and publishes it on the
rostopic ~echo_image.
"""
import cv2 # the open cv library packge
import rospy # standard ros with python p... |
ee54f81bae6481307b238a70493b53288bd675a1 | testcg/python | /code_all/day04/homework/exercise04.py | 706 | 4.0625 | 4 | """
在终端中录入4个同学体重,打印最轻的值.
效果:
请输入第1个同学体重:100
请输入第2个同学体重:120
请输入第3个同学体重:93
请输入第4个同学体重:160
最轻的同学:93
"""
weight01 = int(input("请输入第1个同学体重:"))
weight02 = int(input("请输入第2个同学体重:"))
weight03 = int(input("请输入第3个同学体重:"))
weight04 = int(input("请输入第4个同学体重:"))
min_value = weight01
if m... |
b611365007feff03441dbd95f6091a1748f8ec33 | adigeak/leetcode | /python/leetcode1.py | 195 | 3.609375 | 4 | def square(x):
return x*x
def map_fuc(fuc, arr):
a = []
for i in arr:
a.append(fuc(i))
return a
x = [ i for i in range(1,6)]
squares = map_fuc(square,x)
print(squares) |
38d42bb1b348f608126fe30ad82cf0a50eec55eb | marina8888/gas-analysis-dilution-method | /src/graph_creator/graph_funcs.py | 6,088 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from excel_file.classes import Workbook
import numpy as np
# all functions in this file are a custom set of methods/options to use when creating a new graph plot
plt.style.use('seaborn-notebook')
# the dictionary can be used to access the graph's data (x, y etc. va... |
c6c13277f59cc654ccbd30770ffab9dc6bfc0c2f | DanielFHermanadez/Readme | /Trabajo#1/Python/Trabajo#1.py | 95 | 3.625 | 4 | n1 = 5
n2 = 7
n3 =3
multiplicacion= n1+n2+n3
print("la multiplicacion es",multiplicacion)
|
cabe6c0306c7e734ae3bef039e1138e44e239440 | VFermat/BlockChain | /myblockchain/Block.py | 836 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 08:24:21 2018
@author: Vitor Eller
"""
from hashlib import sha256
from datetime import datetime
class Block:
def __init__(self, transactions, previous_hash):
self.timestamp = datetime.now()
self.transactions = transactions
self.previo... |
6df4a276f9fbaa0b0df7c558fc6a0950509aefd2 | vnpavlukov/Study | /Coursera/2_Coursers/Basic_progr_in_Py/Week_3/Test_12_linear_equation_system.py | 277 | 3.703125 | 4 | a = float(input())
b = float(input())
c = float(input())
d = float(input())
e = float(input())
f = float(input())
if (d * a - c * b) != 0:
x = (e * d - b * f) / (d * a - c * b)
y = (f * a - c * e) / (d * a - c * b)
else:
x = 0
y = 0
print(float(x), float(y))
|
8f1e19ddd0b2ad305243b5fe03a64e6198c55623 | dylanbrams/Classnotes | /practice/change/blackjack.py | 2,133 | 4.34375 | 4 |
def point_from_card (card_value):
'''
Converts a one-letter card name to a numeric value.
:param card_value: String to convert to a card value.
:return:
'''
face_cards = ('J', 'Q', 'K')
if (card_value in face_cards):
return 10
return 0 if (card_value == 'A') else int(card_value)... |
7f69c4d7035594b4d72f9e8143b1996ca238dd53 | godmoves/Poker_CFR | /example_strategy.py | 4,000 | 4.03125 | 4 | # coding: utf-8
import numpy as np
def random_distribution(n_items):
""" Returns a random probability distribution over n items. Formally, we
choose a point uniformly at random from the n-1 simplex.
"""
return np.random.dirichlet([1.0 for i in range(n_items)])
def uniformly_random_strateg... |
acc0c040d0524d48babb988e56a37cafce4db10b | tranj5371/studious-train | /P3HW2_MealTipTax_Tran.py | 1,299 | 4.21875 | 4 | # CTI-110
# P3HW2 - MealTipTax
# Johnny Tran
# February 26, 2019
# Ask user to input the charge for food at restaurant
Charge = float(input("How much did the restaurant charge you for the food? "))
# Ask user how much they would like to tip
Tip = float(input("How much would you like to tip? (15%/18%/20%) "))
# Calc... |
b3f17fb083d52bf93768b291ed120ca82799a274 | Brunox117/Mision_02 | /conversiongrados.py | 256 | 3.78125 | 4 | # Autor: Bruno Omar Jiménez Mancilla A01748931
# Descripcion: Un programa que convierta grados fahrenheit a grados celsius
# Escribe tu programa después de esta línea.
f=float(input("Ingresa los grados Fahrenheit: "))
c=(f-32)*(5/9)
print("Grados Celsius: ",c,"°C")
|
08eb418dd1a32a77613059383bab9d3553d69e5d | GaurangAthavale/Must-do-coding-questions | /BST/BST_insert.py | 959 | 4.125 | 4 | # Tree Node
class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
# The function returns the root of the BST (currently rooted at 'root')
# after inserting a new Node with value 'Key' into it.
def insert(root, Key):
# code here
if(root == None):
... |
20e791f333d25da46ddd4dc61b4f9b6a62d320a7 | ravitej5226/Algorithms | /ambigous-coordinates.py | 2,345 | 3.875 | 4 | # We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string S. Return a list of strings representing all possibilities for what our original coordinates could have been.
# Our original representation never had extraneous ... |
d744e6938ac84628e1a069dcfdeacf523decd993 | ErikaGonzaga/ExerciciosPython | /EstruturaSequencial/Exercicio3.py | 228 | 4 | 4 | # Faça um Programa que peça dois números e imprima a soma.
numero1 = int(input("Informe o primeiro número"))
numero2 = int(input("Informe o segundo número"))
soma = numero1 + numero2
print("O resultado da soma é", soma) |
bda015ac68f4a078074295161d65a7ce4a0fb98e | trinitybest/Learning-From-Data | /homework2-2.py | 7,532 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 12 00:05:14 2016
@author: TH
Q5
"""
import random
import numpy as np
class Point(object):
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self.y = y
def shuffle(self):
self.x = random.uniform(-1.0, 1.0)
... |
96c05016010780f1a8a8494aacadcd629e1fc8b1 | nscherf/linus | /DataConverter/CsvLoader.py | 2,426 | 3.546875 | 4 | import csv
import os
from .AbstractLoader import AbstractLoader
class CsvLoader(AbstractLoader):
""" A helper to load a folder of CSV files and to represent it by:
- a numpy array for the positions, [n_tracks, n_pos_per_track, 3 (x/y/z)]
- a numpy array for attributes, [n_tracks, n_pos_per_track,... |
302764e3fcaa8169f8b36550476a00979070aead | 26sneharoy/programming-lab | /while.py | 186 | 3.6875 | 4 | n=int (input("enter the limit"))
s=0
i=1
while(i<=n):
s=s+i
print (s)
if(s>=25):
break
i=i+1
else:
print("sum of first ", n," natural numbers is ",s) |
cd805eff135bdb2a708e1ffbabdbeeae19b1144c | echeng1514/Python_Homework | /杨辉三角.py | 249 | 3.640625 | 4 | import math
x = 20
for n in range(0,x):
for _ in range(0,x):
print(end=' ')
x-=1
for m in range(0,n+1):
c = int(math.factorial(n)/(math.factorial(m)*math.factorial(n-m)))
print(c,end=' ')
print()
|
3ff7b7ea6a0df8144b05a932f5020e970947749a | pbhuss/ProjectEuler | /problems/p045.py | 933 | 3.796875 | 4 | def triangle_gen():
n = 1
while True:
yield n * (n + 1) // 2
n += 1
def pentagonal_gen():
n = 1
while True:
yield n * (3 * n - 1) // 2
n += 1
def hexagonal_gen():
n = 1
while True:
yield n * (2 * n - 1)
n += 1
def main():
generators = [tr... |
1024cf039c1b5afd010d15c740e2343a6d901260 | chr1sbest/ctci | /python/2_Linked_Lists/2_6.py | 1,382 | 3.96875 | 4 | """
2.6
Given a circular linked list, implement an algorithm which returns the
node at the beginning of the loop.
"""
from classes import ListFactory, SpecialNode
def loopFinder(llist):
"""
Find the start point of a loop within a linked list.
Implements walker/runner.
Time complexity = O(n)
Space c... |
fc5cff75b1b64ef28532b1f08a966ebf295b3d1c | ulfgtm/hilel | /hw 4.py | 889 | 3.578125 | 4 | #1
my_list = [150, 300, 500, 125, 70, 90]
for i in my_list:
if i > 100 :
print(i)
##############################
#2
my_list= [70, 80, 100, 300, 152]
my_results=[]
for i in my_list:
if i > 100:
my_results.append(i)
print(my_results)
############################
#3
my_list = [1, 2, 3, 5]
if... |
11892dde515f48820a4bce9ff93da3a8af912ee0 | damianoimola/fundamentals-of-it-exercises | /pre_exam_functions.py | 13,803 | 3.953125 | 4 | ##############
# PROVA PROF #
##############
""" PROBLEMA 1 """
def checkString(str, alphaCounter, digitCounter):
# @param str : Str
# @param alphaCounter : List
# @param digitCounter : List
lenght = len(str)
if lenght == 0:
return True
elif lenght == 1:
return alphaCounter == digitCounter
... |
a3d4bf86b37ab82552424698a650a572b7df3903 | mourad1081/natural-language-processing | /assignments/assignment 2/Parser.py | 8,898 | 3.5 | 4 | from conllu import parse
class Oracle:
def __init__(self):
"""
Creates an instance of an oracle.
"""
self.reference_parse = {}
def set_reference_set(self, reference_parse):
"""
set the set of features
:param reference_parse: path to the file containing ... |
7ca3b94c318ea20a70344394349a069f627a5405 | GimmeShelter90/tms-python-z14-onl | /src/task_2_4.py | 201 | 4.1875 | 4 | # Создать строку равную введенной строку без последних двух символов.
str = input('Введите строку: ')
print(str[:(len(str) - 2)])
|
ae0d3c929f844448c5a67bd25f00d5926879d186 | RD-Harry/Tarena | /ftp-sever.py | 4,882 | 3.828125 | 4 | """
FTP 服务器客户端
env python 3.6
多线程 tcp 并发
"""
from socket import *
from threading import *
import sys, os
import time
# 全局变量
HOST = '0.0.0.0'
PORT = 8888
ADDR = (HOST, PORT)
FTP = "/home/tarena/PycharmProjects/hannah/" # 文件库位置,后面加一个/是为了方便后面拼接直接+就可以了
# 客户端处理类 查看服务器 上传、下载
class FTPSever(Thread):
def __init__(sel... |
23360ef9cb3a4b546654478e9a3df54c953d6f55 | BCPST/TP | /TP3.py | 2,509 | 4.5 | 4 | """
Les listes :
C'est un type composé/un conteneur -> type str : chaîne de caractères
par opposition aux types simples float/int/complex/bool
Une liste est une collection d'objets séparés par des virgules et est délimitée par des crochets.
Utilité :
- stocker les éléments d'une suite (les premiers termes)
- les list... |
f9e6f560f94f921dc1cafe2cc65cb40312e3d31c | ahsan-javaid/python-learnings | /polymorphism.py | 714 | 3.65625 | 4 | from abc import abstractmethod
from abc import ABC
class TouchScreenLaptop(ABC):
@abstractmethod
def scroll(self):
pass
@abstractmethod
def click(self):
pass
class HP(TouchScreenLaptop):
def scroll(self):
print('hp')
@abstractmethod
def click(self):
pass
c... |
e4d3c847251e15a0ce098dc9809a5dd333bd404f | django-group/python-itvdn | /домашка/starter/lesson 5/Sokolov Aleksandr/Task_1.py | 179 | 4 | 4 | name = input('Your name is: ')
def baz():
if name == '':
print('Hello, ', 'Aleks', '!', sep='')
else:
print('Hello, ', name, '!', sep='')
baz() |
ca12efa7b1cbab5f05bff38c646fa13fc1837a61 | Balakishan77/Spam-Email-Classifier | /spam_ham.py | 4,342 | 3.59375 | 4 | #Categorizing given email is spam or ham
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
dataset = pd.read_csv('spamham.csv')
dataset.head()
dataset .columns #Index(['text', 'spam'], dtype='object')
dataset.shape #(5... |
9e1d36f324b6f147c8012dba63332df8a4c8f720 | sophie-macmillan/python-exercises | /patience/shuffle.py | 685 | 4.0625 | 4 | from random import random
def shuffle(L):
'''
Uses the Dursten algorithm in order to shuffle the list L
'''
n = len(L)
NL = L #creates a new list, identical to the original, so that the original list is preserved
Nlist = range(1, n) #creates a new list, with the indexes of the original... |
4dcf125f8219488be1f166c8b246251213b8ed4a | zerohk/python | /c6_2favo_num.py | 319 | 3.59375 | 4 | favo_num = {
"tom":22,
"jerry":33,
"jack":44,
"rose":55
}
print(favo_num)
print("\n")
print("Tom's favo num is " + str(favo_num["tom"]))
print("Jerry's favo num is " + str(favo_num["jerry"]))
print("jack's favo num is " + str(favo_num["jack"]))
print("Rose's favo num is " + str(favo_num["rose"]))
|
3fc5fea7069c1876bde930acd6132ce44998e6dc | SebastianoFazzino/Python3-Programming-by-University-of-Michigan | /Python Classes and Inheritance/Sorting_Lists_of_Istances.py | 1,048 | 4.40625 | 4 | #given a list of istances, we may want to sort them by some index
class Fruit():
def __init__(self, name, price):
self.name = name
self.price = price
def sort_priority(self):
return self.price
FruitList = [
Fruit('Cherry', 10),
Fruit... |
57925240399caa6637d5191e7cd44e89efe4cd36 | singhsanket143/CppCompetitiveRepository | /UnacademyCourse/IntoductionToPythonJun2020/variables.py | 343 | 3.53125 | 4 | # Variables are buckets that store some piece of information in the memory
x = 10
a,b,c = 10,20,30
print(x)
print(a, b, c)
# python is dynamically typed
# python is sometimes considered both loosely and strongly typed based on different paramteres of the measure
v = 10
v = "hello"
# Swap variables
x , y = 12, 15
x... |
f2a23cec095293276968d6a262cab04f31e28557 | Dust1989/DataStructures-learn | /queue_list_su/linkedlist.py | 1,817 | 4.0625 | 4 | class LinkedList:
def __init__(self):
self.__root = None
def get_root(self):
return self.__root
def add_start_to_list(self, node):
if self.__root:
node.set_next(self.__root)
self.__root = node
def remove_end_from_list(self):
marker = self.__root
... |
fc8467b483bd5abfde36aefcde0a635420fdcac2 | iamsiva11/Codingbat-Solutions | /warmup1/pos_neg.py | 892 | 4.28125 | 4 | # Given 2 int values, return True if one is negative and one is positive.
# Except if the parameter "negative" is True, then return True only if both are negative.
#Correct for more than half the tests
def pos_neg(a, b, negative):
if(negative):
if(a<0 and b<0):
return True
else:
if(a<0 or b<0):
return Tr... |
397c1ea8bec97c80e1fdd8d4e234d74856d086a4 | suprajaarthi/Favourite-Snippets | /OrderedDict.py | 266 | 3.734375 | 4 | from collections import OrderedDict
words = OrderedDict()
for _ in range(int(input())):
word = input()
words.setdefault(word, 0)
words[word] += 1
print(len(words))
print(*words.values())
# ip:
# 4
# bcdef
# abcdefg
# bcde
# bcdef
# op:
# 3
# 2 1 1
|
5cac0d49cd0e3aa11a4984c1084c75e2be53e180 | cravo123/LeetCode | /Algorithms/0186 Reverse Words in a String II.py | 555 | 3.640625 | 4 | class Solution:
def reverse(self, A, start, end):
while start < end:
A[start], A[end] = A[end], A[start]
start += 1
end -= 1
def reverseWords(self, A: List[str]) -> None:
"""
Do not return anything, modify str in-place instead.
"""
... |
ad45638a55d9e23e8f40dcf57549129ab327baef | akshaykalyan/solutions | /binary_multiple_three.py | 164 | 3.59375 | 4 | import re
PATTERN = re.compile(r'^(0)*((0)*1(0(1)*0)*1)*(0)*$')
for x in range(100):
print(re.match(PATTERN,"{:b}".format(x)))
if x%3==0:
print(True,x)
|
ace7363ab943ae0e5966ffb713a120b49fb4ca78 | unmeshvrije/python-summer-school | /Lecture-Notes/2019/pss-2019-spider1.py | 758 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 30 10:20:57 2019
@author: unmesh
"""
import random
import sys
def generate_random_number():
while True:
yield random.random() * 75
# The code to accept the input from user
# n = int(input("How many random numbers do you want : "))... |
be3379d38f3dd391537cc779c9653a607b5a9166 | marjoriecarlson/Advent_of_Code | /9b.py | 883 | 3.828125 | 4 | #!/usr/bin/python
# This time, just count pieces of garbage INSIDE <>s, including excess
# <'s but excluding the < and > that delineate the garbage. Ignore !s.
stream = open('input/9.txt','r').read()
garbageSeen = 0
justSawBang = False # should I ignore this char?
inGarbage = False # will be used to decide whet... |
b622e8162ed5a4b97c142840b4adde086f0051fe | lucasvalhos/books | /PythoneDjangoDesenvolvimentoAgilDeAplicacoesWeb/1 - Starting/programa1.py | 581 | 4.1875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# programa1.py - Primeiro programa
"""
Importa o módulo random e sorteia
um número inteiro entre 1 e 100
"""
import random
numero = random.randint(1,100)
escolha = 0
tentativas = 0
while escolha != numero:
escolha = input("Escolha um número entre 1 e 100:")
t... |
4b8eb0b4c25ae73d1a503891ea9533670192b738 | bennyvo/PRP201_Python | /Course2_Python.Data.Structures/Week6_Tuples.Chapter10/PRP201_C2_W6_Draft.py | 813 | 3.5 | 4 | # d = {'a':10,'b':1, 'c':22}
# t = sorted(d.items())
# print(t)
# for k, v in sorted(d.items()):
# print(k,v)
# c = {'a':10, 'b':1, 'c':22}
# tmp = list()
# for k, v in c.items():
# tmp.append((v,k))
# print(tmp)
# tmp = sorted(tmp, reverse=True)
# print(tmp)
fname = 'romeo.txt'
fpath = '/Users... |
e8dd99e74ad830b46a8f8c313408253c0eab0b8d | genghisken/gkspecies | /inchi/code/tools/python/roman_numerals.py | 1,034 | 4.25 | 4 | # convert an integer to a roman numeral
# keep it reasonable since from 5000 on special characters are used
# see also: http://en.wikipedia.org/wiki/Roman_numerals
# tested with Python24 vegaseat 25jan2007
# 2011-06-20 KWS Roman numerals required to set spectroscopic ionization status for elements.
# ... |
101c493ee697d3fc1e1d8f5d5acff1122ac6c935 | TamaraGBueno/Python-Exercise-TheHuxley | /Atividade Continua 4/Impressão.py | 1,003 | 4.03125 | 4 | #Faça um programa de resolução de tabuada. O programa deve inicialmente receber 2 números que indicam de quais números devem ser impressas a tabuada. Por exemplo, se forem recebidos os valores 2 e 5, seu programa deve imprimir a tabuada de 2, 3, 4 e 5. O programa só deve aceitar valores entre 1 e 9. Enquanto o usuário ... |
f6d251b7ce4ca030b8c98220a4b3b9f5c15d86e8 | brigitteunger/katas | /test_add_binary.py | 1,648 | 3.640625 | 4 | import unittest
class Solution:
def addBinary(self, a: str, b: str) -> str:
return format(int(a, 2) + int(b, 2), '0b')
def addBinaryBitByBit(self, a: str, b: str) -> str:
len_a = len(a)
len_b = len(a)
diff = abs(len_a - len_b)
if len_a > len_b:
b = [0]*diff... |
762b8fdb8ba2f5f35178c585619e459751494d69 | LeafmanZ/CS180E | /[Chapter 06] Functions/Step counter.py | 221 | 3.734375 | 4 | ''' Define your function here '''
def steps_to_miles(user_steps):
return user_steps/2000
if __name__ == '__main__':
''' Type your code here. '''
steps = int(input())
print('%.2f' % steps_to_miles(steps))
|
29b21a9e3d80e634c8e6572ed6c05146b0825853 | chengchengXCC/interview_questions | /LintCode/1st_round_fail/224.py | 1,424 | 4.03125 | 4 | class ThreeStacks:
# @param {int} size, the size of each stacks
def __init__(self, size):
# initialize your data structure here.
self.array = [None for i in range(3 * size)]
self.size = [0 for i in range(3)]
self.maxSize = size
# @param {int} stack_num an integer
# @para... |
c51e9f98db7e05ec3f1adb762eaa10c8367fd83d | karen-pal/SGBDpy | /client_layer/utils.py | 778 | 3.59375 | 4 | import json
def parse_input(infile):
#content = []
#
#for line in open(infile):
# line = line.replace("{","")
# line = line.replace("}","")
# content.append(line)
# print(line)
content = json.load(open(infile))
parsed_content = {}
parsed_content["database_name"]=conte... |
480f4e1a2779aee0301d99cb8a6fddd40c5233db | gauravkdm/PythonInterviewbasics- | /test63.py | 366 | 4.09375 | 4 | for row in range(7):
for col in range(5):
if (row==0 and col!=0 and col!=4) or (row==3 and col!=0 and col!=4) or (row==6 and col!=0 and col!=4) or(col==0 and row>0 and row<4)or (col==4 and row>3 and row<6):
print("*",end="")
else:
print(end=" ")
print()
# Output :
# ... |
b365bbfbf5d51814de9784cd738037baabe44320 | daniel-reich/ubiquitous-fiesta | /94DMDTYe89i6TLCZh_5.py | 786 | 3.609375 | 4 |
def get_languages(num):
if num == 100:
return ['Java','Python','Ruby']
elif num == 25:
return ['C#','JavaScript','PHP']
elif num == 255:
return ['C#','C++','Java','JavaScript','PHP','Python','Ruby','Swift']
elif num == 53:
return ['C#','Java','PHP','Python']
elif num == 12:
return ['Java'... |
2aa776415918254faad34d6bc4379a3da92e7d07 | chengchengpeng/fisher | /fisher/test/format_test.py | 1,333 | 3.9375 | 4 | """
print('通过关键字: '+'{名字}今天{动作}'.format(名字='陈某某', 动作='拍视频'))
grade = {'name' : '陈某某', 'fenshu': '59'}
print('字典作为关键字:'+'{name}电工考了{fenshu}'.format(**grade)
1 print('{1}今天{0}'.format('拍视频','陈某某'))#通过位置
2 print('{0}今天{1}'.format('陈某某','拍视频'))
填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度
1 print('{:^14}'.format('陈某某'))
2 print('{:>14}'.... |
575dc35869360b9b14b6ea99f0cdd228e73fdd4d | vibhuk16/6.00.1x | /FinalExam/Problem3.py | 641 | 4.21875 | 4 | def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
For example, if we lace 'abcd' and 'efghi',
we would get the new string: 'ae... |
e6ee0279d63b701841508b05b741a95ba51a4af5 | flaviokosta/python_basico | /aula2-exercicio.py | 685 | 3.9375 | 4 | '''
EXERCICIO: Faça um formulário que pergunte o nome,
CPF, enderçeo, idade, altura e telefone e
imprima isso em um relatório organizado
'''
nome = input('Digite seu nome: ')
cpf = input('Digite seu CPF: ')
endereco = input('Digite seu endereço: ')
idade = input('Digite sua idade: ')
altura = input('Digite sua altura:... |
40e36630adfeb40592e5eb95d5e1c795c4f3f54b | naresh0101/Warm_up_python | /whichNumRep.py | 241 | 3.75 | 4 | # =============counting a number how much time is repeting
a = input("enter the number")
a = str(a)
flag0 = 0
flag1 = 0
for i in a:
if i == '0':
flag0 = flag0 + 1
if i == '1':
flag1 = flag1 + 1
print "0 : " ,flag0
print "1 : ",flag1
|
97bb398a2b0d49b0ff24fa770d5301763b6f6c7c | jtlai0921/AEL022131_- | /hw04程式設計/hw04_2.py | 501 | 3.921875 | 4 | while (1):
print('=== 主功能表 ===')
print('1. 新增作業')
print('2. 修改作業')
print('3. 查詢作業')
print('0. 結束程式')
c = input('請輸入選項(0~3):')
if c == '1':
print('新增作業…')
continue
if c == '2':
print('修改作業…')
continue
if c == '3':
print('查詢作業…')
continue... |
857cb14c3570f489043415a71204ec1592fa3292 | juliazhuzhu/MyFirstPython | /src/14_4_2.py | 1,130 | 3.75 | 4 | import sqlite3
import os
import json
dbPath = '/Users/zhuyiye/StudyHome/sqlite_testdb/data.sqlite'
if not os.path.exists(dbPath):
conn = sqlite3.connect(dbPath)
c = conn.cursor()
c.execute(''' CREATE TABLE persons
(id INT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
age ... |
f5f7981d6de2145addb0f3eb3ef2963be160ee42 | Ayaanfaraz/CricAnalysis | /extractTest.py | 690 | 3.59375 | 4 | testString = 'jxfbanana1jxfbanana2jxfbanana3jxf'
# while True:
# firstPos = testString.find('ban')
# secondPos = testString.find('jxf',firstPos)
# fruit = testString[firstPos:secondPos]
# print(fruit)
# previousFruit = fruit
# if count >1 and fruit == previousFruit:
# break
# could make a function and rec... |
0db8492dea44f2c30b120f41f5ad01e5379c579c | StanAileron/DataStructure-py | /graph/knight_tour_by_graph.py | 5,169 | 4 | 4 | #!/user/bin/python
# -*-coding:UTF-8-*-
"""使用图解决骑士周游问题:
问题描述:国际象棋中的骑士,行棋方式与中国象棋中的马相类似,走“日”字。
现在的问题是,在国际象棋棋盘上为骑士找到一条路径,
使之可以经过棋盘的每个格子恰好一次,并返回路径参数的表。
"""
from typing import List, Tuple
from graph import Graph, Vertex
DIRS = ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2))
def... |
62759a9ea3e70b7a8235a27a2c91d93416807c7f | RajatPrakash/Python_Journey | /2 d matrix.py | 118 | 3.6875 | 4 | matrix = [
[1,2,3],
[4,6,7]
]
print(matrix[0][1])
for row in matrix:
for item in row:
print(item) |
16ddfcaa72551f1263e9c9ec9b0f5c70f4941b51 | Morgan1you1da1best/unit5 | /sortingProject.py | 1,539 | 3.984375 | 4 | #Morgan Baughman
#11/27/17
#cocktailSort.py - implementation of cocktail sort
from random import randint
from time import time
N = 100 #how many numbers will be sorted
def quickSort(A,lo, hi):
if lo < hi:
p = partition(A, lo, hi)
quickSort(A, lo, p - 1 )
quickSort(A, p + 1, hi)
return... |
1539afb9b78cc5443d21f735cea311b299f2bbc9 | FefAzvdo/Python-Training | /Aulas/010.py | 245 | 4.125 | 4 | # Estruturas condicionais
idade = int(input("Quantos anos você tem ? "))
if idade >= 18:
print("Maior de idade")
else:
print("Menor de idade")
# Condições simplificadas
print("Maior de idade" if idade >= 18 else "Menor de idade")
|
47aebe8f239ac5a17193b17750c9482d1bf28ce8 | RyanLBuchanan/Simple_Linear_Regression | /Simple_Linear_Regression.py | 1,617 | 4.28125 | 4 | # Simple Linear Regression from Machine Learning A-Z - SuperDataScience
# Input by Ryan L Buchanan 10SEP20
# Import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1]... |
4add0c99a9c7e01a2d825ca854593d39bf31f6c5 | AkankshaKaple/Python_Data_Structures | /basic_Python/ex11.py | 230 | 3.75 | 4 | # 11. Write a Python program to check whether a file exists.
import os
exists = os.path.isfile('/home/bridgeit/PycharmProjects/BasicPython/DataStructures/Array2.py')
if exists:
print("Present")
else:
print("Not present") |
e27d656ea9938de7179b24c0e66290e5ef117f5e | davidleonardo11/LaboratorioVCSRemoto | /main.py | 522 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 19:50:52 2020
@author: DAVID LEONARDO
"""
NumeroA = int(input("Ingrese numeroa: "))
NumeroB = int(input("Ingrese numerob: "))
NumeroC = int(input("Ingrese numeroc: "))
NumeroD = int(input("Ingrese numerod: "))
producto = (NumeroA*NumeroC)
Doble = NumeroA*2
Cuadrad... |
a38e6d60040e99d04ee2ce645e488e56ed3901d9 | malik-maciej/python_tasks | /encrypt/main.py | 597 | 4 | 4 | from encrypt import encryption, decryption
def main():
operation = input(("Wybierz operacje (szyfrowanie, "
"deszyfrowanie, wyjscie): ")).lower()
if operation == "wyjscie":
exit()
else:
if operation == "szyfrowanie":
user_text = input("Podaj tekst: ").low... |
46eed9108f6d3b1b50c7b55a272af2e3e0fe7a14 | delaven007/2-advance | /data-structure-数据结构/3-二叉树-二分查找-快排-递归/day3/search.py | 374 | 3.703125 | 4 | """
search.py 基本查找方法训练
"""
# 对有序数列进行二分查找
def search(list_,key):
low,high = 0,len(list_) - 1
while low <= high:
mid = (low + high) // 2
if list_[mid] < key:
low = mid + 1
elif list_[mid] > key:
high = mid - 1
else:
return mid
l = [1,2,3,4,5,6,7,8,9,10]
print("Key index is:",search(... |
d755797413961da565989925d9478839b0db3041 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/hllrob020/mymath.py | 399 | 4.03125 | 4 | #mymath program to calculate permutations
#Robin Hall
#17/04/2014
def calc_factorial(n):
factorial=1
for i in range(1,n+1): #calculates factorial for number n
factorial*=i
return factorial
def get_integer(a):
x=input("Enter {}:\n".format(a))
while not x.isdigit():... |
ddc016ab66f0ff34b2f56a49f50f1654527a4764 | wxm-pythoncoder/niu-niu- | /算牛.py | 2,146 | 3.53125 | 4 | # -*- coding: utf-8 -*-
dict={'A':1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,'J':10,'Q':10,"K":10}
a=[]
n=0
while n < 5:
b=input("please input your card: ")
if b not in dict.keys():
print("请输入正确的牌")
else:
b=dict[b]
a.append(b)
n=n+1
if (a[2]+a[1]+a[0])%... |
78f9934e0215a878c1e6580d60d0993b6012d833 | harshad90/pythonHardWay | /Exercise17.py | 465 | 3.578125 | 4 | from sys import argv
from os.path import exists
script, from_file, to_file = argv
print (f"Does file {from_file} exists:? {exists(from_file)}.")
input_file = open(from_file,'w')
print (f"Contents of input {from_file} file are:")
line1 = input(">")
input_file.write(line1)
indata = input_file.read()
print (f"copyin... |
159bfd175fa3f9c996a128bca534b1d922821d3c | amsun10/LeetCodeOJ | /Algorithm/Python/string-to-Integer-8.py | 1,319 | 3.65625 | 4 |
class Solution(object):
"""
https://leetcode.com/problems/string-to-integer-atoi/
"""
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
value = str.strip()
is_minus = False
if value.startswith("-"):
value = value[1:]
... |
6e551b6a8972453a61c86b3d5071da22a09a99a8 | HoangHip/TaHoangAnh-fundamental-C4E-29 | /Session02/homework/turtle2.py | 309 | 3.859375 | 4 | from turtle import *
speed(3)
shape("turtle")
pencolor("red")
for i in range(6):
left(60)
forward(100)
for i in range(4):
left(90)
forward(100)
pencolor("blue")
for i in range(2):
left(120)
forward(100)
right(60)
for i in range(4):
right(72)
forward(100)
mainloop() |
b01ea64911a9a12ed0158ed240271202a69015df | HyunwooMoon-developer/python-practice | /Tuple.py | 246 | 3.6875 | 4 | # CAN NOT CHANGE
menu = ('PIZZA' , 'PASTA')
print(menu[0])
print(menu[1])
# menu.add("COKE") add is impossible
name = 'Moon'
age = 30
hobby = 'Coding'
print(name, age, hobby)
(name, age, hobby) = ('Moon', 30, 'Coding')
print(name, age, hobby) |
dfdca3cea39aa13f2e34fdfa7d92a48db900ee5f | ThiagoTescaro/estudo-python | /udemy/python_e_kivy/exercicio2-3.py | 288 | 3.796875 | 4 | #coding: utf-8
#Faça um algoritmo que leia dois números e imprima o maior.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
if n1 >= n2:
print("O maior número digitado é %i" %n1)
else:
print("O maior número digitado é %i" % n2) |
43ea248909956c8f680277e3806793b3f10910d0 | ojssuo/python | /while_list.py | 94 | 3.703125 | 4 | # -*- coding: utf-8 -*-
L = ["Bart", "Lisa", "Adam"]
n=0
while n<3:
print(L[n])
n = n + 1
|
76f2c7c566ee7bcdf4c2318f28e5780ef604285c | wyaadarsh/LeetCode-Solutions | /Python3/1056-Confusing-Number/soln.py | 331 | 3.578125 | 4 | class Solution:
def confusingNumber(self, N: int) -> bool:
chars = list(str(N))
if any(ch in chars for ch in "23457"):
return False
d = dict(zip('01689', '01986'))
ans = []
for i in reversed(range(len(chars))):
ans.append(d[chars[i]])
return an... |
e4fa4fc2784d7ae67add643b9df263fc088cce7e | bradyt/project-euler | /python/p074.py | 1,854 | 3.75 | 4 | # Digit factorial chains
# Problem 74
# The number 145 is well known for the property that the sum of the
# factorial of its digits is equal to 145:
# 1! + 4! + 5! = 1 + 24 + 120 = 145
# Perhaps less well known is 169, in that it produces the longest
# chain of numbers that link back to 169; it turns out that there ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.