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 |
|---|---|---|---|---|---|---|
89167fe59613bc1eba62d18d09deea19c0bad38f | jananee009/DataStructures_And_Algorithms | /Stacks_And_Queues/Stack.py | 1,046 | 4.25 | 4 | # Write a program to implement a stack (LIFO). Implement the operations : push, pop, peek.
class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
if(len(self.stack)==0):
return True
else:
return False
def push(self,element):
self.stack.append(element)
def pop(self):
if(len(self.stac... |
8543dcf16df4aef722d628c0d523097f9889b2e3 | e-remington-lee/finance-tracker | /tests/test_utility.py | 366 | 3.578125 | 4 | from ..utility.money import *
print(money(2.1111))
# import unittest
# class Test_money(unittest.TestCase):
# def test_money(self):
# money1 = 12.3334454
# self.assertEqual(str(12.33), money(money1))
# money2 = 14.11115324
# self.assertNotEqual(str(14.12), money(money2))
# if __n... |
78d83f73c9883f07fb2d975607f573465e76e2c5 | AndyFlower/PythonFullstackLearnNote | /projects/day03/02 str.py | 2,649 | 4.03125 | 4 | s1 = 'python'
# 对字符串进行索引,切片出来的数据都是字符串类型
# 从左到右顺序 下标 索引
s2 = s1[2]
print(s2,type(s2)) #t <class 'str'>
s4 = s1[-1]
print(s4) #n
# 安装切片取值 左闭右开
s5 = s1[0:5]
print(s5) #pytho
s6 = s1[2:]
print(s6) # thon
# 切片步长
s7 = s1[:5:2]
print(s7) # pto 2是步长
# 倒序
s8 = s1[-1:-6:-1]
print(s8) # nohty 不加-1不会报错 但没有输出
# 按索引 s1[in... |
383821bb30931d9e849a4d0f14c9291eb5c799a8 | AndyFlower/PythonFullstackLearnNote | /projects/day10/02 函数的参数.py | 1,700 | 4.125 | 4 | # 形参角度
# 万能参数
def eat(a,b,c,d):
print('我请你吃:%s %s %s %s' %(a,b,c,d))
eat('西红柿','黄瓜','葡萄','黄桃')
# 急需一种形参,可以接受所有的实参
# 万能参数 *args 约定俗称 args
# * 函数定义时, *代表聚合 它将所有的位置参数聚合成一个元祖 赋值给args
def eat(*args):
print(args)
print('我请你吃:%s %s %s %s %s ' %args)
eat('西红柿','黄瓜','葡萄','黄桃','红提')
# 写一个函数 计算传入的所... |
33723400399353fbaf453eb09fcd2477f8412612 | AndyFlower/PythonFullstackLearnNote | /projects/day04/01 列表的索引切片.py | 397 | 3.90625 | 4 | li = [100,'sang',True,[1,2,3]]
# 索引
print(li[0],type(li[0])) # 100 <class 'int'>
print(li[1],type(li[1])) #sang <class 'str'>
#切片
print(li[:2]) #[100, 'sang']
# 练习题
li = [1,3,2,'a',4,'b',5,'c']
# 通过对li切片形成新的列表[1,3,2]
# 通过对li切片形成新的列表['a',4,'b]
l2 = li[3:6]
print(l2) #['a', 4, 'b']
l3 = li[1:-2:2]
print(... |
91b6a10ef1de797424fde62157941209132c54fe | AndyFlower/PythonFullstackLearnNote | /projects/day08/02 文件操作的初识.py | 574 | 3.59375 | 4 | #f1 = open('d:\te.txt',encoding='utf-8',mode='r') #OSError: [Errno 22] Invalid argument: 'd:\te.txt'
f1 = open('d:/te.txt',encoding='utf-8',mode='r')
content = f1.read()
print(content)
f1.close()
'''
open 内置函数,open底层调用的是操作系统的接口。
f1,变量,f1,fh,file_handler,f_h,文件句柄。 对文件进行的任何操作,都得通过文件句柄. 的方式。
encoding:可以不写,不写参数,默认编... |
13f3fb9a23a40611721733a7578b78c4858ed1d6 | AndyFlower/PythonFullstackLearnNote | /projects/day15/a.py | 335 | 3.96875 | 4 | '''
自定义模块
模块中出现的变量,for循环 if结构 函数定义称为模块的成员
'''
# 可执行语句
a=1
print(a)
## 定义一个函数 包含测试语句
def main():
print(a)
for i in range(3):
print(i)
# 函数定义
def func():
print('hello')
if __name__ =='__main__':
main() |
78baaf6b57f0f57a6d1c65376b756202388d78d0 | ammv/trinkets | /мат открытия/matesha2.py | 512 | 3.859375 | 4 | def compress(nums):
return [int(nums[i]) + int(nums[i+1]) for i in range(0, len(nums)-1)]
def decompress(nums):
second_num = abs(nums[1] - nums[0])
first_num = abs(nums[0] - second_num)
real_nums = [first_num, second_num]
for i in range(1, len(nums)):
real_nums.append(abs(nums[i... |
9bde2275032318407800361cf31e4eadb7320682 | icesdy115/icesdy115.github.io | /pySrc/other/emailCheck.py | 1,027 | 3.890625 | 4 | #_*_coding:utf-8_*_
import re
#验证邮箱格式
def emailCheck(e):
mess = ['email input right',
'email input format error',
'email length more than 5']
if len(e) >= 5:
if re.match("[a-zA-Z0-9]+\@+[a-zA-Z0-9]+\.+[a-zA-Z]", e):
print(mess[0])
return 1
else:
print(mess[1])
return 2
else:
# print('email len... |
aa27f5aeef39ef7d6c1785e9fb9f48a1c2d0f01b | ilitteri/7541-Algo2 | /apuntes/algorithms/finals/dict_add_all.py | 429 | 3.515625 | 4 | class Dict:
def __init__(self):
self.me = {}
self.engania_pichanga = 0
def add_all(self, y):
self.engania_pichanga += y
def obtener(self, x):
return self.me[x] += self.engania_pichanga
def borrar(self, x):
if x in self.me:
del(self.me[x])
... |
62af1b626bb3b643f74390e99161e11be5c82ee6 | ilitteri/7541-Algo2 | /estructuras_de_datos/grafo/shortest_path.py | 556 | 3.828125 | 4 | from graph import Graph
def dfs(graph, start, end, path: list = [], shortest: list = None) -> list:
#DFS
path += [start]
if start == end:
return path
for w in graph.adjacents(start):
if w not in path: # evita ciclos
if shortest == None or len(path) < len(shortest):
... |
541661d4be7fe3c4d06a47bea34fdeb949164382 | littlelove2013/lab_python_workspace | /general/HomeCreidt/funcs.py | 14,220 | 3.859375 | 4 | # numpy and pandas for data manipulation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.io as scio
# sklearn preprocessing for dealing with categorical variables
from sklearn.preprocessing import LabelEncoder
# File system manangement
import os
# Function to calculate missing val... |
d18a1447bd530ba80b33e922dee32c4d4d45deb1 | EmoN-Fang/Python3_lxf_tutorial | /1.basic/1_4 if.py | 600 | 4.03125 | 4 | age = 5
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
#this is wrong, 不应该先判断>=6
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
#只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
x = 0.1
if x:
print(... |
0231cb1918154af1253355f1facfac210df57998 | qing0429/scripts | /属性方法.py | 714 | 3.75 | 4 | # -*- coding:UTF-8 -*-
class Flight(object):
__status = 0
def __init__(self, name):
self.flight_name = name
def check_flight_status(self):
print "check {} status".format(self.flight_name)
return self.__status
@property
def flight_status(self):
status = self.check_flight_status()
if status == 0:
... |
319040b95800081d238f7ad274a3e3d54a7cd399 | gonearewe/LeetCode | /905. 按奇偶排序数组.py | 649 | 3.6875 | 4 | # 给定一个非负整数数组 A,返回一个数组,在该数组中,A 的所有偶数元素之后跟着所有奇数元素。
# 你可以返回满足此条件的任何数组作为答案。
#
# 示例:
# 输入:[3,1,2,4]
# 输出:[2,4,3,1]
# 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
#
# 提示:
# 1 <= A.length <= 5000
# 0 <= A[i] <= 5000
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
index = 0
for i in ... |
224332028a47e1466bbf4cf7fd83279c34828f96 | almondjelly/ttt | /ttt.py | 1,469 | 4.0625 | 4 | class Player(object):
def __init__(self, name, game_piece):
self.name = name
self.game_piece = game_piece
class Move(object):
def __init__(self, author, position):
self.author = author
self.position = position
class Board(object):
def __init__(self):
self.moves... |
2edd69ed79139966c7969acfe9cf5729866c37c6 | agastyajain/Project-105 | /project work/st_dev.py | 662 | 3.6875 | 4 | import math
data=[60,61,65,63,98,99,90,95,91,96]
squared_list = []
def mean():
total = 0
for i in data:
total += i
mean = total / len(data)
return mean
def squares():
dif = 0
for i in data:
dif = i - mean()
sq = dif * dif
squared_list.append(... |
95c1d47ade4d105851b29eb1bbacf6231d188fbd | GuND0Wn151/Python_OOP | /13_MagicMethods_1.py | 1,670 | 4.4375 | 4 | #C0d3 n0=13
#made By GuND0Wn151
"""
there are some methods in python class
Magic methods in Python are the special methods which add "magic"
to your class. Magic methods are not
meant to be invoked directly by you, but the invocation happens
internally from the class on a certain action.
"""
... |
53f18b79d98cfc5fb94bc561d54248cb33c62165 | GuND0Wn151/Python_OOP | /10_Getter.py | 609 | 4.28125 | 4 | #C0d3 n0=10
#made By GuND0Wn151
'''
The getattr() method retu
the value of the named attribute of an object.
If not found, it returns the default value provided to the function.
'''
class person:
legs=2
hands=2
hair_color='black'
def __init__(self,a):
self.name=a
person1=person("k... |
cd5cb385a4692f325e6424a8051712a92cb97bb9 | keonwoo-Park/efp | /chapter6/p29.py | 646 | 3.875 | 4 | #- coding:utf-8 -*-
#!/usr/bin/env python
import sys
def version_input(sentance):
return input(sentance) if sys.version_info >= (3,0) else raw_input(sentance)
if __name__ == "__main__":
while True:
input_rate = version_input("What is the rate of return? ")
try:
rate = int(input_... |
1a6b7ff23adc74ee928d471937e17a878bd78c52 | keonwoo-Park/efp | /chapter3/p11.py | 262 | 4 | 4 |
euros = int(input("How many Euros are you exchanging? "))
euros_rate = float(input("What is the exchange rate? "))
dollar_rate = 100
dollar = (euros * euros_rate)/100
print("%d Euros at an exchange rate of %.2f is \n%.2f dollars"%(euros, euros_rate, dollar))
|
019b8e89b3ea8521c9125803a2ea6d42fd6cd1d2 | keonwoo-Park/efp | /chapter4/p16.py | 718 | 4 | 4 | #- coding:utf-8 -*-
#!/usr/bin/env python
import sys
age_int = 0
def version_input(sentance):
return input(sentance) if sys.version_info >= (3,0) else raw_input(sentance)
def type_checking(age):
global age_int
try:
age_int = int(age)
if age_int < 0:
return False
retu... |
a8649dac5805f1ab083d69e4d33896bfb377b5ff | keonwoo-Park/efp | /chapter3/p13.py | 507 | 3.921875 | 4 | import math
principal = int(input("What is the principal amount? "))
rate = float(input("What is the rate : "))
period = int(input("What is the number of years : "))
interest_count = int(input("What is the number of times the interest is compounded per year : "))
principal_and_interest = principal*(1+(rate/100)/in... |
88e9c2e5cc95cfb6518df3ea281f748985ce3624 | keonwoo-Park/efp | /chapter5/p25.py | 1,590 | 3.921875 | 4 | #- coding:utf-8 -*-
#!/usr/bin/env python
import sys
import re
def version_input(sentance):
return input(sentance) if sys.version_info >= (3,0) else raw_input(sentance)
def passwordValidator(password):
check_int = False
check_str = False
check_spe = False
length = len(password)
for ch ... |
5eb2c55dc8f825da8ca73d3d558aa14d019fec84 | keonwoo-Park/efp | /chapter3/p12.py | 364 | 3.859375 | 4 | import math
principal = int(input("Enter the principal : "))
interest = float(input("Enter the rate of interest : "))
period = int(input("Enter the number of years : "))
principal_and_interest = math.ceil(principal * (1 + (interest*0.01*period)))
print("After %d years at %.1f%%, the investment will be worth $%d"%(pe... |
28719c5fed80810c43c3376758b82f851f56a05b | DAVIDMIGWI/python | /lesson 3b.py | 399 | 4.15625 | 4 |
a = 40
b = 50
c = 500
if a > b:
print("A is greater than B")
if a > c:
print("A is also greater than C")
else:
print("A is not greater than C")
if c > b:
print("C is the largest")
else:
print("A is the largest")
else:
if b... |
bbf5ab1e29160308baa03a8ae36a0e3f743f16e0 | DAVIDMIGWI/python | /assignment on tuple.py | 244 | 3.828125 | 4 |
# Tuple summation
# Using list() + sum()
# initializing tup
items = (10, 77,40,38,40,20,50,83,45,38,20)
# printing original tuple
# Tuple elements inversions
# Using list() + sum()
res = sum(list(items))
# printing result
print(res)
|
b84c082c91b1a246fc6160ac1649c39b9a2c97eb | DAVIDMIGWI/python | /lesson 5d. lists in tuples.py | 394 | 4.46875 | 4 |
# applying conditional statements in decision making in list/tuples
supermarkets = ["naivas", "Carrefour", "turkeys", "nakumatt","quickmat"]
for supermarket in supermarkets:
print(supermarket)
if supermarket == "quickmat":
print("ill shop there today")
elif supermarket == "naivas":
print("... |
f3e6f46ff88ad0b09d92e16985460415a030bb46 | DAVIDMIGWI/python | /lesson 3c.py | 313 | 3.953125 | 4 |
# loops/control statements
# repeating something end times
# there are 2 types
# 1.for
# 2.while
# for loops
for i in range(0,20001,10):
print("loop",i)
x = 4
y = 8
answer = x + y
print("sum is", answer)
# print from -20........ +20
# print +20........ -20
|
08ae94548c30aa6c045a43e1786b8322d633d698 | Harirarn/tp-games | /hangman.py | 3,170 | 3.90625 | 4 | # Hangman game
import random, string
HANGMAN = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
... |
74188f5255532e286a87f17b2ba9bb8e5ea95096 | jmmiddour/Old-CS-TK | /CS06_Hash_Tables/applications/crack_caesar/crack_caesar.py | 990 | 3.71875 | 4 | # Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Your code here
most_freq = ['E', 'T', 'A', 'O', 'H', 'N', 'R', 'I', 'S', 'D', 'L', 'W', 'U',
'G', 'F', 'B', 'M', 'Y', 'C', 'P', 'K', 'V', 'Q', 'J', 'X', 'Z']
with open('ciphertext.txt', 'r') as file_output:
data = fil... |
369d0f3e749c5419d5e40d9e41f3db3a43c946b7 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/05_lists.py | 1,707 | 4.625 | 5 | # For the exercise,
# look up the methods and functions that are available for use with Python lists.
# An array can only have one data type, list can have multiple data types.
# If you want to add to an array you have to create a new array twice the size of
# the one you have, taking up more space.
# You need to use... |
908eefea02b666792faaab30856099246622787c | jmmiddour/Old-CS-TK | /CS01_Intro_to_Python_2/src/player.py | 738 | 3.59375 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room, inventory = []):
self.name = name
self.current_room = current_room
self.inventory = inventory
def __repr__(self):
return f'{self.inventory}'... |
2589aa703538ead00de18c0b828a84f27aeb16c1 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/14_cal.py | 2,934 | 4.59375 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
... |
1c793dd4a445bc5e5c21dbda91d1a9273d74f82e | berg1ce/S1mple_calculator_4 | /main.py | 1,584 | 3.9375 | 4 | import tkinter as tk
class Main(Frame):
def __init__(self, root):
super(Main, self).__init__(root)
# Функция вычисления операций калькулятора
def calculate(operation: object, label_text=None):
global formula, buttons
if operation == 'C':
formula = ''
elif operation == 'def':
f... |
d5c9dcec4a5cd1ae864a70fb3dc22cfaefa351f1 | ParlamLiao/Python | /类的声明.py | 1,281 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 5 15:59:19 2018
@author: mac
"""
class student:
student_id=0
student_name="NOT GIVEN"
##在这里出现的变量值将在这个类的所有实例之间共享,在内部类或外部类使用类名.变量名访问
def __init__(self,s_id,s_name):
self.s_id=s_id
self.s_name=s_name
print("Ini... |
6706c43052b31596f2fbb2394ad7920a76800ea4 | franceskoback/Bioinformatics_Course | /four/4.py | 4,667 | 3.609375 | 4 | import random
from itertools import *
def main():
print("hello world")
#Dna1=["CGCCCCTCTCGGGGGTGTTCAGTAACCGGCCA","GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG","TAGTACCGAGACCGAAAGAAGTATACAGGCGT","TAGATCAAGTTTCAGGTGCACGTCGGTGAACC","AATCCACCAGCTCCACGTGCAATGTTGGCCTA"]
Dna=["ATGAGGTC","GCCCTAGA","AAATAGAT","TTGTGCTA"]
... |
bd7aca116289a82479d4a28761b5257cfa41f13c | davidpjohnson/exercises | /checkio/checkio/ex1.py | 285 | 3.703125 | 4 | #!/usr/bin/python
#This exercise is the Fizz buzz test
#This was the top ranked for clarity
def checkio(number):
if number % 15 == 0:
return "Fizz Buzz"
if number % 5 == 0:
return "Buzz"
if number % 3 == 0:
return "Fizz"
return str(number)
|
4873affb86ed2bbe50025eeb6871465569c4ae9e | egillgunnarsson1/Capstone | /utils/confusion_matrix_generalized.py | 2,537 | 3.59375 | 4 | import copy
import pandas as pd
import numpy as np
class CMGeneralized:
def __init__(self, table: dict):
"""
The class constructor.
An example of a confusion matrix for multiple classes ('a', 'b', and 'c')
is given below::
(pred)
... |
9d5949a43888ecca43334fea67f8f6ff78c70420 | tarun2502/LanguageNotes | /python/extra.py | 1,312 | 3.71875 | 4 | # To meaure the run time of the program.
import time
def time_execution(code):
start = time.clock()
result = eval(code) #Evaluates any python code
run_time = start - time.clock()
return result, run_time
print time_execution('2 + 2')
def spin_loop(n):
i = 0
while i < n:
i = i + 1
prin... |
d35c02994a80e00f33a21e7523bdd2a78eeb61a1 | DCJoshSP/soyke-pinonja | /List recursion.py | 231 | 3.828125 | 4 | #list recursion
def addNums(numlist):
if len(numlist) == 1:
return numlist[0]
else:
return numlist[0] + addNums(numlist[1:])
#endif
#endfunc
marks = [3, 6, 2, 8, 1]
total = addNums(marks)
print(total)
|
440e4202a02df0e7db4fec3a2c9957114e7506cf | DCJoshSP/soyke-pinonja | /Pygame/Snowflakes.py | 1,977 | 3.75 | 4 | import pygame
import random
import math
#Global Constants
#Colours
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (50,50,255)
YELLOW = (255,255,0)
speed = 1
#Initialise pygame
pygame.init()
#Blank Screen
size = (640,480)
screen = pygame.display.set_mode(size)
#Title of new window/screen
pygame.display.set_caption("... |
5ac4867469510bd162456de8045da4c819d6c659 | MansiKukreja24/Python | /AmusingJoke.py | 184 | 3.625 | 4 | s1=input()
s2=input()
s3=input()
s=s1+s2
l=list(s)
l1=list(s3)
l.sort()
l1.sort()
if(l==l1 and len(l)==len(l1)):
f=1
else:
f=0
if(f==1):
print("YES")
else:
print("NO")
|
815f630ef43505cda440f35896675f43a9197b2f | MansiKukreja24/Python | /Paperdoll.py | 152 | 4.03125 | 4 | def paper_doll(text):
result = ''
for char in text:
result += char * 3
return result
string: str=input()
print(paper_doll(string))
|
a3d39ea100a2803e5faee9ad63e2ee778dc30251 | palfrey/shiv | /stats.py | 598 | 3.96875 | 4 | from math import sqrt
def mean(values):
return sum(values) / (len(values) * 1.0)
def median(values):
avg = mean(values)
values = sorted(values)
for k in range(len(values) - 1):
if values[k] < avg and values[k + 1] > avg:
return values[k]
assert False, "Shouldn't get here"
... |
2e109c4d09eb362c34956761c812b50fe5b131df | cbolles/2048_robot | /original/twenty/model.py | 5,455 | 3.71875 | 4 | from enum import Enum
from typing import List, Tuple
import copy
import random
import numpy as np
class Direction(Enum):
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
class GameModel:
"""
Representation of the game at a given step. Handles storing the state of
the game and also provides the functio... |
078577ec7dcc2b9723dd0446dda4e8f9100f71f4 | pawelborucki/wd | /kolo1/zad1.py | 236 | 3.65625 | 4 | #Zadanie 1
#Wykorzystując python comprehensions (wyrażenie listowe) wygeneruj ciąg 10 elementów 1/n dla n z przedziału <1, 20> z krokiem 2.
def zadanie1():
ciag = [(1/n) for n in range(1,20,2)]
print(ciag)
print(zadanie1()) |
cdd5b6307ff5b4c3ae33a82d701e713dcb571a97 | pawelborucki/wd | /lab3/zad3.py | 221 | 3.859375 | 4 | produkty = {"banany": "kg",
"ananas": "sztuki",
"baton": "sztuki",
"gruszki": "kg"}
sztuki = [key for key,value in produkty.items() if value == "sztuki"]
print(produkty)
print(sztuki)
|
5ef9a110923a762d3bce3e760faaaa29c53ef228 | pawelborucki/wd | /kolo1/zad5.py | 441 | 3.640625 | 4 | #Zadanie 5
#Napisz funkcję, która generuje 10 list 10 elementowych wartości losowych z przedziału <1,100>. Następnie wyświetl te listy w
#kolejności rosnącej, porównując sumę wartości wszystkich elementów listy.
import random as r
def zadanie5():
lista = [[r.randrange(1,100,1) for x in range(10)]]*10
print(list... |
83634f2c2259573e81197822ed93f7fe21ec5dbe | pawelborucki/wd | /lab5/zad2.py | 349 | 3.578125 | 4 | class Kwadrat:
def __init__(self, x):
self.x = x
def __radd__(self, other):
if other == 0:
return self
else:
return self.__add__(other)
def __add__(self, other):
return self.x + other
kwadrat = Kwadrat(5)
kw2 = Kwadrat(6)
duzy_kwadrat = kwadrat.__ad... |
207dc0d1480424787bf9b301a53322efcd08365e | hyungook/python-basics | /1. 파이썬 기초 문법/day07.py | 1,156 | 3.828125 | 4 | '''
문자열과 내장함수
'''
msg="It is Time"
# upper() = 모두 대문자로 변환하는 함
print(msg.upper())
# lower() = 모두 소문자로 변환하는 함
print(msg.lower())
print(msg)
tmp=msg.upper()
print(tmp)
# find('?') = '?' 를 찾는 함수
print(tmp.find('T'))
# count('?') = '?'가 몇 번 있는지 확인하는 함수
print(tmp.count('T'))
print(msg)
# slice = [a:?] = a 부터 ? 번째 글자를 출력
... |
f9fe3b3c7ab27dbdd79e436bf1428703d6a9a499 | hyungook/python-basics | /1. 파이썬 기초 문법/day11.py | 445 | 4.0625 | 4 | '''
함수 만들기
** 복습
'''
'''
# def = 함수 키워드
def add(a,b):
c=a+b
print(c)
add(3,2)
def add(a,b):
c=a+b
return c
x=add(3,2)
# print(add(3,2))
print(x)
def add(a,b):
c=a+b
d=a-b
return c,d
print(add(3,2))
'''
def isPrime(x):
for i in range(2, x):
if x%i==0:
r... |
5f5b18339545e7bebc5ad59910d591856d71d70b | inishchith/DeepSpeech | /swig/Examples/python/reference/runme.py | 1,295 | 3.921875 | 4 | # file: runme.py
# This file illustrates the manipulation of C++ references in Python
import example
# ----- Object creation -----
print "Creating some objects:"
a = example.Vector(3, 4, 5)
b = example.Vector(10, 11, 12)
print " Created", a.cprint()
print " Created", b.cprint()
# ----- Call an overloaded op... |
4a9c94743678d888d379dce6bbcbada0b1282b5f | SynthX00/python-projects | /hashing.py | 257 | 3.921875 | 4 | #learn about hashing
#while True:
# string = input(':')
# print(f'you wrote: {string}')
# hashedString = hash(string)
# print(f'{string} hashed becomes -> {hashedString}')
import numpy as np
#arr = np.array([1,2,3,4,5])
print(np.__version__) |
fb466e4945d41d4a5aedc1293a9075fd4714764e | panosgiogr/Development | /Holidays/ΑΣΚ 4.py | 742 | 3.5 | 4 | min_stu_name=""
min_stu_mark=20.1
max_stu_name=""
max_stu_mark=0.0
for i in range(1,27,1):
stu_name=raw_input(" : ")
stu_mo=0
for i in range(1,11,1):
stu_mo+=float(input(" "+str(i)+" : "+stu_name+" :"))
stu_mo=stu_mo/10
if stu_mo>max_stu_mark:
max_stu_mark=stu_mo
max_stu_... |
54c47e46d2975d6f5c430cea98d8695a3aa3e58c | shirley1206/F2018-507-Project3 | /proj3_choc.py | 15,083 | 3.71875 | 4 | import csv
import json
import sqlite3 as sqlite
import sqlite3
# proj3_choc.py
# You can change anything in this file you want as long as you pass the tests
# and meet the project requirements! You will need to implement several new
# functions.
# Part 1: Read data from CSV and JSON into a new database called choc.db... |
7bd18de392b802e6995ca3c739b1c26df990538b | hhahhahhahha/python | /第五次上机/5-1.py | 292 | 3.828125 | 4 | def drawsq(n):
line=3*n+1
for i in range(1,line+1):
if i%3 ==1:
print(n*"+----",end="")
print("+")
else:
print("| "*n,end="")
print("|")
if __name__ == '__main__':
n=eval(input("请输入阶数:"))
drawsq(n) |
0f194b20c015ac043dc172874d3efc4dd3db1040 | nicoletasima/Marketplace | /tema/marketplace.py | 3,988 | 4.1875 | 4 | """
This module represents the Marketplace.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Lock
class Marketplace:
"""
Class that represents the Marketplace. It's the central part of the implementation.
The producers and consumers use its methods concurrently.
"... |
334402d9599f66308eba13d69e4557b300996db3 | Dark-C-oder/session8 | /session8.py | 1,476 | 3.84375 | 4 | """
Student
name
phone
email
password
isCollegeTraining
collegeName
rollNum
class student:
pass
student = s1
s1.name = "John"
s1.phone = "+91 99999 77777"
s1.email = "john@gmail.com"
s1.password = "pass123"
s1.iscollegeTraining = True
s1.collegeName = " abc"
s1.rollNum = 123
student = s2
s2.fullNam... |
6cbfbdec4731ded67f5b38f02b1793ceca9e50eb | gratsgravelsins/DMI | /uzdevumi.py | 988 | 3.984375 | 4 | # -*- coding: utf-8 -*-
k = 0
name = raw_input("Iebadi savu vardu: ")
name1 = raw_input("Ievadi savu uzvardu: ")
print ("Tavs pilnais vārds, uzvārds ir %s %s ")%(name,name1)
gads = int(input("Ievadi savu gadu, kurā esi dzimis: "))
age = 2017 - gads
if age == 0:
print ("Tev vēl nav gads.")
elif gads > 2017:
print("... |
d8d5249fea1266ce7238694a0ea96c5866de994a | Paahn/practice_python | /read_from_file.py | 487 | 3.765625 | 4 | # Given a .txt file that has a list of a bunch of names,
# count how many of each name there are in the file,
# and print out the results to the screen.
my_dict = {}
with open('nameslist.txt', 'r') as f:
line = f.readline()
while line:
# strip removes the new line characters
line = lin... |
d86a00d4050862b4e14da77ed994e90595b5e40a | Paahn/practice_python | /reverse_word_order.py | 265 | 4.34375 | 4 | # Write a program that asks the user
# for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
a = input("Gimme a string containing multiple words:\n")
b = a.split(' ')
print(b[::-1])
|
7588d9c2400c665eb0be8ca319c3dc17f03ec568 | Paahn/practice_python | /guessing_game.py | 997 | 4.375 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low,
# too high, or exactly right.
# Keep the game going until the user types “exit”
# Keep track of how many guesses the user has taken, and when the game ends, print this out... |
46bc369ca4a6270b77ae963c9188183c37017d7a | Paahn/practice_python | /list_remove_duplicates.py | 518 | 4.0625 | 4 | # Write a program that takes a list and returns
# a new list that contains all the elements of the first
# list minus all the duplicates.
# Write two different functions to do this - one using a loop
# and constructing a list, and another using sets.
a = [2, 83, 3, 64, 33, 67, 33, 64, 69, 83, 67, 3, 33, 2]
b = ... |
3fba2f985e3af34e58a7645ea1411fbed0ad84a6 | elenaozdemir/Python_bootcamp | /HW.py | 571 | 3.734375 | 4 | #Problem 3:
def find_odds(n):
odds = []
for num in range (0, n+1):
if (num % 2 == 1):
odds.append(num)
return odds
n = 19
print(find_odds(n))
#Problem 4: finding the differences between two lists without the use of sets
def find_diffs(a,b):
differences = []
for element in a:
... |
47717a3918ae9d4522508d3125763b31c3298a4d | elenaozdemir/Python_bootcamp | /Week 1/Day Two/Practicing with lists & functions.py | 747 | 4.53125 | 5 | # practicing with lists and functions
# EXAMPLE: Define a function that returns a list of even numbers
# between A and B (inclusive)
def find_events(A,B):
# make an empty list to return to something
evens = []
for nums in range (A,B+1): #inclusive
if (nums % 2 == 0):
evens.append(nums)
... |
841b85c61c86517faa53752c12a6932581d5e0f4 | ggflow123/data-mining | /3layer.py | 1,846 | 3.59375 | 4 | #reference: https://github.com/jiexunsee/Neural-Network-with-Python
from numpy import exp, array, random, dot,mean,reshape,genfromtxt
import sys
class NeuralNetwork():
def __init__(self):
random.seed(1)
l2 = 30
l3 = 40
self.layer1 = 2 * random.random((14, l2)) - 1
... |
560d08982e3e83137d6fc748cba8e793c0031208 | rv0-0/Find-and-Replace---Python-Mini | /Find and Replace.py | 581 | 4.09375 | 4 | import os
import sys
filename=input("Enter a filename: ")
if ".txt" in filename:
filename=filename.replace(".txt","")
try:
file_in = open(filename+".txt", "rt")
except:
input("File not found!")
sys.exit()
old_string=input("Enter the old string to be replaced: ")
new_string=input("Enter the new stri... |
cbe1f8a6dc89f14da0d78ed432445441beb6fc45 | pbrandiezs/python-ex1 | /ex1.py | 272 | 4.03125 | 4 | name = input("Give me your name: ")
print("Your name is " + name)
age = input("What is your age? ")
age = int(age)
print("Your age is " + str(age))
yearsToHundred = 100 - age
yearWhenHundred = 2018 + yearsToHundred
print("You will turn 100 in " + str(yearWhenHundred))
|
533beb705cea1f8052a37b0ad156ae3dca5c6e6e | Beyond-Perfect/autoprotocol | /autoprotocol/_component.py | 3,018 | 3.8125 | 4 | # This file serves to provide an abstract base class which must be used for all hardware (sensor/actuator) classes
# The Confusing Bits:
# The Pins Input:
# Pins can be input to a component using the `pins` input as either an int representing a single pin OR
# a dict representing a pins object containing... |
07980cf18c3e4f6105ae2d5f0be5033b9dfb8ff5 | markbarm/exerciciosPython | /listas/notas.py | 166 | 4.0625 | 4 | notas = []
numero = int(input("Entre com o número de notas: "))
for i in range(numero):
nota = float(input(f'Nota {i+1}: '))
notas.append(nota)
print(notas)
|
e05af64568d7ae631890226b1f965e37ad62f2b0 | darthols/mooc_Python-3 | /w4/w4-s4-c1-legb.py | 822 | 3.953125 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
On veut implémenter une classe pour manipuler une queue d'événements. La logique de cette classe est que :
on la crée sans argument ;
on peut toujours ajouter un élément avec la méthode incoming ;
et tant que la queue contient des éléments on peut appeler la méthod... |
d595dc83de8d96a1db873554252ba2a604d90882 | darthols/mooc_Python-3 | /w5/w5-s2-c1-reduce.py | 1,075 | 4.03125 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
La fonction reduce permet d'appliquer une opération associative à une liste d'entrées.
Pour faire simple, étant donné un opérateur binaire ⊗ on veut pouvoir calculer
𝑥1 ⊗ 𝑥2 ... ⊗ 𝑥𝑛
De manière un peu moins abstraite, on suppose qu'on dispose d'une fonction binaire f ... |
84d7089f4198a73ca5df863b9af38a9e643fb595 | darthols/mooc_Python-3 | /w4/w4-s3-x1-pgcd.py | 684 | 3.75 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
PGCD
L'algorithme d'Euclide sur deux nombres entiers positifs a et b avec a > b ≥ 0 procède comme suit :
Si b = 0, l'algorithme termine et rend la valeur a ;
Sinon, l'algorithme calcule le reste r de la division euclidienne de a par b, puis recommence avec a := b et b ... |
185226e028f27439fa159136cfef3be1d36bad86 | darthols/mooc_Python-3 | /w1/turtle_fractal.py | 825 | 4.25 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
Fractale
"""
import turtle
def left_triangle(length):
for i in range(3):
turtle.forward(length)
turtle.left(120)
def fractal_side(length, fractal):
if fractal == 0:
turtle.forward(length)
else:
length3 = length / 3.
fract... |
12820d26fdbda084ffcc7192a199790b48eb1100 | ta1231/Programmers_Practice | /시저암호.py | 616 | 3.578125 | 4 | def pushing(c, n):
if c == ' ':
return c
if ord(c) >= 65 and ord(c) <= 96:
if ord(c) + n <= 96:
return chr(ord(c) + n)
else:
return chr(ord(c) + n - 26)
elif ord(c) >= 97 and ord(c) <= 122:
if ord(c) + n <= 122:
return chr(ord(c) ... |
6727797b9edf4b788ec5c84577e9625571d35faf | ta1231/Programmers_Practice | /test.py | 1,028 | 3.5 | 4 | def time2min(str):
h = int(str[0:2])
m = int(str[3:5])
h2 = int(str[8:10])
m2 = int(str[11:13])
return [h * 60 + m, h2 * 60 + m2]
def minmax(lst1, lst2):
before = max(lst1[0], lst2[0])
after = min(lst1[1], lst2[1])
return [before, after]
def min2time(min1, min2):
h = "0" +... |
f610dde17c37702c716745ae51f885b1355b8935 | dimmxx/codecademy | /IntroductionToClasses_Inheritance2.py | 681 | 4 | 4 | class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
... |
f9649202be26b662220b390845653ec7ab420b2f | dimmxx/codecademy | /AdvancedTopicsInPython_AnonymousFunctions.py | 489 | 3.921875 | 4 |
my_list = range(16)
print my_list
print filter(lambda x: x % 3 == 0, my_list)
def by_three(x):
return x % 3 == 0
print by_three(9)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda item: item == "Python", languages)
cubes = [x ** 3 for x in range(1, 11)]
filter(lambda x: x % 3 == 0, ... |
78070b11e33457229203f8d9b3eb275e254a712c | dimmxx/codecademy | /AdvancedTopicsInPython_BuildingLists.py | 340 | 3.859375 | 4 |
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50
doubles = [x * 2 for x in range(1, 6)]
print doubles
doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0]
print doubles_by_3
even_squares = [i ** 2 for i in range(2, 11) if (i ** 2) % 2 == 0]
print even_squares
c = ['C' for x in range(... |
03aebfa9208817bd90a95548a0ec3c586e8512f5 | mcewanmi/Open_Kattis | /Python/Kattis_8-30-17/SpeedLimit.py | 351 | 3.734375 | 4 | n = int(input())
while (n != -1):
time=[]
dist=0
for x in range(0, n):
s, t = input().split()
s=int(s)
t=int(t)
time.append(t)
if (x != 0):
dist+=(s*(time[-1]-time[-2]))
else:
dist+=s*t
print(dist, "miles")
... |
3f89e7246c95d855c3ebf7a8ba59bb90d3e64b76 | RabibHossain/asyncAwaitAsyncio | /asyncExample.py | 918 | 3.734375 | 4 | import time
import asyncio
def is_prime(x):
return not any(x//i == x/i for i in range(x-1, 1, -1))
async def hight_prime_below(x):
print('Height prime below %d' % x)
for y in range(x-1, 0, -1):
if is_prime(y):
print('-> Highest prime below %d is %d' % (x,y))
return y
... |
da6feb8ae1136016e80353b627490479a495cd31 | sbollap1/pythondurga | /PrintFunctions1.py | 657 | 3.765625 | 4 | a,b,c=10,20,30
print(a,b,c)
print(a,b,c,sep=',')
print(a,b,c,sep=":")
print("\n-----------------------")
print("durga" + "software")
print("durga","software")
print("\n-----------------------")
print("Hello",end=' ')
print("Python is very",end=' ')
print("easy",end=' ')
print("\n---------------------... |
4c5a3b9f23c9910631860938ce17e86c87a31939 | SBenkhelfaSparta/eng89_python_basics | /string_casting_concatenation.py | 1,567 | 4.34375 | 4 | # using and managing strings
# strings casting
# string concatenation
# Casting methods
# Single and double quotes
single_quotes = 'These are single quotes and working perfectly fine!'
double_quotes = "These are double quotes also working fine"
# print(single_quotes)
# print(double_quotes)
# concatenation
# firs... |
a8f4d513d0b552b70b9baa5767a2ddad07bb0629 | marnyansky/codewars-puzzles-python | /stepik-python-advanced-2021/chapter04_03_unit406261_step10_Pascals_triangle.py | 2,254 | 4.28125 | 4 | """
https://stepik.org/lesson/416753/step/10?thread=solutions&unit=406261
Треугольник Паскаля — бесконечная таблица биномиальных коэффициентов, имеющая треугольную форму.
В этом треугольнике на вершине и по бокам стоят единицы. Каждое число равно сумме двух расположенных над ним чисел.
0: 1
1: 1 1
2: 1 2 1
... |
95a2ee3b58d7fdf3e0bcc499b37b7bfa59a286b6 | Ms-Noxolo/Predict-Team-7 | /EskomFunctions/function3.py | 591 | 4.375 | 4 | def date_parser(dates):
""" This function returns a list of strings where each element in the returned list contains only the date
Example
-------
Input: ['2019-11-29 12:50:54',
'2019-11-29 12:46:53',
'2019-11-29 12:46:10']
Output: ['2019-11-29', '2019-... |
12fa053082bd1766ca29ad04f797b7ecacb0e650 | clarissaorrico2/Hackbio-team-Mcclintock | /script.py | 4,662 | 3.53125 | 4 | # Script Created By : Latifat Abdulkareem
# Date Created : 06/08/2021
# Language : Python
# Biostack : Data Science / Vaccine Informatics
import time
import sys
import re
import datetime
regex_email = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
regex_slack = '[@]\w+[a-z0-9]+[\._]?[a-z0-9]$'
class... |
82b3a49735ee159bdf77e935fbb32ad752b036c3 | kapitalistka/GBpythonLessons | /lesson4/ex1.py | 1,427 | 3.96875 | 4 | # Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
import random
l = [1, 2, 4, 0]
result = [i ** 2 for i in l]
p... |
f9fc50109fc099967240fc027ee76dd19a862f41 | corymb/Realgorithms | /insertion_sort.py | 461 | 4.0625 | 4 | unsorted = [96, 20, 50, 41, 37, 24, 71, 22, 68, 82]
print unsorted
print 'Sorting...'
def insertion_sort(collection):
for position, current_value in enumerate(collection):
while position > 0 and collection[position - 1] > current_value:
collection[position] = collection[position - 1]
... |
84160594be600aa0dfa7df697bb68fa6141eea84 | EgrethName/Test | /untitled/Study/Class_Counter.py | 447 | 3.71875 | 4 | class Counter:
def start_from(self, start=0):
self.start_number = start
def increment(self):
self.start_number += 1
def display(self):
print("Текущее значение счетчика = {}".format(self.start_number))
def reset(self):
self.start_number = 0
c1 = Counter()
c1.start_fro... |
180f36af1f4496e0f2429ed110b078c4efe7ed86 | antonioluna/proyecto_JSON | /pson.py | 7,279 | 3.578125 | 4 | #-*- coding: utf-8 -*-
import json
#Obtiene los codigos de los distritos
def recorrer(dato1, dato2):
datos = {}
for x in educacionr:
datos[x[dato1]] = x[dato2]
return datos
#Obtiene las instituciones por distrito
def instituciones(codigo):
datos = {}
for x in educacionr:
if x[co... |
e680956f7f28316db0a677334caa04a388fa24ff | JeremyJMoss/PwordGeneratorAndStorage | /main.py | 4,323 | 3.59375 | 4 | import json
from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
import pyperclip
def search_websites():
try:
with open("passwords.json", "r") as passwords_file:
data = json.load(passwords_file)
website = website_input.get().lo... |
ba49caa8ba4e25862666a1b33b3968c50c5fe60a | DreXtor/learn_python | /nado_coding/basic/basic_06.py | 2,291 | 3.671875 | 4 | # # 파일 입출력
# score_file = open("score.txt", "w", encoding="utf8") # w : 쓰기 모드
# print("수학 = 0", file=score_file)
# print("영어 = 50", file=score_file)
# score_file.close()
# # 덧붙여서 쓰기
# score_file = open("score.txt", "a", encoding="utf8") # a : append
# score_file.write("과학 : 80")
# score_file.write("\n영어 :... |
65bb30444fc6d8d8c7715c87fc4d9029c836a337 | DreXtor/learn_python | /python_theory.py | 2,448 | 4 | 4 | '''
# 타입을 알아보는 명령어를 기억하자
a_float = 0.2321
a_string = 'hello'
print(type(a_float))
print(type(a_string))
'''
'''
#list에 대하여
days = ['Mon','Tue','Wed','Thur','Fri']
days_02 = ['Mon , Tue , Wed , Thur , Fri']
print("Mon" in days)
print(len(days),len(days_02))
days.copy() #Ccibal 이건 어떻게 쓰는거야?
print(days)
days.clear()
pr... |
706b10b8de94ee69f666a71370b1aa13d41ba1c7 | shafeeqjadoon/Data-Structures | /Python_py_files/Stack.py | 1,396 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def is_matched(string):
opening = '([{'
closing = ')]}'
mapping = dict(zip(opening,closing))
stack = []
for c in string:
if c not in mapping.keys() and c not in mapping.values():
continue
if c i... |
cfee7ee2846981c90bf7128c9685c815b316a77e | MaxwellBo/COMP2048_Pracs | /math/rsa.py | 998 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
RSA Encryption script
Created on Fri Feb 1 12:56:03 2019
@author: shakes
"""
class RSA:
'''
RSA encryption class for encrypting/decrypting messages using modular exponentiation.
'''
def __init__(self, pubKey, key, mod):
'''
Constructor
... |
56d7aafc9c09fc2b5dc5032ccc4efe7a1e6dd4e5 | MaxwellBo/COMP2048_Pracs | /busybeaver/test_turing_multiplier.py | 2,485 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Test script for running a Turing machine unary adder
Created on Fri Mar 29 21:57:42 2019
@author: shakes
"""
from turing_machine import TuringMachine
#create the Turing machine
multiplier = TuringMachine(
{
('q0', '1'): ('SkipFirst', '', 'R'),
# We already have our f... |
37565b62e77071ffab332641122c699ee8872706 | lanxinyi/QA_System | /arithmetic.py | 1,955 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class arithmetic():
def __init__(self):
pass
def levenshtein(self, first, second):
if len(first) > len(second):
first,second = second, first
if len(first) == 0:
return len(second)
if len(second) == 0:
return len(first)... |
1dc7205be57a56441d3a5f7b8912f17724767b09 | syokoysn/studying_programming | /python/Select_Sort/Select_Sort.py | 281 | 3.71875 | 4 |
def select_sort(l):
u = len(l)
for i in range(u-1):
for j in range(i+1,u):
if l[i]>l[j]:
l[i], l[j] = l[j], l[i]
return l
if __name__ == "__main__":
test = [1,32,2,40,5,63,21,23,55,66,45,43,26,17]
print(select_sort(test)) |
2e16a977914650f796809548b9da907b7353d883 | ImmortalKirill/infa_2020_klimanov | /Lab22/GravyMovement.py | 365 | 3.546875 | 4 | import turtle
turtle.shape('circle')
turtle.color('green')
turtle.width(5)
turtle.forward(250)
turtle.left(180)
turtle.forward(250)
turtle.right(180)
i = 0
Vx = 10
Vy = 40
dt = 0.1
g = 10
y = 0
x = 0
turtle.width(0.5)
while i < 10:
x += Vx*dt
y += Vy*dt - g*dt**2/2
Vy -= g*dt
if y < 0:
y = 0
Vy = -0.7 * Vy
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.