blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3e71de50678eb2c84278ff7fc0f912093ad62556 | engelbert974/Introducao_a_Ciencia_Dados | /retangulo_internet.py | 405 | 3.90625 | 4 | def retangulo(largura, altura, caractere):
print(caractere * largura) # cabeçalho
for i in range(altura - 2):
espacos = (largura - 2) * ' '
print("%s%s%s" % (caractere, espacos, caractere)) # meio
print(caractere * largura) # rodapé
largura = int(input("digite a largura: "))
altura = int(... |
05fc2c445bda0f295b4180234a293eb777995098 | dancingninjacoder/DataStructres-Fall2019 | /LAB5-cs2302/MaxHeap.py | 4,768 | 3.734375 | 4 | # Implementation of max heap
# Programmed by Olac Fuentes
# Last modified October 20, 2019
import matplotlib.pyplot as plt
import math
class node:
def __init__(self, word, count):
self.word = word
self.count = count
class MaxHeap(object):
# Constructor
def __init__(self):
self.tr... |
1e70f486ed4a9032d9310a33016ab865034a628e | xueanxi/learnAi | /test/78_枚举类Enum.py | 1,235 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-02-03 20:35:10
# @Author : anxi.xue (xueanxi@163.com)
# @Version : $Id$
import os
from enum import Enum, unique
# 默认的枚举类是从1为索引开始的
Month = Enum('month', ('Jan', 'Feb', 'Mar', 'Apr', 'May'))
# 有多种访问枚举类的方法
print(Month(1))
print(Month['Jan'])
print(Month.Ja... |
e4fd3084f5696151ad0479fe09a9ad3075021535 | okada1220/100knock | /100knock_chapter2/100knock_chapter2_19.py | 306 | 3.671875 | 4 | import collections
text_name = []
with open('popular-names.txt', 'r', encoding='utf-8') as file:
for texts in file:
text = texts.split()
text_name.append(text[0])
frequency_word = collections.Counter(text_name)
print(frequency_word)
frequency_word.most_common()
print(frequency_word) |
6b84ef937cc28c0865e7e1f071fb0518c78103c1 | KwanJoshua/cp2019 | /p02/q07_miles_to_kilometres.py | 505 | 3.796875 | 4 | # Main
print('Miles', 'Kilometers', 'Kilometres', 'Miles')
miles = 1
km_1 = 20
for i in range (9):
km = miles*1.609
km = '{0:.3f}'.format(km)
miles_1 = km_1/1.609
miles_1 = '{0:.3f}'.format(miles_1)
print(miles, f'{km:^18}', km_1, f'{miles_1:^14}')
miles += 1
km_1 += 5
for i in range (1... |
4631901e9d096a4d38b3c3b07ae8404f7472e71c | rasmuskkilp/python_basics | /basics_110_if_functions.py | 634 | 4.25 | 4 | #if functions
#part of control loop along with while function
#syntax
#if <condition>:
#block of code
#elif <condition>
#<block of code>
#else:
#block of code>
age = int(input('what is your age?'))
#if stops at first true condition and then exits
#most specific has to be on top
# conditions are built with o... |
e44fa255a757d96c3b573de1837b1087db7ae527 | sail-y/python | /base/big_test.py | 497 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def getIntInput():
num = raw_input('开始猜数字,请输入数字: ')
while not num.isdigit():
print('输入错误,请输入数字')
num = raw_input('开始猜数字,请输入数字: ')
return int(num)
import random
num = random.randint(1,100)
inputNumber = getIntInput()
while inputNumber != num:
if inputNumber>num:... |
a8bec6cc334ecd4d154f39002e07cc7201e46ff1 | Niloy28/Python-programming-exercises | /Solutions/Q5.py | 455 | 3.953125 | 4 | # Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Also please include simple test function to test the class methods.
class String(object):
def __init__(self):
self.s = ""
def getString(self):
... |
7277c1a8a33b9d64c32296e808fddf91b47207f8 | EduardoSantos7/Algorithms4fun | /Leetcode/572. Subtree of Another Tree/solution.py | 842 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def is_equal(ro... |
fa771c9ec2d8614d27b589e30c0afe286f0e1140 | vanonselenp/Learning | /Python/LPTHW/ex12.py | 156 | 3.5 | 4 | age = raw_input("age:")
height = raw_input("height:")
weight = raw_input("weight:")
print "entered(age, height, weight): %s, %s, %s" % (age, height, weight) |
fd2c03b45022de5c70da5245fa75ffb03cc39093 | JamesTadleyGreen/Instagram_Liker | /instagram.py | 3,168 | 3.53125 | 4 | #Program to load up instagram, login using details, navigate to specific tags
# and like a specified number of photos. Then record data in text file.
#imports
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import webbrowser
import ti... |
045561db29713681e60d1bc5864156b49baf3a6a | hkkhuang/PythonDev | /interPy-Python进阶[3.x]/06_ternary_operator.py | 2,189 | 4.03125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Script Name : 06_ternary_operator.py
# Author : huangkeke
# Time : 2018/6/5 8:49
# Contact : hkkhuang@163.com
# Description : 三元运算符
def ternary_operator_one():
"""
三元运算符-条件表达式(1)
:return:
"""
is_fat = True
stat... |
696b8b6e5ccdf540bf07cf0a70b1bc9eaaafae3e | haeke/datastructure | /filter.py | 580 | 4.03125 | 4 | """
write a method that takes in a list and function with a conditional statement and returns a new list where every element in the original list passes the conditional statement ( returns True)
"""
def filter(arr, fn):
result = []
#pass the element to the function and check if the result comes back tru... |
bd796c4985b4232342d665bb7852bd069fd4eaba | ez4rubidium/CCITICP | /main.py | 1,068 | 3.75 | 4 | #main
import test
import addItem
import dispItem
import searItem
import modItem
import delItem
def quit():
q = 1
print("Have a nice day!! Goodbye.")
exit()
def menu(i):
switch = {
"0" : test.main,
"1" : addItem.main,
"2" : dispItem.main,
"3" : searItem.main,
"4... |
71ce633ffd3af3d02f5137c05e91589e8c1a3c71 | LiuFang816/SALSTM_py_data | /python/rasbt_mlxtend/mlxtend-master/mlxtend/utils/counter.py | 1,373 | 3.5 | 4 | # Sebastian Raschka 2014-2017
# mlxtend Machine Learning Library Extensions
#
# A counter class for printing the progress of an iterator.
# Author: Sebastian Raschka <sebastianraschka.com>
#
# License: BSD 3 clause
import time
import sys
class Counter(object):
"""Class to display the progress of for-loop iterat... |
e9e627b6e846fbb9285dc9124f66d67db7ad6d04 | darkxex/dijkstra | /dikstra terminado.py | 1,314 | 3.921875 | 4 | from collections import defaultdict
from heapq import *
def dijkstra(trans, f, t):
g = defaultdict(list)
for l,r,c in trans:
g[l].append((c,r))
q, seen = [(0,f,())], set()
while q:
(cost,v1,camino) = heappop(q)
if v1 not in seen:
seen.add(v1)
... |
26fb0a2d62c601846a86f112293c1ac0c247354e | priya100697/Python_ | /Generator_gcd/Main.py | 351 | 3.609375 | 4 | from Generator_gcd.Utils import generator, gcd
if __name__ == "__main__":
a = generator()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print("The required gcd is = ", gcd(5, 30))
for i in range(10):
print(i, end=" ")
i += 2
print()
text = "priya"
... |
c074ba310e496bf6fc6d817fb6d18572b4bf848b | JanMagne/Practice-Python | /21/write_to_file.py | 1,236 | 3.75 | 4 | """
Take the code from excerice 19, (decode_web_page_2.py) and write it to a file instead of printing it to screen
Ask the user to input the name of the file that will be saved
"""
import requests
from bs4 import BeautifulSoup
url = "https://www.theregister.co.uk/2014/08/26/top_ten_gaming_keyboard_and_mouse_c... |
02fb7b89f8b1651367edf13d5bbd71327eae9a96 | JDavid121/Script-Curso-Cisco-Python | /127 scope.py | 656 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 10:47:13 2020
SCOPE EXERCISES
@author: David
"""
# functions and scopes
def myFunction():
print("Do I know that variable?", var)
var = 1 # var scope: code when a var is properly defined.
myFunction() #this function takes var value in line 13
print(v... |
24cd5df63861782a54094a5bf723d0f5064ad3a0 | dbetm/cp-history | /HackerRank/Python/Strings/12_TheMinionGame.py | 569 | 3.8125 | 4 | # !/usr/bin/env python3
# https://www.hackerrank.com/challenges/the-minion-game/problem
# tag(s): cadenas
def minion_game(string):
stuart = 0
kevin = 0
i = len(string)
for chr in string:
if(chr == 'A' or chr == 'E' or chr == 'I' or chr == 'O' or chr == 'U'):
kevin += i
else:... |
50e61037fee2907ddd7f5b6483f8235a902e1785 | ChainBreak/highbeam_controller | /timer.py | 279 | 3.609375 | 4 | #!/usr/bin/env python
import time
class Timer():
def __init__(self):
self.reset()
def reset(self):
self.startTime = time.time()
def __call__(self):
return time.time() - self.startTime
if __name__ == "__main__":
t = Timer()
print(t())
time.sleep(1)
print(t())
|
75028b3533bb3bf39c4f33fc7e3d4cf500b7ed3c | ethan9carpenter/Python-Crash-Course | /Part1/Chapter9.py | 956 | 3.984375 | 4 |
class Dog(object):#object in parentheses when not extending class
name=""
def __init__(self, name, age):#constuctor, __ to differentiante from user-named methods
super(Dog, self).__init__()#required for calling superclass in Python 2.7
self.name=name
self.age=age
def getName(se... |
6431d916bf446fd5d01164c7c99c3334fd44eea0 | aga01935/PHSX815_Week5 | /myrandom.py | 3,158 | 3.6875 | 4 | import numpy as np
import sys
import matplotlib.pyplot as plt
sys.path.append(".")
from python.Random import Random
#global variables
bin_width = 0.
Xmin = -0.
Xmax = 3.14
random = Random()
# Normal distribution with mean zero and sigma = 1
# Note: multiply by bin width to match histogram
def Our(x):
return np.sin(... |
f3cdb54fe5eb967efbc43d920a4a7cdb307a1642 | scottmeup/introtopython1 | /quiz_1.py | 2,372 | 4.09375 | 4 | #http://www.codeskulptor.org/#user40_pvAn6U8qWt_21.py
import math
#question 1
"An if statement can have at most how many else parts?"
print "\nQuestion 1"
print "one else"
#question 2
print "\nQuestion 2"
def question_2(p, q):
print(not (p or not q))
return None
question_2(True, True)
question_2(True, False)... |
672cfb502b9e2c39de7fb1811555d257cf308587 | hyunsooDii/TIL_Source | /python/chapter13/ex13_01.py | 1,948 | 4.0625 | 4 | # 예외 처리
# def main():
# str = input("점수를 입력하세요 : ")
# try:
# score = int(str)
# print("입력한 점수 : ",score)
# except:
# print("예외가 발생하였습니다.")
# else:
# print("작업완료")
#
# main()
# 예외의 종류
# def main():
# str = "89"
# try:
# score = int(str)
# print(s... |
dbb3aed762e6a11c3da9ff24d36d56db9e5266b6 | doomnonius/advent-of-code | /2022/day09.py | 2,677 | 3.640625 | 4 | from typing import List, Tuple, Set
def pull(lead: Tuple[int,int], follow: Tuple[int,int]) -> Tuple[int,int]: # just returns one tuple, new location of second knot
# note: just need to check diff b/t x and y to find if too far away
x_diff = lead[0] - follow[0]
y_diff = lead[1] - follow[1]
new_x = follo... |
c249b6ac535568b940b150efd596f3dc980e9b1d | rusterx/ShapeMakeforDDA | /ddshape/hsphere.py | 1,433 | 3.765625 | 4 | # -*- encoding:utf-8 -*-
import ddshape.inc as inc
def hsphere(index=1, data="", center=(1, (0, 0, 0)), outr=25, shell=3, factor=1):
"""
the main function to write hollow sphere
:param index: a number which indicate the line numbers of main shape data
:param data: string with all shape data combined
... |
f95267809fe472647eabb40b83ac7c399b4abddb | XMK233/Leetcode-Journey | /py-jianzhi-round3/JianzhiOffer52.py | 3,789 | 3.828125 | 4 | '''
[剑指 Offer 52. 两个链表的第一个公共节点 - 力扣(LeetCode)](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof)
输入两个链表,找出它们的第一个公共节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value ... |
1919ee3453106bf5ba4c0e435aceda7c2a67e32f | camelia13/JDI | /01_Python/01_Python/exercise.py | 524 | 4.03125 | 4 | class Circle:
pi = 3.14
x = 0
y = 0
def __init__(self, radius, x, y):
self.r = radius
self.x = x
self.y = y
def area(self):
return self.r * self.r * self.pi
def circumference(self):
return 2 * self.pi * self.r
def center(self):
retu... |
99f0c68cc120cca6439bdf85dc148949cf79d803 | zerformza5566/CP3-Peerapun-Sinyu | /assignment/Exercise5_2_Peerapun_S.py | 328 | 3.703125 | 4 | s = float(input("ระยะทางในการเดินทาง : "))
t = float(input("ระยะเวลาในการเดินทาง : "))
v = s / t
print("คุณเดินทางด้วยอัตราความเร็ว :", v, "กิโลเมตรต่อชั่วโมง") |
735de324c899f728610cb82638cc6535b26d674c | SakshiLajurkar/Python-Lab | /Exp_5.py | 400 | 3.9375 | 4 | print("Enter integer numbers between -1000 & 1000: ")
i = True
sum = 0
numbers = list()
while i is True:
n = int(input())
if (n>=-1000 & n<=1000) :
sum = sum + n
if sum >= 0:
numbers.append(n)
else:
i = False
else:
print("Invalid entry")
print("\n... |
28a612402edba4c8dc8a50673a5d0f1b0a43e121 | PauloSeph/Curso-Python | /Firstproject/area_circulo_v8.py | 589 | 4.25 | 4 | #!python
from math import pi
""" Definindo uma função => circulo, puxando a variavel raio entre parenteses do circulo(raio)
e colocando a variavel a baixo dela.
"""
def circulo(raio):
print('Area do circulo', pi * float(raio) ** 2)
""" já que foi definido a função, então colocamos aqui, circulo(raio)
lembrand... |
acf9e5ed092fa821c1ed02d0a2d018d9b5356756 | cccccccccccccc/Myleetcode | /42/trappingrainwater.py | 1,768 | 3.6875 | 4 | """
timecomplexity = O(n) spacecomplexity = O(1)
Initialize left pointer to 0 and right pointer to size-1
While left<right, do:
If height[left] is smaller than height[right]
If height[left]≥left_max, update left_max
Else add left_max−height[left] to ans
Add 1 to left.
Else
If height[right]≥right_max, update right_max
E... |
f217f6afe0864b4c8c40ace1b63362e8739aadb3 | dominiquecuevas/hackbrighthw-melondelivery | /produce_summary.py | 863 | 3.8125 | 4 | def print_delivery_report(day, daily_file):
""" Prints delivery report from daily files as sentences
"""
print("Day", day)
the_file = open(daily_file) # open daily text data file to use in python
for line in the_file: # iterate each line in 5/19 file
line = line.rstrip() # strips right white... |
b5a167cab8418a4c67ea60868bf97270cdac6507 | vdaviot/ft_minirogue | /Main.py | 2,809 | 3.5625 | 4 | # **************************************************************************** #
# #
# ::: :::::::: #
# Main.py :+: :+: :+: ... |
8f327f5fed360d3aa589455372aac7e80aba122c | RuiwenP2018/pypractice | /lists.py | 518 | 4.0625 | 4 | socks = "socks"
jeans = "jeans"
laptop = "laptop"
toiletries = "toiletries"
luggage = [
"socks",
"jeans",
"laptop",
"toiletries"
]
print (luggage [1])
grades = [
96.0,
100.0,
75.5,
89.5
]
sum = 0
for grade in grades:
sum = sum + grade
print (sum)
#print (grades, sum(grades)/len(grades))
luggage = []
d... |
3de5a930c2b0a5be32932c7b3cb0e7d1c6779de5 | syafiq/kattis | /Parsing Hex/parse.py | 985 | 3.609375 | 4 | import sys
def is_hex(input):
if input == "a" or input == "b" or input == "c" or input == "d" or input == "e" or input == "f" or input == "1" or input == "2" or input == "3" or input == "4" or input == "5" or input == "6" or input == "7" or input == "8" or input == "9" or input == "A" or input == "B" or input == "... |
27df2e353d0d9090c0c5e037e2c60c8726c0779c | fitwate/yscript | /pytest/2for_while.py | 514 | 3.953125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#loop
def for_while():
for every_letter in 'Hello world':
print(every_letter)
for num in range(1,11):
print(str(num)+' +1= ', num + 1)
for i in range(1,10):
for j in range(1,10):
print( '{} x {} = {} '.format(i, j, i*j)... |
34ddfae62f8c725a158d2366249ced8189c2740a | koclu/Class5-Python-Module-Week4 | /Dice_Percentage.py | 306 | 3.890625 | 4 | import random
dice = [0, 0, 0, 0, 0, 0]
y= int(input("which number's percentage:"))
for i in range(5000):
x = random.randrange(1, 7)
dice[x-1]+=1 # counting numbers
percentage= dice[y-1]/5000*100 # finding the percentage of number
print("Percentage of throws of value ", y, "=", percentage, "%" )
|
e828917c2e19ec6669effcc5c8e499daff73c47a | lishulongVI/leetcode | /python/738.Monotone Increasing Digits(738.单调递增的数字).py | 2,527 | 3.5625 | 4 | """
<p>
Given a non-negative integer <code>N</code>, find the largest number that is less than or equal to <code>N</code> with monotone increasing digits.
</p><p>
(Recall that an integer has <i>monotone increasing digits</i> if and only if each pair of adjacent digits <code>x</code> and <code>y</code> satisfy <code>x <... |
7add84cb1f0deb43aef849deb579ec20dec7081d | sy-eggplant/nlp100 | /06.py | 445 | 3.71875 | 4 | import ngram
str1="paraparaparadise"
str2="paragraph"
# 集合にする
print("X:",set(ngram.ngram(2,str1)))
print("Y:",set(ngram.ngram(2,str2)))
print("和集合:",set(ngram.ngram(2,str1))|set(ngram.ngram(2,str2)))
print("Xの差集合:",set(ngram.ngram(2,str1))-set(ngram.ngram(2,str2)))
print("Yの差集合:",set(ngram.ngram(2,str2))-set(ngram.n... |
8c846cc125cb1982b37ec7dc47721ef72da15c59 | SrMuesli/Playground | /Python/For_Loops.py | 1,667 | 4.0625 | 4 | # For Loooooooooooooooooops
# Ejercicio A
a = ["banana", "apple", "microsoft"]
for element in a: # Imprime cada "elemento" de la lista.
print(element)
# Ejercicio B
b = [10, 20, 10]
total = 0 # Creo la variable "total" con el valor de 0.
for x in b: # En lugar de "element" se puede usar cualquier cosa. Ent... |
09ec4c207b1ff4829ab07027f64a1ee124b4660d | washimimizuku/python-data-structures-and-algorithms | /elements-of-programming-interviews/4-primitive-types/4.2-swap-bits/swap_bits.py | 617 | 3.890625 | 4 | '''
Take as input a 64-bit integer and swap
the bits at indices i and j
'''
def swap_bits(x, i, j): # Time: O(1)
# Extract the i-th and j-th bits, and see if they differ.
if (x >> 1) & 1 != (x >> j) & 1:
# i-th and j-th bits differ. We will swap them by flipping their values.
# Select the bit... |
05809578172d27189a2bf4763a77d5b2b2db82ea | Maan17/python | /Linked Lists/nth node.py | 580 | 3.796875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def printList(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
if __name__=='__main__':
... |
f76416d6354f0842283e6e9008e1b3dc8b1b0249 | Stani2980/webcrawler | /visualization.py | 662 | 3.78125 | 4 | import networkx as nx
import matplotlib.pyplot as plt
import json
import os
def create_graph(data):
"""
Creates a networkx graph from the urls.
"""
plot_values = []
# Get all the values
for k, v in data.items():
for link in v:
# create tuples with links connected to the "p... |
7f38cf35b8f609826458b890616643f4106cb722 | rjsoroka/Python | /Dating Age Limit.py | 240 | 3.84375 | 4 | def allowed_dating_age(my_age):
girls_age = my_age/2 +7
return girls_age
x = int(input("Start of range: "))
y = int(input("End of range: ")) + 1
for i in range(x,y):
print("Dude's age:", i, "Girl's Age", allowed_dating_age(i)) |
8f739b29c6a3e4aba1408e6545cbfda226fd84ac | anatulea/PythonDataStructures | /src/arrays/01_rev_words.py | 640 | 4.125 | 4 | def rev_words(s):
words = []
length = len(s)
spaces =[' ']
i=0
while i < length:
if s[i] not in spaces: # if the element at index i from the string is not a " "(space):
word_start = i
while i < length and s[i] not in spaces: # keep going until we find nother space
... |
178ed6c32f7c57fef4823e7e645afdb182c5a985 | gaohongfein/PTPSim | /Curves/Cubic.py | 1,576 | 3.609375 | 4 | """
cubic polynomial
线性方程组的解法
Aa=b
在笛卡尔空间采样的,多种求解模式都不满意
改为在frenet坐标系下采样.
"""
from scipy.linalg import solve
import numpy as np
import matplotlib.pyplot as plt
import math
import time
import FrenetMath.calHeading as heading
# state_init = [-1.0, -1.0, -180.0 * math.pi / 180.0]
# state_goal = [-10.0, -2.0, -180.0 * mat... |
9b83d657eb3657a3513ae700bd3e0444ebeb1f89 | dhruvam26/MIT-Club-2021 | /SummaryOfLessonTwo.py | 5,498 | 4.375 | 4 | #MIT Club Python Lesson 2
#Res Sharpe
#11/13/20 (Definately not winging it)
"""
A lot of this lessons concepts are going to build off of what we learned last week,
so before I start teaching I'm going to do a quick review. Last weeks concepts are
CRUCIAL!! So please make sure to take the time to understand them.
"""
... |
c182fd6b1f27d859f8e349db86c2396b34663886 | BhagyashriNBhamare/NITK-IT-DEPARTMENT-LAB-2022 | /DSA part-2 lab/dfs/cycledfs.py | 1,395 | 3.53125 | 4 | class cycledfs(object):
"""docstring for cycledfs"""
def __init__(self, graph):
super(cycledfs, self).__init__()
self.graph = graph
def check(self):
st=[]
visited=[False]*len(self.graph)
on_stack=[False]*len(self.graph)
for w in range(len(self.graph)):
... |
c1d6fcb48202362ae826ba93742e29bbc4162521 | BeastModeSmiley/IT140-Python-Stuff | /TextBasedGame.py | 12,240 | 3.859375 | 4 | answer_N = ["N", "n", "North", "north"]
answer_S = ["S", "s", "South", "south"]
answer_E = ["E", "e", "East", "east"]
answer_W = ["W", "w", "West", "west"]
pickup = ["y", "Y", "yes", "Yes", "Get", "get", "take", "Take", "pickup", "Pickup"]
leave = ["n", "N", "no", 'No']
blaster = 0
chest = 0
helmet = 0
boots =... |
6857a641abf15f36bd255af0d5a7ec153026b650 | hasansajedi/StartMachineLerning | /Python For DataScience/PandasExample/pandas_groupby.py | 564 | 3.609375 | 4 | # Groupby
import pandas as pd
# Create dataframe
data = {'Company': ['GOOG', 'GOOG', 'MSFT', 'MSFT', 'FB', 'FB'],
'Person': ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],
'Sales': [200, 120, 340, 124, 243, 350]}
df = pd.DataFrame(data)
print(df)
byComp = df.groupby('Company')
print(byComp.mea... |
dae250b5f77ee455d0b68987d416fe8c1bfe6d18 | vipin26/python | /PYTHON/New folder/string 74/76 string name reverse not done.py | 117 | 3.53125 | 4 | nm=raw_input("enter the name :")
l=len(nm)
i=0
print "Length is :",l
for l in range(l,0,-1):
print nm[l],
|
4762b4c350e7a057bf925e7b9789385bcfd7e0aa | gradam/project-euler | /035_Circular_primes.py | 583 | 3.671875 | 4 | def is_prime(x):
for i in range(2, int(round(x ** 0.5) + 1)):
if x % i == 0:
return False
return True
def is_even(x):
x = str(x)
for i in x:
if int(i) % 2 == 0 or int(i) == 5:
return False
return True
def is_circ(x):
x = str(x)
for i in range(len(x... |
97c06fa405f8a96bf5308fdc71278870c956a0fe | t0etag/Python | /py4e/read_file.py | 609 | 3.734375 | 4 | #fhand = open('py4e.com/HDD.txt', 'r')
fhand = input("Enter file name:")
try:
fhand = open(fhand)
except:
print("File not found", fhand)
quit()
# count number of lines
cnt = 0
for line in fhand:
line = line.rstrip()
"""
if line.startswith('The'): #print lines with "The"
prin... |
ad0949c406107a93ba0d04c44dea00dc3108ad17 | aprilcotwut/applied_climatology | /station_list.py | 4,820 | 3.8125 | 4 | #!/usr/bin/python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# This script automatically developes a stationlist to use in RClimDex from
# timeseries csv retrieved from PRISM (Oregon State Climate Group).
#
# Author: April Walker
# # # # # # # # # # # # # # # # # # # # # # # # # # #... |
51440415612aca6f66404a0a29cf95bf0dcde96f | Baobao211195/python-tutorial | /pbc032015/List/List.py | 729 | 3.515625 | 4 | s = raw_input("Nhap chuoi :")
# kiem tra chieu dai cua chuoi
print len(s)
# chuyen tu chuoi thanh list.
#phan tu trong list duoc tinh la mot tu
a = s.split()
print a
# tinh so tu trong list
counter = 0
for i in a:
counter = counter + 1
print i
print counter, 'tu'
# tu list tren. ghep thanh chuoi ma ko co ky tu trang... |
c8dffc54c95a6a2ad91b845a46a1a05b85471e42 | gywnqkqh1125/python_study | /20210428/turtle03.py | 131 | 3.71875 | 4 | import turtle as t
t.shape('turtle')
t.speed('fastest')
n=60
for i in range(n):
t.circle(120)
t.right(360/n)
t.mainloop() |
32a2afa98d5a9132e49d6e086d305bee065fd57a | JiaMauJian/model-playground | /2_keras_logistic_regression.py | 828 | 3.671875 | 4 | # Sample Multilayer Perceptron Neural Network in Keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
import numpy as np
# load and prepare the dataset
x_data = np.loadtxt('.\ex4Data\ex4x.dat')
y_data = np.loadtxt('.\ex4Data\ex4y.dat')
# 1. define the ... |
b1b14132845bcd42ef321c151b1b161071b12c27 | gbaghdasaryan94/Kapan | /Razmik/Week6/caesar.py | 337 | 4.09375 | 4 | #!/usr/bin/python3.7
import sys
if len(sys.argv) != 2:
sys.exit("Enter valid")
if not sys.argv[1].isnumeric():
sys.exit("Enter valid")
key = int(sys.argv[1]) % 26
a = input("plaintext: ")
b = ""
for char in a:
b += chr(ord(char) // 32 * 32 + (ord(char) % 32 + key) % 26) if char.isalpha() else char
print("c... |
54f6c7a0b7ec140c2bcb0bbdc3404afa32b53ada | suryakants/DataStructureWithPython | /Generate_all_the_Strings_of_n_bits.py | 210 | 3.90625 | 4 | ####------generate all the Strings of n bits ------######
array = [1,2];
def binary(n):
if n < 1:
print(array);
else:
array[n-1] = 0;
binary(n-1);
array[n-1] = 1;
binary(n-1);
binary(len(array));
|
4fb444e98e9e18726e2f5d5aed06846f94a1d145 | joeljoshy/Project | /Operators/O1.py | 108 | 3.90625 | 4 | num1 = int(input("Enter num 1: "))
num2 = int(input("Enter num 2: "))
print(num1, "*", num2, "=", num1*num2) |
792daa3fb50fb4d8a9aa97bc2c2f4feefc432615 | patricknevindwyer/advent_of_code_2020 | /15/puzzle_01.py | 1,855 | 3.703125 | 4 | import sys
def read_starting_numbers(filename, line=0):
with open(filename, "r", encoding="utf-8") as f:
raw = f.read()
data = raw.split("\n")[line]
return [int(d) for d in data.strip().split(",")]
def counting_game(starts, stop_at=2020):
counting_index = 0
# we match... |
9a7da2d172c41f142bf46de9764940a42c3ab052 | nmahser/sorting-algorithms | /bubbleSort.py | 995 | 4.375 | 4 | ''' Bubble Sort '''
import datetime
# worst case scenario time complexity is O(n^2). However implementing the while loop decreases the run time buy about %82 for this test case
nums = [4, 2, 3, 4, 6, 1, 4, 6, 7]
# ascending bubble sort
def bubbleSortAsc(nums):
# iterates thru the array n times regardless if th... |
ed115ec6c5037d289c35e630b80ed7caf80b65a2 | amitkumar-panchal/ChQuestiions | /c++/q30/Untitled-1.py | 1,817 | 3.90625 | 4 | class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def dist_from_origin(self):
x = self.x
y = self.y
return ((x*x) + (y*y))**0.5
## the comparison magic methods
def __lt__(self, value):
return self.dist_from_origin() < value.dist_fr... |
862c649daf926ea578e3b34b1d237838967a572e | 3224229/anagrams | /test.py | 1,281 | 3.515625 | 4 | import pygame
class game(object):
def __init__(self):
# -------#
# PYGAME #
# -------#
# Game window
self.screen_width = 600
self.screen_height = 400
pg.init()
try:
pg.mixer.init()
except:
print("No sound.")
... |
bdc7a89ca46a3eb72dcc97d4ed199763e40d1249 | johnbhlm/SwordFingerOffer | /005_PrintListInReversedOrder/005_PrintListInReversedOrder.py | 1,256 | 4.03125 | 4 | # -*- coding:utf-8 -*-
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 解法1:栈
def printListFromTailToHead(listNode):
# write code here
stack = []
result = []
node_p = listNode
while node_p:
stack.append(node_p.val)
node_p = node_p.... |
c52e51a961c16d73becaa4479b39a898599d9fac | columbia-applied-data-science/rosetta | /rosetta/cmdutils/groupby_reduce.py | 6,099 | 3.765625 | 4 | #!/usr/bin/env python
"""
Streaming implementation of groupby then reduce. Prints a delimited report
with header e.g.
name|count|sum|mean
smith|1000|239|0.239
jones|100|532|5.32
Note
----
Works in O(N) time but stores unique keys and reduced values in memory. If you
have K unique keys, O(K) storage is required.
Ass... |
96ad728d3bb3bbb81a251056352aec0ccde9a867 | zhyu/leetcode | /algorithms/intersectionOfTwoLinkedLists/intersectionOfTwoLinkedLists.py | 801 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
la, lb = self.getLen(headA), self.getLen(hea... |
9a504366d4048d5202818078e4dde6104e8c2a8e | amishapandey/codekata | /noName.py | 121 | 3.6875 | 4 | n={1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",10:"Ten"}
i=int(input())
print(n[i])
|
7b600fa998440e5033372587ac2d20c31e46b6f3 | teyter/uni | /rei/skiladaemi/s1/kvadrat.py | 265 | 3.640625 | 4 | import math
def newton(a,x):
counter = 0
while not abs(x**2-a) < (10**-5)*a:
counter += 1
print("Itrun nr: " + str(counter))
x = (x+(a/x))/2
print(x)
a = 150593
x = float(input("Ágiskun á kv.rót hennar: "))
newton(a,x)
|
b63fe33c946fc65f90ef00c8a2be7b1489c1ead8 | matthimatik/pytorch-tutorial | /logistic_regression.py | 2,493 | 3.78125 | 4 | """
Logistic regression with pytorch
"""
# 1) Design Model (input size, output size, forward pass)
# 2) Construct loss and optimizer
# 3) Training loop
# - forward pass: compute prediction
# - backward pass: gradients
# - update weights
import numpy as np
import torch
import torch.nn as nn
from sklearn import da... |
f61fb45d510dd5af6d497cec9297e68a81f37889 | gowthamneelakandan/aws-python-cdk-examples | /python-programs/palindrome.py | 136 | 3.90625 | 4 | name="pip"
def palindrome(name):
if name == name[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
palindrome(name)
|
9db6a456de035abb36f2f3a3028211f4d0728ffd | ilkaynazli/challenges | /spiral/spiral.py | 1,900 | 4.6875 | 5 | """Print points in matrix, going in a spiral.
Give a square matrix, like this 4 x 4 matrix, it's composed
of points that are x, y points (top-left is 0, 0):
0,0 1,0 2,0 3,0
0,1 1,1 2,1 3,1
0,2 1,2 2,2 3,2
0,3 1,3 2,3 3,3
Starting at the top left, print the x and y coordinates of each
poin... |
6b7383760a7b8009973113fefcc83e94d835df5b | jayjanodia/LeetCode | /Medium/932. Beautiful Array/Solution.py | 1,408 | 4.28125 | 4 | #Runtime: 40 ms, faster than 52.14% of Python3 online submissions for Beautiful Array.
#Memory Usage: 14.1 MB, less than 97.14% of Python3 online submissions for Beautiful Array.
class Solution:
def beautifulArray(n):
'''
Step 1: Initialize an array with 1 arr = [1]
Step 2: While the length... |
cc9cff3b9c7528e953c77e0c426928da18666bb9 | chile0101/ClickHouse | /python/practice/arrays/find_single_number_in_array.py | 696 | 3.515625 | 4 | from typing import List
from collections import Counter
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums = Counter(nums)
for num, frequency in nums.items():
if frequency == 1:
return num
return -1
# def singleNumber(self, nums: List[int... |
9fc31e9ecb6e7cef55c0ec4f4bbf371037d17db3 | ianlai/Note-Python | /algo/linkedlist/_1019_NextGreaterNodeInLinkedList.py | 1,866 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# Backward traverse, stack stores integer [O(n), 52%]
def nextLargerNodes1(self, head: ListNode) -> List[int]:
print("Backward trav... |
d57de22dc0c7db2592e50c5d5f758d3636382692 | igenhimel/CSE323 | /CSE323/app/pre-emp-priority.py | 1,613 | 3.828125 | 4 | #bt,wt,tat stands for burst time, waiting time, turn around time respectively
print("Enter the number of processess: ")
n = int(input())
processes = []
for i in range(0,n):
processes.insert(i,i + 1)
#Input Burst time of every process
print("\nEnter the burst time of the processes: \n")
bt = list(map(int, raw_input().... |
cb43f154d715ebb5e1644d930ea8fd5c18cd40cf | lucasg13info/estudos-python | /mundo1/ex028.py | 355 | 3.984375 | 4 | #Número aleatorio entre 0 e 5, usuário deve tentar descobrir o número
from random import randint
adivinha = int(input('Tente adivinhar um número entre 0 e 5: '))
valor = randint(0,5)
if adivinha == valor:
print('Show, você acertou o número sorteado {}'.format(valor))
else:
print('Você errou, o valor sort... |
6a1037f3ec573c94ae7762f7775d392579333998 | adam-girard/egc_website | /class_test.py | 833 | 3.78125 | 4 | class family_member:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age = int(self.age + 1)
class kids(family_member):
bed_time = 8
num_kids = 0
def __init__(self, name, age, bed_time=None):
family_member.__init__(self, na... |
dcbb245c630ba7469ad943331f430787c4c821aa | Saurabh-think-different/Python-Matplotlib-projects | /plots.py | 568 | 3.84375 | 4 | import matplotlib.pyplot as plt
#open file name
f = open("file_name.txt", "r")
#initialize array elements to 0
array = []
for i in range(0,26):
array.append(0)
#main starts
for elem in f.read():
c = ord(elem.upper())
if(c >= 65 and c <= 97):
temp = c
temp -= 65
... |
409f0cf2665514bdaee38547111f49a109b62403 | xavierloos/python3-course | /Basic/Files/read.py | 265 | 4.125 | 4 | # 1.Use with to open the file welcome.txt. Save the file object as text_file.
# 2.Read the contents of text_file and save the results in text_data.
# 3.Print out text_data.
with open('welcome.txt') as text_file:
text_data = text_file.read()
print(text_data)
|
db3ebc1521a915a7fbdb6fb1860b0a9760101715 | noorannooran/ciphers | /ciphers/caesar_cipher.py | 2,977 | 3.828125 | 4 | '''caesar_cipher.py: for Caesar cipher encryption and decryption'''
__author__ = "noorannooran"
class Caesar:
#initialization
def __init__(self):
self.letters =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
... |
24b6c6490064bce6017d570f103ea85347a6d79b | broepke/GTx | /final_problem_set/5_plagerism_detector.py | 3,471 | 4 | 4 | # A common problem in academic settings is plagiarism
# detection. Fortunately, software can make this pretty easy!
#
# In this problem, you'll be given two files with text in
# them. Write a function called check_plagiarism with two
# parameters, each representing a filename. The function
# should find if there are an... |
1bdde959365fd931359250e0217522f09222306a | kcyt/Vanilla_FuzzyInferenceSystem | /Python_Implementation_Vanilla_FuzzyLogicInferenceSystem.py | 8,626 | 3.5 | 4 |
# Take in crisp inputs and return a crisp output
def fuzzy_infer(serviceRating, foodRating):
fuzzified_service = fuzzify_serviceRating(serviceRating)
fuzzified_food = fuzzify_foodRating(foodRating)
service_poor = fuzzified_service[0]
service_good = fuzzified_service[1]
service_excellent = fuzzif... |
43573e7f562bc4b9f2f9ed33c8ac17ddf390bc08 | j32u4ukh/Fish | /Fish-4.py | 8,918 | 3.5 | 4 | #%%
import numpy as np
#%% 均方誤差
def mean_squared_error(y_hat, y):
return 0.5 * np.sum((y_hat - y)**2)
#%%
# answer = 2
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
# guess = 2
y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]
# 0.09750000000000003
print(mean_squared_error(np.array(y), np.array(t)))
# guess = 7
y = [0... |
c0fa9f5abec69aab0d39fb1c576fa3df92b88e24 | FedericoBrunelli/reti-project | /measurement.py | 511 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 26 16:42:30 2021
@author: fedebruno
"""
import time, random
MIN_TEMP = -99
MAX_TEMP = 99
MIN_HUMIDITY = 0
MAX_HUMIDITY = 100
class Measurement:
def get_time(self):
t = time.localtime()
return time.strftime("%H:%M:%S", t)... |
dda69e6d9f4e353180c34d94dd1c00be8f043313 | Malgus1995/Algorithm_strudy | /Beakjun/1330/1330.py | 153 | 3.84375 | 4 | inputs =input()
inputs = inputs.split(' ')
a =int(inputs[0])
b =int(inputs[1])
if(a>b):
print(">")
elif(a<b):
print("<")
else:
print("==")
|
279485313f6e198007d61c3c055da7db6e1a9c37 | edmfperez/COSC-proj_slotMachine | /mainUI.py | 7,516 | 3.71875 | 4 |
# Functions that are used globally and are not specific to a game
import mods
import Roulette2
# Welcome the user
print('''
\tWelcome to the Casino!
\n\tYou will be able to choose \n\tfrom three games and save \n\tyour winnings (if you win, \n\tthat is) as you play along.
''')
# Loops through the entire program
sele... |
d477f71add7a56c8a0742564e582712007246f5c | myalcins/algorithms | /insertion_sort/test.py | 443 | 3.640625 | 4 | import unittest
from insertion_sort import insertion_sort
class TestInsertionSort(unittest.TestCase):
def setUp(self):
self.arr1 = [5, 2, 4, 6, 1, 3]
self.arr2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
def test_insertion_sort(self):
self.assertEqual(insertion_sort(self.arr1), sorted(self.arr1... |
f029211303067f8051543949bb66f99435c7b376 | bhattagoutham/scara_simulator | /plot.py | 658 | 3.703125 | 4 | from matplotlib import pyplot as plt
import numpy as np
def plot(ctraj):
#gets list of all x-co-ordinates
x_pt = ctraj[:,0]
#gets list of all y-co-ordinates
y_pt = ctraj[:,1]
plt.plot(x_pt, y_pt, 'g.')
plt.show()
##Documentation and notes for this module:
##x = np.array(
## [[1,... |
83e6aaf9a7456cbf90fd0569d102c05f7d6ca5ae | salujaharkirat/ds-algo | /string/find_words_with_character.py | 546 | 3.625 | 4 | """
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
"""
from collections import Counter
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
temp = Counter(chars)
res = 0
for word in words:
can_form = True
temp_... |
8ed5ef0012433d27f45a3d0e45acd162b7287042 | alexdaigneault/Python_projects | /sals_shipping.py | 1,400 | 3.890625 | 4 | def ground_shipping(weight):
cost = 0
flat_charge = 20.00
if weight <= 2:
cost += weight * 1.50 + flat_charge
return cost
elif weight > 2 and weight <= 6:
cost += weight * 3.00 + flat_charge
return cost
elif weight > 6 and weight <= 10:
cost += weight * 4.00 + flat_charge
return cost
... |
9a9be982996e0148ae20b5294dce26f1eee7f732 | angeloskath/php-sourceclassifier | /data/train/Python/58 | 954 | 3.578125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
def who_win(status):
all_filled = True
for player in ("X", "O"):
S = set([player, "T"])
columns = [[s[i] for s in status] for i in range(4)]
diagonal1 = [status[i][i] for i in range(4)]
diagonal2 = [status[i][3 - i] for i in... |
33be505c6a12b62190b8f03ae8611bc5706179c5 | wangchenkang/python-kk | /sum_sanjinzhi.py | 886 | 3.703125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
def main(stra, strb):
f = 0
list_ = list()
lengtha = len(stra)
lengthb = len(strb)
length = max(lengtha, lengthb)
if lengtha < length:
stra = '0'*(length-lengtha) + stra
if lengthb < length:
strb = '0'*(length-lengthb) + strb
... |
0edc8d19592426de556ee1898cb125131af69d4b | Kriti2885/Census-Data-Analysis | /fixClassSize.py | 22,320 | 3.703125 | 4 | """
@Author : Kriti Upadhyaya
@Order of Execution -4
@Description:
The program implements naive Bayes algorithm for classification by balancing the classes.
The user is given option to choose either own training set length or use heuristic ratio
formula for calculating training set length.
Naive Bayes Algorithm is ... |
37773c2a8f0181fde9fdd9578406a8b4becdbf64 | Alagirl/H-DenseUNet | /Keras-2.0.8/examples/mnist_tfrecord.py | 5,990 | 3.8125 | 4 | '''MNIST dataset with TFRecords, the standard TensorFlow data format.
TFRecord is a data format supported throughout TensorFlow.
This example demonstrates how to load TFRecord data using
Input Tensors. Input Tensors differ from the normal Keras
workflow because instead of fitting to data loaded into a
a numpy array, d... |
cc8261879a95fbe5bd343cdb53741fa0798e4c98 | Suhasnama/Pythonprograms | /myturtle.py | 641 | 4.1875 | 4 | import turtle # allows us to use the turtles library
wn = turtle.Screen()
# creates a graphics window
alex = turtle.Turtle() # create a turtle named alex
alex.forward(150) # tell alex to move forward by 150 units
alex.left(90) # turn by 90 degrees
alex.forward(75)
... |
050d003be35776c9b69db4adc2a7641606df2990 | abhi15sep/Python-Course | /collection/list/examples/list/list_comprehension/exercise4.py | 436 | 4.34375 | 4 | #Given the string "amazing", create a variable called answer, which is a list containing all the letters from "amazing" but not the vowels (a, e, i, o, and u). The answer should look like: ['m', 'z', 'n', 'g'].
#Use a list comprehension!
#Using a string (preferable solution):
answer = [char for char in "amazing" if ... |
9ed567f0569bd2b5a26ac46244da62668c34b6dc | Fay321/leetcode-exercise | /solution/problem 81.py | 5,367 | 4.03125 | 4 | # -*- coding: utf-8 -*-
'''自己尝试写的解答,虽然通过了,但是太耗时'''
class LRUCache1(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.used_time = dict() #记录某个key被get、put的时间戳。返回时间戳对应最小的那个key
self.time_stamp = 0
self.dic = dict()
self.capacity... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.