blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
503c43cd11b0677b60e4d1d81c1a5699b4b20459 | mshamanth23/pythonpractice | /error.py | 304 | 3.78125 | 4 | print('hello')
print("hello")
l=[1,2,3]
print(l[2])
try:
a = int(input("Enter a number"))
b = int(input("enter second number"))
print(a + b)
except:
print("Enter proper number")
else:
print("No Exceptions were Raised!!")
finally:
print("This will anyway execute!!") |
7cf3aa50c52d7f5ce73d3b9e445e002fda16d873 | samarthgupta0309/leetcode | /BinarySearch/find-first-and-last-position-of-element-in-sorted-array.py | 920 | 3.6875 | 4 | '''
Question : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the... |
a93977c2723d020ed0e74c4bd1893e5812bc0c57 | Dipin-Adhikari/Python-From-Scratch | /Dataclasses/main.py | 1,030 | 4.5 | 4 | from dataclasses import dataclass, field
"""Dataclasses let you to quickly build objects that represent data and easily compare, sort, or order them."""
@dataclass(order=True)
class Person:
"""INIT=FALSE to stop initializing as attr, REPR=FALSE to prevent presenting as a string"""
sort: int = field(init=False... |
0d0372d0f4d0a5b17d03dc8c424e0a3f853157b0 | biao111/learn_python2 | /chapter01/chapter06/test_map.py | 704 | 3.984375 | 4 | def pow_number(l):
'''
根据给定的列表数据,计算每一个项目的立方
:param l: 给定一个list/tuple int类型的
:return: 原来列表中的每一项的立方
'''
rest_list = []
for x in l:
rest_list.append(x ** 3)
return rest_list
def pow_use_map(l):
'''
使用map()函数计算列表的每一项的立方
:param l: list/tuple inte类型
:re... |
bc285e3ef5247c23ada41e07d8b07679365ab0e3 | IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-FabianMontoya9975 | /EjerciciosClase6-1Bim/EjemplosSwitch/ManejoSwitch/UsoSwitch.py | 443 | 4.03125 | 4 | """
Ingrese una cadena de texto y verifique que pertenece a un de un día de
la semana.
"""
cadena = input("Ingrese el nombre del día de la semana: ")
if ((cadena == "Lunes") or (cadena == "lunes")):
mensaje = f"{cadena}\n"
elif ((cadena == "Martes") or (cadena == "martes")):
mensaje = f"{cadena}\n"
elif ((cadena =... |
9c12ecc098de0920ebe9b9719440eb204bb25b56 | khanzilmaharibha/sampleguviprg | /even.py | 99 | 3.921875 | 4 | val=int(input())
if val==0:
print("Zero")
elif val%2==0:
print("Even")
else:
print("invalid")
|
536a8e59024358f1fa93bf2136e74a8509d3a394 | SvenDeadlySin/Gitguessinggame | /guessv2.py | 1,145 | 4.25 | 4 | # Guess My Number
import random
import time
print("\tWelcome to 'Guess My Number'!")
time.sleep(2)
print("\nI'm thinking of a number between 1 and 50...")
time.sleep(3)
print("Try to guess it in as few attempts as possible...\n")
# setting initial values
the_number = random.randint(1, 50)
guess = int(in... |
88e56b8743b2d91dd88ed76c19d8ef221bd4d5d5 | AuJaCef/delivables | /python-1.3/Atom#3.py | 491 | 3.890625 | 4 | #atom
#Austin c 11/15/18
#checks atom diffrence
def main():
print("This program checks the weight of a carbohydrate")
H = eval(input("How many hydrogen particles are there: "))
C = eval(input("How many carbon particles are there: "))
O = eval(input("How many oxygen particles are there: "))
Ca = (H... |
9b614d8e2fe54f2db7acd7e3c640a3c70c595e95 | KeiraJCoder/week1 | /Day3/functions.py | 893 | 3.953125 | 4 | def add_up (num1, num2): #paramaters (num1, num2) this is a new function
return num1 + num2
(add_up (7, 3))
print(add_up (123, 480))
balance = 1000
pin = 1234
def atm_function(pin_entered, amount):
global balance
if pin_entered == pin:
print ("Access granted")
if amount <= balance:
... |
11197026d2e2c9b7c8607e4e936e7659ee734393 | PranavMisra/Electricity_Fraud_Detection | /electricity_billing.py | 3,204 | 3.75 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import db.db
import welcome
win = tk.Tk()
win.configure(bg="#D6EAF8")
#making the window to be in the middle of screen
width=win.winfo_screenwidth()
height=win.winfo_screenheight()
x=int(width/2-300/2)
y=int(height/2-100/2)
str1="300x300+"+str... |
773d6e9e0e1e8c80974cfa3cb19a242124325630 | mwang633/repo | /puzzles/Turkey.py | 1,069 | 3.640625 | 4 |
# Created by mwang on 3/3/17.
#
# A week before Thanksgiving, a sly turkey is hiding from a family that wants to cook it for the holiday dinner.
# There are five boxes in a row, and the turkey hides in one of these boxes. Let's label these boxes sequentially where Box 1 is the leftmost box and Box 5 is the rightmost... |
e9952ad11cf0709c344a6d6c2982d89cbfe6b0fd | aCatasaurus/ProjectEuler | /p5/five_2.py | 953 | 4.09375 | 4 | #!/usr/bin/env python3
'''
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
from sys import argv
def min_mul(num):
result = 1
l = list(reversed(range(2, num + 1)))
while l:
x = l.pop()
for i, y in enumerate(l):
if y % x == ... |
b098a1e4e1e1b37524eabddec40d64e3e4cec4c1 | GMags/learn_python | /python_crash_course/ch06/pets.py | 597 | 3.703125 | 4 | pets = []
pet = {
'kind': 'dog',
'breed': 'cavapoo',
'name': 'alfie',
'owner': 'gerry',
'colour': 'brown',
}
pets.append(pet)
pet = {
'kind': 'dog',
'breed': 'lababour',
'name': 'bailey',
'owner': 'ellie',
'colour': 'black',
}
pets.append(pet)
pet = {
'kind': 'snake'... |
f655b1a162ae45628cad5eb11de23d84d356605a | whglamrock/leetcode_series | /leetcode947 Most Stones Removed with Same Row or Column.py | 1,337 | 3.5 | 4 |
from collections import defaultdict, deque
# basically equals to number of islands (Strictly O(n) solution):
# if 2 stones in a same row/column they belong to the same island
# for an island, optimally we can remove all stones until the last one. so the answer = numOfStones - numOfIslands
class Solution(object):... |
acb98abf2a9c56131fd1700eb7fceb0241aa769f | anujaraj10/hacker_rank | /I_Deserve_Code/merge_sort.py | 768 | 3.984375 | 4 | def merge_sort(input_array):
if len(input_array) == 1:
return input_array
else:
mid = len(input_array)// 2
left_half = input_array[:mid]
right_half = input_array[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
... |
c060a85001b22a502c1bc8fa2fc24ea66bb14762 | ME290s-Project/Rocket_simulation | /rocket_sim.py | 4,382 | 3.671875 | 4 | '''
# @ Author: Zion Deng
# @ Description: simulation using matplotlib
For the Rocket here, we use position and angle only for plot.
'''
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import patches as mpatches
from numpy import pi, sin, cos
from MPCsolution import MPC_solve
class Rock... |
27fbdc7655d3ec8ee1cd9d727e545242359b3b64 | jbrzezi/first | /first_script.py | 696 | 4.03125 | 4 | import math
choice1 = input('Choose a path -- left or right: ')
if choice1 == 'left':
print('you fell in a hole...')
choice2 = input('What do you want to do -- climb or sit: ')
if choice2 == 'sit':
print('you sit until dawn and are rescued...')
print()
elif choice2 == 'climb':
... |
0ceb8debefe8bbb21cc3fba272066c5edc465fe7 | Anass-ABEA/Cour-Python-CPGE | /boucles (for-while)/exemple1.py | 204 | 3.53125 | 4 | L = range(9,15)
i = 0
while i < len(L):
if L[i]%2 == 0:
print("element est pair")
else:
print("element est impair")
print("indice i= "+str(i)+" element = "+str(L[i]))
i+=1
|
e95ce6174746f18ab07df323d129a538739aa2ce | Zumcern/GitPodTest | /pset6/credit/credit.py | 1,932 | 3.65625 | 4 | import cs50
import sys
def main():
while True: # get card number
cc_num = cs50.get_int("Enter card number: ")
if cc_num > 0:
break
count_digits = 0
number_check = cc_num
while True:
number_check = number_check // 10
count_digits += 1
if number_che... |
7d3073bcea74715baa28688152dd915c19cda705 | xzcube/test | /recursion/Hanoi.py | 225 | 3.78125 | 4 | def hanoi(n, star, mid, des):
if n == 1:
print(star, "->", des)
else:
hanoi(n - 1, star, des, mid)
print(star, "->", des)
hanoi(n - 1, mid, star, des)
hanoi(3, "A", "B", "C") |
4cc6c398af64a78d36688538072bf62a0c2ab810 | rafaelperazzo/programacao-web | /moodledata/vpl_data/311/usersdata/292/74184/submittedfiles/ex11.py | 609 | 3.90625 | 4 | # -*- coding: utf-8 -*-
dia1=int(input("Digite o dia da DATA 1: "))
mes1=int(input("Digite o mês da DATA 1: "))
ano1=int(input("Digite o ano da DATA 1: "))
dia2=int(input("Digite o dia da DATA 2: "))
mes2=int(input("Digite o mês da DATA 2: "))
ano2=int(input("Digite o ano da DATA 2: "))
if ano1>ano2:
print("DATA 1"... |
a07e99d209fc76479986114197ce5ce14c6ffd7a | saileshkhadka/Concepts_for_AI | /Python .py | 2,038 | 3.859375 | 4 |
# coding: utf-8
# In[2]:
print(5)
# In[4]:
print("Helloworld")
# In[5]:
a=1
print(a)
# In[8]:
a=b=c=1
a
# In[9]:
a=5
type(a)
# In[11]:
b='sailesh'
type(b)
# In[12]:
c=2.5
type(c)
# In[15]:
a="i'm sailesh"
print(a)
# In[17]:
print('{} is {} {}'.format("ghost","sailesh","germany"))
#... |
b47a6bf73cfb90fdc6ca42b6e588fdba690b4237 | kabilasudhannc/simple_us_state_game | /main.py | 1,174 | 3.671875 | 4 | import turtle
import pandas
my_screen = turtle.Screen()
my_screen.title('U.S. States Game')
image = 'blank_states_img.gif'
my_screen.addshape(image)
turtle.shape(image)
jim = turtle.Turtle()
jim.penup()
jim.hideturtle()
data = pandas.read_csv('50_states.csv')
states = data['state'].to_list()
is_game_on = True
guess... |
254527bd72d975f0c66a357da1eb4eb0f442fd32 | ww35133634/chenxusheng | /ITcoach/python_ knowledge_point_practice/迭代器的应用.py | 910 | 3.734375 | 4 | """
迭代器的应用
"""
# print(range(0, 1000))
# range迭代器 可生成 1000 个数据,但它保存的是生成数据的代码,因此可以节省内存空间
# 例1:迭代器生产斐波那契数列
class Fei_Bo:
# 斐波那契数列迭代器
def __init__(self, n):
self.n = n # 返回斐波那契第n个的数值
self.i = 0 # 存放循环自增变量
self.a = 0 # 存放斐波那契第1个数,初始值赋为0
self.b = 1 # 存放斐波那契第2个数,初始值赋为1
... |
73aa4046261b6ea01522beaafa0c7c6c64dc4301 | QitaoXu/Lintcode | /interviews/MS/excelColNum.py | 667 | 3.734375 | 4 | class Solution:
"""
@param n: a integer
@return: return a string
"""
def convertToTitle(self, n):
# write your code here
digits = self.n_to_digits(n)
res = ""
for digit in digits:
res = res + chr(digit + ord('A'))
... |
463141fc5fe5d1dd0e3de1047a77380077868819 | Iam-L/cs344 | /Homeworks/Homework1/traveling_salesman.py | 8,933 | 4 | 4 | """
Course: CS 344 - Artificial Intelligence
Instructor: Professor VanderLinden
Name: Joseph Jinn
Date: 2-20-19
Homework 1 - Problem Solving
Traveling Salesman Local Search Problem
Note:
Don't over-complicate things.
My Python code is inefficient AF due to lack of Python familiarity.
I did try to clean it up a bit ... |
1b98920f390c4f7ca2aac625cc35912cc6da472d | zhanglintc/leetcode | /Python/Unique Binary Search Trees.py | 1,149 | 3.8125 | 4 | # Unique Binary Search Trees
# for leetcode problems
# 2014.08.29 by zhanglin
# Problem Link:
# https://leetcode.com/problems/unique-binary-search-trees/
# Problem:
# Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
# For example,
# Given n = 3, there are a total of 5 unique... |
e508895891fda51b70245250841f68e15f55c967 | gnsalok/Python-Basic-to-Advance | /Interview/Files/i2.py | 1,059 | 3.75 | 4 | '''
Find the overlap of the queue.
Q1 {Name: Q1, country: []string("US", IN), Locale: []string{"english", "hindi"}}
Q2 {Name: Q2, country: []string("US"), Locale: []string{"english", "spanish"}}
Q3 {Name: Q3, country: []string("US"), Locale: []string{"german", "spanish"}}
Q4 {Name: Q4, country: []string("IN"), Locale:... |
2f3591fdd1c4673fa5c94321d05e7ff22101e960 | EthanNah/DataStucture | /arrays-maps/tic_tac_toe.py | 1,878 | 3.9375 | 4 | # MODIFY ME TO IMPLEMENT YOUR SOLUTION
# TO PROBLEM 3: DID I WIN TIC-TAC-TOE?
#
# NAME: FIXME
# ASSIGNMENT: Technical HW: Arrays & Maps
# takes a player character and a 2-dimensional
# array as parameters and returns whether the
# player won the game
# HINT: What does a boolean accumulator look like?
def did... |
6ee9e5a664853108f8a0c8c37fb740a9bda337d2 | emma-l810/Open_CV_Practice | /Open_CV_Practice/imutils.py | 1,570 | 3.984375 | 4 | """
Author: Emma Li
Date: August 27, 2021
Purpose: Convenience Library for Chapter 6.1 Image Transformations Demo
"""
import numpy as np
import cv2
def translate(image,x,y):
'''
translation function
first row of tmatrix: [1,0,tx] where tx = number of pixels shifting left (-) and right(+)
second row of ... |
3bacb595b9717cb2444fa84176806eb6b7428f4f | morwat9/rona_poker | /data_parser.py | 1,320 | 3.875 | 4 | """This module writes and reads data to and from .txt documents"""
def extract_players(player_file):
"""Extracts players and scores, then returns converted data"""
player_data = {}
with open(player_file) as file_object:
for line in file_object:
# Captures player name
player... |
9b07b34f107ea9acf9b1fa001af4c79cbf8fa6ae | pszals/lpthw | /Dropbox/Programming/ex16.py | 1,488 | 4.625 | 5 | # Goes to the system, imports argument variables (input lines into bash)
from sys import argv
# Defines variables 'script' and 'filename' as the two argument variables
script, filename = argv
# Displays text phrase and variable format character 'r,' calls 'r' the filename argv
print "We're going to erase %r." % filen... |
7a681dac5c40d416d43afd8734fd2aaff63e171e | Manpreet1398/Mr.Perfecto | /complexoverload.py | 969 | 3.875 | 4 | class vector:
def __init__(self, num):
self.num = num
def __add__(self, other):
if not isinstance(other, vector):
return NotImplemented
return vector([a + b for a, b in zip(self.num, other.num)])
def __mul__(self, other):
if not isinstance(other, vecto... |
065228a89f2a0ae6644bca54178cf1be0e4f1fc8 | roziana-rdrgs/Python | /three.py | 489 | 4.25 | 4 | '''Escreva um programa que leia duas estruturas (A e B) de 10 posições e faça a multiplicação dos
elementos de mesmo índice, colocando o resultado em uma terceira estrutura (C). Mostre os
elementos de C.'''
list_one = []
list_two = []
list_three = []
for i in range(0, 10):
list_one.append(i * 2)
lis... |
9c1291e1c534a44cc806f45cb580f6c31f108c53 | tokenking6/SafemathChecker | /OperatorParser.py | 5,341 | 3.75 | 4 | # -*- coding: utf-8 -*-
import os
import re
def add(x, y):
return x + ".add(" + y + ")"
def sub(x, y):
return x + ".sub(" + y + ")"
def mul(x, y):
return x + ".mul(" + y + ")"
def div(x, y):
return x + ".div(" + y + ")"
def add_spaces_operator(matched):
return " " + matched.group("operator... |
05ae697356b90b94db322f63dde036b83ea40e8c | calendula547/python_advanced_2020_softuni_bg | /python_advanced_2020/multidimentional_lists/symbol_in_matrix.py | 732 | 4.03125 | 4 | def read_the_matrix():
row_count = int(input())
column_count = row_count
matrix = []
for _ in range(row_count):
row = (", ". join(input()))
matrix.append(row.split(", "))
return matrix
def find_position(matrix, symbol):
row_count = len(matrix)
for row_index in... |
e87f848aa73cb43bb3f526a5d693c4ce02ef0c30 | mayababuji/MyCodefights | /addBorder_LOCAL_4896.py | 663 | 4.0625 | 4 | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"*****"]
'''
de... |
4915c174f8ae076d87986d4863977de37960a60d | Aadeshkale/Python-devlopment | /2.if_loop/if_else.py | 142 | 4.125 | 4 | a=int(input("Enter a:"))
b=int(input("Enter b:"))
if a>b:
print("a is greather than b")
else:
print("b is greather than a")
print("The END") |
d41783def99e98159968f6f3a6962a58da6b8465 | alexandraback/datacollection | /solutions_2463486_0/Python/kavinyao/precompute.py | 448 | 3.875 | 4 | # -*- coding:utf-8 -*-
import sys
import math
from itertools import ifilter, imap
"""
Fair and Square numbers precomputer.
"""
is_palindrome = lambda n: n == int(str(n)[::-1])
def precompute(limit):
upper_bound = int(math.ceil(math.sqrt(limit)))
return ifilter(is_palindrome, imap(lambda x: x*x, ifilter(is_p... |
b19e7c0db991f5e09d898397bfdfcc25d2b4f412 | KaloMendez/Tareassemana6 | /ejercicio3.py | 1,472 | 3.65625 | 4 | def free(row, col):
""" Determina si la casilla rowxcol está libre de ataques.
@param row: Fila
@param col: Columna
@return: True si la casilla está libre de ataques por otras reinas.
"""
for i in range(8):
if tablero[row][i] == 'R' or tablero[i][col] == 'R':
return False
... |
c7a7d33cbacd6353ac547c49034e11164201c899 | nickshaw0609/Luffycity_project | /M1/D5/3.字符串练习题.py | 3,117 | 3.953125 | 4 | # 1.写代码实现判断用户输入的值否以 "al"开头,如果是则输出 "是的" 否则 输出 "不是的"
"""
data = input("请输入内容:")
if data.startswith("al"):
print("是的")
else:
print("不是的")
"""
# 2.写代码实现判断用户输入的值否以"Nb"结尾,如果是则输出 "是的" 否则 输出 "不是的"
"""
data = input("请输入内容:")
if data.endswith("al"):
print("是的")
else:
print("不是的")
"""
# 3.将 name 变量对应的值中的 所有的"l"替... |
d30042d05ea803f001fe9d7924f13d7e55efe375 | hariprabha92/python | /13.3.py | 1,892 | 4.125 | 4 | #Exercise 13.3. Modify the program from the previous exercise to print the 20 most frequently-used words in the book.
from string import digits,punctuation,whitespace
books={'origin.txt','huck.txt','great.txt', 'sherlock.txt'}
def extract(book):
vocabulary = []
flag = False
start_line = "*** ST... |
80bf0cb120a416a36045b6ff8dad44452158c2ff | AswinSatheesh/python-plotly-charts-samples | /bubble_plot.py | 198 | 3.734375 | 4 | import plotly.express as px
df = px.data.iris()
# plotting the bubble chart
fig = px.scatter(df, x="species", y="petal_width",
size="petal_length", color="species")
# showing the plot
fig.show() |
aa2c51bdb22e47273600bde92088810ee9898024 | amweed/Module-12 | /main.py | 212 | 3.5 | 4 | per_cent= {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
money = int(input())
deposit=[]
for i in per_cent:
deposit.append(per_cent[i]*money/100)
print(deposit)
print("Max=",max(deposit))
|
fa72eea1d283d16c20096c1a704a54db62185f4b | ChenYing1025/nowstagram | /venv/xiashi.py | 107 | 3.609375 | 4 | for i in range(4):
for j in range(i+1):
if j<=3:
print('%s=%s'%(j+1,i-j),end = ' ') |
98ca64be453c7fdf22e026ceaffa195d0ab59081 | YifengGuo/python_study | /data_structure/tuple/sumall.py | 371 | 4.3125 | 4 | # Many of the built-in functions use variable-length argument tuples. For example,
# max and min can take any number of arguments:
print(max(1,2,3))
# But sum does not
# Write a function called sumall that takes any
# number of arguments and returns their sum.
def sumall(*args):
res = 0
for item in args:
res +=... |
729f8d1abe6f44747caad59fafbe1b24587facab | icasarino/ProjectEuler | /Euler15/Matrix.py | 785 | 3.78125 | 4 | class Posicion:
def __init__(self,i,j):
self.i = i
self.j = j
def createMatrix(matrix,size):
for i in range(size):
line = []
line.append(0)
for j in range(size - 1):
line.append(0)
matrix.append(line)
def printMatrix(matrix):
for row in matrix:
print(row)
def updateMatrix(matrix,... |
7ed13a070a61c24e2201950b0f1122175ad29de9 | rhashimo/example7 | /convert.py | 963 | 3.71875 | 4 | #!/usr/bin/env python3
import csv
from datetime import datetime
from pprint import pprint
# 1. load input.csv into a variable called `polls`
with open("input.csv") as f:
reader = csv.DictReader(f)
rows = list(reader)
rows = [dict(row) for row in rows]
# 2. write a new file called output.csv and write a row with t... |
7f0eae9366f147b10393fd0a62a59a717bc4ca05 | kimdebie/data-mining-techniques | /Assignment2/code/eda.py | 6,144 | 3.625 | 4 | import pandas as pd
# import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
# import seaborn as sns
from scipy import stats
# sns.set(style="darkgrid")
def missing_values(df):
'''Plot and handle missing values.'''
# Plot the columns with missing values
missing_val... |
518fe0d92105e0084962130979918320335897f7 | ragulkesavan/python-75-hackathon | /THREADING/thread.py | 3,255 | 3.578125 | 4 | from thread import start_new_thread
def chess(a):
"""Calculates the total possible square of a*a chess board"""
copy=a
sum=0
while a>0:
sum=sum+a*a
a=a-1
print "\nthe total possible squares in a*a chess board of a=",copy," : ",sum
start_new_thread(chess,(99,))
start_new_thread(che... |
e80fa89fe460d1a810800403097ff02d0f7e01b7 | hqs2212586/startMyPython3.0 | /第二章-数据类型/编码/py2_encode.py | 422 | 3.8125 | 4 | # python2.7测试用
# -*- coding:utf-8 -*-
"""
s = "武汉武昌"
print s
s2 = s.decode("utf-8")
print s2
print type(s2)
s3 = s2.encode("gbk")
s4 = s2.encode("utf-8")
print s3
print s4
"""
'''
py3 文件默认编码是utf-8
字符串 编码是unicode
py2 文件默认编码是ascii
字符串 编码默认是ascii
如果文件头声明了gbk,那字符串的编码就是gbk
''' |
1f83fa30586eaa4d99c372aa7bc156ccbe13814a | giladgressel/python-201 | /02_more-datatypes/02_03_unique.py | 162 | 3.5625 | 4 | # Write code that creates a list of all unique values in a list.
# For example:
#
# list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]
# unique_list = [55, 'hi', 4, 13]
|
c9355e510b79383885fb153a9640d83d37f78bec | Harshvardhanvipat/Python_workspace | /testing/test.py | 1,372 | 3.75 | 4 | # this is a test file
# this only used in the development environment
# pylint
# pyflakes
# pep8
# testing is a higher level up, to test your code
import unittest
import script
class TestMain(unittest.TestCase):
def setUp(self):
print(' about to start the test')
def test_do_stuff(self):
t... |
55b3bf0669b063973ce4ac65a4849304559e4ffc | Hamdi-Limam/PythonTraining | /day5/courses/os_module/os_module_cwd.py | 842 | 3.78125 | 4 | # OS Module - Handling the Current Working Directory
import os
# Function to Get the current working directory
def current_path(text):
print(f"Current working directory {text}")
print(os.getcwd())
print()
# Printing CWD before
current_path("before")
# Changing the CWD
os.chdir('day5/courses/os_mo... |
5bcc038e1b65a35b826b168c95ccd810e03c2f71 | samsonwang/ToyPython | /PlayGround/03CharacterInput/03CharacterInput.py | 843 | 4.125 | 4 |
'''
https://www.practicepython.org/exercise/2014/01/29/01-character-input.html
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
'''
import sys
from datetime import date
date_today = date.today()
num... |
45c45f5da784117e4e9260a39ded99e865d82b52 | Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Programas da 2a week/1a lista de exercícios extra/digito_das_dezenas.py | 174 | 4.0625 | 4 | num_int = int(input("Digite um número inteiro: "))
unidade = num_int % 10
num_int = (num_int - unidade)/10
dezena = num_int % 10
print("O dígito das dezenas é", dezena)
|
79837d331de1b3f23ade220448f344eda6cd0125 | Iannikan/LeetCodeQuestions | /search2DMatrix/solution.py | 691 | 3.609375 | 4 | class Solution:
def searchMatrix(self, matrix, target: int) -> bool:
rows = len(matrix)
if rows == 0:
return False
cols = len(matrix[0])
left, right = 0, (rows*cols) -1
while left <= right:
mid = (left + right) // 2
testRow = mid // cols
... |
b672b92d252b601ee235565dbd5f937dcdc3f6f9 | Ashmit7Ayush/Projects | /Basic_GUI_SORT/BBubble_sort.py | 557 | 3.8125 | 4 | import time
def Bubble_sort(array, draw_data,time_delay):
mark=False
l=len(array)
for x in range(l):
for y in range(0,l-x-1):
if array[y]>array[y+1]:
array[y],array[y+1]=array[y+1],array[y]
mark=True
# for funality
... |
b62b8c6e887ee11af7da14d8cf186e67cddfd08e | theairdemon/themedPoemGenerator | /getPoems.py | 2,698 | 3.59375 | 4 | from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
def simple_get(url):
"""
Attempts to get the content at `url` by making an HTTP GET request.
If the content-type of response is some kind of HTML/XML, return the
... |
16745c4c6f192c2c3a9823ec9d6e590d0600f269 | mchenyuxiang/MatrixCom | /matrix/sample/line_sample.py | 1,500 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/8/12 23:44
# @Author : mchenyuxiang
# @Email : mchenyuxiang@foxmail.com
# @Site :
# @File : line_sample.py
# @Software: PyCharm
import numpy as np
## 按照矩阵大小生成每行的随机采样位置矩阵
def line_sample_squence(matrix):
row_number = matrix.shape[0]
col_... |
8448d4a7a211b8760d15c10c012f3e0a3cce6aeb | CarterMacLennan/CampusGymAnalytics | /scripts/Temperature_LinearRegression.py | 1,145 | 3.578125 | 4 | # import modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as seabornInstance
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
%matplotlib inline
# Read Dataset
db = pd.read_csv("data.c... |
385eb9256e0f1e386cbc7d9288cfbff7f89b5b07 | laramerlevede/Informatica5 | /06 - Condities/Blad steen schaar.py | 582 | 3.921875 | 4 | # input
speler_1 = input('vorm speler 1: ')
speler_2 = input('vorm speler 2: ')
# wie wint?
if speler_1 == 'blad' and speler_2 == 'steen':
print('speler 1 wint')
elif speler_1 == 'steen' and speler_2 == 'blad':
print('speler 2 wint')
elif speler_1 == 'blad' and speler_2 == 'schaar':
print('speler 2 wint')
... |
09713cfd51b351e660519289e16f95b325fb25a8 | FameIllusionMaya/NPA_week6 | /Hw2_THB_USAStockCalculator.py | 1,085 | 3.765625 | 4 | import urllib.parse
import requests
import json
print("Stock price calculator THB -> stock amount")
while True:
print()
stock_symbol = input("Input stock symbol : ")
money_thb = float(input("Input amount of money(THB) : "))
key = "c1go7qf48v6v8dn0ddeg"
main_api_stock = 'https://finnhub.... |
788adaf0b21916c1872b6177b3e4fe3c15f53549 | rodirigos/snake-python | /main.py | 3,344 | 3.625 | 4 | import pygame
import time
import random
pygame.init()
canvas_width = 800
canvas_height = 600
dis = pygame.display.set_mode((canvas_width, canvas_height))
pygame.display.set_caption('Joguinho da cobrinha')
# Color Constants
white = (255, 255, 255)
blue = (0, 0, 255)
red = (255, 0, 0)
black = (0, 0, 0)
yellow = (255, 2... |
a7513f618fcd37a0fdb0b312ce9b017a7847196f | ugurkam/PythonSamples | /Samples/methods.py | 590 | 4 | 4 | # METHOD :
list = [1, 2, 3]
list.append(5) # append bir method ve liste sınıfının bir öğesi. methodlar önceden tanımlanmıştır.
# liste bir class (sınıftır). Sınıf ise bünyesined bir çok method bulunduran bir yapıdır.
# list class'ı str class'ı vb. birçok class vardır.
list.pop() # pop... |
45c428a6aee60a5a30b59d38c8f26c6ee3782768 | DidiMilikina/DataCamp | /Machine Learning Scientist with Python/16. Introduction to Deep Learning with Keras/03. Improving Your Model Performance/04. Comparing activation functions.py | 1,390 | 3.78125 | 4 | '''
Comparing activation functions
Comparing activation functions involves a bit of coding, but nothing you can't do!
You will try out different activation functions on the multi-label model you built for your irrigation machine in chapter 2. The function get_model() returns a copy of this model and applies the activa... |
22a5ce728d81a6dceb1ceed65c4f26086e5d46b2 | NazarovDA/munchkin | /tests.py | 600 | 3.65625 | 4 | from main import Game
import unittest
list_of_players = ["Player1", "Player2", "Player3"]
global game
class TestGame(unittest.TestCase):
def test_game_creating(self):
global game
game = Game(card_packs=["M1"], players=list_of_players)
def test_players(self):
global game
playe... |
7f0f1877e300767496040c67735fcb91cb8ea650 | A-Mykahl/A-Mykahl | /RandomMandala.py | 692 | 4.0625 | 4 | import turtle
import random
#set turtle speed and background color
turtle.speed(0)
turtle.bgcolor('beige')
#User Input section
limit = 0
shape = int(input("Enter Length of side "))
angle = int(input("Enter Angle "))
counter = random.randint(100, 300)
#Mandala Loop
while limit != 500:
turtle.forward(shape)
tu... |
ac43712ec4bd1eb98b0b8de3dacdafb7812d9d67 | Tsukumo3/Algorithm | /Algorithm/最短経路問題/dijkstra.py | 6,827 | 3.921875 | 4 | class Dijkstra():
''' ダイクストラ法
重み付きグラフにおける単一始点最短路アルゴリズム
* 使用条件
- 負のコストがないこと
- 有向グラフ、無向グラフともにOK
* 計算量はO(E*log(V))
* ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
'''
class Edge():
''' 重み付き有向辺 '''
def __init__(self, _to, _cost):
self.to = _to
... |
a1cb26b9123e5e82e55eaaf6faa9abc1b0a0e3e4 | lakhanjindam/Practice_Codes- | /infosys/lists.py | 1,449 | 3.8125 | 4 | # For removing duplicates values in list
'''l = list(map(int, input().split(",")))
print(l)
li = []
for i in l:
if i not in li:
li.append(i)
print(li)'''
#For intersection of lists
'''li1 = [1,23,12,45,67,31,43]
li2 = [23,56,32,45,68,90,98]
set1 = set(li1)
set2 = set(li2)
set1 &= set2
print(list(set1))'''... |
84f9a63d94c8cc8874189203715da578db0f1260 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.037.py | 652 | 4.28125 | 4 | # 37. Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de
# conversão:
# - 1 para binário
# - 2 para octal
# - 3 para hexadecimal
num = int(input('Digite um número inteiro: '))
print('''Escolha uma das bases para conversão:
[1] Binário
[2] Octal
[3] Hexa... |
3bb051aaf508e989fa94e411419959e969999739 | Aaron9477/tiny_code | /LSTM/PRSA/plot_pollution.py | 446 | 3.5625 | 4 | from pandas import read_csv
from matplotlib import pyplot
# 读取数据
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# 选择几列进行输出
plot_column = [0,1,2,3,5,6,7]
i = 1
# 绘制每一列
pyplot.figure()
for column in plot_column:
pyplot.subplot(len(plot_column), 1, i)
pyplot.plot(values[:, colum... |
69bf17c8a47048acf7384f26f67a0f0c76dcbcab | Crazycosin/dailybing | /bignumber.py | 2,332 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 18-7-25 下午9:57
# @Author : Crazycosin
# @Site :
# @File : bignumber.py.py
# @Software: PyCharm
from threading import Thread,currentThread
'''
模拟310位求解,因为我不知道每10位求解。
我大致使用9位求解,每个线程求一位,第二个线程从倒数开始逐位变9
'''
def bignumber_calculator(bignumber,div):
'''
bignumber为被除数,
d... |
9d650c3e6e90dfc6b89fb7c0dba5f265aafd6825 | ahowe2/FlipItPhysics-Physics2 | /thermodynamics/equipartitionHeatCapacityAndConduction/ExpandingTank.py | 2,724 | 4.03125 | 4 | # coding= utf-8
"""
A 27-m3 tank is filled with 2590 moles of an ideal gas.
The temperature of the gas is initially 300 K, but it is raised to 735 K.
PART A:
What is the change in the pressure of the gas inside the tank?
We can use the ideal gas law equations in order to solve for
the final pressure and then use the ... |
0d5741c67c24cf72a9991a7768030390ba12b9da | ningpop/Algorithm-Study | /07_이인재/Week3/11729.py | 303 | 4.125 | 4 | user_input = int(input())
p1 = 1
p2 = 2
p3 = 3
def Hanoi(n, p1, p2, p3):
if n == 1:
print(p1, p3)
else:
Hanoi(n-1,p1, p3, p2)
print(p1, p3)
Hanoi(n-1,p2,p1,p3)
cnt = 1
for i in range(user_input -1):
cnt = cnt*2+1
print(cnt)
Hanoi(user_input, p1, p2, p3) |
ceb385855d3793df9af5573f267e301adfa83877 | mauodias/project-euler | /2/__init__.py | 307 | 3.765625 | 4 | def main():
total = 0
current = 1
before = 1
limit = raw_input()
while current < int(limit):
tmp = current + before
before = current
current = tmp
if current % 2 == 0:
total += current
print total
if __name__ == '__main__':
main() |
a00106f3b240568c6406f81d02568554f311a3f3 | vuminhdiep/c4t--20 | /session5/intro.py | 461 | 3.921875 | 4 | from random import randint
print(randint(0, 100))
month = int(input("Month of a year"))
print(month)
if month < 4:
print("Xuan")
elif month < 7:
print("Ha")
elif month < 10:
print("Thu")
else:
print("Dong")
from random import randint
weather = int(randint(0, 100))
print(weather)
if weather < 30:
... |
724fe1d03a6ddf0847bdc408e9fa3b7192dbc226 | codio-gcse-2014/teacher-python-4 | /01-oop/task-1.py | 334 | 3.703125 | 4 | # Task 1
# Press the 'Run File' menu button to execute
#
import random
class Dice:
value=0
def __init__(self):
self._value=0
def roll(self)->int:
self.value=random.randint(1,6)
my_dice=Dice()
my_dice.roll() #object methods are called with a dot notation: #object_name.object_method()
print(... |
a672c2826c3b9de125469ed2079772c8f350af62 | SAMPROO/textadventure-game | /textadventure-python/eat.py | 2,033 | 3.53125 | 4 |
def eat(conn, location_id, item):
if item == None:
print("What do you want to eat?")
item = input("--> ")
eat(conn, location_id, item)
cur = conn.cursor()
#CHECK IF IN INVENTORY OR IN A LOCATION
check_loc_inv = "SELECT name, item_location_id, item_character_id, addhp FROM i... |
55cef985c0d00f207b55bdce18b1c8edf48082b5 | MuberraKocak/data-structure-python | /LeetcodeChallenges/remove_vowels.py | 475 | 3.921875 | 4 | def remove_vowels(S):
# result_string = ''
# for letter in str:
# if letter in 'aeoui':
# pass
# else:
# result_string += letter
# return result_string
# With faster look up because of hashset/hash table
retval = []
vowels = set('aeiou')
for letter in... |
915acd305dd974938150a351ac44b8b43d673703 | chengjieLee/pyLearn | /listcomp.py | 396 | 3.8125 | 4 | L1 =['Hello', 'World', 32, 'Apple', None]
L2 = [x.lower() for x in L1 if(isinstance(x, str))]
#对每一项结果操作 |循环 |判断条件
# print(L2)
L3 = ['ADm','AtM','helLo']
def Upper(s):
i=0
y=''
while i < len(s):
if i==0:
y = s[i].upper()
else:
y += s[i].lower()
i = i +... |
feda37e2e7d13ed34fe714811efe85654a18d13d | ByeonghoonJeon/practice-file | /python practice/practice_count.py | 1,053 | 4.0625 | 4 | # Count function practice.
print("Welcome, we will let you know about love level with you and (him/her)")
your_name = input("Please type your name.\n")
lover_name = input("Please type his/her name.\n")
# Make lower case for each input
your_name = your_name.lower()
lover_name = lover_name.lower()
# Count how many o... |
730da9a83617aa4f26d28e5e164b6550be425007 | OlyaIvanovs/automate_with_python | /web_scraping/lucky.py | 844 | 3.53125 | 4 | """
This programm allows type a search term on the com-
mand line and have a computer automatically open a browser with all
the top search results in new tabs.
"""
import sys
import webbrowser
import bs4
import requests
import pyperclip
print("Googling...")
# Get search term from command line
if len(sys.argv) > 1:
... |
87989162736bba2150f0b88920817cff56ccbcc2 | SlimTimDotPng/school_inf_matura | /python/04_O_a_S_stvorca.py | 226 | 3.6875 | 4 | a = float( input("Zadaj dĺžku prvej strany: "))
b = float( input("Zadaj dĺžku druhej strany: "))
print("Obsah obdĺžnika so stranami A a B je", a*b, "centimetrov štvorcových \nObvod je", 2*a+2*b,"centimetrov")
input()
|
dd7947599f02bb6c2ec187c20d06666f3ef74577 | rellen1/python-study | /U18-pratice.py | 940 | 3.671875 | 4 | # for i in range(100):
# if i % 2 == 0:
# continue
# print(i)
# i = 0
# while i < 100:
# i += 1
# if i% 2 == 0:
# continue
# print(i)
# continue는 아래 코드를 건너뛰고 loop 문으로 다시 넘어가게됨
# pass 는 상관없이 바로 다음줄 실행.. 쓸모없을 것같지만 에러관리를 위해쓰는경우가 있음.. 에러가 발생하더라도 계속 코드 진행을 위해 쓰는 경우가있다
# break는 아예 Loop문... |
a9332e2a71a6622d2aa053973bb7953612a69593 | jj1232727/p2p-bittorrent | /applications/peer-to-peer-app/client.py | 2,674 | 3.671875 | 4 | # -*- coding: utf-8 -*-
""" The client
This file has the class client that implements a client socket.
Note that you can replace this client file by your client from
assignment #1.
"""
import socket
import pickle
class Client(object):
def __init__(self):
"""
TODO: implement this contructor
... |
c38ec2a575e7b4e05730f6df8b0a22c347bfbfb5 | yuuura/demo-PySpark2-with-arguments-and-classes | /main.py | 513 | 3.734375 | 4 | import my_spark
import word_count
# Creating a spark session into a global var
my_spark.SparkInit().init()
# By using global var 'sc', we will read a text file 'book.txt', which is in our hadoop cluster
# 'path_in_hadoop_cluster' - The path where our file 'book.txt' is located in hadoop cluster
lines = my_spark.sc.sp... |
465172c789905a003ae4aaab5f0b2b6ffa68448a | rijas8398/code | /strings.py | 748 | 4.5 | 4 | print("working with strings")
str="apples"
'''print(str)
print(len(str))
print(str.upper())
print(str.lower())
print(str.isupper())
print(str.islower())
print(str.upper().isupper())
print(str.isalpha())
print("\n")
num="A8398"
print(num)
print(num.isnumeric())
print(num.isalnum())
print(num.find("39"))
print(num.endsw... |
85f2e8640657462043b1730847a1991e46a3c1ba | AnoushAtayan/PythonTasks | /Play/20.py | 328 | 3.734375 | 4 | def translate(englishList):
dict = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"}
swedishList = ''
for i in englishList.split(' '):
swedishList = swedishList +str(dict.get(i) + ' ')
return swedishList
print translate('merry christmas and happy new y... |
ae8047d1bb063e7dcb4f7ca22238334cffa90cbe | flannaganp/python-branch | /test-prog1.py | 2,439 | 4.25 | 4 | # this program is testing various python concets
# 12/22/18 (pdf, jc)
#
####### begin variable declaration #######
#
py_var= 10+10
weight = 74.2
height = 1.79
bmi = weight/height **2
in_str1 = 'the output'
in_str2 = "is:"
####### endvariable declaration #######
#
# begin main body of code
print ("My first python pro... |
824b5591b4630d52bfec10cfc32fee93cfbaf555 | wushengxuan/python-learn | /wsx.py | 674 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
'''多态'''
__auhtor__ = 'wushengxuan'
class Animal:
def run(self):
print('animal is running')
class Dog(Animal):
def run(self):
print('dog is running')
class Cat(Animal):
aa = 2
__haha = 1
__xixi = 'wsx'
def get(self):
return self.__haha
def run(self):
... |
db07dedea165d9b2034349cba5ac4c104149b103 | ausaki/data_structures_and_algorithms | /rbtree.py | 9,058 | 3.65625 | 4 | """
红黑树的性质:
- 每一个节点要么是黑色, 要么是红色.
- 根节点是黑色的.
- 叶子节点是黑色的.
- 如果一个节点是红色的, 那么它的子节点必须是黑色的.
- 从一个节点到NULL节点的所有路径必须包含相同数量的黑色节点.
"""
import graphviz
RED = 'R'
BLACK = 'B'
DEBUG = False
_print = print
def print(*args):
if DEBUG: _print(*args)
class RBNode:
def __init__(self):
self.value: int = None
... |
6993fc80655fea3457c548994d0eb119a6e092af | eoin-og/sudoku_solver | /sudoku_solver.py | 2,197 | 3.53125 | 4 | import timeit
import time
input_sudoku = [[0,0,0,0,8,9,7,0,0],
[1,0,0,0,4,0,0,0,9],
[0,0,0,0,0,5,0,6,8],
[0,0,6,3,0,0,1,0,0],
[5,8,0,0,0,0,0,0,0],
[0,0,1,0,0,4,9,0,0],
[0,7,0,6,0,0,2,0,0],
[... |
718a324a0d7a4844bc884a007c4a4bffda957115 | cikent/Python-Projects | /LPTHW/ex17-MoreFiles-FileObjects.py | 3,517 | 4 | 4 | '''
# import argv from the sys module
from sys import argv
# import exists from the os.path module
from os.path import exists
# unpack argv into different variables
script, fromFile, toFile = argv
# print to screen a notification to the user what the script will do
print(f"Copying from {fromFile} to {toFile}")
# Ope... |
6a3678a0bb87795d38ec93772189c07fc8bf2416 | dydx2000/Autel_2019_01_07 | /Cam/CamMod/ElectricCar.py | 1,241 | 3.875 | 4 | class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=35
def get_descriptive_name(self):
long_name=str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odome... |
7443785a345fdd53554178b7b9a274f58446973e | anilasebastian-94/pythonprograms | /regular_expression/phone_no_valid.py | 150 | 3.671875 | 4 | import re
x=input('enter no')
n='\d{10}'
match=re.fullmatch(n,x)
if match is not None:
print('valid phone no')
else:
print('invalid phone no') |
95fac007900206de099265ae605f88b5dbdde4ea | MahZin/Python-Automation- | /Section 10_Regular_Expressions/23_exp_lengthy_function.py | 791 | 4.34375 | 4 | # regular expression basics
# used to find text patterns, like ctrl + f
# example of a cumbersome method
def isPhoneNumber(text): # 415-555-
if len(text) != 12:
return False # not phone number-sized
for i in range(0, 3):
if not text[i].isdecimal():
return False # no area ... |
ba93236a439e8d3379a5464a4db173d9831cebeb | fernandezfran/python_UNSAM | /ejercicios/Clase02/informe.py | 1,932 | 3.890625 | 4 | #### informe.py
#
# Este código se corre de la siguiente manera:
#
# $ python3 informe.py ../Data/camion.csv ../Data/precios.csv
#
# E 2.15: Lista de tuplas
#
# [edited] E 2.16: Lista de diccionarios
#
# [edited] E 2.17: Diccionarios como contenedores
#
# [edited - main] E 2.18: Balance
import csv
import sys
def leer_... |
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) |
d4826687406e96dad211de2eebcb007618a9d3e9 | geekhub-python/strings-Rootwar | /task_8.py | 325 | 4.1875 | 4 | #!/usr/bin/env python3
string = input('Enter your string: ')
if string.find('f') == string.rfind('f') >= 0:
print("Index 'f' at string : ", string.find('f'))
elif string.find('f') != string.rfind('f'):
print("First index 'f' at string: ", string.find('f'))
print("Last index 'f' at string: ", string.rfind(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.