blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
08ad2c4a26ef92e16f0239bf08363324275ddec5 | hatttruong/wikipedia-coder | /python/src/reader.py | 2,498 | 3.9375 | 4 | """
Provide functions to read data
# return LIST:
- to_list
# return DATAFRAME:
- to_dataframe
# return ARRAY:
- genfromtxt:
+ Load data with missing values handled as specified.
- loadtxt: TODO
+ This function aims to be a fast reader for simply formatted files
+ Each row in ... |
55c58075366261f651d1d532d91d5e1035e86c3c | BlackThree/PythonStudy | /Exception.py | 1,189 | 3.984375 | 4 |
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#触发异常会跳过同一代码块中后续代码, try-except-else代码块
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
firstNumber = input("\nFirst number: ")
if firstNumber == 'q':
break
secondNumber... |
cf413a25894e7a860a2fced3ec696a2d8fd1236d | WemersonZero/Exercicios | /ex003.py | 151 | 3.84375 | 4 | n1 = int (input('Digite um Valor: '))
n2 = int (input('Digite outro Valor: '))
s = n1+n2
print('O valor entre {} e {} é igual a {}!'.format(n1,n2,s))
|
543686af8fa42395203f4a853ad3371f376790f9 | WemersonZero/Exercicios | /ex010.py | 138 | 3.65625 | 4 | real = float(input('Quanto dinheiro você tem na carteira? R$'))
print('Com R${:.2f} você pode compra US{:.2f}'.format(real, real/3.76))
|
9331464a2bd68f56949258b333c6d4b49fe0357a | logonod/pastlink-tornado | /controller/tools/Pagination.py | 750 | 3.640625 | 4 | #!/usr/bin/env python
#-*- encoding:utf-8 -*-
def topic(current_page_num, total_page_num):
'''
10 pagination
'''
current_page_num = int(current_page_num)
total_page_num = int(total_page_num)
if total_page_num < 12:
return [x for x in xrange(1, total_page_num+1)]
if current_page_num... |
d6169e8362d1c0bf9d5cdcff4dc0c36d720010aa | ReginaFF/pyladies-projekty | /ukol9z5piskvorky.py | 426 | 3.6875 | 4 | # Nacte 1-d piskvorky a vyhodnoti
def vyhodnot_piskvorky():
herni_pole = input("Zadej herni pole: ")
herni_pole = herni_pole.lower()
if ("xxx" in herni_pole) == True:
print ("Stav hry:", "x")
elif ("ooo" in herni_pole) == True:
print ("Stav hry:", "o")
elif ("-" not in herni_pole) ==... |
2f22a5d36383510c16fb209010ceacb7242cf150 | svtanthony/VHDL-Verilog | /Lab2/VHDL/dec_to_bcd.py | 551 | 3.65625 | 4 | bcd_nums = ["0000",
"0001",
"0010",
"0011",
"0100",
"0101",
"0110",
"0111",
"1000",
"1001"]
# To use, enter the number to be converted followed by bits
# Sample input "99 8" output: "10011001"
while(True):
i... |
f66bdd92134a81252316b519e4f92b0b950a025a | SingleHe/LearningPython | /condition.py | 1,104 | 4.3125 | 4 | # age = 20
# if age >= 18:
# print("your age is ",age)
# print("adult")
# age = 3
# if age >= 18:
# print("your age is",age)
# print("adult")
# else:
# print("your age is",age)
# print("teanager")
# age_str = input("请输入您的年龄:")
# age = int(age_str)
# if age >= 18:
# print("adult")
# elif age >=6:
# print("teen... |
a6c2f610540215cd578e0098dc252315a6cd8956 | tatiana-s/theory-code | /Toolbox.py | 260 | 3.71875 | 4 | # checks whether given word is accepted by given automaton
def word_accepted(automaton, word):
for char in word:
if automaton.alphabet.__contains__(char):
automaton.transition(char)
result = automaton.is_in_end_state()
automaton.reset()
return result
|
8586a57935624414aaaecf831140f026b59730ba | gchan1/AdventOfCode | /day4/day4.py | 486 | 3.625 | 4 | #advent of code day 4
import sys
def main():
valid = 0
inFile = open(sys.argv[1], 'r')
for line in inFile:
line = line.strip().split()
words = []
for word in line:
word = word.strip()
word = list(word)
word.sort()
if word not in words... |
8eb726b4f321c2fb596279b52e2e9992de3520bc | gchan1/AdventOfCode | /day3/day3.py | 383 | 3.671875 | 4 | #Advent of code day 3
import sys
def main():
inNum = sys.argv[1]
num = int(inNum)
puzzleWidth = circleRing(num)
def circleRing(num):
puzzleWidth = 0
#1, 8, 16, 24, 32, 40
#1
# 3*2 + (3-2) *2 10 + 6 14 + 10 18 + 14 22 + 18
# num -1 11
# num // 8 1
... |
dfafdf773ad9d37e8b94c4448934b6ce158748e4 | jaylenw/helioseismology | /omegas/gamma1.py | 1,263 | 4.09375 | 4 | from math import sqrt #importing python built in math function
import cmath #importing to handle negative roots
"""Gamma one
I will be assuming the Sun is is made up of all hydrogen just to see how this
works. I will be using pressure and density that I looked up for the Sun.
Although this may change. Let's a... |
33630ce1f5de4dcafadd4381cd463845df119541 | Ken-na/arithmetic-formatter | /arithmetic_arranger.py | 2,596 | 3.65625 | 4 | def arithmetic_arranger(problems, printAnswers = False):
arranged_problems = "\n"
seperatedTop = []
seperatedSum = []
seperatedBot = []
longest = 0
if len(problems) > 5:
return 'Error: Too many problems.'
for s in problems:
seperated = s.split()
seperatedTop.append(s... |
281085709d44facc168cbb6324aa7429bc36f9ce | macoopman/Python_DataStructures_Algorithms | /Recursion/Projects/find.py | 1,934 | 4.15625 | 4 | """
Implement a recrsive function with the signature find(path, name) that reports
all entries of the file system rooted at the given path having the given file name
"""
import os, sys
def find(path, name):
"""
find and return list of all matches in the given path
"""
found = [] ... |
83046855b03c830defd9e840123d8a6abe0d44f5 | macoopman/Python_DataStructures_Algorithms | /Recursion/Examples/Linear_Recursion/recursive_binary_search.py | 968 | 4.25 | 4 | """
Recursive Binary Search:
locate a target value within a "sorted" sequence of n elements
Three Cases:
- target == data[mid] - found
- target < data[mid] - recur the first half of the sequence
- target > data[mid] - recur the last half of the sequence
Runtime => O(log n)
"""
def binary_search(data, targ... |
a1176c834491e81013d6bc3bb6a4a341c99bf954 | fucking-algorithm/algo-py | /algo/two_sum.py | 1,429 | 4.15625 | 4 | """两数之和"""
def two_sum_double_pointer(sorted_nums: tuple, target: int) -> tuple:
"""
返回两个下标, 元素和为 target
对于有序的数组, 首选双指针
"""
left = 0
right = len(sorted_nums) - 1
while left < right:
left_plus_right = sorted_nums[left] + sorted_nums[right]
if left_plus_right == target:
... |
dafa9733c314ccf1e1b5ffc05c6a316c698d5516 | fucking-algorithm/algo-py | /algo/double_pointer.py | 2,893 | 3.90625 | 4 | """双指针"""
class Node(object):
def __init__(self, v=None, next=None):
super().__init__()
self.v = v
self.next = next
def __str__(self):
result = str(self.v)
while self.next != None:
result += "->" + self.next.v
return result
# def __eq__(self, nod... |
f348092808bf0c3f3aff1813ae55ea49d529a76a | fucking-algorithm/algo-py | /algo/dynamic_window.py | 1,306 | 3.828125 | 4 | """滑动窗口"""
def sub_str(source: str, target: str) -> str:
"""最小覆盖子串
找出 source 中的包含 target 的最短子串
如: adoegegbanc 中找 abc, 返回 banc
"""
result = ""
left = 0 # 区间 [left, right] 为窗口, 初始窗口大小为 right - left = 0
right = 0
while right <= len(source):
# 若 right 符合要求, 转而增加 left ,缩小 window
... |
008317fe6ca28ef600fc024c049a39c6bf7db163 | myszunimpossibru/shapes | /rectangles.py | 1,843 | 4.25 | 4 | # coding: utf8
from shape import Shape
import pygame
class Rectangle(Shape):
"""
Class for creating the rectangular shape
Parameters:
pos: tuple
Tuple of form (x, y) describing the position of the rectangle on the screen.
Reminder: PyGame sets point (0, 0) as the upper lef... |
6cff9189a5af1b532644f4fc4682da66671f4e41 | charan2000/10DaysOfStatistics | /geometricDistri2.py | 308 | 3.625 | 4 |
def geometricDistribution(n,p): # For getting the geometric Distribution
return p*(1-p)**(n-1)
n, d = map(int, input().split())
inspection = int(input()) #At this we need a hit
result = 0
for inspection in range(1,6):
result = result + geometricDistribution(inspection, n/d)
print("%.3f"%result) |
10bc9d2a05a9e90a79d0c9cb5d226713861c8960 | jeffreyvt/FIT3139-Computational-Science | /week1/q5_divisible.py | 249 | 3.765625 | 4 | import numpy as np
def divisible(num):
if num % 2 == 0:
if num % 5 == 0:
if num % 7 == 0:
return True
return False
if __name__ == "__main__":
for i in range(1, 100):
print(i, divisible(i))
|
c7b7d3a4c43a01f9bf69c4fe82d62f9fb6770858 | patFish/adventofcode19 | /5.py | 2,486 | 3.515625 | 4 | '''
Stepping forward 4 more positions arrives at opcode 99, halting the program.
Here are the initial and final states of a few more small programs:
1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
1,1,1,4,99,5,6,0,99 becomes ... |
30ae553d99e5ab46ef8843bd28b751f52f0b70a3 | svolodarskyi/invoice-parser | /invoiceparser/datacollector.py | 1,947 | 3.53125 | 4 | import pandas as pd
import os
from typing import Dict
class DataCollector(object):
invoicedata = []
""" The 'Data Collector' object serves as a repository of all invoice parsed during the session
### Overview:
----
The data from each parsed invoice is stored as a dictionary, such as {name:... |
55b6c70988f787cec82df8e2bc81a66826edd23e | rsof14/battleship | /player.py | 1,848 | 3.890625 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from field import Field
from ship import Ship
from random import randint
from point import Point
"""
Абстрактный класс Игрок. Нужен для определения поведения классов Человек-Игрок и Игрок-Компьютер.
"""
class Player(ABC):
SHIPS_NUM = [0, 4, 3,... |
fc45e4604622f2c274a28e9ba7c2e3a88a324267 | truonganhhoang/int3117-2016 | /VuTrungKien/BT3/nonsense.py | 606 | 3.734375 | 4 | def is_x_more_dangerous_than_y(x, y, crazy_level):
x_danger = x
y_danger = y
exciting_level = abs(x - y)
while exciting_level > 0:
if abs(crazy_level) < 9000 \
or crazy_level > 0 \
and crazy_level % 2 == 0:
x_danger += crazy_level
y_danger ... |
b4c5006dc99ac3387d814ec9f4c1d222f4b31551 | Zathrox/CS50 | /pset6/caesar.py | 997 | 4.03125 | 4 | import sys
from cs50 import get_string
def main():
# Checks for the correct arguements
if len(sys.argv) != 2:
sys.exit("Usage: python caesar.py positivevalue")
# Stores the key
key = int(sys.argv[1])
# Checks if Key is value, if not end
if key <= 0:
sys.exit("Usa... |
3615c4a9a185e9ab51e950e7b76336ff7556110e | Shadesoul/i-know-nothing | /我的一元二次方程.py | 829 | 3.65625 | 4 | # encoding=utf-8
import math
def quadratic(a,b,c):
for i in (a,b,c):
if not isinstance(i,(float,int)):
raise TypeError('数据类型错误') # 不知道为什么,这条不管用,仍旧是自带的出错提示。
d = b*b-4*a*c
if a == 0:
return '这不是一元二次方程'
else:
if d == 0:
x1=-b/2*a
x2=x1
... |
9f7e17346473f8f4c8d03067622ced3231b65b1f | Shadesoul/i-know-nothing | /p2.py | 154 | 3.765625 | 4 | d = {'hx':90,'uj':80,'lt':99}
n = input('please input yourself:')
if n in d:
print('yourself:',n,'is:',d[n])
else:
print('no,can not find.',n)
|
9e7e9ecf3da090454e89e06c47c2ce6546bde548 | Rouslan/nativecompile | /nativecompile/dinterval.py | 3,307 | 3.953125 | 4 |
# subclasses tuple for easy immutability
class Interval(tuple):
"""A left-closed right-open interval between two points.
For any value p, p is in Interval(a,b) if a <= p < b.
"""
__slots__ = ()
def __new__(cls,start,end):
if start > end: end = start
return tuple.__new__(cls,(sta... |
19c4dce0def19d72ac55b501ae10d66d6449ab2c | munds/Trellopy | /trellopy/boards.py | 10,401 | 3.59375 | 4 | from backend import Operator
from members import Member
class Board(object):
def __init__(self, name, data=None):
"""
Initializes an Operator instance. The entire board is represented
as a dict with the following attributes and defaults: ::
self.board = {}
... |
13a90a43382d56557e7811852f244431298fc4ee | ccozort/featherblade | /test.py | 1,292 | 3.515625 | 4 | from random import randint
dealer_cards = []
player_cards = []
playing = True
def start():
while len(player_cards) < 2:
player_cards.append(randint(1,11))
def hit():
response = input("Do you want to hit?")
if response.lower() == 'yes':
player_cards.append(randint(1,11))
print("You... |
f1533e02400f2f74fa2d15799ba261763276b4fb | ta-brook/learning-notes | /MLOps/python_for_mlops/unittest/test_class.py | 1,303 | 3.796875 | 4 |
# This function is here for convenience only, in a real-world scenario this function
# would be elsewhere in a package
def str_to_int(string):
"""
Parses a string number into an integer, optionally converting to a float
and rounding down.
You can pass "1.1" which returns 1
["1"] -> raises RuntimeE... |
13567cd51d5b39eb0f2229961789ede446516033 | qqmy/python_study | /python_test/test_savefurnishings.py | 1,503 | 4.1875 | 4 | '''
需求
1、房子有户型,总面积和家具名称列表
新房子没有任何的家具
2、家具有名字和占地面积,其中
席梦思占地4平米
衣柜占地2平米
餐桌占地1.5平米
3、将以上三件家具添加到房中
1、打印房子是,要求输出:户型,总面积,剩余面积,家具名称列表
剩余面积
1、在创建房子对象是,定义一个剩余面积的属性,初始值和总面积相等
1、当调用add_item方法的时候,想房间添加家具是,让剩余面积>=家具面积类
属性:house_type,house_area,item_list,free_area
方法:_init_, _str_,add_item
类:houseItem
属性:name,area
方法:_init_
'''
# ... |
3fadf2d71512a8f57f92779d8aff64ff90df94fe | qqmy/python_study | /网络编程/server.py | 2,178 | 3.84375 | 4 | # import socket
#
# sk = socket.socket()
#
# print(sk)
# # 绑定ip地址和端口
# address = ('127.0.0.1',8006)
# sk.bind(address)
#
# # server端可以容纳的最大排队数
# sk.listen(3)
#
# # 等待客户端连接
# print('等待客户端连接....')
# conn,addr = sk.accept()
# # coon 是客户端的socket对象
# # print(conn)
#
# inp = input()
# conn.send(bytes(inp,'utf-8'))
#
# conn.c... |
eade9c7c9eefe555bf397b33ea38325ef7393e47 | qqmy/python_study | /数据类型/集合.py | 1,640 | 4.0625 | 4 | # 集合的创建(无序,不重复)
# s = set('hello')
# print(s) # {'e', 'o', 'h', 'l'} # 集合元素不能重复,且无顺序,不能通过索引来查找,或者切片操作
# s1 = ['alvin','hello','alvin']
# s2 = set(s1)
# s3 = list(s2)
# print(s2)
# print(s3)
# li = [1,[2,3],4]
# s = set(li) # unhashable type: 'list' 集合的元素必须是可哈希的,既不可变
# li = [2,3,'alex']
# s = set(li)
# print(2 in s... |
bca011644c519994059f10d7dac7ab540bb6654d | qqmy/python_study | /python_test/test_time60.py | 532 | 3.796875 | 4 | # 数值定制
class Time60():
def __init__(self,hr,min):
self.hr = hr
self.min = min
def __str__(self):
return f"{self.hr} : {self.min}"
# _repr_ = __str__()
def __add__(self, other):
# 调用self.__class__相当于调用Time60()
return self.__class__(self.hr+other.hr,self.min+oth... |
b1097ef221aa75725bd111e7457013d2ec521258 | qqmy/python_study | /函数/函数参数.py | 1,351 | 3.828125 | 4 | # 计算机函数 == subroutine 子程序,procedures 过程
'''作用:
1. 减少重复代码
2. 方便修改,更易扩展
3. 保持代码的一致性
'''
# import time
# time_format = '%Y-%m-%d %X'
# time_current = time.strftime(time_format)
# print(time_current)
#
# def print_info(name,age):
# print(name,":",age)
# print_info('张三',10) # 必需参数
# print_info(age='10',name = '李四') # 关键... |
a8a82f9855982770b2582aa6dbc9367aab36bd48 | krusek/advent_of_code | /day5.py | 934 | 3.765625 | 4 | f = open("day5.data", 'r')
lines = f.readlines()
def has_vowels(line):
count = 0
vowels = 'aeiou'
for v in vowels:
count = count + line.count(v)
if count >= 3:
return True
return False
def has_double(line):
c = 'qwer'
for l in line:
if l == c:
return True
c = l
return False
... |
2461edd07dde1fec60a3f079a5625ce3d9534890 | rufi91/sw800-Coursework | /ML-4/mlday4_ex2.py | 641 | 3.78125 | 4 | """Prepare an ML model using KMeans algorithm to cluster some sample input
generated using make_moon function. Plot the clusters. Also plot the same
points by clustering it with Spectral Clustering Model.
"""
from sklearn.datasets import make_moons
from sklearn.cluster import SpectralClustering
import matplotlib.pyplo... |
fe0d6c09f4eacfc2d14944e9a7661ad7d1658a3a | rufi91/sw800-Coursework | /ML-14/ex.py | 1,442 | 4.21875 | 4 | """
1) Implement MLPClassifier for iris dataset in sklearn.
a. Print confusion matrix for different activation functions
b. Study the reduction in loss based on the number of iterations.
2) Implement MLPRegressor for boston dataset in sklearn . Print performance
metrics like RMSE, MAE , etc.
"""
from sklearn.neural_ne... |
67c3e184244493ea547bf376592aeb9ccb59695a | rufi91/sw800-Coursework | /Python/py-26/ex1-6.py | 1,733 | 3.953125 | 4 | """
1. Create a mysql table ai_nn_emp to contain empno,name,deptcode,desig,salary and insert some records(10)
2. Create another table ai_nn_dept to contain dept_no(values match with deptcode of emp ),dept_name,dept_location and insert some records.
(nn must be 01,02,03 etc. i.e. as per your username)
3. Open ipyth... |
1e938a595993cd2a925b02404399cf0b683bbfa3 | rufi91/sw800-Coursework | /ML-12/ex5.py | 760 | 3.625 | 4 | """
Write a program to do face detection and eyes detection using
haarclassifiers.
"""
import cv2 as cv
import numpy as np
face_cascade=cv.CascadeClassifier('haarcascade_face.xml')
eye_cascade=cv.CascadeClassifier('haarcascade_eye.xml')
img=cv.imread('face.jpg')
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
print face_ca... |
0cbd974d5347320807175b3a3c0a17fddab2ac2d | rufi91/sw800-Coursework | /ML-8/ex2.py | 1,996 | 3.609375 | 4 | """
Apply different ML models for regression to suitable dataset from the
below link. Obtain RMSE values and scatter plots.
link ( https://people.sc.fsu.edu/~jburkardt/datasets/regression/regression.html )
"""
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.n... |
6049135043f6aa6b446c2856ee89cee66e7f706f | rufi91/sw800-Coursework | /Python/py-24/ex.py | 2,164 | 4.375 | 4 | """
Open python interpreter/ipython and do the following.
0.import pandas
1.create a dataframe object from a (10,4)2D array consisting of random integers between 10 and 20 by making c1,c2,c3,c4 as column indices.
2.Sort the above oject based on the key 'c1' in ascending and then by 'c3' in descending order.
"""... |
2310417c508e94b2e2d1709f5a884c80bace0e5b | yveslym/cs-diagnostic-yves-songolo | /fuzzbuzz1.py | 943 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 9 12:33:02 2017
@author: yveslym
"""
#problem 5 An algorithm is a way to solve a problem with simple solution
#problem 6
#pseudocode:
#start: function to check weither the first # is divisible by 5 or 3
# end: function to check weither the l... |
193e2b385c0b08f77f5ef956162857a515ef1d00 | gdacosta-fr/RegExpWizard | /Node.py | 722 | 3.5 | 4 | #!/usr/bin/env python3
# coding: utf-8
class Node:
"""
Inspired by <https://stackoverflow.com/a/28015122>
"""
def __init__(self, nom=None, children=None):
self.Name = nom
self.Children = []
if children is not None:
# children may be a list, a tuple, an object...
... |
e15ed2a2030cfec8320576b421cb8237bb8c9dc5 | nshoa99/Leetcode | /Graph/1042.py | 941 | 3.625 | 4 | import collections
# 1. Xây dựng graph
# 2. Tạo 1 dic lưu đỉnh nào trồng hoa gì
# 3. Lặp qua các đỉnh trong graph
# 3.1 Tạo 1 set {1, 2, 3 ,4}
# 3.2 Lặp qua các đỉnh kề của đỉnh đang lặp
# 3.2.1 Tìm ra đỉnh này đang trồng hoa gì dựa vào dic
# 3.2.2 Xóa hoa này ra khỏi set
# 3.3 Đặt phần tử đầu tiên còn lại trong set là... |
e7b8ac86e23d9ddd1a03dba8f75789e4b3288b57 | nshoa99/Leetcode | /List/1324.py | 1,268 | 4.1875 | 4 | '''
Medium
Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
... |
6ea7d768745b0dbb27e17101c167eab77c9b3d93 | nshoa99/Leetcode | /LinkedList/Example.py | 3,277 | 4.15625 | 4 | # Linked List / Danh sách liên kết
# Thêm, xóa phần từ vào mảng thì tốn O(n) -> Với linked list chỉ tốn O(1)
# Sử dụng con trỏ, không sử dụng chỉ mục để truy cập
# Tốn thêm không gian lưu trữ bộ nhớ cho con trỏ
class Node:
def __init__(self, val):
self.val = val
self.next = None
def __repr__(... |
076ac8dcc7af8424b0e1b5fb4da98a8b9a9478c3 | nshoa99/Leetcode | /String/524.py | 1,338 | 4.1875 | 4 | '''
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.... |
58c05ab3bd5c8eff804a197b485adcd1a28a1232 | nshoa99/Leetcode | /List/448.py | 1,164 | 4.0625 | 4 | '''
448. Find All Numbers Disappeared in an Array
Easy
3292
261
Add to List
Share
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space an... |
99fdb125c5c6db51ba5feb02745f023ffd3c0b8f | sajjadm624/Quarantined-Days-Problem-Solving | /Number/Find Cost of Tile.py | 454 | 3.890625 | 4 | def main():
n = int(input("Enter per unit title cost of tile"))
heightTile = int(input("Enter the Height of tile"))
widthTile = int(input("Enter the Width of tile"))
TileArea = heightTile*widthTile
Height = int(input("Enter the height of covering area"))
Width = int(input("Entwr the width of covering area"))
Co... |
6d8d857edded9a8adf2f230a57616148d8cdb867 | akihiro-hosoya/study-python | /python-izm_basic/print.py | 481 | 3.625 | 4 | print('python', end=' ')
print('-', end=' ')
print('izm', end=' ')
print('.', end=' ')
print('com')
# 出力先の変更
f_obj = open('test.txt', 'w')
print('python-izm.com', file=f_obj)
# フォーマット出力
print('Pythonの学習サイト:{}'.format('python-izm.com'))
print('Pythonの学習サイト:{0}-{1}-{2}'.format('python', 'izm', 'com'))
test_int = 100 ... |
fa5988b1ddea35b9c8325fad2859a0fcdbca1c02 | akihiro-hosoya/study-python | /Learning_Python/hensu.py | 1,229 | 3.921875 | 4 | # ローカル変数
def myfunc():
a = 'Python'
print('a:', a)
# これだけだとエラーが出る
a = 'Python'
myfunc()
print(a) # ここではローカル変数はつかえない
# 名前解決
"""
「変数に代入をするときには、通常、ローカルスコープから使われる」
"""
# 1.ローカルスコープ→ローカル変数bはない→×
# ローカルスコープで名前が見つからなければ、次にグローバルスコープから「b」という名前が探される。
# 2. グローバルスコープ→グローバル変数bがある→解決終了
# ローカルスコープ → グローバルスコープ → ビルトインスコープ
... |
ed3128426fa1cae3bca05be6934a24a28a0e1cd3 | akihiro-hosoya/study-python | /python-introducton/lesson7-7.py | 1,394 | 3.71875 | 4 | # coding:utf-8:
import tkinter as tk
# 円をリストで用意する
balls = [
{'x':400, 'y':300, 'dx':1, 'dy':1, 'color':'red'},
{'x':200, 'y':100, 'dx': -1, 'dy':1, 'color':'green'},
{'x':300, 'y':200, 'dx':1, 'dy': -1, 'color':'blue'},
{'x':50, 'y':400, 'dx':-1, 'dy': 1, 'color':'purple'},
{'x':400, 'y':100, 'dx':... |
ccd43f5af3110f8520c1d9595068e773a3c0402d | akihiro-hosoya/study-python | /python-izm_basic/exception.py | 1,274 | 3.71875 | 4 | # 例外処理
# try, expect, finally
def exception_test(value_1, value_2):
print('====計算開始====')
result = 0
try:
result = value_1 + value_2
except:
print('計算できませんでした!')
finally:
print('計算終了')
return result
print(exception_test(100,200))
print(exception_test(100, '200'))
... |
8fca9c9cc9c71fc7f023e98a2bf15bdfacdf8a45 | akihiro-hosoya/study-python | /Learning_Python/if2.py | 462 | 3.921875 | 4 | # if文
# 条件分岐
# 基本構文
number = input('何か数値を入力してください:')
number = int(number)
if number % 2 == 0:
print('even')
else:
print('odd')
# FizzBuzz問題
number = input('何か数値を入力してください:')
number = int(number)
if number % 15 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
prin... |
db613c63c7e11b6969faf8829eb4e483c7ad5adf | phantomlei3/RPICourseTrends | /python/search.py | 3,219 | 3.796875 | 4 | import re
def search(s, lstdept, lstCode, lstCourseName, lstProf, maxNum):
'''
pre:
sets of: dept, course code, name, professors
user input s, which should only contain uppercase letters, digits and '-'
post (return value):
a list of tuple (val, type), val refer... |
4884939092b2b1836b21fc2cdf498d365d189a11 | 1995-1995/Python_DailyExcercise | /CaesarCode.py | 844 | 3.71875 | 4 | #CaesarCode.py
org = input()
enc = ''
for i in range(len(org)):
if (ord(org[i])>64 and ord(org[i])<91):
value = ord(org[i])-64
charEnc = (value+3)%26+int((value+3)/26)+64
if ord(org[i])<88:
enc += chr(charEnc)
else:
enc += chr(charEnc-26)
elif (... |
f5df8abec27ab0edbfbb5ab425d175225d8a6165 | 1995-1995/Python_DailyExcercise | /tryangle.py | 197 | 3.5625 | 4 | #Triangle.py
user = input()
stars = eval(user)
row = int((stars+1)/2)
for i in range(row):
star = '*'*((i+1)*2-1)
lr= int((stars-((i+1)*2-1))/2)*' '
print ('{}{}{}'.format(lr,star,lr))
|
8ac9ddaadceb65263703629d5fc490fccf6c65b4 | dzida/data-tools | /data_tools/math/distance.py | 1,319 | 3.875 | 4 | # encoding: utf-8
from functools import wraps
def assert_same_length(fn):
""" Decorator that checks if given two vectors for distance calculation have the same length.
Raises ValueError if length is different.
"""
@wraps(fn)
def wrapped(v1, v2):
if len(v1) != len(v2):
raise Va... |
2fad19573d22be64978a0f840c1fdea9d0900295 | JimmieLB/Discord-Bot | /handler.py | 1,178 | 3.546875 | 4 | import csv
class Handler:
def __init__(self, filename):
self.file = filename
self.filelength = 0
with open(self.file, newline="") as f:
for i in csv.reader(f):
self.filelength += 1
def balance(self, name):
with open(self.file, newline="") as f:
... |
217ccfd543daf921c553a4612d1294561866c71b | PrtkSec/python_scripts | /Letter-Counter.py | 269 | 3.796875 | 4 | #!/usr/bin/env
#text = "test"
#text2 = "test 2"
#print (len(text))
#print (len(text2))
#request user for input
user_input = input("Enter String:")
#remove spaces
user_input = user_input.replace(" ","")
#print the input length
print (len(user_input)) |
a5bb0ee1ccd80b6bb2daa2a23dab129307260735 | bhagwsom/FinalprojectBhagwagar | /FinalprojectBhagwagar/db.py | 2,103 | 3.875 | 4 | import sqlite3
DBNAME = 'Spotify.db'
def init_db():
conn =sqlite3.connect(DBNAME)
cur=conn.cursor()
statement='''
DROP TABLE IF EXISTS 'Albums';
'''
cur.execute(statement)
statement='''
CREATE TABLE 'Albums'(
'Id' INTEGER PRIMARY KEY AUTOINCREMENT... |
6badacae420c1fad48652e7ecaddfcd8cec5005e | fadzlanilham10/clientserver | /Pertemuan6/Set.py | 356 | 4.09375 | 4 | fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
print("-----------------------\n")
#Menambah data
fruits.add("Ceri")
for fruit in fruits:
print(fruit)
print("-----------------------\n")
#Menghapus Data
fruits.remove("apple")
fruits.add("semangka")
for fruit in fruits:
print(fruit... |
f0e62cce1dffe5de08bb78c584d8b8f5beac6bad | ValjeanShaw/windmill | /src/List.py | 359 | 3.828125 | 4 | # 列表
list = []
# 追加
list.append("12")
list.append("hello")
list.append("list")
# 排序
list.sort()
list.append(302)
print("append结果:", list)
# 插入
list.insert(3, "foreach")
print("insert结果:", list)
# 删除
list.remove(302)
print("remove结果:", list)
# 删除元素
del list[1]
print("remove结果:", list)
# 删除列表
del list
|
899b1ee20ebb1ac16aa3886922499a99bac8dc1e | dizzyg64/edX-MITx-6.00.2X | /Unit 2/deterministicNumber.py | 377 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 20 00:00:12 2016
@author: RichardG
"""
import random
def deterministicNumber():
'''
Deterministically generates and returns an even number between 9 and 21
'''
random.seed(0)
return 2 * random.randint(5,10)
"""
def deterministicNumber()... |
d5a1e894053e3c3075122d367cbe6ff2371aa12e | fionaoriordan/52445_19_iris | /histiris.py | 2,259 | 4.09375 | 4 | # Fiona O'Riordan 28 March 2019
# Project Iris Data Set
# Create histograms for all 4 variables in the data set distinctly showing an approximate frequency distribution of each of the quantitative variables in the set.
# Adapted from:
# https://machinelearningmastery.com/machine-learning-in-python-step-by-step/ [18]
#... |
7e6cb33faa08f6226093c0b64aad449e546e72da | AGH-Narzedzia-Informatyczne-2020-2021/Project-Maze | /CalculatorDir/Rational.py | 2,252 | 3.859375 | 4 | def euclid(a, b):
while b > 0:
c = a % b
a = b
b = c
return a
def to_rational(text): # assume that text is correct
result = None
if "." in text:
nums = text.split(".")
st = to_rational(nums[0])
nd = to_rational(nums[1])
nd /= Ratio... |
a4860f7041355ba52c776402f77612882c074350 | dmdekf/algo | /05_Stack_1/workwhop/backjoon_10828/10828.py | 1,427 | 3.75 | 4 | # push X: 정수 X를 스택에 넣는 연산이다.
# pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
# size: 스택에 들어있는 정수의 개수를 출력한다.
# empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
# top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
import sys
sys.stdin = open('input.txt')
class Stack:
def __init__(self):
... |
9e191caf7477d696ac5bf1e96ff384533c198fb4 | dmdekf/algo | /Algo_jun/Array/bit.py | 223 | 3.671875 | 4 | if 6 & 1:
print('odd')
else:
print('eval')
a = 1 # bit 토글링 비트 익스클루시브연산(0->1,1->0)
print(a ^ 1)
1 << n: 2의 n승
i & (1 << j): i의 j번째 비트가 1인지 아닌지를 리턴한다.
|
ee64bbec7eee7449b7d526f5147d749b07942740 | haroldhyun/Algorithm | /Sorting/Mergesort.py | 1,998 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 20:04:26 2021
@author: Harold
"""
def Mergesort(number):
"""
Parameters
----------
number : list or array of numbers to be sorted
Returns
-------
sorted list or array of number
"""
# First divide the... |
f50711c8abf963a75bfe8d55167a91e95c8a4f86 | algo-gzua/AlgorithmGzua | /BaekJoon/boj_2750/taxijjang/boj_2750.py | 362 | 3.890625 | 4 | import sys
n = int(input())
arr=[]
def bubble_sort():
for i in range(0 , n):
for j in range(0,n-(i+1)):
if arr[j] > arr[j+1]:
tmp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = tmp;
for _ in range(n):
arr.append(int(sys.stdin.readline()))
... |
260a31e88a71de211de7bfcf0ad8f055b600a6e0 | kcarscad/multi-game-pygame | /Pong/Ball.py | 3,151 | 3.5 | 4 | # filename: 'Ball.py'
# author: Keith Carscadden
# date: 5/25/14
# purpose: Ball class, for use by Pong.py
from sys import exit
from random import randint
import math
from math import pi
# input degrees
def sin(a):
return math.sin(a*pi/180.0)
def cos(a):
return math.cos(a*pi/180.0)
def tan(a):
... |
6f18fc440774af93dae3071c7e6d1cf068a166e1 | lizageorge/iDtech-summer2017-assignment-files | /PythonProjects/LizaHello.py | 397 | 3.9375 | 4 | print("Hello World!" + str(5))
print (10 == 10)
def add_these_nums(x, y):
return x + y
print(add_these_nums(1, 2))
string = ["blue", "white", "green"]
print(string)
string.sort()
print(string)
ints = [1, 3 , 5, 2, 3]
ints.sort()
print(ints)
my_list = [1, 2, 3, 4, 'a', 'b', 'c', 6, 7, 8]
print(my_list[... |
35a46553fa38d269e1a032737e2ed64a4da2fd8f | dheeru0198/Project-Euler | /prob4.py | 299 | 3.609375 | 4 | # Project Euler
# Problem - 4
# Find the largest palindrome made from the product of two 3-digit numbers.
p = 0
for a in range(100, 1000) :
for b in range(100, a) :
c = a * b
if c > p :
s = str(a * b)
if s == s[::-1] :
p = a * b
print p
|
f29154dda69589d8d073285ae71baa80c6029ece | JulianNorton/genetic-algorithm | /GA-bytes_OLD.py | 6,866 | 3.734375 | 4 | # ADD MORE PRINT STATEMENTS EVERYWHERE !!
import random
import sys
### Variables
chromosome_length_max = 8
current_generations = 0
max_generations = 1000
population_max = 32
solution = '1' * chromosome_length_max
gene_replacement = random.randint(0,1)
mutation_chance = random.randint(0,24)
solution_found = False
de... |
611db2d327fc6af36e9b725552515a7e3b4cc6aa | fborges42/Python-2.7-Rock-Paper-Scissor-Game | /RockPaperScissors.py | 1,033 | 4.09375 | 4 | import random
optionList = ["Rock","Paper","Scissors"]
playAgain = "yes"
def RockPaperScissors():
humanChoice = input("1- Rock, 2- Paper, 3- Scissors\n")
if humanChoice == 1:
humanChoice = "Rock"
elif humanChoice == 2:
humanChoice = "Paper"
else:
humanChoice = "Scissors"
computerChoice = random.choice(op... |
ee165ece7fcdc7b96082727b49fdad7b40d0a1ed | Seaman51/client-server | /HW_Lesson_1/HW_Lesson_1_1.py | 1,634 | 3.5 | 4 | # 1. Каждое из слов «разработка», «сокет», «декоратор» представить в строковом формате и проверить
# тип и содержание соответствующих переменных. Затем с помощью онлайн-конвертера преобразовать
# строковые представление в формат Unicode и также проверить тип и содержимое переменных.
# представить в строковом формате:
... |
7d51698f79100d3f50b9f1155eba0789162f4db9 | emilyanncr/isup | /isup/main.py | 1,064 | 3.53125 | 4 | # coding=utf-8
import json
import sys
import urllib2
import config
def get_status(website):
website_url = '{0}{1}.json'.format(config.ISITUP_API_URL, website)
request = urllib2.Request(website_url, headers={u'User-Agent': config.USER_AGENT})
response = urllib2.urlopen(request)
data = json.load(respon... |
50bdb9549e82e3d878f25ed233bb2cd113a905de | ganesh93/OnSharp-Inc.-Coding-Challenge-Submission---2-12-2021 | /bowling01/bowling01_Functions.py | 5,144 | 3.828125 | 4 | #------------------------------------------------------------------------------------#
def getUserInput(nFrames,frame,shot,maxPins):
# Prompts the user for the number of pins kncocked down on a particular frame and shot.
# Returns an integer value representing the number of pins knocked down as entered by the u... |
d9a53335c0077ab9f1513f7b696273751d32ca9d | ai38020/pythonlearning | /judge_grade.py | 232 | 3.890625 | 4 | grade = int(input('grade:'))
if grade in range (90,101):
print 'A'
elif grade in range (80,90):
print 'B'
elif grade in range (70,80):
print 'C'
elif grade in range (60,70):
print 'D'
else:
print 'E'
|
7bdd8af12a1d70d9652f7b2600691c198ecd994c | ObaidKazi/dwm-lab | /LinearRegression/simplelinearregression.py | 1,198 | 3.921875 | 4 | import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
#importing dataset
dataset=pd.read_csv('Salary_Data.csv')
x=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1:].values
#splitting the dataset into the training
from sklearn.model_selection import train_test_split
#used model... |
a985d1439e1f07522b6d141260b8e299278e045b | Kritika05802/DataStructures | /area of circle.py | 235 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
radius = float(input("Enter the radius of the circle: "))
area = 3.14 * (radius) * (radius)
print("The area of the circle with radius "+ str(radius) +" is " + str(area))
# In[ ]:
|
c72814a6e71391c763399e5db0a4dcaed65141d9 | cyrillemidingoyi/SQ_Wheat_Phenology | /test/openalea/fibonacci.py | 370 | 3.609375 | 4 | import numpy as np
from copy import copy
from math import *
def fibonacci(n):
"""
fibonacci function
Author: Pierre Martre
Reference: to write in package
Institution: INRA Montpellier
Abstract: see documentation
"""
value = 0
b = 1
for i in range(0,n):
temp = value
... |
358e116cbccddaceede21f3c52c87a292900b2f4 | CDTong/MIT-6.0001 | /ps3.py | 6,993 | 4 | 4 | import math
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v'... |
75227965827b1834ab4587fd399c7c996d818bf4 | opopiol/Zaliczenie-CDV-python | /6.py | 468 | 3.84375 | 4 | #6. Utwórz skrypt dodający ułamki zwykłe.
print('Ten program służy do dodawania ułamków zwykłych')
licznik1=int(input('Podaj licznik pierwszej liczby: '))
mianownik1=int(input('Podaj mianownik pierwszej liczby: '))
licznik2=int(input('Podaj licznik drugiej liczby: '))
mianownik2=int(input('Podaj mianownik drug... |
1a4d53fa633394f0b12a4417b3818145cb72ff42 | SubhankarHalder/Algorithms-DataStructures | /more_linked_list/more_ex_linked_list.py | 916 | 3.71875 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, newdata):
if not self.head:
self.head = Node(newdata)
self... |
0abcc2119c88023644e8ba7a5f3ef0e9a4a74d64 | SubhankarHalder/Algorithms-DataStructures | /solutions/linked_list.py | 570 | 3.5625 | 4 | class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, newdata):
self.data = newdata
def set_next(self, newnext):
self.next = newn... |
ebee9d2bdf0f37356eb61c91c742dd45d024117d | SubhankarHalder/Algorithms-DataStructures | /solutions/linked_list_ordered.py | 2,613 | 3.859375 | 4 | class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, newdata):
self.data = newdata
def set_next(self, newnext):
self.next = newn... |
438c7127d620e87fe8d0dd4fab1149e7f5358d95 | SaicharanKandukuri/python-from-scrach | /img2csv/gg.py | 1,141 | 3.5 | 4 | #take image
# convert image to csv
from PIL import Image
import numpy as np
import sys
import os
import csv
#Useful function
def createFileList(myDir, format='jpg'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
for name in files:
if name.endswith(fo... |
90dad9d930547c4b6fbd04661618d4be8fd9ad9e | SaicharanKandukuri/python-from-scrach | /class/fact.py | 87 | 3.84375 | 4 | num = int(input("Enter Number to do op \n : "))
print("Factorail is "+str(num*(num-1))) |
3b1cff625f4f0bfd41659aa365dd8b09f8c7454c | SaicharanKandukuri/python-from-scrach | /pegi 12/peiceofcontest.py | 145 | 4.0625 | 4 | # Boolen
while input("Do you know what a boolean is ?[yes/no]") != "yes":
continue
print("Nice")
def f(x):
if x > 0:
return True |
f73b9bbd8cf7eafeab385cf29833f2a2a2675b95 | ralvarep/Digitaliza-ProgramacionRedes | /Python/04_if.py | 386 | 3.9375 | 4 | numero=int(input("Número: "))
if numero < 20:
print("El número "+ str(numero) + " es menor que 20")
elif numero < 40:
print("El número "+ str(numero) + " es mayor o igual que 20 y es menor que 40")
elif numero < 60:
print("El número "+ str(numero) + " es mayor o igual que 40 y es menor que 60")
else:
p... |
523652c4e584a6bcd2c994e1649758b97ad4375c | ggallo87/pythonDesafios | /DesafiosFuncionales/concatena_letras.py | 466 | 3.6875 | 4 | """
Crear una función llamada gen que reciba el número de letras a generar, y devuelva un string con
todas las letras generadas concatendas.
Ejemplo:
gen 4
"abcd"
gen 10
"abcdefghij"
"""
import sys
import string
numero = int(sys.argv[1])
def gen(x):
letras = string.ascii_letters
contar = 0
concatenar = ... |
f066e25dd7044e0a2e7fb37a9f0729e6190c38e7 | prd-dahal/sem4_lab_work | /toc/lab7.py | 684 | 4.5625 | 5 | #Write a program for DFA that accepts all the string ending with 3 a's over {a,b}\#Write a program for DFA that accepts the strings over (a,b) having even number of a's and b's
def q0(x):
if(x=='a'):
return q1
else:
return q0
def q1(x):
if(x=='a'):
return q2
else:
return q0
d... |
998a7721ba659d2f3db922bc6f7e2b928d42893e | wang1128/email-formality-detection | /features/spelling.py | 1,415 | 3.546875 | 4 | __author__ = ['Upasita', 'Sangmi']
import re
import os
def ratio_misspelled_words(email):
"""
Finds common misspelled words based on "the top misspellings according to the Oxford English Corpus"
(http://www.oxforddictionaries.com/words/common-misspellings)
:param email:
:return percentage of miss... |
d892e53c416746a8996fa883df83ba52fdb82746 | ben203/SDEV-300 | /LAB 5/DataAnalysis.py | 18,067 | 3.984375 | 4 | # Python Data Analysis Code
# Author: Bedemariam Degef
# Date; February 15, 2020
# Allows a user to load one of two CSV files and perform data analysis
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
#Read the csv file for population change
file1=pd.read_csv(os.path.join(os.path.dir... |
0b7c2b351c39fa1b718a156eb41ffc9e19b9382e | felixguerrero12/operationPython | /learnPython/ex12_Prompting_asking.py | 397 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# Created on July 27th
# Felix Guerrero
# Exercise 12 - Prompting - Learn python the hard way.
#Creating Variables with Direct Raw_Input
age = raw_input("How old are you? \n")
height = raw_input("How tall are you? \n")
weight = raw_input("How much do you weight? \n")
# Print Variables
print "... |
3a069734693a40536828bdaf82eb3db7188d5e2e | felixguerrero12/operationPython | /learnPython/ex03_Numbers_And_Variable_01.py | 703 | 4.34375 | 4 | # Created on July 26th
# Felix Guerrero
# Exercise 3 - Numbers and math - Learn python the hard way.
#Counting the chickens
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
#Counting the eggs
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.