blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fb773acb386e68e91e38b21b62797cb2b0370ef8
Monster-ISFJ/urltoip
/py1.py
1,258
3.5625
4
# coding:utf-8 # Author:si1ent # 2018-11-2 # 第一步,首先定义一个urltoip的函数主要作用是用于域名正向解析到IP地址 # 第二步,打开我们自己保存的域名地址,并新建一个保存解析后存放IP地址的txt文档中,之后再调用这个函数即可实现函数的作用并成功解析域名并保存IP地址到txt中。 # 第三部,读取、新建的文件需要"关闭"连接。 # 重要部分:1、函数的建立,2、for循环读取URL,3、gethostbyname函数获取IP地址,4、urllist读取,新建iplist以及函数调用。 import socket def urltoip(): for oneurl in url...
3b1add97ac4db53c3e544e5c5114b7f12f646684
zhangx953/python
/test_file.py
284
3.625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import os try: filename = raw_input('请输入打开的文件名:') f = open(filename,'r') allLines = f.readlines() f.close() except IOError: print "您输入的文件名不存在!" exit() for eachLine in allLines: print eachLine
3be01a7699423fe42244a38906a8f3181caa129c
cugis2019dc/cugis2019dc-Najarie
/Code Day_2.py
1,625
4.15625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import plotly dir(plotly) print("My name is Najarie") print("Hello how are you doing") print(5*2) print(5/2) print(5-2) print(5**2) print((8/9)*3) print("5*2") def multiply(a,b): multiply = a*b print(mul...
e5eca8bc41c1d7071ae1d77fef0b10e57fc4f541
dgzara/eecs510
/util.py
1,581
3.78125
4
#!/usr/bin/python import json def parse_json(data): return json.loads(data) def get_tweet_nested_parameter(tweet, parameters): """ :param tweet: the tweet in json format. :param parameters: a list of string parameters of the tweet, or just one string parameter. :return: if the list is like [x,y,...
a5dd622aee34ec26f59c64cb9bbc3eec6fbcdc15
NicDDDD/InteractiveDictionary
/appWalk.py
868
3.609375
4
import json from difflib import get_close_matches data = json.load(open("data.json", encoding= "utf8")) def translate(word): word = word.lower() if word.title() in data: return data[word.title()] elif word.upper() in data: return data[word.upper()] elif word in data: return data[word] elif len...
716fb7e3b689ec89909de397470581911b1657e4
jaklinger/nesta_toolbox
/sandbox/jaklinger/example/is_number.py
602
3.9375
4
''' is_number This snippet gives an example of some code that would never be promoted to nesta-toolbox.official. The idea of the function is_number is determine whether the input is a number or not. The problem is, however, poorly defined. For example, who is to say that any of the strings: "NaN", "Inf", "Exp",...
f21ce26d317ba37911644e64d9f09d45f04da431
whyfzhou/intropython
/arithmetic.py
1,055
3.625
4
# --------------------------------------------------------------------- # 基本算术运算 print('1 + 1 = {}'.format(1 + 1)) print('5 - 4 = {}'.format(5 - 4)) print('3 * 9 = {}'.format(3 * 9)) print('25 / 4 = {}'.format(25 / 4)) # 真除法 print('25 // 4 = {}'.format(25 // 4)) # 整数除法 print('25 % 4 = {}'.format(25 % 4)) # 求模 print...
8b98623fa886697e058eb7ad0d36fa96105ab29a
nathankrishnan/data_analysis
/numberofrecords.py
354
3.546875
4
from processingcsv import * def num_of_records(data_sample): return len(data_sample) # minus one because we don't want to count the header line of the file number_of_ties = num_of_records(data_from_csv) - 1 print(number_of_ties, " ties in our data sample") def num_of_records2(data_sample): return data_sample.size...
155465bf6d1e4a4084f23265ce38e17049286ff9
coder777/Trapped_Game
/Room.py
1,881
3.671875
4
from Command import Commands, Command, Panic, Climb, Sit, Take, Open from Room_Object import RoomObjects, RoomObject, KeyRoomOne, Chair, VLrock, Door class Room(object): def __init__(self,commands,room_objects,inventory): self.commands = commands self.room_objects = room_objects self.inven...
81f832ef239ffcd68f26ed476c7081cbf9917849
chanchalkumawat/Pythonproject
/ex2of46.py
287
4.09375
4
def max_of_three(a,b,c): if a>b and a>c: return a elif b>c: return b else: return c print"Enter the numbers" first=int(raw_input()) second=int(raw_input()) third=int(raw_input()) ans=max_of_three(first,second,third) print "greatest number is :%d"%ans
41651c07df30dd071b4fb407ab57c4e10b74b6db
erikgust2/OpenAI-Feedback-Testing
/dataset/Fahrenheit/Fahrenheit_correct.py
353
4.25
4
def fahrenheit(): celsius = float(input("Enter a temperature in Celsius: ")) fahrenheit = (celsius * 9/5) + 32 print("The equivalent temperature in Fahrenheit is", fahrenheit) if(fahrenheit > 90): print("It's hot!") elif(fahrenheit < 32): print("It's cold!") else: print(...
8069f69be88366495aa469528b79d67fab132510
erikgust2/OpenAI-Feedback-Testing
/dataset/BMI/BMI_functionality.py
208
4.1875
4
def bmi(): height = float(input("Enter your height in centimeters: ")) width = float(input("Enter your width in centimeters: ")) area = (height * width) / 2 print("Your area is", area) bmi()
2dcc31f0f9acc373275c4887fb8f487f89301fee
MFTI-winter-20-21/DIVINA_2020
/04 puzzle.py
682
3.875
4
isGuessed = False while isGuessed != True: puzzle = "\nХоккеистов слышен плач \nПропустил вратарь их …" answer = input(puzzle) if answer == "шайбу": print("Дааа! ТЫ МОЛОДЕЦ!") isGuessed = True elif answer == "мяч": print("ПОПАЛСЯ! Не мяч)") else: print("Нет, не уг...
138d0811eb7d9a682b21a74330e2c510cde131ac
stevenbyrd/primeFactorFinder
/primeFactorFinder.py
676
3.609375
4
def primes(): sieve = [] current = 2 while True: isPrime = True for prime in sieve: if current % prime == 0: isPrime = False break if isPrime: yield current sieve.append(current) current = current + 1 def primeFactors(x, factorsList): primeList = primes() current ...
25c958d5804d038db5656996d265d76b369bbf8a
RahulMittal18/Hangman
/words.py
507
3.90625
4
import random def load_words(): """ this function help to load more words by updating word_list (list) """ inFile = open("words.txt", "r") line = inFile.read() word_list = line.split() return word_list def choose_word(): """ word_list (list): list of words (strings) t...
545ab0c0f7c50d5ff7061f3c7062b9e2f2be6b64
Mister7F/cmdargs
/examples/test_2.py
567
3.6875
4
from cmdargs import console, parse_args @console def sum(a: int, b: int = 5): ''' Sum a and b and print the result Args: a: First integer b: Second integer ''' print('Result:', a + b) @console def product(a: int, b: int = 5): ''' Multiply a and b and pr...
9306a590261d23bcc5b3ecaa53d633392200444a
KennyMC155/JustTom.py
/main.py
469
3.765625
4
from funk import searchingGame, mathematicOper, main_menu import time print("Hello, my name is Tom, let's play") time.sleep(2) main_menu() gamenumber = int(input()) while gamenumber != 3: if gamenumber == 1: searchingGame() time.sleep(3) main_menu() gamenumber = int(input()) e...
da67f666b7c822465a0c840ced404d2e075e8302
dravinbox/pythonCat
/chuanDiDemo.py
371
3.84375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- #===值传递 a = 1 def change_integer(a): a = a + 1 return a print change_integer(a) #注意观察结果 print a #注意观察结果 #===指针传递 b = [1,2,3] def change_list(b): b[0] = b[0] + 1 return b print change_list(b) #注意观察结果 print b #注意观察结果
008bc0bb4a9c278cd2399d2250f9a09b3e1bc614
benkyoukai/benkyoukai
/algorithm/inversion_count/inversion_count.py
931
3.546875
4
def isort(nums, cmp=cmp): length = len(nums) if length < 2: return nums, 0 left_length = length / 2 right_length = length - length / 2 left, left_count = isort(nums[0: left_length], cmp) right, right_count = isort(nums[left_length:], cmp) count = 0 merged = [] i, j = 0, 0 ...
a69d864cf3cd3032e5104135f008e274859deb28
benkyoukai/benkyoukai
/algorithm/min_distance/min_distance.py
639
3.625
4
import sys import os sys.path.append(os.path.abspath("../merge_sort")) from merge_sort import * def min_distance_1d(points): if len(points) < 2: return None points = merge_sort(points) (pre, cur), points = points[:2], points[2:] min_ds = abs(cur - pre) for pt in points: ds = abs(pt - cu...
7bea1a88372a5815a9e968edd244edd1b990a5e3
asyaaamayak/DC_2
/11.files.py
1,045
4.1875
4
# *** Работа с файлами **** # *** Создание файла и запись в этот файл # контектстный менеджер with # Режимы функции open: # w - write (записи) # a - append (добавление) # r - read (чтение) # with open("hello.txt", "w") as f: # f.write("Hello, world!\n") # f.write("How do u do?\n") # *** Добавление новой за...
1b8a90d4ef959296cc30b52059d83d34e7423c15
Sahana-Anbazhagan/Perception-for-Autonomous-Robots
/Outlier rejection and Homography/Code/Question2_dataset2_LS_R.py
1,541
4.03125
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd """ To read the input data from the csv file """ data = pd.read_csv('data_2.csv') x = data.iloc[:,0] y = data.iloc[:,1] """ This is a scalar value multiplied to the identity matrix to obtain the curve using Least square with Regularization """ R =...
8433d200545f02fe1e3ee912d3a0fac296d99cc3
Sahana-Anbazhagan/Perception-for-Autonomous-Robots
/Outlier rejection and Homography/Code/Question2_dataset2_LS.py
1,584
4.15625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt """ To read and plot the input data from the csv file """ data = pd.read_csv('data_2.csv') x_axis = data.iloc[:,0] y_axis = data.iloc[:,1] """ Building the model for this dataset Calculating the A and B matrices to determine X, B = inverse((transp...
513266273a82b0e41e0b03eeb3c33a7de1e88496
all1m-algorithm-study/LeetCode-Solutions
/solutions/1315/1315-kir3i.py
701
3.546875
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 sumEvenGrandparent(self, root): ans = 0 #DFS s = [(root, False)] while ...
76bd9debcb07383c6a8fc628dedc749e7a1e4e3a
all1m-algorithm-study/LeetCode-Solutions
/solutions/684/684-yongjoonseo.py
834
3.5
4
# check # return the answer that occurs last class Solution: def find(self, x, parents): if parents[x] == x: return x parents[x] = self.find(parents[x], parents) return parents[x] def union(self, x, y, parents, ranks): xr = self.find(x, parents) yr = self.find(y, pa...
893667d5faff2c5b4d572cf41b7ddd00bd72f1b2
Jeckjun/MyPythonLearnWay
/threeDay.py
5,037
3.59375
4
# 随机排序 # import random # lists = ["张三", "李四", "王二", "麻子", "皮特", "鲍勃", "苏珊", "阿三"] # newList = [] # for i in range(1, len(lists)+1): # name = random.choice(lists) # newList.append(name) # lists.remove(name) # print(newList) # 九九乘法表 # for i in range(1, 10): # for j in range(1, i+1): # print("{0:...
5b5abcedc32f9fe5486ef99f4a895ae9992a3307
ShalakaPawar/PPL-Assignment
/PPLAssign_Exception.py
593
3.921875
4
#Name: Shalaka Pawar #Mis: 111903095 # Division: 2 # Program to raise an exception and handle it # This program can be used to take integer input only import sys List1 = [ 'a', 0, 2 ] for i in List1: try: print("Entered value = ", i) reciprocal = 1/int(i) except: print("Error found -...
93d93a542cfefb780b4bfdbb40673c2a8d35939c
DaanKaak-HU/pythonProgramming
/Les7/pe7_2.py
332
3.765625
4
def woord(): while True: woord = input('Geef een woord met 4 letters: ') tel_letters = len(woord) if tel_letters == 4: print('Inlezen van correcte string: ' + woord + ' is geslaagd') break else: print(woord + ' Heeft ' + str(tel_letters) + ' letter...
29b9543e4e4f1451097f0bde93e92a01ab3bdd40
edisonmora95/rpg
/rpg/room.py
2,705
3.875
4
class Room(): ''' CONSTRUCTORS ''' def __init__(self): self.name = None self.description = None self.state = 'unlocked' self.linked_rooms = {} self.character = None self.items = [] def __init__(self, room_name): self.name = room_name self.description = None self.state ...
57b0736b75f8f48f19a8bab5095fed7c90d711ff
anastasia21112/Python_Work
/Python Crash Course/Chapter 5/conditional_tests.py
337
3.96875
4
pizza = 'cheese' print("Is the pizza cheese? I think it is.") print(pizza == 'cheese') best_friend = 'Greeley' print("\nIs you best friend Greeley? Perhaps.") print(best_friend.lower() == 'greeley') vegetables = ["carrot", "cucumber", "broccoli", "squash"] gross = "broccoli" print(gross in vegetables) print(gross not...
006cd79c9896cba72c606083a7bd24962c9459c9
rajatrj16/learncode
/scripts/palindrome.py
239
4.28125
4
# Write a Python function that checks whether a passed in string is palindrome or not. def palindrome(mystring): if mystring == mystring[::-1]: print("Palindrome") else: print("Not Palindrome") palindrome('madam')
06fbad69188997de38edf0cdb0e03ccecdede6e4
rajatrj16/learncode
/scripts/dateprint.py
164
3.890625
4
from datetime import date, datetime from datetime import time today = date.today() time = datetime.now() print "Today's date is ", today print "The time is ", time
84e14b2b640ea4eb286b2d6700f5f2a1206f6e6e
rajatrj16/learncode
/scripts/evenodd.py
107
4.21875
4
num = input("Enter no: ") if num % 2 == 0: print ("The no is even") else: print ("the no is odd")
ddb672db095de3c947c926fcfef71222fbea983f
mknittel/diplomacy-ai2
/actions.py
1,661
3.921875
4
class Action: def __init__(self, start): self.start = start self.action_power = 1 self.hold_power = 1 def add_power(self): self.action_power += 1 def print_action(self): print "Action on", self.start class Hold(Action): def __init__(self, start): self.i...
249958da141dafd525ef16e404076caf6599c7b2
lrussell21/ICPC_Template_Code
/Algorithms/OldProblems/problem13/main13.py
3,030
3.6875
4
import os import copy import sys from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.output = '' self.count = 0 self.circuitCount = 0 ...
ae275ee4355e014c8315bd34ff773856ad1daefd
lrussell21/ICPC_Template_Code
/Algorithms/OldProblems/problem14/main14.py
6,576
3.6875
4
import os import copy from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.output = '' self.count = 0 self.circuitCount = 0 self....
8076e10dc203355a8622eb7c207debd2f958eeb0
miohsu/Python_Algorithm_interview
/Chapter_01/1.1.py
1,713
4.125
4
class LNode(object): def __init__(self): self.data = None self.next = None def reverse(head): pre = next = None cur = head.next while cur: next = cur.next cur.next = pre # 节点后移 pre = cur cur = next head.next = pre return head def recurs...
92108ecc74e16ffb1594954dcb022e154d2c808a
QMSS-G5072-2021/cipher_mahdy_sali
/cipher_sfm2136/src/cipher_sfm2136/cipher_sfm2136.py
962
4.5625
5
def cipher(text, shift, encrypt=True): """ Encrypts text. Parameters ---------- text: A string that will be encrypted. (str) shift: The number of positions shifted up or down the alphabet. (int) encrypt: If True will be shifted by the integer indicated. If False will be a negative shift (bo...
8e3e8d776b92f385001493b1a9121dea3e9d77c9
krassowski/basic-particle-simulator
/simulations/gas.py
834
3.578125
4
# name: Gas simulation # You can to turn gravity :) let("earth_gravity", False) # Also: you can try to >play< a simulation for a few seconds and then >pause< it, # change speed to -10 or change "forward" to "backward" in the line below: let('direction', 'forward') # and then >play< it again. # Change you have made co...
780b296bee565e1233e5e87b6cb38265e5d0d3da
ky13-troj/College-Finder
/Proj-4.O Calculator/Expression_Calc.py
1,828
3.625
4
ip = input('Enter You Expression : ') index = 0 ip = ip.split() print('Original Input: ', ip) print('Simplifying...') #Power simplify while True: temp = False for i in range(0, len(ip)): if ip[i] == '^': temp = True if temp == False: break for i in range(0, len(ip)): if ip[i] == '^...
c9cd202d1475492fa597b7478259d235e157f159
aljs2017/Rev-Pol-Notation
/Reverse Polish Notation.py
3,014
3.640625
4
NY_line = [] NY_line[:0] = input() NY_line.append("~") NY_line.insert(0, "~") TX_line = [] CA_line = [] def main_func(NY_line, TX_line, CA_line): for car in NY_line: if car == "~": if len(CA_line) > 0: final_round(car, TX_line, NY_line, CA_line) ...
18c9793077a0cc79a742a65ffe6205a4109dd9f0
mmanishh/leetcodesoln
/easy/remove_element.py
726
3.765625
4
""" Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond th...
fce9d448555f0c4d98491a51614259e2a9e748e6
mmanishh/leetcodesoln
/easy/buy_sell_stock_2.py
899
3.609375
4
import sys class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ i = 0 valley = prices[0] peak = prices[0] max_profit = 0 while i < (len(prices)-1): while (i...
1936d7ae1d229221fd98b4d732fd89d1ac107bdf
mmanishh/leetcodesoln
/easy/remove_duplicates.py
701
3.78125
4
""" Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ class Solution: def removeDuplicates(self, nums: list) -...
3310c83021b5deb9bb93061a2eafa96f9773d3d5
ntnshrm87/Python_Quest
/Prob8.py
734
3.65625
4
# Prob 8: # Question: Is Python 'call-by-value' or 'call-by-reference' # Example: x = 3456 print(id(x)) y = 3456 print(id(y)) x = 1234 print(id(x)) # Answer: NEITHER. Its just binding of a name to an object. # Solution: # 140397975727952 # 140397975727952 # 140397975785328 # Reference: # The id number is a conce...
a10674d3fb1705e7668c2a22b4e1fb5bd2766f80
Hansimov/zuc-attack
/binaryOperation.py
3,053
3.671875
4
def circShiftLeftOfList(list_in, bits=1): list_out = [0] * len(list_in) if bits >= 0: bits = bits % len(list_in) list_out[-bits:] = list_in[0:bits] list_out[0:-bits] = list_in[bits:] else: bits = (-bits) % len(list_in) list_out[0:bits] = list_in[-bits:] list_o...
c4492f7f2feb6a4f45861c225d812df8c0b0f117
stormchasingg/leetcode-desktop
/exercise/剑指offer/二叉搜索树与双向链表.py
696
3.625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.pHead = None self.pTail = None def Convert(self, pRootOfTree): # write code here if not pRo...
58e8fcb5c06a315b440c2de6b9e28a841f3963e6
VincentJ1989/PythonTutorial
/chapter9/write_message.py
689
4.03125
4
# 写入文件 file_name = 'programming.txt' # 默认不传'w'是指只打开文件'r' # 读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+') with open(file_name, 'w') as file_object: # 写单行 file_object.write("I like Python.") # 在写一行-- 发现挤在一起了 file_object.write("I like Kotlin.\n") # 加换行符即可 file_object.write("I like Julia.\n") ...
983d8b73841eda869a71aeb0b08287ca579d0105
VincentJ1989/PythonTutorial
/chapter8/ClassRun.py
726
3.609375
4
# 从一个模块导入一个类,多个类 from chapter8.Car import Car, ElectricCar # 导入整个模块 # import chapter8.Car # 从一个模块导入所有类 # from chapter8.Car import * from chapter8.Dog import Dog my_dog = Dog("haha", 6) print("My dog's name is " + my_dog.name.title() + '.') print("My dog's age is " + str(my_dog.age) + '.') my_dog.roll_over() my_dog.si...
825126ebd233baaf6dff290502563e3574271a02
bryanyaggi/Coursera-MR
/assign/course4/project1/code/project.py
3,606
3.78125
4
#!/usr/bin/python3 from heapdict import heapdict import sys ''' Course 4 A* Search Project ''' ''' Class for storing node information ''' class Node: def __init__(self, x, y, heuristic): self.x = x self.y = y self.heuristic = heuristic def __repr__(self): return 'Node((%s,%s)...
84ebf3ceaf994c89bbcb2926e1290320e31bc7df
kankishore/OOP_DEMO
/demo_class.py
698
3.953125
4
class Employee(): #one Special method called __init__(). This is similar to a constructor in Java # It executes at the time of creating an object/instance def __init__(self,E_ID,E_NAME,E_DEPT): print("Executing init") EID=E_ID NAME=E_NAME DEPT=E_DEPT print("Employee ...
0ead1f1e2ef3c28c35cdd1d9059731c6e00d00e0
GeovaneF55/pucminas
/6º Semestre/Redes I/Trabalho Prático/batalha naval/naval_battle.py
8,975
3.5625
4
from random import randint import math def print_game(show_enemy_board, enemy_board, my_board): column = 'A' print('\nTabuleiro Inimigo\t\t\tMeu Tabuleiro') # Imprime os tabuleiros Inimigo e do jogador print(' ' + ' '.join(rows()) + '\t\t' + ' ' + ' '.join(rows())) for (enemy_row, my_row) in ...
a7d2c30ceb25bbaf6e980e4296b788dcf9f295b9
GeovaneF55/pucminas
/6º Semestre/Redes I/Trabalho Prático/sistema de precos/client.py
4,974
3.78125
4
# Externo import json import socket import struct import select def input_type(): """ Retorna o tipo de mensagem a ser enviada para os servidor (dados ou pesquisa). @return inteiro representando o tipo, sendo 1 para dados e 0 para pesquisa. """ valid_type = False while not valid_type:...
43144f046b4844e07f373ac7864b4abd7b077f2c
Jorge-Solana/Economical_Sports_Hisotry_and_Best_suitable_sport
/src/model_functions.py
3,180
3.71875
4
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error, r2_score money = pd.read_csv('money_sports_clean.csv', index...
77270360a95530cdf4373efd92ffbf8d164a4494
wesleyit/story_teller
/story_teller/utils.py
2,777
3.734375
4
""" The `utils` module presents a lot of functions to import and transform data. """ import pickle """ This table may be used many times during the program.""" puncts_table = { ".": "||period||", ",": "||comma||", "\"": "||quotation||", ";": "||semicolon||", "!": "||exclamation||", "?": "||que...
37d8389e0a95f0f625e96161bc59a544bdf714d1
AlexandraPolozenko/celebrity-profiling
/tf_idf_functions.py
1,360
3.578125
4
from sklearn.feature_extraction.text import TfidfVectorizer from text_formating_functions import text_prepare corpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?', ] def tfidf_features(X_train, X_test): ""...
c02fc1ddb66997ea3abb7ef99c5bf64f3688138c
rtequida/UofA
/CSC120/Studying/Exam 2/10.py
331
3.90625
4
def is_in_string(s, c): if s == "": return False elif s[0] == c: return True return is_in_string(s[1:], c) print (is_in_string("hello", "a")) """def is_in_string(s, c): if s == ‘’: return False if s[0] == c: return True else: return is_in_string(s[1:],...
29150016eb8a13a702ec6391a5165360ed11d023
rtequida/UofA
/CSC120/Assignment 5/ngrams.py
3,807
3.765625
4
""" File: ngrams.py Author: Ruben Tequida Purpose: Find and return the ngrams with the highest occurence within a user provided text document. Course: CSc 120, Section: 1H, Semester: Fall 2018 """ from sys import * class Input: def __init__(self): """ Initializes an Input o...
ce66c97b1ee654591b2fcbe0950e57dfac48b7bb
rtequida/UofA
/CSC120/Studying/Exam 2/11.py
697
3.78125
4
class Node: def __init__(self, value): self._value = value self._next = None def get_next(self): return self._next def __str__(self): return str(self._value) class LinkedList: def __init__(self): self._head = None def get_head(self): return self._head ...
26c54630ffc779bea8d41ce97d069e4786d795bd
rtequida/UofA
/CSC120/Testing/tempclass.py
799
3.796875
4
class Temp: def __init__(self, temp, unit): self._temp = temp self._unit = unit def __str__(self): return str(self._temp) + " " + self._unit def same_unit(self, other): if self._unit != other._unit: if self._unit == "C": self.convert() ...
0bfe1aeb57df350b010c08b0e93923b563f9b35d
rtequida/UofA
/CSC120/Studying/Exam 2/9.py
655
4.25
4
def recursive_primes(n): if n == 2: print (2) elif n == 3: print (2) print (3) else: if n % 2 == 0: n -= 1 recursive_primes(n - 2) if is_prime(n): print (n) def is_prime(n): if n == 2 or n == 3: return True return helpe...
595a2b8b0b842d03390c47d3e9351b065cd0e0ba
rtequida/UofA
/CSC120/Assignment 12/genome.py
1,710
3.5625
4
""" File: genome.py Author: Ruben Tequida Purpose: Initializes a GenomeData object, creates the ngram set and returns GenomeData attributes. Course: CSc 120, Section: 1H, Semester: Fall 2018 """ class GenomeData: def __init__(self, name, seq, N): """ Initializes a GenomeData...
d02288a2d27a6d09c1a6b05b6263eab2fedd415d
zhvkgj/test-task
/src/snippets/task1.py
450
3.578125
4
from functools import wraps def n_times(times): def deco(func): @wraps(func) def inner(*args, **kwargs): for _ in range(times): func(*args, **kwargs) return inner return deco @n_times(times=3) def do_something(): print("Something is going on!") if ...
de1f2b601268fb9ca54485bc6791ef27ebeacc0d
R-Rayburn/FlaskRestAPIs
/python_refresher/type_hinting.py
331
3.578125
4
from typing import List def list_avg(sequence: List) -> float: return sum(sequence) / len(sequence) print(list_avg(123)) class Book: def __init__(self): pass # Use string version of class when returning # the class you are in. @classmethod def hardconver(cls) -> "Book": re...
6a9d66b3585b44e690a420969e85b16baed60f82
R-Rayburn/FlaskRestAPIs
/python_refresher/store.py
1,117
3.8125
4
class Store: def __init__(self, name): self.name = name self.items = [] def add_item(self, name, price): if name in [i.name for i in self.items]: [i for i in self.items if i.name == name][0].price = price else: self.items.append(Item(name, price)) de...
f13b94598fe035b0c491b11e95654f0a4feb3051
R-Rayburn/FlaskRestAPIs
/python_refresher/mutable_default_parameters.py
559
3.71875
4
from typing import List class Student: # default parameters are defined when the class is created. # This is just creating names to the same list. # a fix: grades: Optional[List[int]] = None self.grades = grades or [] def __init__(self, name: str, grades: List[int] = []): # This is bad! se...
eac4d4367953b49707ebda546a64f63e50e09dd7
flaviojaf/attspd
/Ex1Questao2.py
82
3.765625
4
n = input('Digite um número: ') print('O número informado foi {}.'.format(n))
4da90e84bf0ec87d2057a6f970cbf807fdb8ad37
ImAlexisSaez/curso-python-desde-0
/lecciones/16/ejercicio_2.py
283
3.671875
4
def evalua_password(password): valido = True if len(password) < 8 or " " in password: valido = False return valido password = input("Introduce contraseña: ") if evalua_password(password): print("Constraseña OK.") else: print("Contraseña errónea.")
02cf24cb5a19c44e6b8d2571de84efc2534908ab
ImAlexisSaez/curso-python-desde-0
/lecciones/33/cadenas_1.py
245
4.09375
4
nombre_usuario = input("Introduce tu nombre de usuario: ") print("El nombre es:", nombre_usuario) print("El nombre es:", nombre_usuario.upper()) print("El nombre es:", nombre_usuario.lower()) print("El nombre es:", nombre_usuario.capitalize())
650e019a6ee8eb4e9fb04c45e34e4422f690649e
ImAlexisSaez/curso-python-desde-0
/lecciones/33/ejercicio_1.py
215
3.96875
4
email = input("Introduce email: ") if email.count("@") == 1 and email.count("@", 1, len(email) - 1) == 1: print("La dirección de correo es correcta.") else: print("La dirección de correo es incorrecta.")
973b7498dc99cf15a7ab303b40d3b91ba9f0cb24
ImAlexisSaez/curso-python-desde-0
/lecciones/07/listas.py
1,640
3.96875
4
mi_lista = ["María", "Pepe", "Marta", "Antonio"] print(mi_lista) # ["María", "Pepe", "Marta", "Antonio"] print(mi_lista[:]) # ["María", "Pepe", "Marta", "Antonio"] print(mi_lista[2]) # Marta print(mi_lista[0]) # María print(mi_lista[-1]) # Antonio print(mi_lista[-3]) # Pepe print(mi_lista[0:2]) # ["María", "...
beb28636a00c8145835135cf558f0de3837367c6
ImAlexisSaez/curso-python-desde-0
/lecciones/11/condicionales.py
402
3.96875
4
print("Control de calificaciones") nota_alumno = int(input("Introduce la nota: ")) if nota_alumno < 0: print("Nota incorrecta.") elif nota_alumno < 5: print("Insuficiente.") elif nota_alumno < 6: print("Suficiente.") elif nota_alumno < 7: print("Bien.") elif nota_alumno < 9: print("Notable") elif ...
93e1e65bb7abadbf590a1eeeb6a234d8fd9cc10f
ImAlexisSaez/curso-python-desde-0
/lecciones/44/interfaces_5.py
382
3.546875
4
from tkinter import Tk, Frame, Label, PhotoImage root = Tk() root.title("Probando el widget Label") root.resizable(width=True, height=True) root.iconbitmap("icon.ico") root.config(bg="lightblue") frame = Frame(root, width=500, height=400) frame.pack() imagen = PhotoImage(file="avengers.png") Label(frame, image=im...
942db6d242a30559e4fa11d840fa6760c6e3f697
ImAlexisSaez/curso-python-desde-0
/lecciones/41/guardado_permanente.py
1,861
3.828125
4
import pickle class Persona: def __init__(self, nombre, genero, edad): self.nombre = nombre self.genero = genero self.edad = edad print("Se ha creado una persona nueva con el nombre de", self.nombre) def __str__(self): return "{} {} {}".format(self.nombre, self.genero,...
df095f3d213c09eed3800a389a21b7077312c193
ImAlexisSaez/curso-python-desde-0
/lecciones/45/interfaces_6.py
1,395
3.59375
4
from tkinter import Tk, Frame, Entry, Label root = Tk() root.title("Probando el widget Entry") root.resizable(width=True, height=True) root.iconbitmap("icon.ico") root.config(bg="lightblue") frame = Frame(root, width=450, height=300) frame.pack() nombre_label = Label(frame, text="Nombre:") nombre_label.grid(row=0, ...
e98f7d955df769137ef062adf5f153bf1515ad94
ImAlexisSaez/curso-python-desde-0
/lecciones/11/ejercicio_3.py
243
4
4
num1 = float(input("Introduce el primer número: ")) num2 = float(input("Introduce el segundo número: ")) num3 = float(input("Introduce el tercer número: ")) media = (num1 + num2 + num3) / 3 print("La media aritmética es: " + str(media))
df661de20182ed48e00c47d942479eab802a16b8
mahmoudahmed02/list
/dell.py
284
3.59375
4
def remove_many(args,*vartuple): list = args new_value = 0 for value in vartuple: print(value - new_value) print(list) del list[value - new_value] new_value +=1 print('----------') print(list) remove_many([1,2,3,1,2,1] ,0,3,5)
173b540316b04795d0414d6d153dd569dfafffd8
wuna0835/RTree
/readFile.py
416
3.53125
4
# !/usr/bin/env python 3 # !-*-Coding:UTF-8-* pathIn = "D:/work/shape/errorShape.txt" pathOut = "D:/work/shape/errorShapeID.txt" fileWriter = open(pathOut, 'w') with open(pathIn, 'r', newline='', encoding='UTF-8') as fileReader: num = 0 for line in fileReader: fileWriter.write(line.strip()...
8a4de025fcc1bb159fd31f7bba6dd99f5cf6e616
lambdalife/holland
/holland/library/fitness_weighting_functions.py
2,199
4.28125
4
import math def get_uniform_weighting_function(): """ Returns a function that returns a constant, regardless of input; see :ref:`selection-strategy` :returns: a function that returns a constant """ return lambda x: 1 def get_linear_weighting_function(slope=1): """ Returns a function that weights i...
6b1a8963cec8eb1f260fe3e9a2bbabf020dfb5d3
lambdalife/holland
/holland/evolution/selection.py
3,837
3.6875
4
import math from ..utils import select_from, select_random class Selector: """ Handles selection of genomes for breeding :param selection_strategy: parameters for selecting a breeding pool and sets of parents; see :ref:`selection-strategy` :raises ValueError: if any of ``top``, ``mid``, ``bottom``,...
a27a0f09162574e43cc88fbf5469897cc8ec7a20
shiratsu/scikit-learn_test
/skutil.py
688
3.84375
4
# coding: UTF-8 import numpy as np import pandas as pd def makeFeatures(x): # 数値変数のスケーリング cn_num = ['age' ,'tenure' ,'execution.score' ,'cognitive.score' ,'social.intelligence' ,'compensation' ,'OT.hour' ,'joining.year' ...
5fa935fe9f8090a61e85d96fe01b29e15d5b5bbf
RPCodeBox2/05_Pandas_Code
/01_Pandas_Basics.py
6,341
4.03125
4
# In[1] - Documentation """ Script - 01_Pandas_Basics.py.py Decription - Basic functional of Pandas Author - Rana Pratap Date - 2020 Version - 1.0 """ print(__doc__) # In[2] - Import and Create data frames import pandas as pd ## Create DataFrame by Column (Top - Down) df = pd.DataFrame( {'a':[4,5,6], 'b':[7,8...
77cd11d10199899e274d4ff798582ea1363f4464
Ang3lino/theory-of-computation
/practice2.py
2,792
3.625
4
""" Segunda practica de Teoria computacional ======================================== Programa que determina si un usuario ingresa una CURP valida Caracteristicas --------------- Se hace uso de expresiones regulares para determinar si una cadena contiene una CURP valida. ...
7e79d318b9529fe24aad78fd69a1c8cffdc2a03a
marcelotakayama/URI
/Python/uri1768.py
388
3.625
4
while True: try: base_arvore = int(input()) espacamento = base_arvore // 2 original_espacamento = espacamento for i in range(0, base_arvore, 2): print(espacamento * " " + "*" * (i+1)) espacamento -= 1 print(original_espacamento * " " + "*\n" + (origina...
9d9f7207f4ee53d9bb41c903cda4e47f6aa5fba6
marcelotakayama/URI
/Python/uri1011.py
93
3.65625
4
n1 = float(input()) vol = (4/3.0) * 3.14159 * (n1**3) print ("VOLUME = {:.3f}".format(vol))
c3b91fa6f9fdaddf3a018f577319c29a6bd74d42
marcelotakayama/URI
/Python/uri1042.py
207
3.640625
4
valores = input().split(" ") a = int(valores[0]) b = int(valores[1]) c = int(valores[2]) lista = [a, b, c] lista.sort() print(lista[0]) print(lista[1]) print(lista[2]) print("") print(a) print(b) print(c)
4005abfb11bc6f127854c27ef1fc910a1016d734
jacob1st/Blackjack
/Blackjack02.py
7,864
3.84375
4
# A basic text based blackjack game against a computer dealer # *It's a little hard to follow all of the text ingame, therefore there are times when you need to press enter to continue the game # if you want to disable them put a '#' symbol before lines 24, 88, 167 (Another way to make it easier can be to use pytho...
0446d7f9201293ecf0397c57667346c5bf7a5084
konikoni428/smartlock
/database.py
2,692
3.515625
4
# -*- coding: utf-8 -*- import sqlite3 from contextlib import closing db_name = "manager.db" def make_info(student_id, name, idm): with closing(sqlite3.connect(db_name)) as conn: c = conn.cursor() sql = "insert into users(student_id,name,idm) values(?,?,?)" param = (student_id, name, idm)...
db726a1e466f2c63e8016d3d9f6b0ec6ab6f0a80
Apeksha1626/RockPaperScissorGame
/main.py
2,829
4.21875
4
#Rock Paper Scissor Game import random lst = ['r', 'p', 's'] chance = 10 no_of_chance = 0 computer_point = 0 human_point = 0 print(" \t \t \t \t Rock,Paper,Scissor Game\n") print("r for rock \np for paper \ns for scissor \n") # making the game in while loop while no_of_chance < chance: _input =...
aac99e1f9ca3816465d60fd950c388131954ba55
shokri-matin/Python_Basics_OOP
/MRO.py
436
3.78125
4
class X: i = 0 class Y: i = 1 class Z: i = 2 class A(X, Y): pass class B(Y, Z): pass class M(B, A, Z): pass AObj = A() print(AObj.i) BObj = B() print(BObj.i) MObj = M() print(MObj.i) # Output: # [<class '__main__.M'>, <class '__main__.B'>, # <class '__main__.A'>, <class '__main__....
7121f2e52c179c0b1e90c4e656a2e6f4708dce76
shokri-matin/Python_Basics_OOP
/09Functions.py
978
4.46875
4
# Create Function # def Name (List Of Parameter) : # Statement def absolute_value(num): """This function returns the absolute value of the entered number""" if num >= 0: return num else: return -num # Output: 2 print(absolute_value(2)) # Output: 4 print(absolute_value(-4)) def po...
11dbc44f5d851d7cd20664b4dc709b3ca3ca497b
gitfernandojmm/devcode_python_notas
/cap02/6_console.py
115
3.609375
4
# Interaccion con la consla x = "Hola Mundo!" print(x) x = input() print(x) x = input("Que deseas leer: ") print(x)
ce6a6b59905aa392960170f09037a79d7609609e
gitfernandojmm/devcode_python_notas
/cap02/4_math_oper.py
334
3.796875
4
# Operadores matematicos x = 2 + 2 print(x) x = 4 - 52 print(x) x = 21 * 24 print(x) x = 25 / 2 print(x) x = 321 % 5 print(x) x = 2 ** 12 print(x) # ===================================== x = 2 + 2.3 print(x) x = 4 - 52.2 print(x) x = 21 * 24.4 print(x) x = 25 / 2.6 print(x) x = 321 % 5.3 print(x) x = 2 ** ...
b62f88cd532bf8fcdce0ce8fcfac9d6fe4da96a4
PiggyAwesome/hangman
/hangman.py
3,131
3.578125
4
from string import ascii_lowercase as suscii_lowercase from getpass import getpass as getsus from os import system as sustem import sys as sus platform = sus.platform word = getsus("Enter Hangman word: ").lower() word_og = word lines = [] for letter in word: if letter == " ": lines.append(" ") else: lines....
a58b3813d687acae038d6c865334f9386d77729a
wkwiatkowski/kurs-py
/exercises/w3resource/circle_area.py
362
4.5
4
#!/usr/bin/env python # Write a Python program which accepts the radius of a circle from the user and compute the area. import math r = float(input("Please enter a radius of a circle: ")) a = math.pi * r **2 print print("A area of circle is: " + str(a)) print("\nOr\n") print ("The area of the circle with radius " ...
338f1d0c2bb2bb219553e5b99e351632107c867e
wkwiatkowski/kurs-py
/old/solo-1.py
1,315
4.21875
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: wk186012 # # Created: 29-10-2016 # Copyright: (c) wk186012 2016 # Licence: <your licence> #------------------------------------------------------------------------------...
2b0ba6a4479a0caf6f32c26852ca81b85779dc0c
mrcxmrj/Hangman
/hangman.py
3,496
3.75
4
""" Simple Hangman Game english dictionary from https://github.com/dwyl/english-words """ # Import and initialize the pygame library import pygame import pygame.freetype from time import sleep import random pygame.init() #variables for width and height x = 1000 y = 500 # Set up the drawing window screen = pygame.dis...
4bd3579cf2039b8174576f9ceb5b59c0eaa0f74a
cixr0x/ADyCS
/test.py
199
3.59375
4
def sum(numberList): total = 0 for x in numberList: try: float(x) total+=x except: return total print (sum([1, 'a', 5, 'dfasdfsa']))
17ee9407f0525b06bd6010865d9639d2575b1c08
kandrosc/Encryption
/vigenere.py
1,553
3.671875
4
def encrypt(alphanum,message,keyword): output='' for i in range(len(message)): output=output+alphanum[ord(keyword[i])-97][ord(message[i])-97] return output def decrypt(alphanum,message,keyword): output='' for i in range(len(message)): alpha=alphanum[0] row=alphanum[...
ac7601421b35ef195e829a12a287dfaa36f1b4c6
dmyerscough/codefights
/stringPermutations.py
692
4.34375
4
#!/usr/bin/env python def stringPermutations(origin_str, s, p=None, c=''): ''' Given a string s, find all its potential permutations. The output should be sorted in lexicographical order. >>> s = 'CBA' >>> stringPermutations(s, s) ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] >>> s = "ABA" ...