blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
1c323c793a58d3736ccbec00ffbccb447f7ca21c | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.8 Definite Loops and Dictionaries.py | 376 | 4.4375 | 4 | __author__ = 'Kevin'
# 06/04/2015
# Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a
# dictionary - actually it goes through all of the keys in the dictionary and looks up the values
counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
for key in counts:
... |
44df3f26086799bea3f88ec4e814ee785fba53ef | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.1 Lists Introduction.py | 1,057 | 4.1875 | 4 | __author__ = 'Kevin'
# 01/04/2015
# A List is a kind of Collection
# - A collection allows us to put many values in a single "variable"
# - A collection is nice because we can carry all many values around in one convenient package.
friends = ['Joseph', 'Glenn', 'Sally']
carryon = ['socks', 'shirt', 'perfume']
print f... |
151748740604378d807b3bc5fd24e1be09c73350 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 6 Strings/Code/Lab 6.15 Making everythin UPPERCASE.py | 350 | 4.21875 | 4 | __author__ = 'Kevin'
# 23/03/2015
# You can make a copy of a string in lower case or upper case.
# Often when we are searching for a string using find() - we first convert the string to lower case
# so we can search a string regardless of case.
greet = 'Hello Bob'
nnn = greet.upper()
print nnn
# HELLO BOB
www = gree... |
b58f7834041a1b85d3b8d153d45278be7c67f89b | Ivan-Sorochinsky/DriveSupervisor | /mouth_chart.py | 1,120 | 3.8125 | 4 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.style.use('dark_background')
fig = plt.figure()
# рот
ax = fig.add_subplot(1, 1, 1)
def animate(i):
try:
# данные о уровне открытия рта
with open('mouth_data.txt') as mouth_file:
mouth_data = mouth_file.rea... |
bf28f2d0c1a53d612df23922a87c9fea398cf44c | AnumFatima210/PIAIC_python_assiignments | /marksheet.py | 2,055 | 4.09375 | 4 | print("*************************MARKSHEET GENERATOR*************************")
input_roll=int(input("Enter your roll_number(XXXXXX) : "))
print("CHOOSE YOUR MAJOR SUBJECT")
print(" 1. SCIENCE \n 2. COMPUTER")
user_input_major_subject=int(input())
if(user_input_major_subject==1 or user_input... |
9b8d4507753005eb6b821ca3b73136ac26106908 | thedarknstormy/python_crash_course | /name_cases.py | 353 | 4.0625 | 4 | first_name = "sharod"
last_name = "duncan"
full_name = f"{first_name} {last_name}"
#this line will print full_name in lower case
print(full_name.lower())
#this line will print full_name in all upper case
print(full_name.upper())
#this line will print full_name with capitalized first letters of the first_name and la... |
3ae00b60c745ba85a6984d27ab7651010f037243 | ScoJoCode/ProjectEuler | /problem56/main.py | 315 | 3.625 | 4 | import time
import math as m
start = time.time()
SUM = 0
for i in range(1,100):
for j in range(1,100):
num = pow(i,j)
word = str(num)
sum = 0
for n in range(0,len(word)):
sum+=int(word[n])
if sum>SUM:
SUM=sum
end = time.time()
print SUM
print 'time elapsed: ' + str(end-start)
|
4ff057f5206a6d6509d5de02f88c51b495ae9bda | ScoJoCode/ProjectEuler | /problem19/main.py | 881 | 4.15625 | 4 | import time
start = time.time()
def isLastDay(day,year,month):
if day==31 and (month==1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
return True
if day==30 and (month ==4 or month == 6 or month == 9 or month == 11):
return True
if month == 2 and day==28:
if ... |
04eb9290d1e2879eeb7a6ecae50d10bd4b037795 | ScoJoCode/ProjectEuler | /problem15/recursive.py | 517 | 3.859375 | 4 | import time
start = time.time()
side = 18
def move(i,j):
sum = 0
#if i==side-2:
# return (side-j+1)*(side-j+2)/2
#if i==side-3:
# return (side-j+1)*(side-j+2)*(side-j+3)/(2*3)
if i==side-4:
return (side-j+1)*(side-j+2)*(side-j+3)*(side-j+4)/(2*3*4)
if i<side and i==j:
sum = sum+2*move(i+1,j)
... |
73a8e94b6dce1be0d52c46cc00f2cbc571a3df62 | ScoJoCode/ProjectEuler | /problem58/main.py | 769 | 3.78125 | 4 | import time
import math as m
start = time.time()
def isPrime(n):
for i in range(2,int(m.sqrt(n))+1):
if n%i==0:
return False
return True
#primes = [2]
#j=3
#while j < 1000000:
# for e in primes:
# if j%e==0:
# break
# if m.sqrt(j)<e:
# primes.append(j)
# break
# j+=1
nDiag=1
nPri... |
cd8b81f4e1ebacec17d279cb1a4edec3122ab1a2 | TakayukiTooyama/react-konva-test | /psm-2/parabolic_sums.py | 733 | 3.796875 | 4 | import math
# useful link: https://www.intmath.com/integration/6-simpsons-rule.php
def calculate(func, x0, x1, subdivision_length_approx):
def f(x):
return eval(func, {'x': x})
area_length = x1-x0
n_of_subdivisions = math.floor(area_length / subdivision_length_approx)
if n_of_subdivisions % 2... |
816e1dc1a516ea224ff95dfab6f0cafef8000192 | nirajp786/Bookshop-Database-App | /frontend.py | 3,246 | 4.15625 | 4 | """
A program that stores this book information:
Title, Author
Year, ISBN
User can:
View all records
Search an entry
Add an entry
Update entry
Delete
Close
"""
from tkinter import *
import backend
def get_selected_row(event):
global selected_tuple
if books.size() > 0:
index=books.curselection()[0]
... |
c46edd82588625e9d2c94313872017b4ae7aad0e | dundubi/Data-Sampling-C110 | /code1.py | 751 | 3.671875 | 4 | import random as rd
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics as st
import pandas as pd
data = pd.read_csv("medium_data.csv")
population_mean = st.mean(data)
def random_set_of_mean(counter) :
dataset = []
for i in range(0,counter) :
rand_index... |
6639ac6d83f8150127ae7c31870cb8da4d35e074 | wanuix/DM_Study | /TreePloter/TP_Building_02.py | 1,204 | 3.546875 | 4 | """
对每个特征划分数据集的结果计算一次信息熵
然后判断按照哪个特征划分数据集是最好的划分方式
"""
import TP_Building_01 as TP1
def splitDataSet(dataSet, axis, value):
"""
按照给定特征对数据集进行划分
:param dataSet: 数据集
:param axis: 划分数据集的特征
:param value: 特征值
:return:
"""
# 创建新的list对象
retDataSet = []
# 抽取数据集中的数据
... |
4a0956244406e25735f30a9a2df2823f9748537a | Vliseev/made_algo2 | /13/1/solution.py | 2,101 | 4.09375 | 4 | from dataclasses import dataclass
import io
import math
import sys
@dataclass
class Circle:
x: int
y: int
r: int
def __add__(self, other):
return Circle(self.x + other.x, self.y + other.y, self.r + other.r)
def __sub__(self, other):
return Circle(self.x - other.x, self.y - other.... |
a2bc17247a54545c5073239455e16956d2f66db9 | Namrata9910/python-algorithm | /cracking_the_coding_interview/ch_8_recursion_and_dynaminc_programming/(8.6)tower_of_hanoi.py | 229 | 3.9375 | 4 | def hanoi(n, From, to, using):
if n > 0:
hanoi(n - 1, From, to, using)
print("move disc from ", From, " to ", to)
hanoi(n - 1, From, using, to)
if __name__ == "__main__":
hanoi(3, "A", "B", "C")
|
3fdd83cbfe08f47d53f648341c87ab9885e99ee6 | afeeni/Survive | /PlayGame.py | 2,627 | 3.90625 | 4 | from CreateGame import *
from State import *
from crash_site import *
from intro import *
startStates = [introState0, crashState0]
# This method simply introduces the user with game intro
def introduction():
print("*****Welcome to Survive!*****\n\nThis is a choice based survival game where you need to make right cho... |
717ff8afe8fb98acf1ee2e7f879c1280057b3517 | prateeeksagar/Information_Security_Assignment1 | /frequency_Attack.py | 1,995 | 3.84375 | 4 | freq_list = [0] * 26;
# this list has to made sorted with len 26 containing 0
freq_list_sorted = [0] * 26;
# used alphabet for making key list with len 26 containing 0
used_alphabet = [None] * 26
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',... |
10f98da7fd14fd6b44198d9ce62350e7d43ef088 | sivajipr/huffman_data_compression | /frequency.py | 125 | 3.71875 | 4 | def frequency(str):
freqs={}
for ch in str:
freqs[ch]=freqs.get(ch,0)+1
return freqs
print frequency('my name is siva')
|
cfe13f958a741ab5bf7afdbbacc76f743b1818aa | wojsamjan/scraping_101 | /app.py | 1,199 | 3.734375 | 4 | # import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup
# specify the url
quote_page = 'http://www.bloomberg.com/quote/SPX:IND'
# query the website and return the html to the variable 'page'
page = urlopen(quote_page)
# parse the html using beautiful soup and store in variable 'soup'
sou... |
1df6003cb9391e24a428f5e70a92d8b2a9b884e7 | alphacoder01/python_codes | /array_deletion.py | 363 | 3.6875 | 4 | # taking array as input
n = int(input("Enter number of elements "))
lst = list(map(int, input().rstrip().split()))
# print(lst)
m = int(input("Enter element to be deleted "))
count = 0
for i in range(n):
if m != i:
count += 1
if count == n:
m = int(input("Enter a valid number"))
o = int(input(... |
45515af7dc0ade4f3f485f73a87031e87b8aa30d | alphacoder01/python_codes | /classes.py | 1,138 | 4.03125 | 4 | '''class computer:
def __init__(self, cpu, ram):
self.cpu = cpu
self.ram = ram
def config(self):
print("config is", self.cpu, self.ram)
com1 = computer('i5', 16)
com2 = computer('ryzen', 8)
com1.config()
com2.config()
'''
class Person:
def __init__(self, initialAge):
... |
51a73135a2d653756ba673459f868e0cd712cb3b | alvaro16589/cursopython | /intro.py | 145 | 3.71875 | 4 | a = int(input("introdusca un valor : "))
b = int(input("introdusca otro valor : "))
print("esta es una prueba cuyo resul tados es : ", a + b)
|
1ac8c0b823f56b2ea04221d7ee9b0e7de53dd846 | alvaro16589/cursopython | /ejercicios/ciclos/dibujos.py | 1,793 | 4.0625 | 4 | op=1
print("···············································································")
print(". MENÚ .")
print(". 1> Dibujar un rectángulo .")
print(". 2> Dibujar un triángulo ... |
8975f1560c316508b771ab7ba6d9027665136c40 | alvaro16589/cursopython | /ejercicios/programaSimples/circulos.py | 135 | 3.640625 | 4 | from math import pi
rad = float(input("Ingrese el radio: "))
print("Perimetro: ", round(2*rad*pi,2), "\nÁrea: ", round(pi*rad**2,2) )
|
9946cbdd549e0565936fdb066060341807253693 | Python-study-f/Algorithm-study_1H | /Leetcode/Linked_List/Palindrome_Linked_List_234/234_210307_jjong.py | 460 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
st = []
while head is not None:
val = head.val
st... |
d151226480e54f12bd3c52f607629e566828f0c4 | Python-study-f/Algorithm-study_1H | /Algorithm_2021/May_2021/210502/42583_Passing_Truck/42583_210427_algo.py | 1,068 | 3.53125 | 4 | def solution(bridge_length, weight, truck_weights):
answer = 0 #시간
t_list = [] # 트럭저장하는 큐 (리스트로 만듬) - 다리상황과 동일하다고 생각하면 됨
# 트럭뽑는 함수
for i in truck_weights: # [7,4,5,6]
q_truck =i
while q_truck !=0:
if len(t_list) == bridge_length: # 길이가 같으... |
18f4373bc0d2eba46478f95ddf64c222cba01af7 | Python-study-f/Algorithm-study_1H | /Leetcode/Hash_Table/Longest_Substring_Without_Repeating_Characters_3/771_210314_jeung.py | 777 | 3.5625 | 4 | # https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution1:
def lengthOfLongestSubstring(self, s: str) -> int:
max_t = 0
for each_i in range(len(s)):
# tmp_s = ''
existing = []
t = 0
curr_s = s[each_i + t]
... |
a5a68a7a46c410fe574951cd8c23f0b7dc1ab6e4 | Python-study-f/Algorithm-study_1H | /Baekjoon/Deque/Card2_2164/2164_210314_jeung.py | 275 | 3.546875 | 4 | from collections import deque
def solution(N):
# left = top
# right = bottom
queue = deque(range(1, N+1))
while len(queue) > 1:
card2throw = queue.popleft()
card2move = queue.popleft()
queue.append(card2move)
return queue.pop()
|
514dbc6258f786ef29491f0b331c76a035235624 | Python-study-f/Algorithm-study_1H | /Leetcode/Linked_List/Reverse_Linked_List_206/206_210307_jjong.py | 623 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, l1: ListNode) -> ListNode:
head = ListNode()
answer = head
st = []
if l1 is None:... |
9c69945080a1fec30d65c13900e7b131835f1c9a | Python-study-f/Algorithm-study_1H | /Leetcode/String/Valid_Palindrome_125/125_20210228_jjong0416.py | 221 | 3.546875 | 4 | class Solution():
def isPalindrome(self, s):
s = s.lower()
_s = ""
for i in range(len(s)):
if s[i].isalpha():
_s += s[i]
return _s == _s[::-1]
|
f579496efc890ce8f7db12aa7cda131556b7bca5 | edurox/SAS | /Public Key Certificate/main.py | 804 | 3.734375 | 4 | from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
key = RSA.generate(1024, e=65537)
publicKey = key.publickey()
#Open the file you want to certificate, hash it with sha256. After that encrypt it with RSA.
file = open('sylvanas.jpg', 'r')
fileData = file.read()
fileHash = SHA256.new(fileData).digest()
... |
ce602fd6526a830a0bab118951cb9a16c21efd8e | shivam0071/exploringPython | /Python_2018/Customizing_String_Formatting.py | 1,024 | 4.28125 | 4 | # Customizing String Formatting
_formats = {
'ymd' : '{d.year}-{d.month}-{d.day}',
'mdy' : '{d.month}/{d.day}/{d.year}',
'dmy' : '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code)... |
7675e524670e6341d32906a1394af537d3112c0a | shivam0071/exploringPython | /Python_2018/Meta_Programming.py | 3,307 | 4.34375 | 4 | # any time you are faced with a problem of creating highly repetitive code (or
# cutting or pasting source code), it often pays to look for a more elegant solution. In
# Python, such problems are often solved under the category of “metaprogramming.”
# metaprogramming is about creating functions and classes whose main... |
053fdf48d2a952f44167939db060cd2a4843edde | Mawiszus/TOAD-GUI | /utils/scrollable_image.py | 3,109 | 3.5 | 4 | # based on https://stackoverflow.com/questions/56043767/show-large-image-using-scrollbar-in-python/56043976
from tkinter import *
from tkinter import ttk
import platform
class ScrollableImage(Canvas):
def __init__(self, master=None, **kw):
self.image = kw.pop('image', None)
super(ScrollableImage, ... |
67f0ab4a980d97a817df7f841c107407fcbc7a2d | dstoianov/video-converter | /src/rename_files.py | 523 | 3.734375 | 4 | import os
files_dir = "/media/funker/3/FOTO/"
# Function to rename multiple files
def main():
for filename in os.listdir(files_dir):
if "download_" in filename:
new_name = filename.replace("download_", "")
src = files_dir + filename
dst = files_dir + new_name
... |
27e022f50c719d4a1dd3f2e037a0cf8472749b5c | Sushanth172308/projectForCV7 | /currencyConverter.py | 513 | 3.828125 | 4 | with open('currencyData.txt') as f:
lines = f.readlines()
currencyDict = {}
for line in lines:
parsed = line.split('\t')
currencyDict[parsed[0]] = parsed[1]
#print(currencyDict)
amount = int(input('Enter the amount:'))
print('Enter the name of the currency you want to convert this amount to? Available op... |
ce69f5eae883f65cfd15dfecefa69fed0972ae91 | ADesoutter/src-python | /10-functions.py | 1,662 | 3.953125 | 4 | # définition
def hello():
print("Hello World!")
# appel
hello()
def moyenne(valeurs):
somme = 0
for valeur in valeurs:
somme += valeur
return somme / len(valeurs)
nombres = [100, 123, 3.14, 46]
m = moyenne(nombres)
print("moyenne des nombres:", m)
points = [100, 143, 167]
m = moyenne(point... |
57faae3efa7f954be9d533c20faea1118d324974 | huntercollegehighschool/srs1pythonbasicsf21-davis5040 | /main.py | 786 | 3.6875 | 4 | from part1 import trianglearea
from part2 import twodigitodd
from part3 import isprime
from part4 import possibletriangle
from part5 import isotriangle
program = int(input("Which program (1, 2, 3, 4, or 5)?"))
if program == 1:
base = float(input("Enter a base: "))
height = float(input("Enter a height: "))
... |
63783f9c5bc6d2fd739d4af1bad1815efc4ac83e | LiawKC/CS-Challenges | /GC16.py | 2,214 | 3.765625 | 4 | name = input("PLease input your name: ")
uppercases = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lowercases = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numbers = ["1","2","3","4","5","6","7"... |
995de8aa21616cb80720217b3ab93bec5556e912 | LiawKC/CS-Challenges | /TU03.py | 117 | 3.828125 | 4 | MyAge=int(input(print("What is your age")))
print("I am younger than", MyAge)
print("I am younger than %d" % MyAge) |
6518e4352f5c2fda38787af1eb3cc08577d5b845 | LiawKC/CS-Challenges | /AS06.py | 142 | 4 | 4 | Vowels = "aeiouAEIOU"
Count = 0
Text = input("What is your text? ")
for i in Text:
if i in Vowels: Count = Count+1
print(Count) |
3d698dbd2f2e42af6f8abdd40e96d43c5bcf409a | LiawKC/CS-Challenges | /GC08.py | 627 | 4.21875 | 4 | weight = float(input("What is your weight"))
height = float(input("What is your height in m"))
BMI = weight / height**2
print(BMI)
if BMI < 18.5:
print("Bro head to mcdonalds have a big mac or 2 you're probably anorexic")
if BMI < 25 and BMI > 18.5:
print("Ok, you're average but don't get fat or we... |
384ec36fafe6d39ade7869f1ed7c4b341c92ba78 | LiawKC/CS-Challenges | /TU05.py | 179 | 4 | 4 | raining = input("Is it raining? Yes or No? ")
if raining in ("Yes", "yes"):
print("Oh dear, no football today!")
if raining in ("No", "no"):
print("Yeet!, football today") |
2b9386e6b1945077bde87542428ccc2544fd580a | LiawKC/CS-Challenges | /AS73.py | 676 | 3.734375 | 4 | import random
x = " "
Colour = input("What do you want for your favourite colour?")
Location = input("What is your favourite location?")
Animal = input("What is your favourite animal?")
SpecialCharacters = ["!","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","=","<","=",">","?","@","[","]","^","_"]... |
1321b3594bdd74b27f586390845e91e8db6a6fd2 | LiawKC/CS-Challenges | /TU12.py | 809 | 4.0625 | 4 | #Challenge 1
import time
import random
Choose_Name = ["James","John","Mark","Rick"]
print("The list of names are", *Choose_Name, sep=", ")
time.sleep(1)
for i in range (1,5):
chosen = random.choice(Choose_Name)
print("The gods have chosen", chosen)
Continue = input("Do you wish to delete th... |
ed224eb604a4783850d5dbecb0b25f0c582fcdc8 | sgetme/python_turtle | /turtle_star.py | 1,104 | 4.1875 | 4 |
# first we need to import modules
import turtle
from turtle import *
from random import randint
# Drawing shape
# I prefer doing this with a function
def main():
# set background color of turtle
bgcolor('black')
# create a variable called H
H = 1
# set speed of turtle
... |
f26c438133a62f69f242ee99b1ad753137e6d566 | Fover21/Linux | /笔记/Linux02.py | 4,327 | 3.53125 | 4 | 今日内容博客地址:
https://www.cnblogs.com/pyyu/articles/9314206.html
作业详解:
1.查看linux的path变量
echo $PATH
2.简述linux的文档目录结构
根目录下有一些子目录,子目录有着自己的不同的作用
3.递归创建文件夹/tmp/oldboy/python/{alex,wusir,nvshen,xiaofeng}
mkdir -p /tmp/wzy/python/1 /tmp/wzy/python/2 /tmp/wzy/python/3 (p就是parent的意思)
4.显示/tmp/下所有内容详细信息
ls -al
5.简... |
81e2172babf2c2abe51b17f4124e72a4e41ba923 | eliwangila/Passwordlocker | /run.py | 11,099 | 4.21875 | 4 | #!/usr/bin/env python3.7
from user import User
from credentials import Credentials
"""
Run module
File that runs the application
import the two class modules to be run
"""
def create_user(name, password):
"""
function that creates a user account
Args
name: name of choice by user for their acc... |
ed8849fc16f85dfddc65354a1bd0240503c39dc0 | MohamedNour95/Py-task1 | /problem3.py | 199 | 3.90625 | 4 | str = input("please enter a string: ")
char = input("please enter a character: ")
n = -1
newlist = []
for x in str:
n = n+1
if x == char:
newlist.append(int(n))
print(newlist) |
980e284b513a95820bae35101c10120b4dd1e208 | MohamedNour95/Py-task1 | /problem9.py | 240 | 4.5 | 4 | PI = 3.14
radius = float(input('Please enter the radius of the circle:'))
circumference = 2 * PI * radius
area = PI * radius * radius
print("Circumference Of the Circle = "+ str(circumference))
print("Area Of the Circle = "+ str(area)) |
26040c62c4a9759d06e9d82996e8c84e9d36f7d7 | AJPassDe/machineLearning | /intermediateMachineLearning/01-missing-values.py | 6,196 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 20:00:40 2020
https://www.kaggle.com/learn/intermediate-machine-learning
data iowa:
https://www.kaggle.com/c/home-data-for-ml-course/overview
@author: AJ
"""
# 3 approaches :
# 1. Simple option: drop a column
# you lose lots of potential information unless mo... |
f78715cfe91c4131818f7d11590803bfca591d29 | nbvc1003/python | /ch02/join.py | 218 | 3.9375 | 4 |
# 문자열 사이에 ,를 넣은 string으로 리턴
print(",".join("abcd"))
# 리스트 파라메터 또한 각 원소 사이에 삼입한 string으로
print(','.join(['a','b','c','d']))
print(int("2")+ int("5"))
|
9f2156a0e6b22a3d71531d6e2aa826e82213c858 | nbvc1003/python | /ch04_5/bit.py | 276 | 3.578125 | 4 |
a = 17 # 0000 1100
b = 61 # 0011 1101
# and 의 의미 & 하나는 bit 연산자
print(a & b)
# or 연산
print (a | b)
# xor 연산
print (a ^ b)
print( a and b) # 1100
print( a or b) # 111101
a = 12
print(a << 2)
print(a >> 2)
# if a and b :
# print("true")
|
08788782b45fa1f309c2ed0f71d53792e596311e | nbvc1003/python | /ch08/oper1.py | 833 | 3.875 | 4 |
while True:
li = [1,2,3]
print('인덱스 번호를 입력하세요')
num1 = input()
if num1 == 'x':
break
try:
num = int(num1)
print('{} / 2 = {}'.format(li[num], li[num]/2))
# 각 예외별로 처리 할경우
# except IndexError:
# print("exception 인덱스 값이 범위 밖입니다.")
# except ValueError:
#... |
29e0245301b8b38120a79ca0804c19df834eb349 | nbvc1003/python | /ch05_4/ex2.py | 86 | 3.53125 | 4 |
c= 0
sum = 0
while c < 1000:
if c%3 == 0:
sum += c
c += 1
print(sum) |
f4682b994bb3a857b67c75b83f2beaa48732359d | nbvc1003/python | /ch13/ser_del2.py | 320 | 3.53125 | 4 | import pandas as pd
fruit = pd.Series([4000, 3000, 3500, 2000],
index=['apple','blueberry','orange','kiwi'])
# banana 2500 추가
# apple 4200
# kiwi 삭제
fruit["banana"] = 2500
fruit["apple"] = 4200
print(fruit)
del fruit["kiwi"]
print(fruit)
# 3000 이상만 출력
print(fruit[fruit >= 3000])
|
609e6e27bfd061803869bbea32f20d6de8c81833 | nbvc1003/python | /ch10/thread4.py | 496 | 3.578125 | 4 |
import threading, time
def prn(n):
#대박이라고 n번 쓰레드 10회 출력하고 1초씩 sleep
for i in range(10):
print('{} 번쓰레드 대박:{} \n'.format(n,i))
time.sleep(1)
# thread를 사용하여 prn 실행 n에 1,2 사용
# 사건 이라는 글자를 10회 실행
for i in range(1, 3):
id = '대박 {} '.format(i)
th = threading.Thread(target=prn, args=(id,... |
db4ada357ed4d1b13c36352248938e18cad79e18 | nbvc1003/python | /ch05_4/num_int.py | 387 | 3.515625 | 4 |
# 빈리스트 만들기
numbers = [] # numbers 에 자연수 1, 10까지 추가
numbers[:] = range(1,11) # 리스트에 1~11 의 값을 넣어 준다.
print(numbers)
#홀수 제거
# del numbers[::2]
# print(numbers)
# 짝수 제거
del numbers[1::2]
print(numbers)
# numbers 의 인덱스 0 자리에 20을 삽입
numbers[0] = 20
# numbers를 정렬 해라
numbers.sort()
|
51d7e5515a3d89d5db81f3a65154f8d7e35b820c | nbvc1003/python | /ch06/reverse.py | 428 | 3.671875 | 4 |
some_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def flip(some_list):
str = []
for i in range(len(some_list)):
str.append(some_list[len(some_list)-1 - i])
return str
def flip2(some_list):
if len(some_list) < 2:
return some_list
else:
return flip2(some_list[1:]) + some_list[:1]
... |
85cacd104a15efa9acd5eceab5e0c157b4377d27 | nbvc1003/python | /ch13/ser_index3.py | 224 | 3.671875 | 4 | import pandas as pd
s = pd.Series(range(3), index=['a','b','c'])
print(s)
# index가 문자인 경우 속성처럼 스리즈명.인덱스명 으로 사용가능
print(s[1], s['b'],s.b) # 3가지 방법으로 사용가능
|
8c6f61a6e8ff8286a049a1eae23d4e0bce0ed246 | nbvc1003/python | /ch13/sort1.py | 590 | 3.921875 | 4 | import pandas as pd
import numpy as np
fr = pd.DataFrame(np.arange(8).reshape(2,4),
index=['three', 'one'], columns=['d','a','b','c'])
print(fr)
print(fr.sort_index()) # index 기준 즉 행의 순서 정렬
print(fr.sort_index(axis=1)) # column 즉 열의 순서 정렬
# 숫서를 알수 있는 값들만 가능
print(fr.sort_index(ascending=False, axi... |
e81d011032e72593aa809ea971916d4a12eb7cbe | nbvc1003/python | /ch11/meta2.py | 329 | 3.796875 | 4 | import re
# $는 끝나는 문자 short 으로 끝나는지
print(re.search("short$", "Life is too short, you need python"))
print(re.search("short$", "Life is too short"))
# '$' 글자를 찾을때는 []를 사용
print(re.search("[$]", "Life is too $ short"))
print(re.search("\$", "Life is too $ short")) # 위와 동일
|
aa9afbf0e4be7370831867bcea7dfab44404ec0a | nbvc1003/python | /ch07/car1.py | 858 | 3.921875 | 4 |
class Car: # 클래스명 은 대문자로시작
def __init__(self): # 전역변수 선언 할때 사용 ( 생성자와 같다. )
# 변수 선언및 변수 초기화.
self.color = "red" # 클래스 전역으로 선언
self.size = 18
self.displacement = 2000
test = 1.0
#매소드, 함수 정의
def forward(self):
print("전진")
def backward(self):
print("후진")... |
74eacaabe1dc864aa4ecf49314f04a508213c8e9 | nbvc1003/python | /ch12/likesp3.py | 231 | 4.0625 | 4 | import numpy as np
arr = np.array([
[[0,1],[2,3],[4,5]],
[[6,7],[8,9],[10,11]]
])
# flatten , ravel 다차원 배열을 일차원 배열로 변환
print(arr, arr.shape)
print(arr.flatten())
print(arr.ravel())
|
9aadb4f6516b4c82de0b2c0a23cf7beb0007bc68 | nbvc1003/python | /ch02/str6.py | 128 | 3.515625 | 4 |
str ="Good Morning"
# in은 문자열에 포함되어 있는지 검사
print("o" in str)
print("m" in str)
print(len(str))
|
11b2e0a8d2d6db7dd1941e6b04a13b228201062f | nbvc1003/python | /ch07/property2.py | 915 | 3.953125 | 4 | # property name, age : age는 음수는 에러 , get, set 을 반드시 사용
# p1 객체를 생성하고 이름과 나이를 변경하여 출력
class Person:
def __init__(self, name):
self.__name = name
def set_age(self, age):
if age < 0:
print("음수입니다. ")
self.__age = 0
else:
self.__age = age
def get_age... |
a795cc256e1491fc1b9963df8cd1f5c1b1136607 | nbvc1003/python | /ch05_4/dic3.py | 405 | 3.625 | 4 | d1 = {'이름':'하니','나이':23,'취미':'노래'}
print(d1.keys(), type(d1.keys())) # 키값 리스트
print(d1.values()) # value값 리스트
print(d1.items()) # keyValue 값
d2 = d1.copy()
d1.clear()
print(d1)
# 해당 키값의 value를 출력
print(d2.get('이름'))
print(d2.get('나이',['대박']))
print(d2.get('고향',['대박'])) # 키가 있으면 value 없으면 '대박' 이 출력
|
21ab952d75c77d9371fca12b5db3228ab27f5d65 | nbvc1003/python | /ch17/scatter_rand.py | 381 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
N = 30
np.random.seed(123)
x = np.random.rand(N)
y = np.random.rand(N)
# print(x, y)
size = np.random.rand(N)
color = np.random.rand(N)
# 랜덤하게 적당한 크기로
sizes = np.pi*(15*np.random.rand(N))**2
# c, s 각각 색과 사이즈를 다르게 설정하기 위한 목적
plt.scatter(x,y, c=color, s=sizes)
plt.show(... |
afcef1d0d86d8c422d9d89ab8afd45f460e4a1fd | nbvc1003/python | /ch08/super.py | 378 | 3.703125 | 4 | class Base:
def __init__(self, name):
print('Base.__init__')
self.message = "안녕"
print(name)
class Derived(Base):
def __init__(self):
print("Derived.__init__")
# 명시적으로 부모 생성자를 콜해줘야 실행됨
super().__init__('미호')
print('메세지: {}'.format(self.message))
d1 = D... |
521751aed1869480bdf232c2c809c5f800ad6b8b | nbvc1003/python | /ch13/dframe_oper1.py | 440 | 3.953125 | 4 | from pandas import DataFrame
item1 = {'1':{'price':1500}, '2':{'price':15000}, '3':{'price':1000}}
item2 = {'1':{'price':1500}, '2':{'price':15000}, '4':{'price':1000}}
data1 = DataFrame(item1)
data2 = DataFrame(item2)
# .T -> DataFrame 내부 함수
data1 = data1.T; data2 = data2.T
print(data1)
print(data2)
print(data1 ... |
d3352bb084d5a07a8747db13454a29644c7978f3 | nbvc1003/python | /ch05_4/charge_cal.py | 327 | 3.6875 | 4 |
# 거스름돈 계산기
# 50000, 10000, 5000, 1000
def calcurator_change(pay, price):
change = pay - price
moneys = [50000, 10000, 5000,1000]
for i in moneys:
print("{}원 {} 장".format(i, change //i))
change %= i # 나머지 값을 저장후 다음 단계로
calcurator_change(90000, 60000)
|
980d31f860e38463a246ea612e959dd1190e4a34 | nbvc1003/python | /ch12/slice1.py | 291 | 3.71875 | 4 | import numpy as np
ar1 = np.array([1,2,3,4,5])
ar2 = ar1[0:3] # 0~3 열
print(ar2)
ar3 = ar1[-2:] # -2열부터 끝까지
print(ar3)
ar4 = ar1[:2] # 처음 부터 2열 앞까지
print(ar4)
br1 = ar1[0:3].copy() # 데이터 복사 (주소가 아닌)
print(br1)
ar1[0] = 77
print(ar2, br1)
|
827c5382b3c1c67e81fd4930a48ee04958e1acde | nbvc1003/python | /ch03/sorted.py | 150 | 3.5625 | 4 |
num = [6,8,4,9,5]
# 결과 값만 출력
print(sorted(num))
print(num)
# 데이터 자체를 변경
num.sort()
print(num)
num.reverse()
print(num) |
36611415ee3525269779a3d731bfcb3531f64732 | nbvc1003/python | /ch13/iloc2.py | 455 | 3.546875 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(10, 22).reshape(3, 4),
index=["a", "b", "c"],
columns=["A", "B", "C", "D"])
print(df)
print(df.iloc[0])
print(df.iloc[0,1])
print(df.iloc[:2,2]) # 0/1행 2열
print(df.iloc[0,-2:]) # 0행 -2열부터 끝까지
print(df.iloc[1:3, 1:3]) # 1~2행, 1~2열
print(df.... |
daa49da1e78fa5e80b7f0cc89a4e75df7c7d8aed | nbvc1003/python | /ch03/strlen.py | 412 | 3.546875 | 4 |
# def 함수 선언
def strlen(st):
return len(st) # st의 길이를 리턴
data = ['Morning','Afternoon','evening','Night']
#함수를 실행한 결과를 가져와서 그것을 기준으로 sort
# key = lower, upper 대소문자로 바꾼후 정렬
# key = 요소별 숫자 값을 줄경우 숫자의 내림차순으로
data.sort(key=strlen)
print(data)
data.sort(key=strlen, reverse=True)
print(data) |
df9ffe8db9ddf8a6d930434e2010f1e43775bcdd | nbvc1003/python | /ch04_5/pass1.py | 331 | 3.515625 | 4 |
# in, not in
pocket = ['휴대폰','지갑', '종이']
if '지갑' in pocket :
money = int(input("지갑에 돈이 얼마"))
if money > 10000: print('택시타고가')
else : pass
else :
card = input('카드 있니 y/n 으로 ')
if card == 'y':
print('택시')
else:
print('걸어가')
|
6a33fa59107c166d6fc88a0c666dd758598cf94a | nbvc1003/python | /ch04_5/d2.py | 208 | 3.65625 | 4 | import sys
import os
print('정수를 입력하세요')
num = int(input())
if num != 0:
print('{0:d} / 3 = {1:0.2f}'.format(num, round(num/3),2))
for i in range(len(sys.path)):
print(sys.path[i])
|
05e8cfd20f1770a228270d0ac31ef29ab71296e9 | nbvc1003/python | /ch04_5/functionReturn.py | 110 | 3.5 | 4 |
def plus(num1, num2):
# 리턴은 값 반환
return (num1+ num2)
print(plus(12,4))
print(plus(3,6)) |
de6d66b4639b48a8918b9a3b675b0d2c0f25fb85 | nbvc1003/python | /ch05_4/orderDic1.py | 302 | 3.921875 | 4 | from collections import OrderedDict
keys = ['one','two','threee']
values = [1,2,3]
dic = dict(zip(keys, values))
print(dic)
# 추가된 순서를 기억해서 저장
dic2 = OrderedDict(zip(keys, values))
print(dic2)
for k in dic:
print(k,':', dic[k])
for k in dic2:
print(k,':', dic2[k]) |
218bebfee3de522638626109cf30bccd3e3efd30 | nbvc1003/python | /ch06/lambda1.py | 256 | 4.03125 | 4 |
def f1():
return 1
print(f1())
# 단축된 형태의 함수 선언
f = lambda : 1
print(f())
def f2(x,y):
return x + y
print(f2(3,6))
# 람다함수 선언 방법
# lambda 인수 : return될 내용
f3 = lambda x,y : x + y
print(f3(3,6))
|
d08362607d8e9dd0e3b2d311561d1c148b3ca8e0 | nbvc1003/python | /ch05_4/alias2.py | 230 | 3.890625 | 4 |
# call by reference
# 대표적으로 배열, 함수객체
x = [2,3,5,7,11]
y = x # 기존 리스트의 주소를 복사한다.
y[2] = 4
print(x)
print(y)
# 새로운 list를 만든다.
z = list(x)
z[2] = 3
print(x)
print(z)
|
69f6091557f10f47bccebca1bead2ffec413d5e2 | nbvc1003/python | /testPackage/delegate1.py | 866 | 3.734375 | 4 |
class Delegation:
def __init__(self, li):
self.li = li
def __getattr__(self, item):
print("Delegation {}".format(item))
# getattr (a, b) : a데이터셋 안에 b값이 존재 하는지 1/0 True/False 로 리턴한다.
print(self.li, item)
print(self.li, item)
# list = [1,2,3]
# print(list... |
1edea9d480f8b026fb0c7da4ad93d6a6c4914dc2 | nbvc1003/python | /ch07/lift.py | 389 | 3.8125 | 4 | class Lift:
def __init__(self, current_floor = 0):
self.current_floor = current_floor
def setFloor(self,floor):
self.current_floor = floor
def getFloor(self):
return self.current_floor
def print(self):
print("현재 {}층 입니다. ".format(self.current_floor))
lift = Lift()
lif... |
173894e3ea3de40837b190ba64ed47b9beeb3016 | nbvc1003/python | /ch02/ex7.py | 495 | 3.90625 | 4 |
# a1 = "안녕 친구야 " 친구를 컴 동지로 변경
# b1 = "사과 , 복숭아, 배, 딸기" 리스트로
# c1 = " hi friend 를 대문자로 변경
# 소문자로 변경
a1 = "안녕 친구야 "
print(a1.replace("친구","컴 동지"))
b1 = "사과,복숭아,배,딸기"
b2 = b1.split(",")
print(b2)
c1 = "hi friend"
print(c1.upper())
print(c1.lower())
a = 'My name is {0}. I am {1} years old.'.format('Mario', 40)
prin... |
401a90b4a82399bad08650bc816a0385d3f44740 | nbvc1003/python | /ch13/stat4.py | 648 | 3.734375 | 4 | from pandas import Series, DataFrame
import pandas as pd
import numpy as np
items = {'apple':{'count':10,'price':1500},
'banana': {'count':5, 'price': 15000},
'melon': { 'count':7,'price': 1000},
'kiwi': {'count':20,'price': 500},
'mango': {'count':30,'price': 1500},
'orange... |
4ec65a6426dfa1e36d68db08cdeb274fca9840d3 | miliart/ITC110 | /nth_fibonacci_ch8.py | 1,116 | 4.25 | 4 | # A program to calculate the nth spot in the Fibonacci
# Per assignment in the book we start at 1 instead of which is the result of 0 plus 1
# by Gabriela Milillo
def main():
n= int(input("Enter a a spot in the Fibonacci sequence: "))#variable n is the user input
#per the book Fibonacci sequence starts at ... |
9acb8cc3358478f635b9e8527ab273eadb078ebf | lizhanguo/python_S09 | /S09_Python_Learn/Day4/class-1/main.py | 568 | 3.828125 | 4 | #!/usr/bin/env python
#_*_encoding:utf-8_*_
__author__ = 'lizhanguo'
#˽Ժ˽з
class Person(object):
def __init__(self,name,age):
self.name = name
self.__age = age
self.__gender = 'male'
self.__weight = 100
def say_weight(self):
print 'my weight is %d'%(self.__weight)
... |
fc45ebebc0d3acc2b406216b14050a952e05e5fb | shencheng-js/machineStudy | /linear/two.py | 1,739 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020-11-23 16:15
# @Author : shen
# @File : two.py
# @Software: PyCharm
# 需要对数据进行归一化
# data2 = (data2 - data2.mean()) / data2.std()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
path = r'D:\fireFox_download\机器学习题目代码及数据文件\线性... |
1c75c6bc172d9656d6200381a5b1be5b443c5dec | pratyushcloud/jobc | /example.py | 809 | 4 | 4 | import datetime
t = datetime.datetime(2013, 02, 14)
print t.strftime( '%m/%Y')
a = 7
b = 10
class A1:
def printA(self):
print "Value of a is %d, value of b is %d" % (a,b)
def setA(self,value):
c = 9
global a
global b
a = value
b = 2* value
print "Inside setA, a is now %d b is now %d" %(a,b)
cla... |
218bff962ace899835afadeaaf8e381d5870d691 | EduardoCastro15/Reconocimiento-de-patrones | /Practica1/Codigo/distanciaEuclidiana.py | 503 | 3.9375 | 4 | d1=((x1-x)**2 + (x2-y)**2)**(1/2)
d2=((x3-x)**2 + (x4-y)**2)**(1/2)
d3=((x5-x)**2 + (x6-y)**2)**(1/2)
print("Distancia euclidiana con respecto al Z1")
print("d1(x,y)= " + str(d1))
print("Distancia euclidiana con respecto al Z2")
print("d2(x,y)= " + str(d2))
print("Distancia euclidiana con respecto al Z3")
p... |
0c075d8dd90a81324e4ccb3876af15d16a46747f | reenaramesh/first | /exp4.py | 383 | 3.890625 | 4 |
#sort according to length
"""a=['wergte','rgrg','trghrtg','trh']
#for n in a:
#for i in range(0,n+1):
a.sort(key=len)
print(a)"""
# union of list
"""a=[25,55,22,10]
b=[22,20,36,55]
c=[]
for i in range(0,len(a)):
for j in range(0,len(b)):
if a[i]==b[j]:
temp=a[i]
a[i]=b[j]
... |
180c438f7f9079e0a8904c70890b86639a3fce7e | Ivan-Malinin-IBM7968/mars-rover | /tests.py | 3,958 | 3.53125 | 4 | import unittest
from rover import Rover
from position import Position
from direction import Direction
class RoverTest(unittest.TestCase):
def test_west_turn_left(self):
direction = Direction.W
position = Position(0, 0)
rover = Rover(position, direction)
commands = ('l')
ro... |
a6b64abe51de2e4f246bd1eef8af98e1ef5da95b | ktheis/pqcalc_py3 | /calculator.py | 45,109 | 3.71875 | 4 | # coding=utf-8
"""
Functions to run an interpreter for expressions containing physical quantities.
Based on the Q class in the quantities module, this provides functions to input and interpret expressions,
calculating their values and showing the steps, and finally storing the quantities so that they can be
used for f... |
e8617f7bc2ce9e4c83da1911ce56cd496c65db4a | EduChancafe/EduardoCH | /condicionalesmultiples/ejercicio9.py | 790 | 3.734375 | 4 | import os
#declarar variables
comprador,numeros_de_botellas_de_vino,precio_de_cada_vino="",0.0,0.0
verificador= False
#input
comprador=os.sys.argv[1]
numeros_de_botellas_de_vino=int(os.sys.argv[2])
precio_de_cada_vino=float(os.sys.argv[3])
#processing
precio_botella=(numeros_de_botellas_de_vino*precio_de_cada_vino)
... |
2f9aefff07f0e08a5dd225575a4c98651ebfa456 | EduChancafe/EduardoCH | /condicionalesmultiples/ejercicio3.py | 736 | 3.5 | 4 | import os
#declarar variables
cliente,numeros_de_zapatillas,precio_de_zapatilla="",0.0,0.0
verficador= False
#input
cliente=os.sys.argv[1]
numeros_de_zapatillas=int(os.sys.argv[2])
precio_de_zapatilla=float(os.sys.argv[3])
#processing
costo_zapatilla=(numeros_de_zapatillas*precio_de_zapatilla)
verificador=(costo_zapa... |
0bd7bf82bda45e837fdb42779140b14eaf1b0401 | dashajarikova/homework | /hwprog2.py | 379 | 3.953125 | 4 | print ("Введите число")
num=int(input())
print ("Введите слово")
w=input()
while w!= "программирование" and w!= "программирование":
for i in range(num):
print (w)
print ("Введите число")
num=int(input())
print ("Введите слово")
w=input()
print ("Конец")
|
ec1c76fe596e0597c2f12fda9365087925edf848 | dashajarikova/homework | /hwprog4.py | 119 | 3.75 | 4 | word=input("Введите слово: ")
n=[]
for i in range(len(word)):
n=word[len(word)-i:]
n+=word[i:]
print(n)
|
157b2203a0f29979719e75580d4d89ae0e3fb013 | nathaliamsoares/agenda-telefonica | /main.py | 1,025 | 3.90625 | 4 | lista_contatos = []
def adicionar(nome, telefone, email):
contato = {nome, telefone, email}
lista_contatos.append(contato)
def deletar(posicao):
if posicao <= len(lista_contatos):
del(lista_contatos[posicao])
else:
print('Não existe essa posição')
opcao = 100
while opcao != 0:
... |
af0eaee7964ecf839540b116ca8b602b120377aa | abhi12mohan/Automated-Dorm-Visit-System | /Encryption Work/Encryption_Server Side.py | 690 | 3.609375 | 4 | from Crypto.Cipher import AES
import base64
import binascii
key = bytes('tmf63mnxpy3hf2cw',encoding ='utf-8')
cipher = AES.new(key, AES.MODE_ECB)
ciphertext = "67f4f89c24873f6d602dfa6361f2b663" #cipher.encrypt(b'Tech tutorials x')
# msg = bytes(ciphertext, encoding = 'utf-8') #converts mg to Byte type
#print(str(ms... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.