blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
aef193e69c925483ca035a17485800439a593157 | jiangjinshi/1807 | /13day/学生系统.py | 448 | 3.796875 | 4 | a = []
while True:
print("欢迎来到学生系统")
print("1:添加学生信息")
print("2:查找学生信息")
print("3:修改学生信息")
print("4:删除学生信息")
print("5:退出学生系统")
i = int(input("请输入序号:"))
if i == 1:
name = input("请输入姓名")
age = input("请输入年龄")
sex = input("请输入性别")
d = {}
d["name"] = name
d["age"] = age
d["sex"] = sex
a.append(d)
p... |
5510b33e93e7bd0c27694933ebab2e80819cbf72 | shibing624/python-tutorial | /06_tool/re_demo.py | 437 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: 正则表达式示例
"""
import re
a = "物流太糟糕了,申通{服务恶劣啊,自己去取的"
for i in re.finditer(',', a):
print(i.group(), i.span()[1])
s = '{通配符}你好,今天开学了{通配符},你好'
print("s", s)
a1 = re.compile(r'\{.*?\}')
d = a1.sub('', s)
print("d", d)
a1 = re.compile(r'\{[^}]... |
2f28196f0a6b12348cc3e9af4d6b1916d035e05a | sanketdofe/pythonlabwork | /fibonacci.py | 182 | 3.875 | 4 | n=int(input("Enter the length of sequence:"))
list1 = []
a = 0
list1.append(a)
b=1
list1.append(b)
for i in range(2,n):
j=list1[i-1]+list1[i-2]
list1.append(j)
print(list1)
|
721c1b5e13917b43a6d2110425d768b7cc113e25 | pr4nshul/CFC-Python-DSA | /Siddhant/q4.py | 480 | 3.609375 | 4 | def Anargams(lists):
result = []
for string in lists:
freq = {}
for item in string:
freq[item] = freq.get(item, 0) + 1
result.append(freq)
ans = []
for i in range(len(result) // 2):
for j in range(i + 1, len(result)):
if result[i] == result[j]:
... |
d0149daa8a12ab0a9de316166a4539f7b28f874b | jeangiraldo/Python-Curso | /excepciones python.py | 433 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 12:49:17 2020
@author: CEC
"""
try:
print("1")
x=1/0
print("2")
except:
print("Oh dear, something went wrong...")
print("3")
try:
x=int(input("Enter a number"))
y=1/x
print(y)
except ZeroDivisionError:
print("... |
8a9acc007b1d766c50a48464617cc0c8f033f307 | MACHEIKH/Datacamp_Machine_Learning_For_Everyone | /21_Introduction_to_Deep_Learning_with_Keras/1_Introducing_Keras/helloNets.py | 1,198 | 4.3125 | 4 | # Hello nets!
# You're going to build a simple neural network to get a feeling of how quickly it is to accomplish this in Keras.
# You will build a network that takes two numbers as an input, passes them through a hidden layer of 10 neurons, and finally outputs a single non-constrained number.
# A non-constrained out... |
34a07326e375ed006620ed4b1aca6ee683885546 | pamnesham/magic8Ball | /magicBall8.py | 293 | 3.859375 | 4 | import random
answers = ['Yes',
'Very probably',
'Should not get your hopes up.',
'No',
'Eh, unlikely',
'Would not bet on it.']
print('Think of a question and then press enter.')
input()
print(answers[random.randint(0, len(answers)-1)])
|
bdd8fb2f247bc1c9fa0754f5b6393fc97a33fd28 | Adlaneb10/Python | /Lab6/q6.py | 314 | 4.21875 | 4 | # Ask the user to enter a number and print it back on the screen.
# Keep asking for a new number until they enter a negative number
num = 0
while(num > -1):
num = int(input("Enter a negative number "))
print("You entered ",num)
if num < 0:
print("Thank you")
break
|
8477c5ab45f0f1cf9dfcfb09f18892575083361a | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 86 - ReverseLLII.py | 1,370 | 4.0625 | 4 | # Reverse Linked List II
# Question: Reverse a linked list from position m to n. Do it in-place and in one-pass.
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
# Return 1->4->3->2->5->NULL.
# Note: Given m, n satisfy the following condition:
# 1 ≤ m ≤ n ≤ length of list.
# Solutions:
class ListNode(obje... |
12e1cb5334565b3e15ad395c88e34a44d9a70cda | saywordsahn/DataScience1 | /CA Housing Model/2.stratify.py | 1,255 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pd.set_option('display.max_row', 1000)
pd.set_option('display.max_columns', 50)
data = pd.read_csv('housing.csv')
# split into training and test data sets
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split... |
eae84ef179c725c044fc79ba78b08820d6e14597 | jeffreytzeng/HackerRank | /Python/02. Basic Data Types/03. Nested Lists/grades.py | 441 | 3.65625 | 4 | from operator import itemgetter
n = int(input())
students = sorted([[input(), float(input())] for i in range(n)], key=itemgetter(1))
lowest = min(students, key = lambda grade: grade[1])
second_low = min(filter(lambda grade: grade[1] != lowest[1], students), key = lambda grade: grade[1])
names = list(filter(lambda gra... |
1020fa3bba3aa0397b62c93f2caa171bacb1ee71 | Ignotus111/labyrinth | /classes/position.py | 1,129 | 4.1875 | 4 | class Position:
"""Class that handles position on the grid"""
def __init__(self, x, y):
self.position = (x, y)
def __repr__(self):
"""Return a position object in string"""
return str(self.position)
def __hash__(self):
"""Give a hash for each created object"""
re... |
81c40d90180f84416242f3e01154fe02e94c06ac | aitorlb/Udacity-Free-Courses | /Intro to Computer Science/Lesson_5_How_Programs_Run/19-Better_Hash_Functions/supplied/studentMain.py | 620 | 4.15625 | 4 | # Define a function, hash_string,
# that takes as inputs a keyword
# (string) and a number of buckets,
# and returns a number representing
# the bucket for that keyword.
# https://discussions.udacity.com/t/challenging-the-professor-testing-times-need-your-help-to-analyze-this-fun-discovery/121419
def hash_string(keyw... |
e01a1e8bc03b3dedaeb37a36ea645a39593b3662 | victormasayesva/Project-One | /hangman/python/Functions/debugFunctionDrillsV1.py | 2,718 | 4.09375 | 4 | '''
The following functions have problems that keep them from
completing the task that they have to do.
All the problems are either Logical or Syntactical errors with FUNCTIONS.
Focus on the functions and find the problems with the FUNCTIONS.
For this debug, there could be problems with executing the functions... |
99c9891b0a4e0dd886a353329e7dfd6ca852289f | rvsp/cbse | /9_python.py | 456 | 3.875 | 4 | # 9) Write a recursive code to display and calculate the sum of Geometric
# progression . a, ar, ar2 , ar3 , ar4 Up to n terms
# function to calculate sum of geometric series
def sumOfGP(a, r, n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a * r
i = i + 1
return sum
... |
465d816600d73bf9c1b478fe6f1cce75446ca5a0 | SujeethJinesh/Computational-Physics-Python | /In Class/in_class.py | 374 | 3.890625 | 4 | def in_class():
t = float(input("Please input the time: "))
height = float(input("Please input the height: "))
g = 9.8 #m/s^2
distance = (1/2.0)*g*t**2.0 #m
height_above_ground = height - distance #m
if height_above_ground <= 0:
print ("The ball hit the ground")
else:
print("The h... |
559461103eb714962dfb97c97d38132b17ec0976 | caliuf/hacker_rank | /code_flows_r1/getMaximumOutfits.py | 2,114 | 3.90625 | 4 | #!/bin/python3
# -*- coding: utf-8 -*-
"""
Points: 50
Result: 3/8
Time: 13m+30m
Note: I can't manage to understand how to make the last 5 tests pass. Maybe I don't well understand the specs, I tried:
- Go ahead until it find an outfit it can't buy, then exit
- [My final choice] Go ahead until money is over or the li... |
1ccf6856f9756f22743094806b0b1a32478989a5 | felipesergios/Python | /039.py | 495 | 4.0625 | 4 | from datetime import date
atual = date.today().year
nascimento = int(input('Ano de Nascimento:'))
idade = atual-nascimento
print('Quem nasceu no ano de {} tem {} anos de Idade '.format(atual,idade))
if idade==18:
print('Voce Precisa se Alistar!!')
elif idade>18:
saldo=idade-18
print('Voce Precisa Ir A Junta... |
ada0dcc3257266e28f37253861992bab4b3ea1c8 | yingCMU/tensor_flow | /kalman_filters/trigonometry.py | 1,601 | 4.6875 | 5 | # Python's math module has functions called sin, cos, and tan
# as well as the constant "pi" (which we will find useful shortly)
from math import sin, cos, tan, pi
# Run this cell. What do you expect the output to be?
print(sin(60))
from math import pi
def deg2rad(theta):
"""Converts degrees to radians"""
# ... |
8e748c411118a132508c57ccaf68d304f0798d92 | BenThomas33/practice | /interviews/csvparser.py | 1,486 | 3.5 | 4 | import unittest
class Solution:
def add_cell_to_row(self, cell, row):
row.append(''.join(cell).strip())
del cell[:]
def add_row_to_result(self, cell, row, result):
self.add_cell_to_row(cell, row)
result.append(list(row))
del row[:]
def parse(self, s):
row,... |
c08f83a83e7ce83cb69275d3c02c30782ae5f94d | ironsubhajit/india_map_pattern | /app.py | 780 | 3.546875 | 4 | # Python3 program to print india map pattern
# code by ironsubhajit
a = 0
b = 0
c = 10
s = ("TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs"
" UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPe"
"HBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFA"
"gcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm S"
"On TNn ULo0ULo#ULo-WHq!WFs XDt!")
# Read each charac... |
26908a07581f0ad329293d6cf3a841ccb52a887e | dougmcnally/school-projects | /ProteinFolding/smart_protein_folding.py | 15,027 | 3.640625 | 4 | # Computational Physics Final Project
# Protein Folding
# - Optimized for faster runtime
# author Doug McNally
### IMPORTANT ###
# Running this program in IDLE may cause catastrophic failure when testing the plot_dynamic_temp()
# function. Run this program manually from a directory, i.e. double click on the fi... |
b3b3e6b370aa81c2c271fc3f11d86cfe18f924bf | inki-hong/python-oop | /f111_instance.py | 543 | 3.609375 | 4 | class Sedan():
no_of_doors = 4
def set_owner(self, owner):
self.owner = owner # alice_sedan.owner = 'Alice'
def set_plate_no(self, plate_no):
self.plate_no = plate_no
def set_mileage(self, mileage):
self.mileage = mileage
alice_sedan = Sedan()
# print(alice_sedan.owner) # attribute error
Sedan.... |
ff2cf5445211321ab385bafa073b5c5f0cf95096 | brunoreyes/python_fundamentals | /sorting.py | 1,291 | 4 | 4 | pangram = "The quick brown fox jumps over the lazy dog"
#pangram is a phrase that contains all letters of the alphabet, to check lets sort
letters = sorted(pangram)
print(letters)
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'a', 'b', 'c', 'd', 'e', 'e', 'e', 'f', 'g', 'h',
# 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', ... |
b8aa1b2038d7260f60df01496283180bb97494b4 | quanwen20006/PythonLearn | /day1/基础语法.py | 2,171 | 3.625 | 4 | # _*_ coding:utf-8 _*_
'''
主要是记录学习基础过程中的demo
该文档记录的主要是基础知识
'''
# 2022.5.24
int = 1
#查看数据的类型,使用type可查看到
print(type(int),int,'\n数据相加\t',type(1+1.1),'\n数据相乘\t',type(1*1.1),'\n数据相除\t',type(1/1))
#整形数相除,但是想得到整形
print('整形相除、但是想得到整形:',type(1//1))
print('转换为16进制',hex(13))
print('转换为8进制',oct(13))
print('转换为2进制',bin(1... |
098887ea4aa1bca0ccc297af45c5b365d29c7184 | quadrant26/python_in_crossin | /Lesson/lesson14_task.py | 352 | 3.75 | 4 | from random import randint
print('Guess what i think!')
num = randint(1, 100)
bingo = False
while bingo == False:
answer = int(input())
if answer < num:
print('%d is too small!' % answer)
if answer > num:
print('%d is to big!' % answer)
if answer == num:
print('%d is equal!'... |
5a29058b09ae15c2e5a2bb1b096cd1f29cc00728 | Dimildizio/learn_tkinter | /alt_pygame_canvas/BFS.py | 7,088 | 3.515625 | 4 |
import queue
from random import choice
'''
27. Terrain class:
27.1 attributes
27.1.1 terrain difficulty
27.1.2 terrain danger
27.2 terrain_effect()
'''
class Terrain:
def __init__(self, name, speed_penalty = 1, penalty = 1, effects = []):
self.name = name
... |
455a43db949c61853979efd29ceb5673a19d716a | GeekChao/Coding | /Educative/coding/fast_slow_pointers/ex3.py | 1,371 | 3.953125 | 4 | """
Problem: Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number ‘1’. All other (not-happy) numbers will never reach ‘1’. Instead, they will be stuck in a cycle of numbers which does not include ‘1’.
Difficulty... |
8ab7e1919f49b823a53545560559877092d0f0c4 | 5ran6/Algorithm-challenges | /random_algorithms/sum_of _smallest_number.py | 172 | 3.796875 | 4 |
# sum of two smallest numbers
def sum_two_smallest_numbers(numbers):
numbers.sort()
return numbers[0] + numbers[1]
print(sum_two_smallest_numbers([19,5,42,3,77])) |
d849291eb2e78233ab477d22c14acf3e9422c3dc | Coalin/Daily-LeetCode-Exercise | /111_Minimum-Depth-of-Binary-Tree.py | 1,960 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
... |
623ad63a942ad344e1e339c7e9b5f5cfb41aeefd | AhmedShehab/leetCodeFun | /RomanToInteger.py | 553 | 3.734375 | 4 | def romanToInt(s: str) -> int:
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
# These are there valuse
romanNumerals = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
number = 0
track = 0
for i in range(len(s)-1,-1,-1):
digit = romanNumerals[s... |
2eb18ebfa2f9edf979740b1473e3684d954b583d | RoryBaxter/Route-Planner | /gui.py | 13,784 | 3.96875 | 4 | '''Setup and running of the GUI, as well as calling to other sub systems
'''
import tkinter as tk
from time import time
from PIL import ImageTk
from goompy import GooMPy
import location
import search
class RoutePlanGUI:
'''The GUI for the Route Planning System
All the GUI features are created and run thou... |
22bf75f98127604df26dac5c4a3bf674b48bf3a1 | DavidHan6/Week2 | /Week2/ImageProcessing.py | 4,275 | 3.515625 | 4 | from PIL import Image
from PIL import ImageFilter
print(" What is your request? ")
print(" a is invert")
print(" b is darken")
print(" c is brigten")
print(" d is greyscale")
print(" e is posterize")
print(" f is solarize")
print(" g is denoi... |
5dadbbe6ec2cf90c77f482417ac263e4ab9dd88d | sai10/Python-Sample-Programs | /Practice/CONDITIONAL/IfElif.py | 197 | 3.6875 | 4 | a = 5;
b = 9;
if a>b:
print('greater');
elif a<b:
print('other way round')
else: # optional or when required
print('check your code');
|
94ff7641dd48da4411b59e4f9f209eb4207a4b45 | chixujohnny/Leetcode | /Leetcode2020/剑指offer/链表/剑指 Offer 24. 反转链表.py | 978 | 3.734375 | 4 | # coding: utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
... |
9746e66d27ee13bc57868c25b1daaacee030a4c6 | shouliang/Development | /Python/SwordOffer/re_order_array_01.py | 1,221 | 3.828125 | 4 | '''
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,
所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路: 两指针,一个从左向右扫描,遇到偶数停止,一个从右往左扫描,遇到奇数停止,然后交换两数
但是此方便不能保证奇数和奇数,偶数和偶数之间的相对位置不变
'''
# coding=utf-8
class Solution:
def reOrderArray(self, array):
if not array:
return []
begin, end = 0, len(array... |
54030f834bc1b2c021574a78940131efd22afa81 | NARESHSWAMI199/5-Star-On-Hacker-Rank-Python | /modified_kaprekar_number.py | 397 | 3.6875 | 4 | start_point = int(input())
end_point = int(input())
string = ''
if start_point == 0 or start_point == 1:
print(1 ,end=' ')
for x in range(start_point,end_point+1):
square = str(x*x)
length = len(square) // 2
if len(square) == 1:
continue
else:
if int(square[0:length]) + int(square[length : ]) == x:
prin... |
1d3a6beef7fcb71e048d788bef2a7290a97490e4 | wellington-ishimaru/IFSP--Estruturas-de-repeticao | /questao4.py | 2,087 | 3.75 | 4 | # -*- coding: UTF-8 -*-
print("******************************")
print(" Venda de passagens de ônibus ")
print("******************************\n")
poltrona_janela_esq = [0 for x in range(0, 12)]
poltrona_corredor_esq = [0 for x in range(0, 12)]
poltrona_janela_dir = [0 for x in range(0, 12)]
poltrona_corredor_dir = [0 ... |
70fc0a35c3c41f4d490021f46444b720a21c03bb | hudingjing244/interview | /py_interview/distribute_candies.py | 884 | 3.90625 | 4 | """
给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
示例 1:
输入: candies = [1,1,2,2,3,3]
输出: 3
解析: 一共有三种种类的糖果,每一种都有两个。
最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。
示例 2 :
输入: candies = [1,1,2,3]
输出: 2
解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。
注意:
数组的长度... |
95c39250eb139a54473d04b02f080bf68884b1c0 | gsaurabh98/machine_learning_basics | /mlPackage/pandas/missing_data.py | 561 | 3.640625 | 4 | import numpy as np
import pandas as pd
d = {'A':[1,2,np.nan],'B':[1,np.nan,np.nan],'C':[1,2,3],'D':[np.nan,np.nan,np.nan]}
df = pd.DataFrame(d)
print df
# for removing NaN value
print df.dropna()
#by removing column which has Nan
print df.dropna(axis=1)
#Keep only the rows with at least 2 non-na values:
print df.dr... |
b4ebfcf72dbeecf7881cd779c60f58a4aa136471 | gridl/Lonang | /lnn/statements/variable.py | 1,609 | 3.671875 | 4 | from .statement import Statement
from variables import Variable
from operands import Operand
def variable(c, m):
"""Variable or constant definition. For instance:
byte little = 42
short big = 1234
byte[5] vector1
byte[] vector2 = 1, 2, 3, 4, 5
const VALUE = 7
"""
... |
1470c0335c3ff17a6aa7c48a09ce1a1e27510c93 | Miguelsantos101/algoritmos1-2021-1 | /palindromo.py | 736 | 3.71875 | 4 | # Retorna o número de digitos de num
def contaDigitos(num):
dig = 0
while num != 0:
num = num // 10
dig = dig + 1
return dig
#----------------------------------------
# Função que recebe n e retorna True se n é palíndromo, False caso contrário.
def EhPalindromo(n):
numero = n
digitos = contaDigitos(n)
n ... |
4ccd439d367504072cc73d63d9d5dc53b5058858 | tomim19/frro-soporte-2019-09 | /practico_04/ejercicio04.py | 3,850 | 3.890625 | 4 | ## 4. Ejercicio al Formulario del Ejercicio 3 , agrege los siguientes botones 1- un botón Alta
## que inicia otra venta donde puedo ingresar una ciudad y su código postal .
## 2 – un botón Baja que borra del listad de ciudades la ciudad que esta selecionada en Treeview .
## 3 – un botón Modificar . Todos los cambi... |
1365e2539b4f9e7eb4fd961a5e85f79fbe04dcc2 | siddharth952/Interview-Prep | /CodeForces/54/A.py | 639 | 3.703125 | 4 |
''' Question:
Letters can be deleted from s => it results to "hello"
Solution:
Have to keep track of stream of hello
'''
from collections import Counter
from sys import stdin
def read_int():
return int(stdin.readline())
def read_ints():
return map(int, stdin.readline().split())
def main():
t... |
7c4796031a510f6c7718d012c4cff221e3196ad6 | CorinnaBuerger/yinyang | /yinyang.py | 926 | 3.609375 | 4 | from turtle import circle, begin_fill, end_fill, dot, left, right, fillcolor, pencolor, pensize, shape, shapesize, speed, fd, penup, pendown, hideturtle, home
def jump(distance, angle):
penup()
left(angle)
fd(distance)
left(-angle)
pendown()
def yin(diameter, color_1, color_2):
radius = diamet... |
e45a47d64dc34024f14eac262daa74627712b5a2 | nikkokun/nlp | /nlp-02.py | 697 | 4.34375 | 4 | # STOP WORDS
# !/anaconda/bin/python python 3
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentence = "This is an example showing off stop word filtration."
def main():
# main code here
stop_words = set(stopwords.words("english"))
print(stop_words)
words = word_t... |
2d473e283ea5b1adace7f70d5a433f452da96d73 | CarlosG4rc/CursoPy | /Curso Python/3. Listas/list.py | 554 | 4.15625 | 4 | numeros = [1,2,3,4]
datos = [4, "una cadena",-15,3.14,"Otra cadena"]
print(datos[0])
print(datos[1])
print(datos[-2:])
print(numeros + [5,6,7,8])
pares = [0,2,4,5,8,10]
print("pares incorrectos" )
print(pares)
pares[3]=6 #modificar valores
print("pares correctos")
print(pares)
pares.append(12) #agrega... |
d9cf91d569f339edcbc905ca3beb9d8aca8c24b7 | someshwar123/python | /arrind.py | 500 | 3.984375 | 4 | #-------------------------------------------------------------------------------
# Name: module4
# Purpose:
#
# Author: Somesh
#
# Created: 01/08/2018
# Copyright: (c) Somesh 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
array = []... |
b101b01f621e02578cd918ee672c7524e484d57b | AngelRem1/TXT_test | /main.py | 2,565 | 4.3125 | 4 | # Name : Angel Remigio
# SSID : 1848012
# Assignment #: 3
# Submission Date : 10/26/2020
#
# Description of program :
# Single Player Tic Tac Toe against a computer
from random import randint
# void function to print the board state
the_board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
# Printing the fun... |
f0280f9a182c0ecf15cc710cf6ac125e6af5f81d | GOUTHAMRAEES/python | /python/palindrome.py | 170 | 4 | 4 | a=input("Enter the string")
b=""
for i in range(len(a)-1,-1,-1):
b=b+a[i]
if(b==a):
print("it is palindrome")
else:
print("Not a palindrome")
|
cbb6f70c92d9cad7a7b505f1ead50ca138a13386 | IlkoAng/-Python-Fundamentals-Softuni | /05. Lists Advanced Exercises/04. Office Chairs.py | 463 | 3.671875 | 4 | number = int(input())
free_chairs = 0
isEnough = True
for num in range(1, number+1):
room = input().split()
chairs = room[0]
people = int(room[1])
diff = abs(len(chairs) - people)
if len(chairs) > people:
free_chairs += len(chairs) - people
elif len(chairs) < people:
p... |
63c1b0a0fa507248f8b064fe6c98ad4049e48697 | bus1029/HackerRank | /Statistics_10days/Day4/GeometricDistribution2.py | 754 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
# Task
# The probability that machine produces a defective product is 1/3.
# What is the probability that the 1st defect is found during the first 5 inspections?
# 첫 5개 검사에서 첫 번째 결함이 발견될 확률은 얼마입니까?
# # => 첫 5개의 검사에서 최소 하나의 결함이 발견될 확률은 얼마입니까?
# 첫 번째... |
70e50a44d8497d7b18d8c9e0f2b78eefc99bbc19 | arshdeepsinghsandhu/lab7 | /task.py | 159 | 3.53125 | 4 | import math
class cal():
def __init__(self,a,b):
self.a = a
self.b = b
def sum(self):
return self.a + self.b
inst = cal(2,3)
print(inst.a + inst.b)
|
a3401d21d8eb870b808d6ae62353f87e3f8b67e4 | gregorybrooks/BetterQueryBuilder2 | /programfiles/get_noun_phrases_from_spacy_daemon.py | 687 | 3.5625 | 4 | import spacy
import sys
"""Calls spaCy to extract noun_phrases from a string.
Pass the string to extract from via STDIN.
This script returns the extracted phrases in STDOUT.
"""
# Load English tokenizer, tagger, parser, NER and word vectors
nlp = spacy.load("en_core_web_sm")
# Get query from stdin:
while True:
t... |
7ed47818311ed2b45e245341dc907f6f7bed9c97 | mehuman/GitGeo | /geolocation.py | 1,458 | 3.921875 | 4 | """geolocation functionality."""
from geographies_list import (
ALL_COUNTRIES,
CITY_COUNTRY_DICT,
CODE_COUNTRY_DICT,
STATE_ABBREV,
STATE_NAMES,
)
def get_country_from_location(location_string):
"""Return country (Hungary, United States, etc) from user location text
This function implemen... |
1e5fa231d85312cd8f076c1c30477f061871f7e3 | kimjane93/udemy-python-100-days-coding-challenges | /day-3-adventure-game/adventuregame.py | 926 | 4.21875 | 4 | print("Welcome to Treasure Island.\nYou're mission is to find the treasure.\nYou're at a cross road.")
first_choice = input("Where do you want to go? Type 'left' or 'right'\n")
if first_choice == "right":
print("Game Over")
else:
print("You come to a lake.\nThere is an island in the middel of the lake.")
se... |
940a48063b1d87ba947ae77e2d196408a92e4f72 | AmitGupta700/Python | /set of first N prime no.py | 227 | 3.703125 | 4 | n=int(input("Enter The n prime no: "))
count=0
i=1
l=[]
while count<n:
for d in range(2,i,1):
if i%d==0:
i+=1
else:
l.append(i)
i+=1
count+=1
s=set(l)
print(s)
|
c499117826e31a4c9354311775bd645b3cc60910 | Mr-Nicholas/udacity-studies | /python-intro/secret-names/secret-names.py | 605 | 3.875 | 4 | import os
def rename_files():
# get all the names from folder path
file_directory = os.listdir("/Users/Heath/Downloads/prank")
saved_path = os.getcwd()
print saved_path
os.chdir("/Users/Heath/Downloads/prank")
saved_path = os.getcwd()
print saved_path
# for each file, remove... |
d838d1c8c89173a94d58006819b878398d0fa841 | gentle-potato/Python | /17_exception/exception_처리.py | 2,296 | 3.953125 | 4 | # 예외 발생 상황 처리
# ZeroDivisionError: division by zero
# print(10/0)
try :
print(10/0)
# print(10/2)
except :
print('ZeroDivisionError')
finally : # 오류 발생 여부와 관계 없이 항상 나오는 부분
print('나누기')
# 예외처리 클래스 지정
try :
print(10/0)
# print(10/2)
except Exception :
print('ZeroDivisionError')
finally :
... |
79b3185e486b884470c1641b6c89eda1dfa8443d | Frankiee/leetcode | /dp/140_word_break_ii.py | 3,069 | 3.765625 | 4 | # https://leetcode.com/problems/word-break-ii/
# 140. Word Break II
# History:
# Facebook
# 1.
# Aug 18, 2019
# 2.
# Mar 12, 2020
# 3.
# Apr 24, 2020
# Given a non-empty string s and a dictionary wordDict containing a list of
# non-empty words, add spaces in s to construct a sentence where each word
# is a valid dict... |
542c42f76a11656ad3652fa1e995be5e3519bc1f | vincentzhang/coding-practice | /linked_list/node.py | 2,683 | 3.828125 | 4 | # My own
class Node(object):
def __init__(self, key=None, next_ptr=None):
self.key = key
self.next_ptr = next_ptr
def getKey(self):
return self.key
def getNext(self):
return self.next_ptr
def setKey(self, key):
self.key = key
def setNext(self, ptr):
... |
990293afbcb90ebae7f66a7775cadf8894eacec7 | iniudin/baris-kode | /python/tgs_tabungan.py | 777 | 3.6875 | 4 | """
Goal:
Membuat program peritungan tabungan
input: tahun
ouput: jumlah tabungan tiap bulan dan tahun.
"""
# Preparation
tahun : int
bulan : int = 12
# Diasumsikan sebulan ada 4 minggu
minggu : int = 4
# Setoran tetap adalah Rp 50.000
setoran : int = 50000
# Mula-mula tabungan adalah 0
tabungan = 0
tahun = int(... |
0380de1ab287baae48c99551e02d3769b9e6c2a0 | sakshi978/Competitive-Platforms | /Hackerrank/Permutation.py | 713 | 4.1875 | 4 | '''
Question:
Task
You are given a string S.
Your task is to print all possible permutations of size k of the string in lexicographic sorted order.
Input Format
A single line containing the space separated string S and the integer value k.
Output Format
Print the permutations of the string S on separate lines.
Sampl... |
b4f8a0e75abd8d06c43c5852ce417e412b95a98f | eungju/kata | /CodeDojo/srp.py | 1,499 | 3.765625 | 4 | import unittest
WIN = 1
LOSE = -1
TIE = 0
class Rock:
def match(self, other):
return other.matchWithRock()
def matchWithPaper(self):
return WIN
def matchWithRock(self):
return TIE
def matchWithScissors(self):
return LOSE
ROCK = Rock()
class Scissor... |
57d44fda64399e9de3e4bf10f266323f8a6e5f90 | tadeze/goproject | /ds/quicksort.py | 631 | 3.984375 | 4 |
"""
Quick sort implemetnation. The idea of quick sort is to partition the whole array based on the pivot point. The pivot is selected such that
the left side is less than the large side of the arra.
a = [2, 8, 7,20, 12, 4]
"""
def quick_sort(a, l, h):
if l < h:
p = partition(a, l, h)
qui... |
179c75625f4e3a25ce879ad6400e4ef1c4d6843a | Acejoy/LeetcodePrep | /62. Unique Paths/pythonSolution.py | 234 | 3.71875 | 4 | import math
def uniquePaths(m,n):
return math.factorial(m+n-1-1)//(math.factorial(m-1)*math.factorial(n-1))
if __name__ == "__main__":
rows = 3
cols = 7
print(f'The no of unique paths are:{uniquePaths(rows,cols)}.') |
afa4982d7020e4059ff660e19128842c93c00e58 | rashi174/Codewars | /iq_test.py | 727 | 3.640625 | 4 | def iq_test(string):
#your code here
numbers = string.split()
noOdds = 0
noEvens = 0
position = 0
for i in range (0, len(numbers)):
if(int(numbers[i]) % 2 == 0):
noEvens = noEvens + 1
else:
noOdds = noOdds + 1
if(noOdds > noEvens):
... |
9b394726a4aa21e3bb99afccafedd948d31851e7 | ypliu/leetcode-python | /src/044_wildcard_matching/044_wildcard_matching_DpTable.py | 1,093 | 3.5 | 4 | class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if None == s:
return None == p
elif None == p:
return False
if 0 == len(p):
return 0 == len(s)
return self.chec... |
ff4c16a0ff8ededd95e7773f6c76adb1dddf80f7 | CryFR/dz | /PyDZ/Task 4/str_op.py | 230 | 3.671875 | 4 | s = "У лукоморья 123 дуб зеленый 456"
if 'я' in s:
print(s.index('я', 1))
print(s.count('у'))
if s.isdigit():
print(s.upper())
if len(s) > 4:
print(s.lower())
print(s.replace(s[0], 'О')) |
00665b71ffc7a3fa1d85a794fc3f49037a0c62f1 | philipwoodward/Practicals | /Prac01/tarrifElectricityBillEstimator.py | 710 | 4.15625 | 4 | """
Program to calculate and display
the electricity bill. Inputs will be price per kWh in cents,
daily use in kWh and the number of days in the billing period
"""
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = 1
while tariff == 1:
tariff = int(input("Enter which tariff please - 11 or 31: "))
if tariff == 1... |
193ab79cf396a5fceb5e5fe05740850709b83a13 | pmsorhaindo/adventOfCode2019 | /day5/day5.py | 6,084 | 3.59375 | 4 | f = open('input.txt')
line = f.readline()
ADD_OP_CODE = 1
MULT_OP_CODE = 2
INPUT_OP_CODE = 3
OUTPUT_OP_CODE = 4
JMP_IF_TRUE_OP_CODE = 5
JMP_IF_FALSE_OP_CODE = 6
LESS_THAN_OP_CODE = 7
EQUALS_OPCODE = 8
def load_program():
return [int(s) for s in line.split(',')]
def ammend_program(noun, verb, program_list):
prog... |
5d13ff162ea2edae798b43a18bc516e824d0d752 | jangui/Implementations | /problems/leetcode/1441-buildArrayStack/Solution.py | 847 | 3.546875 | 4 |
class Solution:
def __init__(self):
pass
def buildArray(self, target: List[int], n: int) -> List[str]:
"""
:param target: list of ints we want to build using stack
:param n: limit of iteration
:return: list of stack operations
"""
# edge case
if ... |
861d83f5bdc40f1c83fe96efde61b6187bf4fed3 | Draymonder/Practices-on-Pyhton | /Day_7/property.py | 719 | 3.8125 | 4 | class Student(object):
#@property装饰器将方法变成属性调用,本身又创建了另一个装饰器@score.setter,可以限制赋值,避免属性的暴露
@property
def score(self):
return self._score
@property
def name(self):
return "chengkang"
@score.setter
def score(self, value):
if not isinstance(value, int):
raise V... |
eed1bc0ea3f640ea3422f794010bf3293dde4af1 | franklingu/leetcode-solutions | /questions/random-pick-index/Solution.py | 1,116 | 3.96875 | 4 | """
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {... |
4d27abec8c3be964b81eec05cd9b5c00ac22faca | jsonkao/mks22 | /hw/mks22-hw0404.py | 1,274 | 3.859375 | 4 | # Problem 5:
def replaceAll(astring,lookfor,replaceWith):
pos = -1
for c in astring:
pos += 1
if lookfor == astring[pos:pos + len(lookfor)]:
astring = astring[:pos] + replaceWith + astring[pos+len(lookfor):]
return astring
# Test results:
# 1. Pass
# 2. Does not pass.
# 3. Pas... |
36869f1f039ab14be6e656c223e9bdcdfac86a58 | heitorchang/learn-code | /pangloss/code/interview/sorting/radix_sort.py | 483 | 3.984375 | 4 | # Algorithms (Cormen)
from operator import itemgetter
def radix_sort(lst):
"""Sort a list of integers, first sorting by the ones place,
then the tens, and so on"""
# set up the list, separating numbers into digits
lst_str = list(map(str, lst))
len_longest = len(max(lst_str, key=len))
lst_pad ... |
619ed2a92374dfbfd07be06c45b9a7e5e5a41560 | wan-catherine/Leetcode | /problems/N2594_Minimum_Time_To_Repair_Cars.py | 841 | 3.875 | 4 | import math
from typing import List
"""
Key point is : All the mechanics can repair the cars simultaneously.
So for some times, we can calculate the cars all mechanics together can repair.
If the number of cars >= given cars , then we reduce the times, or we increase the times.
So perfect binary search .
"""
class S... |
44e95c72e35ddf07eb964fe944f4721e51c2956a | paulyun/python | /Schoolwork/Python/In Class Projects/3.24.2016/test.py | 702 | 4.09375 | 4 | current_tuition = 15000
for p in range(1,11):
increase_rate = float(input("What is your tuition's increase rate for year"))
current_tuition = current_tuition + current_tuition*increase_rate
print("The Current Tuition for year ", p, "is $", format(current_tuition, '.2f'))
current_tuition = 15000
inc... |
ff8851fe44f1205398b4874fcbc89bd1422fe71a | Frky/p-euler | /src/p54.py | 9,255 | 4.0625 | 4 | #-*- coding: utf-8 -*-
from src.p import Problem
class Hand(object):
"""
Object representing a poker hand (i.e. five cards)
Contains methods to evaluate the hand and to compare to hands.
"""
def __init__(self, hand):
# a card is a tuple (value, color)
self.hand = hand
... |
966fbf4d60cff653a3b1851dc9ee7289b5bff448 | xuezhizeng/hwang_robot_works | /RIK_simulator/src/lbd_playback/bin/MikesToys/timer.py | 1,551 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import time
def ms(f):
return round(f,9)
class Timer():
def __init__(self, _name="Timer"):
self.name = _name
self.count = 0
self.total = 0
self.min = -1
self.max = -1
self.create = time.time()
self.lastEnd = -1... |
0013c9ea1ddc3f662af8f2ca4a9eda65e3ec554c | Naimulnobel/python-learning | /ignorcasesensitive.py | 262 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 20 15:03:32 2019
@author: Student mct
"""
import re
r = re.compile(r'nobel', re.I)
m=r.search('nobel is a programmer').group()
print(m)
search1=r.search('Nobel is a programmer').group()
print(search1) |
af953c5aea0480c3529d362a062b76ff9e86f23f | eessm01/100-days-of-code | /python_para_todos_p2/paquete/subpaquete/moduloo.py | 895 | 3.984375 | 4 | """
Si los módulos sirven para organizar el código, los paquetes sirven para
organizar los módulos. Los paquetes son tipos especiales de módulos
(ambos son de tipo module) que permiten agrupar módulos relacionados.
Mientras los módulos se corresponden a nivel físico con los archivos,
los paquetes se representan med... |
7c71bff585dac4e841f0f0f5561dc29bb728b6c7 | Coni63/CG_repo | /training/easy/the-descent.py | 281 | 3.875 | 4 | import sys
while True:
mountain_h = [int(input()) for _ in range(8)] # represents the height of one mountain, from 9 to 0.
print(mountain_h.index(max(mountain_h)))
# Write an action using print
# To debug:
# The number of the mountain to fire on.
|
f76d3aca1ba400957d0c1229ab9745d8e2dd3cba | kaikoh95/leetcode-solutions | /solutions/easy/q7-reverse-integer.py | 610 | 3.515625 | 4 | """
https://leetcode.com/problems/reverse-integer/
"""
def reverse(x: int) -> int:
group = list(f"{x}")
if len(group) == 1 or (len(group) == 2 and group[0] == "-"):
return x
if group[-1] == "0":
return reverse(int("".join(group[:-1])))
index = 1 if group[0] == "-" else 0
reverse_gr... |
82710975144f557d6bb09cad4e6d307e41f49d8a | Levintsky/topcoder | /python/leetcode/divide_conquer/843_guess_word.py | 3,802 | 3.90625 | 4 | """
843. Guess the Word (Hard)
This problem is an interactive problem new to the LeetCode platform.
We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.
You may call master.guess(word) to guess a word. The guessed word should have type string and must... |
423004e85f8ded34e4b4cc2a7aca4f78454b7af9 | AbdulAbdullah/Data-Science-Journey- | /My Project/python classes/class example.py | 647 | 3.796875 | 4 | class Student:
perc_raise = 1.6
def __init__(self, first, last, grade):
self.first = first
self.last = last
self.grade = grade
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
def ap... |
846f963f3b5a7c8c7c07b041f36900c8245f8fb3 | MrN1ce9uy/Python | /multiply2.py | 201 | 4.1875 | 4 | #! usr/bin/python3
num1 = int(input('Enter the number to be multiplied: '))
num2 = int(input('Enter the number to multiply by: '))
result = num1*num2
print(num1, 'multiplied by', num2, '=', result)
|
bd46705fd7bb92a37d3eb7d1761a81f3cf64a672 | logd-py/simple-calc | /python-progs/py_palindrome.py | 242 | 4.34375 | 4 | #Python program for palindrome.
x=input("Enter the string to be checked for Palindrome: ")
y=x[::-1]
if (x==y):
print("The entered string",x,"is a Palindrome.")
else:
print("The entered string",x,"is not a palindrome.")
|
2aace637253c628f725df5b6f482b3121bc57e93 | yuispeuda/pro-lang | /python/calısma-soruları/liste_topla.py | 320 | 3.703125 | 4 | # -*- coding: cp1254 -*-
def liste_topla(liste):
m = 0
for i in liste:
toplam = 0
if type(i) == list :
for k in range(len(i)):
toplam += int(i[k])
print "d[",m,"]'nin elemanlar toplam",toplam
m += 1
liste_topla([[2,3,4],4,[8,9],67])
|
b846d9d9a0e1603f10678e9e12c606f90507600d | mssubha/practice | /practice.py | 1,927 | 4.15625 | 4 | def checkPossibility(nums):
print(nums)
non_decreasing_count = 0
max_value = 0
if len(nums) <3:
return True
for i in range(len(nums)-1):
if max_value > 0 and i > 0:
if nums[i+1] < max_value:
print ("Inside 1")
return False
if (nums[... |
e2b92a81bcfd7cdd5135ed7eca22087359f428bf | Aasthaengg/IBMdataset | /Python_codes/p02711/s527728491.py | 64 | 3.609375 | 4 | N=input()
if N.find("7")!=-1:
print("Yes")
else:
print("No") |
454882e6a840b4d90d4c687e4c67e164f8cce57d | EugeneShell/python_for_dqe | /functions.py | 6,089 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 02 12:17:25 2021
@author: Yauheny_Shaludzko
"""
# HW2 Refactor using functional approach
'''
Task: Create a list of random number of dicts (from 2 to 10)
dicts random numbers of keys should be letter,
dicts values should be a number (0-100),
example: [{'a':... |
438767e8fe6e3f7315da5a5d276fa7dc8241ef14 | FiberJW/hsCode | /guess_my_number_v3.py | 3,930 | 3.96875 | 4 | def guess_user_num():
import random, time
print('\t\t\tGuess My Number!\nI will think of a number between 1 and 100 (Inclusive)\n\nTell me what you think the number is. I\'ll give you hints\n\n')
def main(): #define main instructions as function for calling later
num = random.randint(0, 100)
... |
c6f1a9ed7c4748a0b4e414181e47241f49fa6a5b | szat/Blackjack | /game21/Hand.py | 2,930 | 4.15625 | 4 | __author__ = "Adrian Szatmari"
__copyright__ = "Copyright 2018"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Adrian Szatmari"
__status__ = "Production"
class Hand:
"""
This class implements the a hand, i.e. a set of cards of a player belongin together.
A hand has a list of cards, a last card... |
597325f5eea09ec904a078b766903584ba0b9e0a | IceDerce/learn-python | /learning/2.py | 470 | 3.625 | 4 | a = [45, 67, 23]
b = []
if a[0] < a[1] and a[0] < a[2]:
b.append(a[0])
if a[1] < a[2]:
b.append(a[1])
b.append(a[2])
else:
b.append(a[2])
b.append(a[1])
elif a[0] > a[1] and a[0] > a[2]:
if a[1] < a[2]:
b.append(a[1])
b.append(a[2])
b.append(a[0])
... |
3c9060f17337d2ede40c2f74a14ca16f166ed092 | krnets/codewars-practice | /6kyu/Find the odd int/index.py | 920 | 3.96875 | 4 | # 6kyu - Find the odd int
""" Given an array, find the integer that appears an odd number of times.
There will always be only one integer that appears an odd number of times. """
# from collections import Counter
# def find_it(seq):
# return [x for x, y in Counter(seq).items() if y % 2][0]
# from functools imp... |
56a5dd1f71386790f84ec2fa784abc8a5d14d905 | itzelot/CYPItzelOT | /libro/problemas_resueltos/capitulo2/problema2_8.py | 698 | 3.921875 | 4 | compra = float(input("Ingresa el monto de la compra: $"))
if compra < 500:
pagar = compra
print(f"El total a pagar es de: ${pagar}")
else:
if compra <= 1000:
pagar = compra-(compra * 0.05)
print(f"El total a pagar es de: ${pagar}")
else:
if compra <= 7000:
pagar = com... |
e81d9762dce142337e149945b7c4b68d7ba8cd12 | Yasmin-Core/Python | /Mundo_2(Python)/elif/aula12_desafio40.py | 235 | 3.953125 | 4 | nota1= float(input('Digite uma nota: '))
nota2= float(input('Digite a segunda nota: '))
a= (nota1 + nota2) / 2
if a >= 7.0:
print(' APROVADO ')
elif a < 5.0:
print (' REPROVADO ')
elif 7 > a >= 5:
print(' RECUPERAÇÃO ')
|
ecc56471276e1a396daf61a369b443e0e3619937 | henryZe/code | /leetcode/daily/2285_maximumImportance.py | 482 | 3.734375 | 4 | from typing import List
class Solution:
def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
degree = [0] * n
for w, v in roads:
degree[w] += 1
degree[v] += 1
degree.sort()
res = 0
for d, i in enumerate(degree, 1):
res += d... |
c477b544b3dc0e8a64e66aee4e93d719df59717e | HyoHee/Python_month01_all-code | /day14/commdity_manager_system.py | 3,543 | 3.890625 | 4 | """
商品信息管理系统
"""
class CommodityModel:
def __init__(self, cid=0, name="", price=0):
self.cid = cid
self.name = name
self.price = price
def __str__(self):
return f"商品编号:{self.cid},商品名称:{self.name},商品价格:{self.price}"
def __eq__(self, other):
return self.cid == o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.